1

I would like to customize a form base on the users' request info in a page callback. I use drupal_get_form (or node_add for node create form) to get the renderable array, but most changes to the array here have no effect.

I know that we usually use hook_form_alter, but it seems not suit here.

I would like to hide/set a field, change a field's title/options etc. based on the query parameters or page arguments.

Do we have any methods to get the "raw describing form" and then modify and render it?

  • Please tell us your Drupal version, thx. – No Sssweat May 17 '16 at 8:34
  • hook_form_alter() is the right way to alter a form, mileage will vary if you try to use the render array because it's already been built and cached by that point. It's not often you find something that can't be accomplished using hook_form_alter(), but it does happen - if you can explain why you think you can't use it, that would help – Clive May 17 '16 at 8:37
1

You should definitely use hook_form_alter() for that - no need to go a different route, it'll just make things harder for no benefit. Doing things the standard way your code could be as simple as:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo_form' && isset($_GET['bar'])) {
    $form['baz']['#access'] = FALSE;
  }
}
  • The form_alter hook would become unreadable if I have many cases, but if I seperate the logic in the page callback, it would be more straightforward. I would use this if it is hard to do this in page callback. Thanks! – leetom May 17 '16 at 8:58
  • There's nothing you can do to separate the logic in a page callback that you can't do in a form alter, they're both bog standard global PHP functions. You might be able to get your idea working, but why not just use the tools that were provided for the job? – Clive May 17 '16 at 9:04

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.