Skip to content

Instantly share code, notes, and snippets.

@insaurabh
Created February 28, 2019 06:19
Show Gist options
  • Save insaurabh/feed5b2c2daa97398d5ac93d63418fc5 to your computer and use it in GitHub Desktop.
Save insaurabh/feed5b2c2daa97398d5ac93d63418fc5 to your computer and use it in GitHub Desktop.
Update a custom field in custom plugin controller folder and reset the required fields.
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 = craft()->entries;
// update Sponsored entries
$entry = $entries->getEntryById($entryId);
if ($entry != null) {
$attrs = $entry->getContent();
$fields = $entry->getFieldLayout()->getFields();
$referentialFields = array();
foreach ($fields as $layoutField) {
$field = $layoutField->getField();
if ($field->getFieldType() instanceof BaseElementFieldType) {
$referentialFields[$field->handle] = $entry->{$field->handle}->ids();
}
}
$attributes = $entry->getContent()->getAttributes();
$measurementField = craft()->fields->getFieldByHandle('hero');
$measurementsBlocks = [];
// fetch all old/existing matrix blocks
$criter = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criter->fieldId = $measurementField->id;
$criter->ownerId = $entry->id;
$oldBlocks = $criter->find();
// Index them by ID
foreach ($oldBlocks as $oldBlock) {
$measurementsBlocks[$oldBlock->id] = $oldBlock;
}
// $attributes['hero'] = $measurementsBlocks;
// $entry->getContent()->setAttributes($attributes);
$entry->getContent()->setAttributes(array(
'lightswitchFieldHandle' => 1,
'hero' => $measurementsBlocks
));
$entry->setContentFromPost($referentialFields);
$success = $entries->saveEntry($entry);
$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()
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment