Score:1

Hiding machine name from a form temporarily only during validation

ph flag

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]

Score:1
cn flag

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.

Inbal Jona avatar
ph flag
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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.