Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Update a single field from a FormController AJAX method

2
by mjauvin, last modified on May 2nd, 2024 - Previously published on OctoberTricks

When using an AJAX handler in your Controller, you can update a single form field as shown below:

public function onYourAjaxHandler($id = null, $context = null)
{
   if (is_null($id)) {
           $model = $this->formCreateModelObject();
           $model = $this->formExtendModel($model) ?: $model;
   } else {
           $model = $this->formFindModelObject($id);
   }

   $fieldName = 'fieldToUpdate';
   $fieldId = sprintf("#Form-field-%s-%s-group", class_basename(get_class($model)), $fieldName);

   $model->{$fielName} = "new value";
   $this->initForm($model, $context);

   $fieldMarkup = $this->formRenderField($fieldName, ['useContainer'=>false]);

   return [
      $fieldId => $fieldMarkup,
   ];
}

public function create_onYourAjaxHandler()
{
   return $this->onYourAjaxHandler(context:"create");
}

public function update_onYourAjaxHandler($id)
{
   return $this->onYourAjaxHandler($id, context:"update");
}

You can find the Id of the Form Field Group by inspecting your Form's HTML code using the Debug Tool Inspector in your browser, but the above code should be able to generate the Id based on the value you assign to $fieldName.

If you need to replace the field container, set useContainer => false. If you need to keep the container, set useContainer => true.

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.

Discussion

1 comment

0
mrkbingham
Post on March 29th, 2022 11:39 PM

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 ];

We use cookies to measure the performance of this website. Do you want to accept these cookies?