texts: Using image transforms sometimes results in bloated file sizes.

texts:
I'm in the process of setting up Asset image transforms for my site and was playing with the quality setting to find the right balance between file size vs. output image quality.

As part of the testing process I was outputting matching images at the same final transform size in Photoshop at various levels of "Save for Web..." quality. I was surprised to see that the images Craft was generating were consistently larger in file size  than the images Photoshop was generating with approximately the same final visual quality. Typically the difference was anywhere from 20-40%.

It feels important to note that I realize that Craft's image transform quality settings don't equate to Photoshop's "Save for Web..." quality settings (i.e. using a quality setting of 65 in Photoshop is not the same as using an image transform quality setting of 65 in Craft).

I tested a variety of image types at a variety of transform and quality settings and found the results to be roughly the same in every scenario.

I'm curious if anyone else has seen / noticed this issue and if there might be a fix.


texts: Handling Endless Recursion in saveEntry?

texts:
I'm trying to update the expiry field—based on an existing field (in this case classDate)—as soon as an entry is saved.

Based on this answer, the clever recursion code in carlcs' Auto Expire plugin, I was able to get it working with this code:

public function init()
{

craft()->on('entries.saveEntry', function(Event $event) {
    $entry = $event->params['entry'];

    if ($entry->section->name == "Classes")
    {
        $entry->expiryDate = $entry->classDate;

        static $recursionLevel = 0;

        if ($recursionLevel == 0)
         {
            $recursionLevel++;
            $saved =   craft()->entries->saveEntry($entry);
         }

    }

});
}

But that seems a little dirty because saveEntry is going to get called again.

Is there a better way to handle the recursion? Bob's answer here leads me to believe you can call craft()->elements->saveElement which won't raise the saveEntry event again but I couldn't get that to work.

What am I missing? Seems too easy...


texts: Problem with truncated Freeform checkbox group value when mapped to another field

texts:
NB: this is not the same as Freeform Checkbox Group Field only returns one value, which was resolved by field name markup invoking an array: name="fieldname[]".
I'm already doing that. And stored Freeform form submissions are respecting multiple values.
My issue is that I am using Element Connections to map the form fields to other fields in the system which are assigned to user accounts.
The receiving fields are multiline Plain Text fields and they are only receiving a single value.
For example:
For a Freeform checkbox group…
<input name="group[0] type="checkbox" value="val1">
<input name="group[1] type="checkbox" value="val2">
<input name="group[2] type="checkbox" value="val3">

…that maps to user account field userData2.
When all three checkboxes are checked:

the Freeform group field stores a value of val1, val2, val3
but userData2 only receives val1.


texts: Is it possible to add a custom field to User model from a plugin?

texts:
Within a plugin I'm working on, I'll be adding user synchronisation with a third-party database to enable SSO, so will be creating users within Craft based on an interaction from this other service.

I'd also like to associate the user ID from the other service against the Craft User model. Obviously you can create custom fields from within the CP - but is there a way for a plugin to automatically add a custom field so the admin doesn't need to do it themselves?


texts: Pull info from a Related field within Matrix > within Super Table

texts:
Ok, my mind is about to implode with this… any help on template syntax very welcome!

I have 2 Sections: ‘artists’ and ‘schedules’

In the ‘schedules’ section I have a Matrix field called ‘stageSchedule’, with a Block type called ‘dayOfEvent’

In that Block type I have a Super Table field called ‘schedule’. - breakdown....

schedules (Section)

stageSchedule (Matrix) > dayOfEvent (Block)

schedule (Block field (Super Table)) - ST

In ‘schedule (ST)’ I have a date field called ‘timeOn’, which is when the artist is due to be on stage. I thought I could get this information from ‘schedule (ST)’ by having an ENTRIES field called 'act' (in the same ST field) which is linked to a specific artist from the ‘artists' section.

What I want to do... On the individual ‘Artist Bio’ pages I want to display what time they’re going to be on stage by pulling that information from ‘schedule > stageSchedule (M) > dayOfEvent (B) > schedule (ST) > ‘timeOn’.

I have tried every which way but I either get an error or nothing at all :/

I hope that makes sense... Thanks to anyone who can work this one out!

EDIT

As a test I created a Super Table field on it's own (not within Matrix)  and got the data correctly using this:

{% set reverseRelatedElements = craft.superTable.getRelatedElements({
    relatedTo: {
      targetElement: entry,
      field: 'testTimes.artist' // Super Table Field
    },
    section: 'schedules’
  }) %}

  {% for relatedEntry in reverseRelatedElements %}
    {{ relatedEntry.testTimes.timeon|datetime('H:i') }}
    {{ relatedEntry.testTimes.timeOff|datetime('H:i') }}
  {% endfor %}

So basically I need to do the same but target a Super Table field nested in a Matrix field?  Here's an image...


texts:
Transformed Images are failing to load with a 404 error  For example:

http://mysite.com/index.php?p=cpresources/transforms/382&x=v0nGRK3Qr

This happened after I swapped the db.  So, everything had previously been working.

Also:

My images reside /public_html/mysite/img/posts/
BUT, Update Asset Indexes generates The path of your source "Main Post Image" appears to be invalid And, none of the images load when I try to view Assets in cp.
I can access the image from the public URL to the assets is http://www.mysite.com/img/posts.  And, I can access the original uploaded images here.
I assume the path to my images (which I understand can be different from the URL) is the problem.
Path is current set to /mysite/img/posts/'.  I have tried multiple permutations - nothing seems to work.

Help/Thanks


texts: how to specify entry type on front end entry form?

texts:
I have a section with 2 entry types. Logged in users need to be able to submit to each type. I had planned on having 2 different entry forms.

How do I tell the form which entry type to save to? I assume it's a hidden field but what's the field name and where do I find the value?


texts: How can I pass a Craft Field into a JavaScript function?

texts:
I have a chart generated in script.

{
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
},

This is what I want to do (and I know this is not correct).

{
    "country": "{{ entry.country }}",
    "visits": {{ entry.visits }},
    "color": "#FF6600"
},

What do I need to do?


texts: When using "createElementSelectorModal()" how do you respect selected locale?

texts: When using createElementSelectorModal() in a plugin, how do you make your source list show items from the current locale selected in the CP? It only seems to show the items from default locale no matter what locale you have selected.


texts: What is the best way to have an entry for top-level categories?

texts:
I'm currently working on an eCommerce project with categories for products:

- Category 1
    - Sub-category 1
    - Sub-category 2
    - Sub-category 3
- Category 2
    - Sub-category 1
    - Sub-category 2
    - Sub-category 3

What I am hoping to achieve, is to give each top-level category its own entry in Craft, so I can apply my site-wide SEO, matrix content and utility fields.

I am aware you can apply fields to categories, but the whole double-clicking on a category and managing the content from the small modal window approach isn't ideal, especially with category pages that are a bit heavy on the content side.

These categories do have their own URL, and creating an entry with the same slug results in incrementation: example-category-1, which is to be expected.

Is there any way in Craft I can get round this? I guess if there is no other way I can apply fields to the category, but I wanted to see if anyone had any other ideas.


texts: Update Craft CMS, now I get HTTP ERROR 500

texts:
I have a site that's been running Craft 3 and has been running smoothly for several months now.

I was going to update a post today, and noticed that there were updates to Craft 3 that needed to happen (there were several craft updates, along with two plugins). I selected the Craft CMS first to update, and after hitting the update button, it did its thing for about a minute, then gave me a message that the update failed. When I tried to go back to my admin panel, I got the HTTP ERROR 500. Same when going straight to the website.

I tried change my php mode from FastCGI to just CGI as suggested in another post, but that hasn't helped. I also tried setting the devMode to true in my general.php config file, but nothing has changed there.

At this point, I'm dead in the water.

Any suggestions?


texts: I have 80,000+ files on S3 that need to be added to Craft. The Update Asset Indexes works, but takes over 24 hours and cannot be interrupted. Does anybody have a way to programmatically index assets like this in batches?


texts: Does Craft have an installer error log I can check?

texts:
I've tried to install Craft on a variety of systems, and it seems that no matter what I try, I cannot get all the way through the installation process. In most cases, my install hangs on the "Oops" screen.

I've learned not to trust this screen, because if I immediately close the window and cancel my installation, the installer screen continues to show up when trying to access the admin login /admin/.

Instead, if I just let it sit for a few minutes then close the screen, it seems like the install actually works as expected. Visiting /admin/ in my browser has the desired affect, and I'm able to use the CMS as expected.

My thought is that it might be something related to the install cleanup process - but I'd like to take a peek at the install log file to see exactly where things went wrong.

I've checked system requirements, although on some systems, I'm unable to personally verify all of the requirements are met. But I'd like to know why I got that "Oops" screen. It's obviously a non-critical error, or else the db and system would not function properly - which it does.


texts: What's the difference between 'user', 'currentUser', and 'account'?

texts:
I notice in the template examples that user, account and currentUser are all being used, but not seeing clear documentation on these. Can someone perhaps explain the difference?

Example User Registration Form uses {{ account.username }}

Example User Profile Form uses {{ user.username }}

and there is a Global Variable called {{ currentUser.username }}

I assume that user is perhaps just an alias to currentUser (unless explicitly defined otherwise)? And that account is something that is used exclusively for user/saveUser?

The reason I ask is that I'm creating edit profile pages, and want to make sure they are secure. Seems like just using user is enough, as that appears to always be populated correctly with the currentUser data; and if not logged-in it redirects to the log-in page.

Thanks.


texts: Problem cloning existing Craft instance on staging

texts:
I copied my entire existing install on a new staging server for some developmental work. Right now the craft/config/db.php file has not been changed and it is still connected to the production database.

The website loads fine on the dev server but I cannot login to the Craft admin. When I enter my login credentials, I get the following error in my chrome web console

  Failed to load resource: the server responded with a status of 400 (Bad Request) /index.php?p=admin/actions/users/login

When I try to load the above URL (mydomain.com/index.php?p=admin/actions/users/login), I get a 404 page not found error.

The craft/config/general.php config file has the correct config for the dev server as far as I can tell. What am I missing here?


texts:
It is weird that I can delete some entires in the app but some I can't. When selecting specific entry to delete, I don't see the option to delete it. I only have "edit entry" and "view entry". In some other entries I have the "delete..." option as well.
Why is that?


texts: How to fetch ALL users related to a field, including unverified/pending?

texts:
My users have a relationship field called Organisation.

In my plugin, I am trying to fetch all users that are related to the organisation I pass it.

BUT I would like ALL users including Pending, so those who have not verified their email and set a password yet.

I am using this code but it only fetches the verified users, not pending.

$entries = craft\elements\User::find();

$relatedEntries = $entries->relatedTo(
    array(
        'targetElement' => $organisationId,
        'field'         => 'organisation'
    )
);

// Fetch all entries
$relatedEntries = $relatedEntries->all();

I have also tried using combinations of ->status(null), e.g.

$entries = craft\elements\User::find();

    $relatedEntries = $entries->relatedTo(
        array(
            'targetElement' => $organisationId,
            'field'         => 'organisation'
        )
    );

    // Fetch all entries
    $relatedEntries = $relatedEntries->status(null)->all();

or

$entries = craft\elements\User::find()->status(null);

    $relatedEntries = $entries->relatedTo(
        array(
            'targetElement' => $organisationId,
            'field'         => 'organisation'
        )
    );

    // Fetch all entries
    $relatedEntries = $relatedEntries->all();

But they always just show all verified users.

Thanks

Edit

I have changed my logic and database setup a bit, and so decided to try using just template tags now. And so I got it working OK using .status(null with template tags.

{% set organisations = craft.entries().section('suppliers').authorId(currentUser.id) %}

{% for organisation in organisations %}

    {% set users = craft.users().relatedTo(organisation).status(null %}
    {% for user in users %}
        {{user.firstName}} {{user.lastName}} - {{user.status}}<br/>
    {% endfor%}

{% endfor%}


texts: Comprehensive logging of user actions with Craft Pro?

texts: I am considering a purchase of Craft Pro in place of a new ExpressionEngine build for a client. One of the client's requirements is that there be a comprehensive set of logs like Audit Pro of what each user is doing (logging on, deleting entries, changing settings) and when. Is that data logged in Craft Pro, or is there a plugin that would accomplish that functionality?


texts: Contact Form - ReplyTo or Output fromEmail

texts:
So I have a contact form set up in Craft using the Contact Form plugin. I have it rigged up with Mandrill as the SMTP provider and unfortunately with the notifications, the from email address is getting stripped out of the headers by Mandrill. So there's no way to determine who the email came from in order to reply to that person.

So my question is - is there a way to set the replyto to the fromEmail OR is there a way to output the from: email address in the resulting notification message?

Many thanks in advance from me and the client dealing with it!

Cheers,
J


texts: How do I get the data from a relation field?

texts:
If use the following code:

$currentEntry = craft()->entries->getEntryById($entryId);
$currentContent = $currentEntry->getContent()->getAttributes();
$currentAttributes = array();

$fieldLayout = $currentEntry->getFieldLayout();
foreach ($fieldLayout->getFields() as $fieldLayoutField) {
    $field = $fieldLayoutField->getField();
    if (isset($currentContent[$field->handle])) {
        $currentAttributes[$field->handle] = $currentContent[$field->handle];
    }
}

It retrieves all data that I want, but I don't get the data from relation fields. If an asset or entry has been selected, I won't receive that data. The result from that field is always null.

Does anyone know how to do this?


texts: I need to embed some forms into a new site

texts:
We are moving to a new Craft site and we have some forms that live on our form server. I am wanting to embed these forms into the appropriate pages.
There is a PHP file that I can download that looks Like this:
<?php

date_default_timezone_set(@date_default_timezone_get());
header("p3p: CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
session_start();

require("/var/www/html/machform/machform.php");

$mf_param['form_id'] = 10824;
$mf_param['base_path'] = 'https://myform.mydomain.com/';
$mf_param['show_border'] = true;
display_machform($mf_param);

?>

Or I can get embed codes for iFrames, etc...What I don't see is a way to add the embed code into an existing page.  Is there a plugin for that? How do I edit the HTM to embed the form on the page?
Thanks for helping this Craft NooB.


texts:
I'm trying to use the Imager-Craft plugin to make specific image transformations, but cannot figure out how to access Imager within the element-api.php file.

Imager shows plenty of template examples, but I'm not sure how to translate template code like this into straight Element API php.

{% set image = craft.assets().one() %}
{% set transformedImage = craft.imager.transformImage(image, { width: 1000 }) %}
<img src="{{ transformedImage.url }}">```

Specifically, I'm trying to access that craft.imager.transformImage function.

Is this possible?


texts:
I've tried to apply eager loading per Craft's docs, but it doesn't seem to work. When I do this, will I have access to all the entry fields? If not, do I have to include all the fields I want in the with attribute?

{% for entry in craft.entries.section('news').with['image'] %}
  {% set image = entry.image[0] ?? null %}
  {% if image %}
    <img src="{{ image.url }}">
  {% endif %}
  {{ entry.title }}
{% endfor %}

When I tried it, the code barfed when trying to output {{ entry.title }}.


texts: How do I save a front-end form as a specific Entry Type?

texts:
I have a few different forms on my site for different kinds of enquiries, each represented by an Entry Type with different fields in a single Enquiries channel. How can I get the entries/saveEntry form to save as a specific entry type?

My existing form:

<input type="hidden" name="action" value="guestEntries/saveEntry">
<input type="hidden" name="redirect" value="/hire-us/get-a-quote/success">
<input type="hidden" name="sectionId" value="61">

I have two entry types in that channel, ID 111 and 112. When I add the line:

<input type="hidden" name="typeId" value="111">

then submit the form, I get an error message saying "Unable to find the template 'hire-us/enquiryPlanningEvent'". It appears that Craft is looking for a template named after the entry type I'm trying to save, but obviously there isn't one.
What's the solution to this?


texts:
Is there any way to rename files upon there upload to an assets field?

I know I can hit the options of the file and rename manually, but was wondering if there was a way to do this automatically? i.e. renamed based on the entry ID.


texts: Using Craft to render frontend pages in addition to using it headless

texts:
I’m looking to create a craft site for some digital storytelling pieces. The pages will be curated by various people within my team. But I also like the idea of using the CMS to push separate content within the cms, to things other than the website. This would give us a lot of flexibility. Can you use Craft to render the front pages using twig as normal, and additionally run it in headless mode? Or if i want the benefit of using it as a headless CMS would I instead have to render the frontend site using a static site generator, like Gatsbyjs? What are my options if I want to use it both ways?

Thanks,

Richard


texts: As a web design shop we would like to license Craft not for ourselves but for our customers who run and own the future websites. How do we do that?


texts: Query only Tags wich are not connected to a revision

texts:
I wrote a query like this:
 $query = (new Query())
        ->select('COUNT(elements.id) as count, tags.*')
        ->from('relations')
        ->join('INNER JOIN', 'tags', '{{relations}}.targetId={{tags}}.id')
        ->join('LEFT JOIN', 'content', '{{content}}.elementId={{tags}}.id')
        ->join('LEFT JOIN', 'elements', '{{elements}}.id={{tags}}.id')
        ->where([
            'elements.enabled' => 1,
            'elements.revisionId' => NULL
        ])
        ->groupBy('{{relations}}.targetId')
        ->orderBy('count DESC');

So my intention there is to fetch all tags wich have content and do have revisionId IS NULL.
But it never works. I get just all the relations including these one related to elements with a revisionId not null.
Can someone help me in this issue.
I am completely new to craft and use to the symfony query builder wich is kind of different.


texts:
After updating from version 2.x to version 3.x with composer and terminal the plugin delivers this error:

  We’ve detected that both the new 3.x and old 2.x versions of Freeform
  are installed.

But looking in the plugin settings and composer.json, there is only one plugin visible.

How can I get rid of this conflict?


texts: Is there an easy way to access global sets from an Element API endpoint, so its content can be included in the JSON response?


texts:
How can I assign a user group to a user when it's created through the front end?

EDIT: So a few more details. I see there are some great answers if you want to put all users in one group, but unfortunately that's not the case. I have different forms for different groups. Ideally I would like to have checkboxes on the front end you I can choose which group they are assigned to.


texts: How to add an Element sortOption to sort by number?

texts:
I have an Element. It's a Structure, with one level (not sure if that is relevant). I'd like to add a Sort Option that allows a user to sort the Element Index page for this Element by a number. The number attribute is stored in the database as an int and named count.

On the Element class, I can add a way to sort the Element by a row alphabetically:

protected static function defineSortOptions(): array
{
  $attributes = [
    'someTextField' => Craft::t('my-plugin', 'Some Text Field')
  ]
}

However, I haven't yet been able to figure out how to give the option to sort by a number:

protected static function defineSortOptions(): array
{
  $attributes = [
    'someTextField' => Craft::t('my-plugin', 'Some Text Field'),
    'count' => Craft::t('my-plugin', 'Count')
  ]
}

The above example does not work. I've also explored the non-shorthand syntax that I see in the Craft Commerce Subscription sort options, however, have been unable to figure out how to adjust things to work with numbers.

protected static function defineSortOptions(): array
{
    return [
        [
            'label' => Craft::t('commerce', 'Subscription date'),
            'orderBy' => 'commerce_subscriptions.dateCreated',
            'attribute' => 'dateCreated'
        ],
    ];
}

How can I allow a user to order an Element Index page by a numeric column?


texts: How can I programmatically set the value of an Entries field type?

texts:
I need to set programmatically the value of an Entries field type when I'm going to create a new entry from the admin form, after the form loads I'm searching for the entry I need to set in the Entries field, so I'm making something like setAttribute('companyField', $companyEntry) but it didn't work.

I need to find a way to set/lookup that value in the Entries field type so the user can see it in the UI.


texts:
I have a form that is set up to include multiple values with checkboxes. I pass all those values into an array

{% set specsQuery = craft.request.getParam('specs') %}
{% set productSpecsCategory = craft.categories.group('productSpecs').slug(specsQuery) %}

My problem is the code below is seeing those values as OR instead of AND. I'm assuming it's because it's all put on the one targetElement line. The amount of criteria a user can select is essentially infinite (as in the max right now is 5 but more categories can be added in craftcms admin area and are created dynamically on the site as more options.

{% set entries = craft.commerce.products('footwear').relatedTo('and',
      { targetElement: productSpecsCategory, field: 'productSpecs' }
) %}

edit: I have tried

{% set entries = craft.commerce.products('footwear').relatedTo(['and',
  { targetElement: productSpecsCategory, field: 'productSpecs' }
]) %}

edit: This works with 2 criteria, but no more or less (obviously). Is there a way to loop the targetElement?

{% set entries = craft.commerce.products('footwear').relatedTo([ 'and',
  {targetElement: productSpecsCategory[0], field: 'productSpecs'},
  {targetElement: productSpecsCategory[1], field: 'productSpecs'}
]) %}


texts: stream_socket_enable_crypto() error when sending email via SMTP

texts:
I'm using a third-party email service called SendGrid to send email but am coming up with what I think is a server issue with the SSL. A temporary fix is to edit a line similar to this in a PHPMailer example:

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

But Craft doesn't use anything that resembles that to me.I want to try hacking the core to see if I can get a temporary fix up but can't find where to put it, despite scouring EmailService.php. Can anyone point me to the function where I'd add these details?

Here's the error,  by the way:

stream_socket_enable_crypto(): Peer certificate CN=`#################' did not match expected CN=`smtp.sendgrid.net' (/home/################/craft/app/vendor/phpmailer/phpmailer/class.smtp.php:367


texts:
In a custom plugin, I would like to use Craft's ability to register email message keys in order to keep emails consistent, and I would like to be able to send these emails to users as well as non-users. My understanding is that I would need to use the sendEmailByKey method of the EmailService to send emails using registered keys, which is defined like this:

public function sendEmailByKey(UserModel $user, $key, $variables = array())

This method only accepts a UserModel for the recipient, so it doesn't look like there's a way to send an email by key to an arbitrary email address. Is there a different way to send these registered emails to non-users?


texts: How to check if a user has any entries they're an author of... in a plugin?

texts:
This seems pretty simple in a template; along the lines of

if( craft.entries.authorId(10) | length ){ ... }

But how do I do that from a plugin?

craft->entries->authorId(10)

doesn't seem to exist and I've been banging my head against the docs not knowing what I'm actually looking for...

[EDIT]

I now have the following code:

$entryCriteria = craft()->elements->getCriteria(ElementType::Entry);
$entryCriteria->authorId = $existingUser->id;
$existingPages = $entryCriteria->find();

if ($existingPages) {
    AutoUserEntryPlugin::log('User already exists and has a page belonging to them; aborting.', LogLevel::Info);
    throw new Exception(Craft::t("You already have an account and a page created for you. Aborting. You have not been charged."));
} else {
    AutoUserEntryPlugin::log('User with ID ' . $existingUser->id . ' does not seem to have a page.', LogLevel::Info);
}

But with a user I know for a fact has an Entry for which they are the author, it's returning "User with ID 1198 does not seem to have a page".


texts: What is the best way to handle HTTP requests within a plugin using Yii or Craft?

texts:
I have a custom module which is moderating content before entry save, I am looking to use a Microsoft Azure API to handle the moderation, in their documentation they use a HTTP library to make the request.
Is there something which Yii or Craft already offers which I could utilise, if so, how would I perform the same function which is below.
The example provided by MS Azure is below. {body} would be content which I pass in.
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/contentmoderator/moderate/v1.0/ProcessText/Screen');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Content-Type' => 'text/plain',
    'Ocp-Apim-Subscription-Key' => '{subscription key}',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
    'autocorrect' => '{boolean}',
    'PII' => '{boolean}',
    'listId' => '{string}',
    'classify' => 'True',
    'language' => '{string}',
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_POST);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

Thanks


texts: How to create a Matrix Relation field / relate Matrix Blocks to other Elements

texts:
I would like to create a field / a way to relate a certain Matrix Block to another Element. Is this possible?

For example:

Entry A contains a Matrix Field matrix and has several blocks. I want to relate one of those blocks to Entry B


texts: Switch to graphical buttons in Redactor 2

texts:
I am trying to replace the text-based buttons in Redactor 2 with graphical ones as per this article on the imperavi website:
https://imperavi.com/redactor/examples/buttons-default-icons/

I created a simple plugin loading a JS file (a copy and paste of the JS on the page above) and a CSS file (fontawesome.min.css). These two files and the fonts are in the resources/ folder of the plugin. Example of plugin file in this post:
Can a plugin add JS or CSS to the control panel?

Everything seems to work fine: CSS file loaded in the head and JS file loaded right before the  tag.

My problem is that the JS loaded by my plugin comes before the main JS redactor file. Console barfs an error at me for trying to work with $.Redactor.prototype, which obviously does not exists yet.

Is there an easy way for my plugin to load the JS file at the end of the JS queue or at least after the main redactor JS file ?

EDIT 1:

Following Carl's advises below, I managed to get it working.

Basically, the approach is to create a RedactorPlugins object and populate it with what you need so it is available for redactor when it runs afterwards. The plugin you create that way can be used in your redactor config files.

Something like

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.iconbuttons = function()
{
  return {
      init: function ()
      {
          var icons = {
              'format': '',
              'lists': '',
              'horizontalrule': '',
              'image': '',
              'link': ''
          };

          $.each(this.button.all(), $.proxy(function(i,s)
          {
              var key = $(s).attr('rel');

              if (typeof icons[key] !== 'undefined')
              {
                  var icon = icons[key];
                  var button = this.button.get(key);
                  alert(key + " - " + button + " - " + icon);
                  this.button.setIcon(button, icon);
              }

          }, this));
      }
  };
};

Once you have created a plugin loading this JS file and the CSS you need, you can tell Redactor to use that plugin in your redactor config files:

"plugins": [ "iconbuttons", "source" ]

EDIT 2:

I will probably abandon this altogether and roll with the default text-based version of redactor 2. It looks like this approach does not work with some buttons where Craft has to do some work. It seems that when the replaceRedactorButton function in craft/app/resources/js/RichTextInput.js is run, it removes buttons customisation.


texts:
I have a route set up with a tag:
news/tag/[tag] => news/_tag

How do I generate urls that will match that route for all possible tags (including tags with punctuation)?

How do I resolve that url back to a tag (including tags with punctuation)?

Note that twigs url_encode filter href="{{tag.name|url_encode}}" will generate urls that don't route to the template for some tags.


texts: Select products that have stock and products where showWhenNoStock is true

texts:
We've been working on a sneaker shop and the product overview page is only showing the products that are in stock. Now the client also wants to show some selected products on the overview even if there is no stock.

To show only the products with stock we've added:

hasVariant: {
    hasStock: true
}

Is there a way to select products that have stock and products that don't have stock but where showWhenNoStock is true?

May be good to know showWhenNoStock is a field on the main product not the variant.


texts: How to limit number of entries to a given user/user group

texts:
I have a site where users can add entries of an entry type/section called Listings.

I would like to limit the number of Listings to a maximum of three per user.

In another CMS I did this by writing a plugin that got triggered when a new Entry was created. This plugin determined the number of existing Entries for a given user and if the maximum was reached, the plugin cancelled the creation of a new entry and instead showed a message that the user had reached their maximum limit of entries.

Not to say that this is the best way to do it, or do it in Craft, but I am new to Craft CMS and have been looking for a hook or event that is triggered when a new entry is created, but I don't seem to be able to find anything like that.

I have also done a fair bit of searching on this topic and cant seem to find any Stack questions or posts on the net....

Any suggestions much appreciated.....


texts: How does "hash" work in the context of the Contact Form?

texts:
I'm running into some trouble using the "hash" filter in Craft's first-party Contact Form plugin. The docs suggest using it like so:

<input type="hidden" name="redirect" value="{{ 'contact/thanks?from={fromName}'|hash }}">

On my development site, this is redirecting an otherwise-successful form to domain.com/hash_valuecontact/thanks?from=name, and therefore a 404 page.

Changing the value to '/contact/thanks?from{fromName}'|hash results in a more proper URL (domain.com/hash_value/contact/thanks?from=name) but still a 404. The docs suggest the hash is prepended to the value so the URL is expected but I'm not sure how the hash is decoded. And since the name is sent via the query string, I'm not sure what the hash is really doing in the first place, or why it's important.

So my question—is the hash actually important in this context, and if so how is it implemented? The docs don't contribute much information there. Thanks for any help.


texts: Redactor II Craft 2.5 Prevent Paragraphs

texts:
I realize Craft 2.5 ships with Redactor II which has many changes.

With Redactor I a combination of

paragraphize: false,
replaceDivs: false,
linebreaks: true,
enterKey: false

kept text from being wrapped in p tags.

I want to give someone the ability to add simple formatting such as bold and italic, but not wrap it in any HTML.

Has anyone found how to continue doing this with Redactor II?

Thanks.


texts: Is it possible to find what Matrix Block aren't being used

texts: I have a fairly large site with the main content on most pages driven by a Matrix field. That Matrix field has 15 or so different Blocks - we are now doing a tidy up on the site and going to try and reduce the number of blocks available - is there any way to tell if a block isn't being used?


texts: Is it possible to prevent disabled Matrix Blocks showing in a Live Preview?

texts:
I have a template which loops through Matrix Blocks. The site itself correctly ignores any Blocks which are 'disabled', but on viewing the page in the Live Preview, those Blocks are visible. A key part of the reason for using Craft as the CMS for this site was the draw of the Live Preview, so this is important for us to get right.

I can't see anything as part of a Matrix Block Model which would indicate an assigned status to each Block which I could access. If there was, as there is with a straight entry, I could at least do some sort of a work around e.g. forcing the collation of Blocks to only those with a particular status of 'enabled'.

This feels like it might just be a bug; I am seeing other complications with this particular Live Preview, for instance if any offset or limit is given to the Blocks, rearranging the blocks in the Live Preview has no effect either.

If anyone could shed some light / offer some advice that would be much appreciated!


texts:
For some reason, when outputting 'featured' tagged items, It's ordering them I presume by alphabetical values which is breaking the nth-child CSS set on every 3rd element? Is there anyway to stop this?

Getting Tagged Categories

  {% set tag = craft.tags.slug('featured').first() %}
  {% set categories = craft.categories.relatedTo(tag) %}

  {% if categories|length %}
    {% for category in categories.limit(3) %}

        {% for asset in category.universityImage %}

        {% endfor %}

          {% for asset in category.universityLogo %}

          {% endfor %}

{{ category.description }}

    {% endfor %}
  {% endif %}

CSS

.university-widget:nth-child(3n)
{
  margin-right:0px;
}

Picture Evidence


texts: Is Craft's Email Service Protected Against Mail Header Injection Attacks?

texts:
We have a client website using Sprout Forms for a contact form. The client has queried a number of security topics with us, one of which is about Mail Header Injection attack protection (https://www.acunetix.com/blog/articles/email-header-injection/).

I've reached out to Ben at Barrel Strength and his response was that Sprout Forms uses the default Craft email service so any security steps Craft is taking they're piggybacking on.

The site is currently using the PHP Mail email setting.

Does the Craft email service have any protection / validation in place to mitigate against potential Mail Header Injection attacks or would we need to implement any updates to protect against this?


texts: Categories not displaying as nested in control panel

texts:
Try as I might I just can't seem to get categories to show as nested in the Control Panel as shown on https://docs.craftcms.com/v3/categories.html#creating-and-editing-categories

There's no level of depth set on the category group, so not sure what else is at play?


texts: Paginate a list of product variants with categories parameters

texts:
I have got a category multi-select feature that allows users to filter variants by more than one category. On selection the URL is concatenated as a new category as follows:

?cat=blue
?cat=blue+decorative
?cat=blue+decorative+white
etc

I am just trying to setup the paginate tag to show a list of variants that are filtering by the categories from multiple category fields that the variants have.

In this case they are 'colour' and 'shape'. There are discussions amongst the team about converting a multiple category group structure into a single nested category group to make functions like this easier.


texts: Access Element API JSON in another environment

texts:
First Craft project and off to a great start. I don't think i'll ever touch Wordpress again. :)

I'm using the Element API plugin to build out one of my feeds of entries and hoping to use that on a couple sites as a little widget.

JSON: https://csgoevents.gg/api/events.json

Using jQuery for now: http://codepen.io/eboyer/pen/kXqNXJ

Getting this error: "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access."

Historically, i'm more of a designer/html/css developer, so HTTP & API work is new to me. From what I understand this can be avoided if the server could return JSONP? Or if I had any sort of control over nginx configurations? (I'm hosting with Web Faction)

Are there any examples out there of using Element API data on other domains?

Hopefully its something with a quick solve. Thanks in advance, excited to be here!


texts: A user cannot change the password without completing the profile

texts:
I have an issue. I have custom fields in the user profile, some of them are required.

I also have a change your password page and a change your email password.

A user can create an account (Without the custom fields).

But when he/she tries to change the password without completing the profile (In the change password page), the password won't be saved as there are some required fields empty.


texts: Return the current section type? (plugin)

texts:
Is there an easy way to check what the current page section type is, within a plugin?

I wonder if I'm overlooking a little function that simply returns: "single", "channel", "entry", etc...?

UPDATE:

Thank you Aevlan, this was the approach I took originally. I've been struggling to determine wether the user is currently on the root of a channel/structure, or if they are on an entry page.

This is how I can determine "single", "channel" or "structure".

$element = craft()->urlManager->getMatchedElement();
$element_exists = $element && $element->getElementType() == ElementType::Entry;

$currentPageType = $element->section->type;

The reason I need to know this, is so I can perform some checks before I add certain navigation throughout the site. To help with my specific issue, I will use "hasDescendants()" or check the segment counts.

Thanks again. Mark


texts:
Curious if anything exists like this for Craft?

http://www.wpexplorer.com/create-rss-news-aggregation-portal-wordpress/

Just looking for something that can look at an RSS feed and post entries to a Craft powered site.


texts:
I'm trying to set up a basic PHP Mail setup with Craft. I really just need it set up to handle new account activation e-mails. I can't seem to find any instructions on the Craft site or elsewhere on how to set this up specifically for Craft. Does Craft require any specific configuration for PHP Mail to work?

Thanks.


texts: Matrix block fields returning NULL when using MatrixBlock query

texts:
$blocks = MatrixBlock::find()->relatedTo($entry)->all();

The above returns the correct blocks but all fields are returned as NULL.

I've read over at GitHub that we need to specify a fieldId param but can't seem to figure out how.  The below e.g. doesn't work:

$blocks = MatrixBlock::find()->relatedTo($entry)->fieldId([33])->all();

Help anyone?


texts:
I have 2 forms on my site, one that registers for the WHOLE site and one that registers for just the downloads on the site. I wrote this custom function to change the user group if the email existed. So basically what i'm going for here is if someone signed up for ONLY the downloads and wanted to signup for the whole site to let them use their email they used to sign up originally.

So basically they fill out the sign up form use the same email etc.

Currently the code i have isn't working properly. It changes the user group and allows the user to sign up IF they already signed up, however it won't update the rest of my user fields on the form. If a new user comes to the site and tries to sign up for the whole site the signup form doesn't work, it doesn't save the user, just redirects to the login page.


texts:
I'm trying to figure out the best way to create an entry that is live but "unlisted". I know wordpress has the option, and the same thing you can do when uploading videos to youtube.

What's the best way to have a post be live but not included into the regular posts returned when listing items?


texts:
I would like to get all enabled variants for a product. I refer to the following question, where a method for limiting a for-loop is given:

Disabled product variant still shows in {% for %} loop

In the comments Andreas provides a way to get all enabled variants for a product:

{% set variants = craft.commerce.variants({ product: product, enabled: true }) %}

However, in my case this does not return any variants, while there are two active. Instead, it returns the following object:

object(craft\commerce\services\Variants)#2364 (3) {
  ["_events":"yii\base\Component":private]=>
  array(0) {
  }
  ["_eventWildcards":"yii\base\Component":private]=>
  array(0) {
  }
  ["_behaviors":"yii\base\Component":private]=>
  NULL
}

How can I get all the active variants for a product?


texts: Entries Related by Category with Filler Entries After

texts:
At the bottom of an entry I want to display links for eight other posts. To make this useful, what I'd like to do is:

start with entries that are related to the post currently being viewed by category (generally there are 4-5 of these)
then fill in the remain slots with the other posts (not related by category), newest first

Is there a simple-ish way to do this? I started down the path of separate queries, counting, and merging results but something about that feels more complicated that it should be. I'm wondering if this can be achieved via ordering or grouping?

Thanks in advance.


texts:
A portion of my template is being cached, using the standard cache tag:

{% cache %}

Within that cached section of the template, I'm using a template hook:

{% hook 'myTemplateHook' %}

Within that template hook, I'm collecting entry data via a normal ElementCriteriaModel:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'mySection';
$myEntries = $criteria->find();

So I'm wondering... Will my PHP-based query be cached?

I'd like for the caching of this query to mimic any caching that would take place via Twig templates. What do I need to do to ensure this follows normal caching patterns?

EDIT:

Great answers so far, but they don't really touch on the heart of my concern...

Normal Twig-based caches actually record all criteria and elements used in the cached HTML, for the purpose of invalidating that cache when either of those things change. What I really want to know is, would my PHP-based criteria and resulting elements be recorded as well? Since the criteria is built in PHP, and the elements are collected in PHP, I'd like to know if they are being stored (as they normally would via Twig).

This obviously makes a difference for cache invalidation... If an element fetched via PHP is updated or deleted, I'd like to be confident that the cache would be cleared as well.


texts:
Does Craft CMS support MySQL over SSL?

Thanks!


texts: Set logging path/file to use php://stderr

texts: I'm rethinking our Craft environment/workflow.  My idea is to accommodate disposable and/or multiple container (or server) environments.  As a result I want to use log aggregation apps like papertrail, logstash, etc to consolidate and investigate logging across multiple servers.  They recommend logging to php://stderr.  Is this possible?  What approach would you take to override the apps log route?


texts: Refresh Craft for loop with form parameters

texts:
Recently new to Craft and Twig although I have used Expression Engine in the past. I am looking for a way to update a for loop that is pulling entries from a defined category based on the current entry/page category by using a dropdown list with all categories available.

Entries: Vehicles

Categories: Truck, Suv, Compact, Economy

Fields: Color, numofDoors, passangers, gasmileage

Example of code:

{% set related = craft.entries.section('vehicles').relatedTo(entryVehicleCategories%}

{% for vehicle in related %}

    {% if related|length %}

Name:{{vehicle.name}}

color:{{vehicle.color}}

Number of doors:{{vehicle.numofdoors}}

    {% else %}

No content

    {% endif %}
{% endfor %}

<form action="{{ url('search/results') }}">
    <select name="vehicle-search" placeholder="Search">
        <option value="Truck">Truck</option>
        <option value="Suv"> Suv </option>
        <option value="Compact"> Compact </option>
        <option value="Economy"> Economy </option>
    </select>

    <input type="submit" value="Go">
</form>

Upon form submit I am hoping I can change/set related to something new.

Example: Current loop is looping and showing all related truck entries.

Action wanted: User selects suv and div reloads suv entries on page without reloading page.


texts: How do I create pagination links for my entry index page?

texts:
So I may be somewhat obtuse here, but I’m trying to discern what I might be doing wrong in this instance. I’m attempting to use a {% paginate %} tag inside my craft.entries loop to return a simple next/previous set of pagination links. I have ensured I have two entries already, so I should be seeing the pagination links, correct?

{% for entry in craft.entries.section('houseRules').limit(1) %}

            {# Content is Here #}

    {% paginate craft.entries as entries %}
        {% if paginate.prevUrl %}Previous Page{% endif %}
        {% if paginate.nextUrl %}Next Page{% endif %}
    {% endpaginate %}
{% endfor %}


texts: I'm creating a plugin but want to simplify the title that appears in the CMS' left-hand main navigation for my client. I understand that by default it pulls from the getName method but I want to choose something different than what's set there. Is it possible to do this?


texts: Craft or Twig filter for MD5 or SHA3 hash creation?

texts:
I've been digging around and haven't found an existing Twig filter for what I'm trying to do. Basically, I'd like a filter that would provide a hash of a phrase.

Pseudo-template code would be something like this:

{{ "my phrase here"|hashwithmd5 }}

And would generate this in my rendered template:

6e6d5618f8ab8a302a236eac07c59300

Does something like this exist? Am I going about this in a bad way?


texts: Password protect whole staging site. Redirect to original page not working

texts:
I'm trying to password protect a staging site. So I've put a {% requireLogin %} at the top of my _layout.html inside of a conditional tag. It's working except the redirect after login always goes to the dashboard instead of the original page. What am I doing wrong?

I'm aware of the possibility of using htaccess protection, but I think doing it the "Craft way" is nicer.


texts:
I want to skip an element within Feed me after if a condition passes.

So i am listening to the stepBeforeElementMatch event.
Within this event i would have something like this:

if($event->feedData['status'] == "false") {

    // dont import, skip me
}

I couldn't find any way how i would skip this specific element. I am wondering if there is a way to even skip an element?


texts: Incorrect canonical URLs and redirect chains

texts:
I have installed SEOMatic. However, I am getting incorrect canonical URLs. Here is an example: https://jenoffvanhulle.com/en/
The URL has a trailing slash, the canonical URL not
A second problem is that I'm having redirect chains. e.g. www.jenoffvanhulle.com -> https://www.jenoffvanhulle.com -> https://jenoffvanhulle.com
It's clear that some settings are not right. Can somebody help me solving both issues please?
Below you find a listing of some relevant settings:

htaccess

# Redirect www traffic to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

general config

'siteUrl' => [
'nederlands' => 'https://jenoffvanhulle.com/',
'english' => 'https://jenoffvanhulle.com/en/',
],

base URL settings in Craft

SSL certificate settings


texts: Front-end entry field validation problem

texts:
I have this simple code:

<form method="post" accept-charset="UTF-8">

    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="services/{slug}">
    <input type="hidden" name="sectionId" value="3">
    <input type="hidden" name="enabled" value="1">

    Service <input type="text" name="fields[service]">

    {# Entry field (required) #}
    Client <input type="text" name="fields[client][]">

    <input type="submit" value="Submit">

</form>

{% if entry is defined %}

{{ dump(entry.getErrors()) }}

{% endif %}

The client field is set as required.

Submitting the form with empty client field I get no validation error but a CDbException.

If I remove the line with the client input field I get a validation error as expected:

  array(1) {   ["client"]=>   array(1) {
      [0]=>
      string(23) "Client cannot be blank."   } }

What am I missing?
How can I validate entry fields?


texts: Dynamic fields layout based on categories

texts:
I have entries called products. Those entries are organized in categories. I'm using fields to save technical data for each product ( ex. Flow rate, Pressure, Voltage, etc. ).
Not all fields suit all product categories ( ex. Voltage doesn't make sense for pneumatic pumps ).
Is there a way to associate some fields only to products in a specific category?

Thanks


texts: Ordering Element API by Category and Title

texts:
I'm looking for a way to order the ElementAPI json array by category and title. I can only get one to work whether it's 'group' => 'stockistRegion.first().title' or 'order' => 'title' using the criteria attribute.

Has anyone achieved this or know of a solution?

return [
    'endpoints' => [
        'stockists.json' => [
            'elementType' => 'Entry',
            'criteria' => [
                'section' => 'stockistsListing',
                'search' => 'stockistRegion:*',
                'group' => 'stockistRegion.first().title',
                'order' => 'title'
            ],
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'stockistWebsiteUrl' => (string)$entry->stockistWebsiteUrl[url],
                    'address' => $entry->stockistAddress1 . ', ' . $entry->stockistAddress2 . ' ' . $entry->stockistAddress3 . ' ' . $entry->stockistPostcode,
                    'formatted_address' => $entry->stockistAddress1 . '
' . $entry->stockistAddress2 . '
' . $entry->stockistAddress3 . '' . $entry->stockistPostcode,
                    'stockistAddress2' => $entry->stockistAddress2,
                    'stockistAddress3' => $entry->stockistAddress3,
                    'stockistPostcode' => $entry->stockistPostcode,
                    'stockistRegion' => (string)$entry->stockistRegion[0],
                    'latitude' => $entry->latitude,
                    'longitude' => $entry->longitude,
                    //'jsonUrl' => UrlHelper::getUrl("stockist/{$entry->id}.json"),
                ];
            },
        ],

    ]
];


texts: Asset Meta Fields vs Section with Asset field + the other fields?

texts:
Let's say we have products, and some of these products have a Firmware Update file (or several firmware update files) that may be associated with the product entry.

The Firmware file assets will have associated "metadata" for each, including:

Version
Region
Release Date
Notes
Install Instructions

My question is would it be better to add a new section for Firmware, with separate fields for the above (plus associated Product and Firmware Asset Entry), or just have the Asset contain all those fields as metadata on the asset entry itself?

I guess this might be a philosophical question. Maybe it will be flagged as too subjective, but I thought I'd ask.


texts: Filtering orders by date bring wrong results

texts:
I'm having a problem with wrong results when filtering order by date.

I use this code:

{% set orders = craft.commerce.orders.dateOrdered(' >= 2016-07-01 00:00:00').dateOrdered(' <= 2016-07-01 23:59:59').find() %}

The last order has been placed on 2016-06-29, and there has been no orders placed on 2016-07-01, so I would expect order to have no results. However it just lists all orders in the system.

If I change the date to 2016-06-10, the result is empty - as expected.

Is this bug in Craft / Craft Commerce, or do I miss something?

How do I make sure I get no results, if there have been no orders on this date?


texts: Craft hosted on Google App Engine - failing to load Craft classes?

texts:
Have tried getting Craft working on Google App Engine (GAE) using the GAE SDK and after defining CRAFT_STORAGE_PATH first up in the index.php, setting it to a Google Cloud Storage path eg. gs://craft-gae-storage/ I found I had to uncomment the workings of craft_ensureFolderIsReadable function in bootstrap.php so it didn't fail on the folder checks, but then it still dies with the error:

Fatal error: Class 'Craft\PhpMessageSource' not found in /Users/.../Craft-gae-HappyLager/craft/app/framework/YiiBase.php on line 213

I'm using the HappyLager demo combined with the Yii GAE codebase from https://github.com/poul-kg/yii-app-engine with a slightly modified base setup to try to get craft working:
https://github.com/moldedjelly/craft-gae


texts:
I’m trying to bootstrap Craft as a service inside of another framework (lumen). I’m requiring the bootstrap file which seems to get me up and running except that plugins and assets aren’t included in the EntryModel results.

I’m requiring Craft like this:

$craft = require_once base_path().'/../craft/app/bootstrap.php';

$this->app->singleton('Craft', function() use ($craft)
{

    return $craft;

});

and then getting my EntryModel like this:

$criteria = app()->make('Craft')->elements->getCriteria(ElementType::Entry);

$criteria->section = 'emails';

$criteria->slug = 'tuition-agreement-link';

$email = $criteria->first();

Text content returns perfectly, but asset fields return null. The one thing I can see that craft/app/index.php does differently than me is calling $app->run() (since I'm not actually trying to run the full blown app with request routing). Anyone know if there is an additional step I can take to bootstrap assets and plugins without running the full blown app? Am I trying to do the impossible?


texts:
My legacy URLs have this structure:

/teachings/tag/13721/omnipotent/ or
/teachings/series/17764/fearless/

For both the tag and the series they are always followed by a string of digits and then slug I want to capture and redirect to the new formats:

/teachings/topics/omnipotent and
/teachings/series/fearless

I've tried various ways using https://regexr.com/ to capture the slug and target each legacy URL but I can't seem to figure it out. I've seen the basic instructions here but I can't seem to find a way to target the unique legacy formats of these strings.

Any help you can provide would be greatly appreciated.


texts:
I have two product types. One has variants. One has not.

So I try to write an image tag that works for both.

{% set imageThumb = item.defaultVariant.variantThumb.one()  %}

For the product with one variant this returns:

  Impossible to invoke a method ("one") on a null variable.

This works only for the product type with multiple variants. defaultVariant doesn't seem to be present on products with just one variant.

Trying to fit both cases with one and with multiple variants:

{% for item in craft.products.all() %}
   {% if item.defaultVariant | length %}
     {% set imageThumb = item.defaultVariant.variantThumb.one()  %}
   {% else %}
      {% set imageThumb = item.variantThumb.one()  %}
   {% endif %}
      <img src="{{ imageThumb.url }}"
 {% endfor %}

This code is not working. How do I have to write this?


texts:
I am working on a project with multiple developers and another member of the team is getting on with a Plugin to assist with some CraftCommerce integrations.

As it's not a publicly available plugin, it's being stored locally in our repo.

However, whenever I run any Composer command on my local machine I get the following error:

[RuntimeException]
  Package <agency>/<plugin> cannot install to
  "/Users/jaycollett/Development/project/build/custom/<plugin>"
  inside its source at "/Users/jaycollett/Development/project/build/
  custom/<plugin>"

We have found this response from Andrew Welch, but it can't be this because our Composer.json repositories section is as follows:

  "repositories": [
    {
      "type": "composer",
      "url": "https://asset-packagist.org"
    },
    {
      "type": "path",
      "url": "./custom/<plugin>"
    }
  ]


texts: Misconfiguration error when accessing URL without file name

texts:
When accessing www.myurl.com/services, I get this error below the content of my page:

The server encountered an internal error or misconfiguration and was unable to complete your request.

I don't get this error if I access www.myurl.com/index.php/services. I'm new to Craft, but am particularly confused, because nothing else on my site is broken, I just keep getting this error appended to the end of my html. Additionally, I have followed the directions to include an .htaccess file in the web root. This error does not occur locally. Thoughts?


texts: Craft 3 Ubuntu installation error via composer setup

texts:
After running composer and then initiating craft setup I keep getting this error:

Username: [admin]
Email: abc@test.com
Password:
Confirm:
Site name: test
Site URL: test.com
Site language: [en-US]
Installing Craft...

Exception 'craft\errors\MigrationException' with message 'An error occurred while executing the "craft\migrations\Install migration: Error while sending QUERY packet. PID=25472'

in /vendor/craftcms/cms/src/db/MigrationManager.php:267

My MySQL version is 5.7.18-0ubuntu0.16.04.1.


texts: How can I retrieve Users of a specific User Group with GraphQL?

texts:
I want all the users but filtered by User Group:

query getAllUsers {
  users {
    id,
    username
  }
}

I cannot see any query parameter on the Schema


texts: Multiple structures sharing the same entries?

texts:
I'm working on a site that currently has one structure ("projects") that organizes my entries for each specific project. In the admin I can reorder these entries manually... so far so good!
But now, I was wondering if I could have two different structures: 1. for "featured projects" on the home page and 2. for a "project index" - both that I could reorder manually but in a different order from one another. Does that make sense?
So I was wondering if it was possible to have two different structures share the same set of entries?
Thanks for your thoughts!


texts:
My question is re: localization of ElementTypes in a plugin.  I have the records all working fine in multiple locales.

The part that I'm not "getting" is I think there should be one Element in craft_elements and then for each localization, there should be one record in craft_elements_i18n yes?  And then for each localization, there should be a separate record in my craft_seomatic_meta table for each localized version yes?

This is where in my controller it saves the ElementType: https://github.com/khalwat/seomatic/blob/master/controllers/SeomaticController.php#L173

And here is the function is calls in my service to save the element & record: https://github.com/khalwat/seomatic/blob/master/services/SeomaticService.php#L683

When I call $result = craft()->elements->getElementById($metaId, 'Seomatic_Meta', $locale); how does it "know" which record to look up to load the returned Seomatic_MetaElementType with data?

I'm clearly missing something basic regarding how this should all work


texts: Can't add anymore fields / blocks to Matrix Field

texts:
I have a really big / flexible Matrix field for one of my websites. It works great and is easy to handle.

The problem is that I need to add another block containing some fields.
I already extenended the php_value max_input_vars to 9000. This worked for a while but I guess I need even more now.

The Matrix field contains 25 blocks with an average of 5 fields per block as of now but, I need to build another one. If I add another block right now the block will stay but If I add a field to the block and save it, it won't appear when reloading the matrix field.

I know it's alot of blocks inside a matrix field but, it actually is really easy to work with.

Now the question is. Is there another way to extend the limit or maybe a better solution?


texts: Return the contents of a template from a custom Twig function in a module?

texts:
I have a template that outputs some JSON formatted data.

I've built a simple module that needs to get the contents of that template, decode the JSON data, and return it.

I believe I need to use craft()->templates->render('path/to/template'), but when I do, I get:

Call to undefined function modules\importjsonmodule\twigextensions\craft()

The only explanation I can think of is that craft() cannot be used in a module in the way it can in a plugin. Is that the case? If so, is there any way I can access the Templates service from within a module?

Thanks


texts: Check for logged in user with the Element API plugin

texts:
Working on a SPA with Vue and Craft and looking to check if a user is logged in to run some Vue conditional logic.

I imagine that will then enable me to check if the logged in user owns content to return as well?


texts: Let a client log in to the site when the system is off

texts: I would like to let a client log in to the site when the system is off, but without CP access. I have created a user group named «testing-group» with one checkbox checked: «Access the site when the system is off», and I have assigned a user to this group. I have created a 503.html template in the templates folder, and the login form provided in the docs,  http://buildwithcraft.com/docs/templating/login-form, is in this template. The form is displayed, but nothing happens when I try to log in (happens both with admin account and the user assigned to the group «testing-group» ).


texts: Allow users to edit user account email from front end form in Craft 3?

texts:
Is there a way to allow users to edit their email address via a front-end form in Craft 3?

My understanding is this would require an 'elevated' user session. Which I'm guessing can only be achieved via plugin. In the API docs I see that there is a startElevatedSession() method.

At a minimum, I'm assuming this might work:

Submit form with existing password and new email to a custom controller.
Controller starts an elevated session via startElevatedSession(), sets new password on user, saves user, and redirects to success page.

If I were to create a 'confirm email' workflow for security — how might that work? Can I tap into the Craft native workflow? Or would it all need to be custom?

FYI... in this case, the site is set to useEmailAsUsername if that makes a difference.

As a follow-up, would changing the email address affect relationships to commerce orders? I assume that they are related by something other than just email address.

Any general pointers would be much appreciated. Thanks.


texts: Craft not Downloading Auto Update - HttpException on OS X PHP56

texts:
I have a development system running OS X / nginx / php-fpm 5.6 and I've pulled down a version of my site from my git repository. The site is currently running an out of date version of craft, however it appears to have issue connecting to the craft update server when I check for an update, simply saying ‘You’re up to date!' (which it isn't).

This only happens on the testing system so I'm guessing it's a configuration issue in php, but having reconfigured php several times I still have this issue. It also causes plugins like the Directory plugin and DUKT's Videos plugin to return errors like 'Couldn't retrieve account' when querying apis.

Looking at the logs turns up a HttpException, although I'm not entirely sure what would cause this issue? Craft hasn't said anything is wrong with my environment but clearly something is failing somewhere...

2014/10/27 23:42:04 [warning] [application] 404 -
in craft/app/etc/errors/HttpException.php (29)
in craft/app/controllers/TemplatesController.php (59)
in craft/app/etc/web/WebApp.php (293)
2014/10/27 23:42:04 [error] [exception.Craft\HttpException.404] exception     'Craft\HttpException' in craft/app/controllers/TemplatesController.php:59

I installed PHP through homebrew with the command:

brew install php56 --with-homebrew-curl --with-homebrew-libxslt --with-homebrew-openssl --without-snmp --without-apache --with-fpm --with-mysql php56


texts: Commerce: How can I save a custom SKU from a plugin?

texts:
I have a plugin that is listening to the onSaveProduct event.

In my product settings, in the "Automatic SKU Format" field I have:

{product.title}

That way I am always working the main product title.

For the SKU, I want to only use the first initial of each word - so I am doing this from my plugin:

...
$default_sku = $event->params['product']->defaultVariant->sku;
$expr = '/(?<=\s|^)[a-z]/i';

preg_match_all($expr, $default_sku, $matches);

$sku = strtoupper(implode('', $matches[0]));

...

error_log((craft()->config->get('devMode')) ? 'SKU: ' . $sku : '');

Let's say I have "My Super Product" as the title. The above is generating this: MSP

Perfect!

But, now I'm not sure how to go back and re-save the product.

Do I need to re-find the product and then set the defaultSku and then re-save it? Not sure how to proceed.

Thank you for any suggestions!


texts: Address form not redirecting to payment form in Craft Commerce

texts:
I've had this working before but with the billing address as well. Do both the billing and shipping addresses need to be filled out in the same form for this to work? I get this error when I click the submit and the page just refreshes instead of redirects.

  CWebUser.flash.error' => 'Cart not completely updated.',

Here is my code

<form method="POST" class="flex-container flex-center flex-col nav-buttons flex-lg">
    {{ getCsrfInput() }}
    <input type="text" name="email" value="" placeholder="email@site.com"/>
    <input type="text" name="shippingAddress[firstName]" value="" placeholder="First Name">
    <input type="text" name="shippingAddress[lastName]" value="" placeholder="Last Name">
    <input type="text" name="shippingAddress[address1]" value="" placeholder="Street Address">
    <input type="text" name="shippingAddress[address2]" value="" placeholder="Apartment/Suite/etc">
    <input type="text" name="shippingAddress[city]" value="" placeholder="City">
    <input type="text" name="shippingAddress[zipCode]" value="" placeholder="Zipcode">
    <input type="hidden" name="shippingAddress[countryId]" value="233">
    <select style="width:100%; padding:10px 0; margin:10px 0; text-align-last:center;" name="shippingAddress[stateId]">
        <option>State</option>
        {% for stateId, stateName in craft.commerce.statesArray["233"] %}
            <option value="{{ stateId }}">{{ stateName }}</option>
        {% endfor %}
    </select>
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="store/checkout/payment">
    <input type="submit" value="To Payment">
</form>


texts: Creating HTML and Text version of entry via different templates

texts:
So I'm using Craft to create code to be pasted into a blast email program. My standard template is at the following:

newsletter/_entry

However, I'm having trouble getting the text version to display in any way. I tried creating the following folder structure which did not work (404).

newsletter/text/_entry

I tried using routes in the backend to do this, but does not work either. I know I must be missing something simple. Any ideas?


texts: Freeform - Alternate Success Markup after AJAX Submit

texts:
Regarding Solspace Freeform: I want to have a custom message when submitting a form via AJAX. In the docs, there is some JS I used (see below). It works, but I want to know what to replace the code below with to have it work with just one specific form... what is the form ID? I tried putting in the form name in various formats without luck.
// Find the form element, can be a specific ID or just look for any forms
var form = $('form[data-id]');

The page in the docs: https://docs.solspace.com/craft/freeform/v3/guides/ajax-return-loads-success.html#from-existing-div


texts: Craft Commerce Trigger Event to Re-save All Products

texts:
Because Commerce doesn't support Twig product title formatting right now, I built a custom plugin to automatically update the title field upon save of a product.

Here is the part from the plugin where I am hooking into the commerce_products.onBeforeSaveProduct event:

craft()->on('commerce_products.onBeforeSaveProduct', function(Event $event) {
    $product = $event->params['product'];

    if (count($product->collection))
    {
        $collection = $product->collection[0]->title;
        $titlePieces[] = $collection;
    }

    $modelNumber = $product->modelNumber;
    $titlePieces[] = $modelNumber;

    $titleSuffix = $product->titleSuffix;
    $titlePieces[] = $titleSuffix;

    $product->getContent()->title = implode(' ', $titlePieces);
});

All that works great when I manually edit a product, but we have about 500 products in the system right now, and nobody really wants to open up every entry and manually save it. The hope was that we could do something in the CP to trigger an event to re-save all product entries.

I went into the Commerce settings for each Product Type and re-saved the settings, which did trigger a "Resaving Furniture products" task. But, that didn't appear to update the title field for all the products.

Any other ideas on how I could avoid manually re-saving all entries?


texts: group Matrix blocks and also order by Matrix field for a given block

texts:
I'm wondering if I might have a little too much inception madness in my thinking with this problem.

Enhancing a site we built for a conference last year. As there's an annual conference each year and some of the speakers are the same, we decided to reevaluate the approach.

What we have now is 2 channels, Speaker and Conference. Speaker contains all the speakers that could ever make an appearance at the conference and Conference contains the specific details about that conference.

Within conference, we have a Matrix field called Talks with a workshop, general and special event block.

I want to be able to group talk blocks by their block type, is that possible?

Going a step further, in the case of a workshop - that block has a workshopRound select field of 1, 2 or 3 - I'd love to be able to then group entries with those blocks by their round number.

Any thoughts on how this could be achieved?


texts: Paginate and Cache Together and SEOmatic helpers

texts:
I am struggling to get this working correctly.
If I keep the element queries outside the cache tag then this naturally stops the cache being broken and so is not a viable option. However, when I put the element queries inside the cache tag, I hit issues with not being able to get the pageInfo variable to pass to the pagination links but also to SEOmatic.
So how can I combine the ability to paginate the content, cache it but then also place it in the correct place so future or new posts automatically break the cache.
Here is the full code outside the cache tag:
Caching works, SEOmatic and Pagination URLS work - but the page cache is never broken.
{% set firstPending = craft.entries({
  section: 'news',
  status: 'pending',
  orderBy: 'postDate asc'
}).one %}
{% set cacheUntil = firstPending ? firstPending.postDate : now|date_modify('+1 year') %}

{% set news = craft.entries
  .section('news')
  .with('articleImages')
  .limit(4) %}

{# Get the articles and paginate them #}
{% paginate news as pageInfo, pageEntries %}

{# SEOmatic pagniate codfe into head #}
{% do seomatic.helper.paginate(pageInfo) %}

{% cache globally using key 'url: ' ~ craft.app.request.getFullPath() until cacheUntil %}
  {% for entry in pageEntries %}

      {% include 'pages/news/_partials/_news-teaser.twig' %}

  {% endfor %}
{% endcache %}

Here is the code inside the cache tag:
Caching Works, Cache is broken, but then the SEOMatic and Pagination URLS break as they cannot access pageInfo as it is not set.
{% cache globally using key 'url: ' ~ craft.app.request.getFullPath() until cacheUntil %}

  {% set firstPending = craft.entries({
    section: 'news',
    status: 'pending',
    orderBy: 'postDate asc'
  }).one %}
  {% set cacheUntil = firstPending ? firstPending.postDate : now|date_modify('+1 year') %}

  {% set news = craft.entries
    .section('news')
    .with('articleImages')
    .limit(4) %}

  {# Get the articles and paginate them #}
{% paginate news as pageInfo, pageEntries %}
  {% do pageInfo.setBasePath('news') %}

  {% for entry in pageEntries %}

      {% include 'pages/news/_partials/_news-teaser.twig' %}

  {% endfor %}
{% endcache %}

I am sure I could hack a way around this but duplicating element queries etc.
But it doesn't feel right. I would like to know the ideal way to code this.
Thanks.


texts: Pictures (Assets) not showing (error 404)

texts: My pictures were not showing - even if everything looked great (files were available at the right place, template code was correct, ...). My first reaction was to check the htaccess file, but (see my answer below).


texts:
Unless I'm missing something, it seems like it is impossible to search by ID in the CP (and therefore via ElementCriteriaModel's search).

I know you can make it sortable using modifyEntrySortableAttributes, but it still doesn't make it searchable.

I've also tried id::"123", which doesn't work.

Any way to do this?


texts: Shortest code to link to CSS and JS file

texts:
Is there a helper tag to output a complete stylesheet link.

I used helper tag for lack of knowledge. Helper tag is used in Statamic.

In Statamic {{ theme:css src="style" tag="true" }} outputs

<link rel="stylesheet" href="/site/themes/redwood/css/style.css" />

I've seen <link rel="stylesheet" type="text/css" href="{{ siteUrl }}assets/css/happylager.css"> in Happy Lager's template but I'm looking for something shorter.


texts:
I keep getting the 404 after successful payment.

I am pretty sure I have everything set up correctly, the thanks template is there, but it seems like Craft won't respond to the request, so the routing is not trigged, Apache is still trying to serve that file directly, it won’t recognize the {hash} part in the URL, so keep return the 404 page.

The only way I find to make this work is manually add another redirect in the Route section (last screenshot), but it's not a nature way.

Any insight would be great.


texts: How to disable the Javascript "actions/queue/run" on frontend?

texts:
After upgraded our Craft from 3.3 to 3.4.14 we have noticed that there is a new Javascript on the footer of the homepage (frontend) that runs "index.php?p=actions/queue/run".

We run the tasks via crontab and there is no need for that.

How can we disable it on the frontend?

Thank you


texts: Diagnosing Slow Database Connection for Entries (Frontend and Craft Admin)

texts:
We have set up a remote database connection for Craft CMS so that I and my colleague can work on the same database locally. The connect seems very slow both front end and in the admin area.

Contacting the VPS provider they assure us that the Database is running efficiently. They tested using MySQL Workbench (see results below) and concluded that the slow speed we are experiencing is on connectivity/CMS level. We know this isn't isolated to one ISP as we experience the same thing at home as well as work.

I'm a bit stumped as to what the issue could be. I don't 'think' this is a front end issue but I have also attached a screenshots of the Database Debug for the front end and admin area for entries... just in case this reveals anything... I'm not entirely sure what I'm meant to be looking for. Any help/tips and ideas would be appreciated.

Database Debug (frontend for entry)

Database Debug (admin area for entry editor)

Database Workbench Testing

Slowest Database Queries


texts: How to remove category link from redactor links but leave assets and entry link

texts:
This is a follow up from How to remove Link To Category from Redactor.
I've been able to setup the module and remove all links with this:
Event::on(
  RedactorField::class,
  RedactorField::EVENT_REGISTER_LINK_OPTIONS,
  function(RegisterLinkOptionsEvent $event) {

          $event->linkOptions = [];
  }
);

Which removes all Craft links, but how do I remove the categories links only?


texts: Imager plugin using it's transformImage method doesn't produce correctly resized images

texts:
I'm using the lovely "Imager" plugin to produce a srcset of images, however it seems to only produce one size of image, which isn't really what i was expecting!

My code is:

{% set image = entry.image.first() %}
{% set transformedImages = craft.imager.transformImage(image, [
    { width: 1370, height: 600 },
    { width: 1000 },
    { width: 800 },
    { width: 600, jpegQuality: 65 },
    { width: 400, jpegQuality: 65 }
], { position: image.focalPoint, mode: 'crop', jpegQuality: 80 }) %}

Have i missed something here?


texts: How can I get the correct label of a dropdown that has matching values?

texts:
I have a drop-down field in the CP - It represents a range of numbers that are based either a percent or a fixed number.

For example, a choice could be Fixed 5% or a choice could be Variable 5%
In either case, the value of my field is 5.00 for both options. The label is different, one says "Fixed" the other says "Variable".

It seems that this is a bad approach as I will usually get the first match based on value.

Let's say I have Fixed 5% listed first in my drop down field, but I actually choose Variable 5%. Currently, I am getting Fixed 5% as the selected option instead of Variable 5%.

I'm not sure how I can set up this field correctly so that Craft can see what I have chosen correctly. Perhaps there is a better way to setting up my drop down?


texts: Cannot delete user that was subscribed to a subscription

texts:
A user was subscribed to a subscription with 30day trial.
User decided to unsubscribe "Immediately" within 30day trial. Now In CP I cannot delete this user.

I check user, then delete, and confirm delete, then the success message says "Users deleted" , but the user remains there and is not deleted.

Commerce: 3.0.6

Stripe for Craft Commerce: 2.2.3

CraftCMS: 3.4.5

Issued also occurred on Commerce: 2x version.

Is there something I'm missing or not doing properly before a user can be deleted?


texts: Does setting requireMatchingUserAgentForSession to false have any additional implications to be aware of?

texts:
I recently ran into an issue that I was able to fix with what feels like a workaround – updating the config setting requireMatchingUserAgentForSession to false.

While I expect something changed on the website where I needed to do this, I'm not sure what would have changed and am curious if anybody with deeper knowledge of how user agents and sessions work could help explain what factors are at play here.

In my situation, members of the site were getting logged out shortly after they logged in and, while I could login to the control panel and navigate to several pages, each time I tried to access the Users tab, no users would display and I'd get logged out.  Each time this happened the corresponding item in the logs referenced a discrepancy between the user agent in the cookie and the current user agent.  The specific error message was:

  Tried to restore session from the the identity cookie, but the saved
  user agent (Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)
  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109
  Safari/537.36) does not match the current userAgent (Mozilla/5.0
  (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like
  Gecko) Chrome/48.0.2564.116 Safari/537.36).

The error outlines a discrepancy between Chrome/48.0.2564.109 in the cookie vs the current Chrome/48.0.2564.116.

What scenario creates a discrepancy between the User Agent in the cookie and the current User Agent? What variables can change that cause a previously working membership site, to require suppressing differences in these variables to work?  Does suppressing this required match and allowing for differences in the current User Agent and the session open up possibilities for other issues to arise?


texts:
What are I doing wrong here?

I'm setting block types 'stripCustom' and 'stripShowroom' to 'stripBlock'

{% set stripBlock = entry.contentImage.type(['stripCustom', 'stripShowroom']) %}

Then in a loop checking if 'stripBlock' is last and the current block is last but one.

<div class="section {% if loop.last == stripBlock and loop.revindex0 == 1 %}gutter-bottom--double{% endif %}">
....
</div>


texts: Getting an zero index and count for an entry list

texts:
I currently have an entries field which outputs a list of related entries on page. I'm trying to find a way to display two values for these entries.
The first would be a zero index. I'm trying to assign each entry to link up with a slider. Long story short, each of the 4 assigned entries would be listed as such
0 Entry One
1 Entry Two
2 Entry Three
3 Entry Four
The second would be to display a simple count of sorts before each entry. This would be displayed as

Entry One
Entry Two
Entry Three
Entry Four

I'm sure this must be possible but I'm unsure about the zero based index format. If anyone could help, I'd really appreciate it.
My code is currently set up as such
{% for project in sliderWork %}

This is where the simple numbering would be displayed{{project.title}

 {% endfor %}


texts: When adding a new Entry, I'm having an error

texts:
I'm new at Craft and I want to add new Entry into a jobs section. But I'm always receiving en error message.

{% extends '_layouts/site' %}

{% block body %}

    {% set company = entry.company %}
    {% set jobDescription = entry.jobdescription %}
    {% set jobRequirements = entry.jobrequirements %}
    {% set location = entry.location %}
    {% set salary = entry.salary %}
    {% set email = entry.email %}
    {{ company }} &nbsp; - &nbsp;{{ entry.postDate.rfc1123 }}

    Description
{{ jobDescription }}
    Requirements
{{ jobRequirements }}
    Location
{{ location }}

    Contact us at
 {{ email }}

Salary
{{ salary }}

{% endblock %}


texts:
So I have /calendar and linking previous/next months on that template. The previous/next month urls are /calendar/2015-08 and /calendar/2015-08.

I have this custom route setup:

On my /calendar/2015-08 I'm getting this:

Variable "entry" does not exist

Part of my template looks like:

{% extends '_inc/_layout' %}

{% block meta %}
<title>{% if entry.metaTitle|length %}{{ entry.metaTitle }}{% else %}{{ entry.title }}{% endif %}</title>
<meta name="description" content="{{ entry.metaDescription }}" />
<meta name="keywords" content="{{ entry.metaKeywords }}" />
{% endblock %}

I know why this happening but my question is how do I circumvent this? I want some of the same data on /calendar to be on subsequent monthly calendar pages.

Thanks in advance!


texts: Craft 3 Element API: Query the "parent" entry of a "child" entry with Matrix blocks connected by an 'Entries' field

texts:
In a Matrix block field of a "page" entry, I'm using an Entries field to manually select a list of "article" entries to the "page" entry.

When I query an "article" entry, is it possible to query its "parent" page entry that's connected using the above method or do I have to use categories?

BTW it'd be appreciated if the solution is written for the Element API plugin or PHP code if possible.

Thanks!

EDIT: edited question to be more accurate by adding the Matrix details.  Also, the correct query would be:

Entry::find()->section('page')->relatedTo([
    'targetElement' => $article,
    'field' => 'articleSections.articles'
])->all();


texts: How do I set the Post field after manipulation

texts:
I'm trying to write a simple plugin that will intercept registration form's data, manipulate it and move it forward. What I'm struggling with is how to set the Post content of a field after the manipulation.

I'm trying to achieve something like that, how do I set the Post field after manipulation, setRawPostContent doesn't seem to work here.

 craft()->on('users.onBeforeSaveUser', function(Event $event) {

        if(craft()->request->isSiteRequest())
        {
            $companyId = craft()->request->getPost('email');
            $event->params['user']->setRawPostContent('fields[companyId]', $companyId);
        }

    });


texts:
Our Craft installation is now working on the Production Cloud-Server, except that if I'm logged in the CP, after maybe 30 sec the login-modal pops up and says that the session has expired.
If I just reload the CP, I'm in again without the need to login.

That behaviour didn't show up on the development server.
I didn't make any Configuration Settings like userSessionDuration or something like that, that's all default.

Any idea?


texts:
I have a service which am passing a model and an identifier (optional) to.

The model contains new data and the aim is that if an existing record exists then we merge the two responses into a json_encoded string for storage. There is some jiggery pokery going on within the service to check against existing records before merging the results and then saving to either 1) a new record (if no id) or 2) update the existing record.

All well so far until it comes to saving the record. This returns true within my code but existing records within the database are not saved/updated.

Any thoughts on why this might be happening appreciated? Service code here:

public function saveReport(MS_ReportModel $model,$id = null) {
  if ($id > 0) {
    $tmp = [];
    $record = MS_ReportRecord::model()->findByAttributes(array('id' => $id));
    $fields = json_decode($record->report);
    // merge jiggery pokerey here //
    $record->setAttribute('report',json_encode($merge));
  } else {
    $record = new MS_ReportRecord;
  }
  // add other attributes here //
  if ($record->save()) {
    return $record->id;
  } else {
    return false;
  }
}

I've found a similar thread at Craft CMS Plugin Save Record to DB from Variable but cannot reproduce the solution discussed.

Cannot see for the life of me why the record is saving (i.e. returning a true response) but the relevant values are not being reflected in the database. If I output the $record object at any stage after the merge has taken place it contains the values I expect.

Ta, Cole


texts:
I have been working as a freelance web designer now for over 2 years, building websites using plain html, css and jquery.

Most of my clients require simple showcase websites that look well, load fast, well optimised for Google, are easily navigated and show a portfolio of projects. Most also require a blog.

My question is, what is the level of knowledge required in order to take a static html, css website and add Craft CMS to it. The only areas of the website that I would want my clients to have access to would be for them to complete simple tasks such as adding on another project page with an image slider and project details or to add a blog post with a few pictures.

I have little to no knowledge of PHP and don't have the time to learn anything too advanced.

All replies would be very much appreciated. Thanks.


texts: Migration: Removing field from GlobalSet/Entry

texts:
Im creating my own migrations to better handle adding/removing fields on all environments.

Is the following safeDown() function the correct way to remove a field from a fieldlayout? It works but im open if their is a better way to archive this.

  public function safeDown()
{
    $tabStructure = [];
    $cartDestinationUrl = Craft::$app->fields->getFieldByHandle('cartDestinationUrl');
    $headerGlobalSet = Craft::$app->globals->getSetByHandle('header');
    $tabs = $headerGlobalSet->getFieldLayout()->getTabs();

    foreach ($tabs as $tab) {
        $fields = $tab->getFields();
        $fieldIds = [];
        foreach ($fields as $field) {
            $fieldId = $field->id;
            if ($fieldId !== $cartDestinationUrl->id) {
                $fieldIds[] = $fieldId;
            }
        }
        $tabStructure[$tab->name] = $fieldIds;
    }

    //remove empty tabs from layout
    $tabStructure = array_filter($tabStructure);

    $globalSetLayout = Craft::$app->fields->assembleLayout($tabStructure);
    $headerGlobalSet->setFieldLayout($globalSetLayout);

    return (Craft::$app->globals->saveSet($headerGlobalSet));
}


texts: How do I use divisibleby() in a for loop to display two columns?

texts:
I try to write a row in which there are two columns:

{# and so on and so on #}

Now maybe there is only one block_txt div at the end so I try to wrap the row tag in a devisibleby conditional to only write the row tag every second time, or at the end.
It looks like this:

{% for entry in entriesInYear %}
   {% if loop.index is divisibleby(2) or loop.first %}
{% endif %}

This gets repeated n times

   {% if loop.index is divisibleby(2) or loop.last  %}
{% endif %}
{% endfor %}

But that doesn't work the way I want. Every third block_txt isn't wrapped in a row. How do I have to math this? Or is there a better way to write the whole piece?


texts:
I have a field categories in a channel news, and I want to find all the entries in news that don't have a category set. I know I could loop over the entries and find them that way, but I'm hoping to do it with a query. I tried

{% set uncategorized = craft.entries.section('news').categories(':empty:') %}

But it returned none.


texts:
I have a list of students and can sort them by name, sport, and school. The name and sport portions are easy, I'm grabbing the values without issue.  Where I'm struggling is the school value is from a Dropdown field.
Using the following code results in no students being listed let alone being sorted by school.
   {% set usersSchoolQuery = craft.users().group('athlete').all() %}
   {% set usersBySchool = usersSchoolQuery|group('schoolAttended.one()') %}
   {% for users in usersBySchool.all() %}
   {% for user in users %}

This should work but isn't. Could someone see where I'm going wrong here?


texts: Craft Commerce payment gateway: general info requested

texts:
one of our clients requested us to create a global webshop for their business. We have little experience with webshops and as we are avid fans of Craft, we'd like to start on this project with Craft Commerce.

It would be built with Commerce 1.x as their current site is based on Craft 2 and an update to Craft 3 is not possible at the moment.

My questions are a bit broad and is based on our little experience we have with Magento:

how far does Craft Commerce go when a user puts an order?
- The user buys something on the website
- The order is sent to the Payment gateway
- When the payment is processed, the gateway sends a confirmation back.
- What does Craft do next? Does it automatically set a new order status "paid"? It creates an order, but does it handle cancelations or order credit notes?
Or does Craft Commerce quits when the order is created?

Magento has some sort of built-in bookkeeping, but how far does Craft go?

What gateway is best for global/international payments?


texts: In upgrading from Craft 2 to Craft 3 I'm getting a SQL error saying the translationMethod column is missing

texts:
The full message is:

Internal Server Error
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'fields.translationMethod' in 'field list'
The SQL being executed was:
SELECT fields.id, fields.dateCreated, fields.dateUpdated, fields.groupId,
fields.name, fields.handle, fields.context, fields.instructions,
fields.translationMethod, fields.translationKeyFormat, fields.type, fields.settings
FROM craft_fields fields WHERE fields.context='global'
ORDER BY fields.name

In looking at the database I only see the translatable column. How can I go about fixing this?


texts: Craft Commerce stock not updated when order deleted

texts:
Is this deliberate, or a bug? Delete an order and the products within the order don't have their stock updated again.

I'm only running Craft Commerce 1.2.1327 but I don't see any mention of it in the update notes to the current version so I'm not sure updating is the answer. I'm also cautious about updating at the moment in case it breaks my third-party payment gateway plugin.


texts: First steps with Craft Nitro: hostname not working after successful install

texts:
I installed Docker and Nitro and successfully used nitro create <folder-name>, and ended up with the 'Welcome to Craft CMS!' message.
I cded into the new folder and invoked ./craft setup, which along the way has reported 'success!' at testing database credentials.
After saying yes to installing on the command line and creating an admin user account, I've received:
*** installed Craft successfully (time: 12.240s)

Generating project config files from the loaded project config ... done

I can see my new local dev instance running in Docker.app, but when I go to the site in a browser I get 503 – Service Unavailable.
If I go to {hostname}/admin I get the browser prompt to Install Craft. If I try and fill that out I get PDO exception: SQLSTATE[HY000] [2002] Connection refused.
The potential ease of use of Nitro looks really promising so it's frustrating to be so close!
What could I be missing?

Update 1
I have the following in my .env:
DB_DRIVER=mysql
DB_SERVER=127.0.0.1
DB_PORT=3306
DB_DATABASE=<dbname>
DB_USER=nitro
DB_PASSWORD=nitro
DB_SCHEMA=
DB_TABLE_PREFIX=

where <dbname> is the DB name I was asked to define (during nitro create I think) and which it said it could connect to.
Under 'Databases' nitro context reports:
Databases:
  engine:        mysql 5.6      hostname: mysql-5.6-3306.database.nitro
  username:      nitro  password: nitro
  port:  3306

Update 2
To start from scratch, I junked my nitro instance in Docker and uninstalled nitro, and then reinstalled it, and went through nitro create again, and…
ended up in basically the same place.
I've tried my custom database name as the value of DB_DATABASE and the default nitro database name, and it makes no difference.


texts: Live Preview only works with published entries

texts:
We have a site where Live Preview only works with entries that have been previously published. When trying to preview entries we're working on (or drafts), we see either the latest entry for that section instead - or sometimes the correct entry template but with other/missing data in it.

Puzzled as to what is going on. There are no console errors.