2

How can I edit a lightswitch field in an entries field layout via PHP? This is my current approach

public function actionSponsoredEntriesPriority() {
    $this->requireAdmin();
    $this->requireAjaxRequest();
    $success = false;
    $message = Craft::t('Any message from controller');

    $newPriority = craft()->request->getPost('newPriority');
    $entryId = craft()->request->getPost('entryId');

    $entries = craft()->entries;

    $entry = $entries->getEntryById($entryId);

    if ($entry != null) {
        $entry->getContent()->setAttributes(array(
            'lightswitchFieldHandle' => 1
        ));

        $success = $entries->saveEntry($entry);
        $success == true;
    } else {
        //return null;
        $success = false;
    }
}

But since there are other required fields that are currently empty for this entry I receive the following response

message: {featureImage: ["Feature Image cannot be blank."], hero: ["Header cannot be blank."]}

I tried to resave the required fields still stuck at matrix field. Here is code Reset required field

Error : Correct the errors listed above.

Do i need to update the required field as well or there is a way to bypass while updating a field ?

Update : Solution as suggested in answer [Update field directly ]

public function actionSponsoredEntriesPriority() {
        // $this->requireAdmin();
        // $this->requireAjaxRequest();
        $newPriority = craft()->request->getPost('newPriority');
        $entryId = craft()->request->getPost('entryId');
        $success = false;
        $message = Craft::t('Any message from controller');

        // entries object
        $entries = craft()->entries;
        // entries  by id ( $entryId passed by js )
        $entry = $entries->getEntryById($entryId);

        if ($entry != null) {
                $command = craft()->db->createCommand();
                $success = $command->update(
                    'content', // table name
                    array(
                    'field_lightswitchFieldHandle' => 1,
                    'field_sponsoredEntriesPriority' => $newPriority
                    ), // fields
                    'elementId=:id',
                    array(':id'=> $entryId)
                    );
                $message = Craft::t('Priority saved');
                $success == true;
            } else {
            //return null;
            $success = false;
        }
        // send response true/false with message
       if($success == true){
           $this->returnJson(
            array(
                'success' => $success,
                'message' => $message
            ));
       }else{
           $this->returnJson(
            array(
                'success' => $success,
                'message' => $entry->getErrors()
            ));
       }
    }
6
  • As soon as an Element has content and is enabled it will be validated, in Craft 2 there is no "easy and fast" way to prevent it. You could either recreate the EntriesService and include the parameter $success = craft()->elements->saveElement($entry, false); or if you only want to edit the single field create a query and set it directly in your content column Feb 28, 2019 at 10:08
  • if i use direct query is there any dependency on any another table while updating one field value.
    – inrsaurabh
    Feb 28, 2019 at 10:20
  • No, the dateUpdated value in your entry won't be updated but if that's no problem there are no other dependencies. Well and certain events won't be fired such as afterSave but if you don't need them there are no disadvantages Feb 28, 2019 at 10:24
  • Ok thank you, will try to update directly, In craft 3 is this solved ?
    – inrsaurabh
    Feb 28, 2019 at 10:42
  • Yes Craft 3 handles everything much better. If you can I would suggest you to update for countless reasons. The main one is the switch from Yii to Yii2. Yii is really old Feb 28, 2019 at 10:43

1 Answer 1

2

If it's only one single field and you want to bypass all Craft validations for required fields you can change the value directly in your database using Yii commands and the update function

function update($table, $columns, $conditions='', $params=array())
$command = craft()->db->createCommand();
$command->update('craft_content', 
    array(
        'field_yourLightSwitchField' => 1,
    ), 
    'elementId=:id', array(':id'=>1)
);

If you have a multilocale setup you need to include the condition for the correct locale as well

1
  • ii think we dont need to add craft_ as YII did this for us.
    – inrsaurabh
    Feb 28, 2019 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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