October CMS resources and help articles

Simple and to the point. Optimized by the community.

Update a single field from a FormController AJAX method

8
by mjauvin, last modified on October 26th, 2020

When using an AJAX handler in your FormController, you can update a single field in your form using this:

public function onYourAjaxHandler($recordID)
{
   $model = MyModel::findOrFail($recordID);
   $model->fieldToUpdate = "new value";
   $this->initForm($model);

   $fieldMarkup = $this->formGetWidget()->renderField('fieldToUpdate', ['useContainer' => true]);

   return [
      '#field-id' => $fieldMarkup
   ];
}

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

Since v452 of OctoberCMS, it is now possible to use the formRenderField() method directly as the "options" argument has been added to it:

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

Discussion

0 comments

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