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()
));
}
}
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 columndateUpdated
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 asafterSave
but if you don't need them there are no disadvantages