Daimos
Daimos

Reputation: 1473

Drupal 8 form element with #autocreate taxonomy term

I made module with form, that use autocomplete field like that:

    $form['field_taxonomy_tags'] = [
       '#type' => 'entity_autocomplete',
       '#target_type' => 'taxonomy_term',
       '#selection_settings' => [
           'target_bundles' => array('tags'),
       ],
        '#autocreate' => array(
          'target_bundles' => array('tags'),
          'bundle' => ('tags'),
        ),
       '#title' => ('tags'),
        '#tags' => TRUE,
     ];

Autocomplete works fine, and i can add taxonomy terms from tags vocabulary easily. But there is some problem with #autocreate option i think. Have searched all documentation, and code inside drupal core. Entity is never created ;/ When i try to get value from this field, my browser is dead... there is some entity type variable, but huge.

After some debugging i found way to get it work, but im not happy about it :) Very strange, maybe some of you guys can help me to find better way?

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $tags = $form_state->getValue('field_taxonomy_tags');
    foreach ($tags as $tag)
    {
        if(is_object($tag['entity']))
        {
            $tag['entity']->save();
        }
    }
  }

As you can see, I need to save those tags manually, dont know why ;/ Without it, there is no term created.

Upvotes: 2

Views: 1644

Answers (1)

Daimos
Daimos

Reputation: 1473

It is better way. I dont need to save every tag, its enough if we attach them to a node. Its entity object, that can be passed as node value, and after that, all tags will be created:

  $node = Node::create(array(
      'type' => 'YOUR_content_type',
      'title' => $form_state->getValue('title')
  ));
  $fieldNames = array_keys($node->getFieldDefinitions());
  $values = $form_state->getValues();
  // be aware with that, i use this loop for testing because i have same names
  // you can use $node->set('content type field name', $value); directly without any field definitions
  foreach ($values as $key=>$value)
  {
      if(in_array($key, $fieldNames))
      {
          $node->set($key, $value);
      }
  }
  // here we save all data, taxonomy entities too
  $node->save();

Upvotes: 1

Related Questions