1

Created a content type and add taxonomy form in it using Inline entity Form module.

So, the rendered taxonomy add term looks like :

enter image description here

What I want to do is ADD CUSTOM VALIDATION to the "NAME" field.

I tried:

function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  //kint($form_state->getStorage('inline_entity_form'));die;
  // $entity = $form_state->getFormObject()->getEntity();
  //   $nid = $entity->get('name')->getValue();
  $userInput = $form_state->getUserInput();
 // kint($form_state->getUserInput()['field_plan_features']['form']['inline_entity_form']['name']);die;
 // $form_state->setErrorByName('name', t('Term already exists in taxonomy blah'));
}

How it can be done.. please suggest some way.

1 Answer 1

0

I suggest you implement hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) function.

    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Check if the $form_id is your node type add form.
             if ($form_id == 'article') {
                // Add a custom validation function. Example:
                $form['#validate'][] = 'custom_form_test';
              }
    }

Then you need to implement the custom function where you will put your logic.

function custom_form_test(&$form, FormStateInterface $form_state) {
  // Get value of the field which use the inline entity form display.
 $tags_value = $form_state->getValue('field_tags');

}

See the screenshot of the $form_state dump and also with the field_tags taxonomy term reference values: enter image description here

So you can access all the values from the inline form display. For example to access name value:

$name = $tags_value[0]['inline_entity_form']['name'][0]['value'];

Just looping into arrays. Once you get the value that you want you cand restrict finishing the submision of a node by write a message error. Example:

 $form_state->setErrorByName(
                'field_tags',
                'The name is WRONG!'
              );

Hope to help you!

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.