1

I’m looking for a solution to hide machine_name from a form temporarily (only during validation) and restore it afterward.

When the form has validation with errors the machine name appears (with a different label like: "Internal name"). I need to hide the machine name while validation has errors. And also force the user to change the name of the source to avoid errors.

My solution (that still not working) is:

  1. In form_alter() add a new validation function callback in form alter before calling to the validation add  $form["name"]["access"] = FALSE; //to hide the machine name from the form.
  2. In the validation function check if the element name is unique.
if false (meaning error)
  $form_state->setError()
else
  $form["name"]["access"] = TRUE;
  $form_state->setRebuild(TRUE);

This works to the point that the machine name is hidden and when there is an error it shows my error message.

The problem is that if the name of the element is unique (meaning there are no validation errors) - It doesn't save the form.

What am I missing here? 

[I'm using drupal 9 on The Apigee Developer Portal Kickstart distribution]

1 Answer 1

1

By denying access you are removing the form element and there will be no value submitted.

For hiding you can try CSS

$form['name']['#attributes']['class'][] = 'visually-hidden';

or transform the form elment to #type = hidden.

1
  • Thank you for your reply. Your code helped to hide the input element, but showed the error message of the element in the validation. I also added $form_state->clearErrors() to show only my custom message for the element. So now the situation is this: If I enter a unique name - the form is submitted as expected. If the name is not unique, it shows my custom error message. If I got error in the validation and change the name to a unique name - > I can't save the form. So... I still need to understand how fix that.
    – Inbal Jona
    Nov 30, 2022 at 11:44

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.