By Lazaro Cruz on
Hello, I am trying to validate a form in Drupal. I have tried the following 2 codes and they do not work for me. Could you help me with it? Thanks in advance !!!
I did not put any validation conditions to make the code less complicated and find the problem.
1.
<?php
use \Drupal\Core\Form\FormStateInterface;
function validations_form_alter($form, &$form_state, $form_id){
$form['#validate'][] = "validate";
}
function validate(&$form, &$form_state){
$form_state->setErrorByName('Error',t('Error'));
}2.
<?php
use \Drupal\Core\Form\FormStateInterface;
function validations_form_validate($form, &$form_state){
$form_set_error('Error',t('Error'));
}
Comments
The first way should work if
The first way should work if you add "&" symbol before $form, like this:
Also, the first parameter of the setErrorByName() is the name of the form element.
But how would it be if it does not depend on any field?
Thank you very much, yes it already works when making the corrections that you tell me, but what would I do if what I want is to validate that no more content of a specific type is inserted? In that case I cannot associate the error to any field.
This is what I try to do:
The use case is not clear,
The use case is not clear, could you provide more info and also share the implementation of the validation function.
You can use FormState::setError() instead and maybe, in your case it makes sense to pass the $form as the parameter. See the examples.
Yes, it's exactly what you were looking for
Yes, it's exactly what you were looking for, but it only prints the error if there is another one. if it's the only error then it ends up submitting the form when it shouldn't.
The idea is that it is not allowed to insert more than one content of type "logo". This is the code after the corrections:
Your use case is still not
Your use case is still not clear for me. You can try to provide more extended explanation (what is the form you are talking about, what fields/elements does it have, where and how do you insert content of type "logo"?). If we understand the use case, we will try to help
I already found the problem
Thank you very much but I already found the problem. The $form_id is returning "node-logo-form--4cHWyNinmi0" and so $form_id == "node-logo-form" is returning false. Now the question is why does it contain that code behind that is always different?
I already tried and it happens to me only with that content type.
Solution
I already got what I needed, thank you very much for your help, it was very useful.
Here is the final code: