Score:0

Update body field from ajax callback

cn flag

I need to update the common "body" field when I change some paragraph fields value.

Here is my hook_form_alter :

$form["body"]["#prefix"] = "<div id='body__update_real_time_seo'>";
$form["body"]["#suffix"] = "</div>";

$form["field_content_edito"]["widget"][3]["subform"]["field_paragraph_subtitle"]["widget"][0]["value"]["#ajax"] = [
    "callback"  => "_update_real_time_seo",
    "event"     => "change",
    "wrapper"   => "body__update_real_time_seo",
    "method"    => "replace",
];

And my custom callback :

function _update_real_time_seo(&$form, FormStateInterface $form_state) {
    $form["body"]["widget"][0]["#default_value"] = "ok";
    return $form["body"];
}

When I change my paragraph field, I got the "Please wait..." but nothing happen, I still see my old value "ok" value. Stuck on this issue since few hours with multiple correction attempts from stackoverflow.

PS: When I dump before the "return", I see my new value "ok".

Hope anyone can help me. Thanks in advance.

No Sssweat avatar
ua flag
Try with `#value` instead.
cn flag
@NoSssweat It still show the old value after refreshing.
No Sssweat avatar
ua flag
After ajax runs, any JS errors in the browser's console?
No Sssweat avatar
ua flag
For debugging purposes, if you try to change the body value without ajax, does it work?
cn flag
@NoSssweat nothing in the console. And yes, if I change the body value, then save, I can see the new value after the reloading.
berliner avatar
bd flag
@guish Not sure if this is your problem, but the general pattern for AJAX with Form API is to (1) Build everything in the form build method (form alter in your case), (2) use the AJAX callback function only to return the specific part of the form that should be replaced using the wrapper selector. That and `#value` instead of `#default_value` worked for me. Alternatively you can also trigger an AjaxResponse (see https://www.drupal.org/docs/drupal-apis/javascript-api/ajax-forms#s-example-dynamic-textfield). The body field being potentially driven by CKEditor might further complicate things.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.