Score:0

Error when trying to retrieve a term with ajax

zm flag

We are creating a custom form to edit a certain node. We do this above because there are some things that cannot be accomplished with the default form.

I want to use AJAX to populate the fields of the custom form with the values entered in the existing node, as shown below.

$form['client_company'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#tags' => TRUE,
  '#selection_settings' => array(
    'target_bundles' => array('vid', 'client'),
  ),
  '#weight' => '0',
];
$term = $this->taxonomyStroage->load($node->field_project_refercompany->target_id);
$form['client_company']['#value'] = $term;
$response->addCommand(new ReplaceCommand(".form-item-client-company", $form['client_company'])); // Line 208

return $response;

However, I get the following error.

Error: Drupal\Core\Template\Attribute->__toString() in Call to undefined method Drupal\taxonomy\Entity\Term::render() (/app/web/core/lib/Drupal/Core/Template/Attribute.php line.324)
/app/web/modules/custom/projectmanager/src/Form/ProjectManagerForm.php (208): Drupal\Core\Ajax\AjaxResponse->addCommand(Object(Drupal\Core\Ajax\ReplaceCommand))

I do not know how to fix this.

Score:0
pk flag

In your code $term will be a term entity object.
Try setting the value of the form to the term id.
$form['client_company']['#value'] = $term->id();

EDIT:
Actually, it seems you already have the term ID, so you should not need to load the term entity. Maybe just do:
$form['client_company']['#value'] = $node->field_project_refercompany->target_id

shibasaki_stack avatar
zm flag
Thanks,error not occured.Am I correct in understanding that the entity "term" itself cannot be entered into the form, but only text-based items such as target_id and name can be entered into the form?
I sit in a Tesla and translated this thread with Ai:

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.