0

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.

1 Answer 1

0

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

1
  • 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? Apr 3, 2023 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.