3

I have a simple plugin that fires some events entries.onSaveEntry based on if a lightswitch is turned on with that entry. What I would like to do as the last event in my plugin would be updating the value of the lightswitch with that entry to be turned off (or 0) so if you went back in to the entry it would be turned off again.

Would appreciate any guidance.

5

You can set the value and save like so:

craft()->on('entries.onSaveEntry', function(Event $event)
{
    $entry = $event->params['entry'];
    if ($entry->section == 'mySection') {
        if ($entry->getContent()->myLightSwitchField == 1) {
            $entry->getContent()->setAttributes(array(
                'myLightSwitchField' => 0
            ));
            craft()->entries->saveEntry($entry);
        }
    }
});

However, you might consider using onBeforeSaveEntry so that you don't have to save the entry twice (and/or run the risk of creating an endless loop).

craft()->on('entries.onBeforeSaveEntry', function(Event $event)
{
    $entry = $event->params['entry'];
    if ($entry->section == 'mySection') {
        $entry->getContent()->setAttributes(array(
            'myLightSwitchField' => 0
        ));
    }
});
1
  • Works perfectly.
    – Chris
    Mar 29 '16 at 0:11

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.