2

I am writing an extension on EE 3.5.11 and I am using the before_channel_entry_save hook. In the EE documentation it says and modifications to the object will be saved. I am doing something like this but no matter what I do my modifications do not get saved. Ideas?

public function set_custom_fields($entry, $values)
{
    $customFields = $entry->getCustomFields();

    foreach ($customFields as $field) {
        if (strpos($field->getShortName() === "my_custom_field_name") {
            // I have tried just and also with the line below
            $field->setData('my custom value');

            // I have tried just and also with the line above
            $values[$field->getShortName()] = 'my custom value';
        }
    }
}

If I dump the values after this I see that my custom field value has indeed been updated but it is not saved the database.

5

This was driving me insane but I've figured it out.

You need to edit the $entry object (1st parameter of the function) in order for this to work. You can, however, use the 2nd parameter, $values, for easy reading of the data.

public function before_channel_entry_save( $entry, $values )
{
    // Set value for specific field name
    $entry->setProperty( 'field_name', 'Custom value' );
}

setProperty will save the field value to the $entry object automatically. Nothing needs to be returned for this to take effect.

Your example

public function set_custom_fields($entry, $values)
{
    $customFields = $entry->getCustomFields();

    foreach ($customFields as $field) {
        if (strpos($field->getShortName() === "my_custom_field_name") {
            $entry->setProperty($field->getShortName(), 'my custom value');
        }
    }
}

Additional info.

You can view system/ee/EllisLab/ExpressionEngine/Model/Channel/ChannelEntry.php for some pointers on what can be done with the $entry object (look for $this->x). For example:

// Get current $entry channel id
$entry_channel = $entry->Channel->getId();

// Check permissions
$entry_permissions = $entry->Author->MemberGroup->can_edit_other_entries;
  • THANK YOU!!!!!!!!!! I can't believe it was that easy. This saved me so much frustration. – Trevor Orr Nov 3 '17 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.