0

In a custom module of mine, I have two custom entities A and B with a one to many relationship from A to B.
This is Edit form for EntityB: Edit form for EntityB

I want to have this check in validateForm: if 'Contact' (boolean) is checked, 'Adhérent' (entity_reference to EntityA) shouldn't be empty.

Here is my validateForm:

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values=$form_state->getValues();
ksm($values);
    if ($values['estlecontact']['value']==1 && $values['adherentid']['target_id']==NULL) {
      $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
    }
  }

In this case, I should not have the error message and still...
What am I doing wrong?
Here is the result of ksm: ksm

  • Hi, can you check and say if your logic is even entering inside the if statement ? – Oleg Videnov Mar 21 '17 at 10:52
  • It is the case: I get the error message sent by $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.')); – gbmapo Mar 21 '17 at 10:56
2

I figured it out!
this works:

$values=$form_state->getValues();  
if ($values['estlecontact']['value']==1 && $values['adherentid'][0]['target_id']==NULL) {  
  $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));  
}

Note that $values['adherentid'] is a mutliple value field. I was missing an array level. Adding [0] before accesing target_id solves the problem.

| improve this answer | |
  • Nice that you found it. I am not still used to kint. I preferred the output of the old dpm() command. Lately I am using PHP storm copy path feature in the xdebug. it allows me to copy the structure in complex nested arrays – Oleg Videnov Mar 21 '17 at 13:04
  • @sanzante thanks for adding details to the solution. – gbmapo Mar 22 '17 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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