Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Update a single field from a FormController AJAX method

3
by mjauvin, last modified on May 16th, 2025 - Previously published on OctoberTricks

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.

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?