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.

Chris
  • 395
  • 2
  • 11

1 Answers1

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
        ));
    }
});
Douglas McDonald
  • 13,457
  • 24
  • 57