Update a single field from a FormController AJAX method
3
When using an AJAX handler in your Controller, you can update a single form field as shown below:
Note: if using the Javascript API, don't forget to add the form
attribute to your JSON request. (ref. https://wintercms.com/docs/v1.2/docs/ajax/javascript-api)
public function onYourAjaxHandler($id = null, $context = null)
{
if (is_null($id)) {
$model = $this->formCreateModelObject();
$model = $this->formExtendModel($model) ?: $model;
} else {
$model = $this->formFindModelObject($id);
}
$this->initForm($model, $context);
$formWidget = $this->formGetWidget();
// use method below instead to work with the RelationController's manage form
// $formWidget = $this->relationGetManageWidget();
$fieldName = 'fieldToUpdate';
$field = $formWidget->getField($fieldName);
$fieldId = sprintf("#%s-group", $field->getId());
$field->value = 'My Dynamic Value';
$fieldMarkup = $formWidget->makePartial('field', ['field' => $field]);
return [
$fieldId => $fieldMarkup,
];
}
public function create_onYourAjaxHandler()
{
return $this->onYourAjaxHandler(context:"create");
}
public function update_onYourAjaxHandler($id)
{
return $this->onYourAjaxHandler($id, context:"update");
}
Tip: if you want to update a repeater field from another custom formwidget on the same form, just use this instead:
$controller = $this->controller;
$controller->initForm($model);
$fieldMarkup = $controller->formRenderField('fieldToUpdate', ['useContainer'=>false]);
And return the result shown previously.
This didn't work exactly as suggested for me when using a nested form. I used the method below to update a widget field inside a nested form:
// Get model and update value
$model = MyModel::findOrFail($recordID);
$model->nestedFieldName = "new value";
$this->initForm($model);
// Get form widget and retrieve nested form
$formWidget = $this->formGetWidget();
$nestedForm = $formWidget->getFormWidget('name_of_my_nested_form');
$nestedForm->bindToController();
$fieldMarkup = $this->widget->formNestedFormNestedFieldName->render();
return [ '#field-id' => $fieldMarkup ];