0
votes

I am rather new to Drupal.

I came across 2 methods to pre-populate a form, namely hook_form_alter() and hook_prepare()

I have read the docs, and I believe that both methods can achieve what I want.

I was wondering what were these 2 functions created for? Is there one that is made for a designated function or so?

As far as I understand, hook_form_alter() takes the current form state, and acts on it. Does this mean that this function is made to alter the actual form itself? Like changing certain fields, or adding custom fields and so on?

Hook_prepare() on the other hand, takes a node and acts on it before it populates the add/edit form.

Assume the case is that I am trying to pre-populate a form. Would hook_prepare() be the "right" way to do it? Or it really just doesnt matter? And what if I am using the webform module, rather than a content type?

1

1 Answers

1
votes

The two hooks are completely different, they don't do the same thing at all.

hook_form_alter() is invoked whenever a form is built using drupal_get_form(). It allows modules to alter elements or metadata (manipulating field properties, adding AJAX, adding CSS properties, etc.) related to the form, in a structured manner. The hook is invoked for any module that implements it.

Conversely, hook_prepare() is for acting on node objects before they are passed to an entity form for addition/edition. It is only ever invoked for the module that defines the node type which is being prepared. So, unless you've defined a custom 'node type module' as they're known, this hook will not be invoked.

The short answer is that 99% of the time you will use hook_form_alter(). hook_prepare() only comes into the equation under a very specific set of circumstances, which if you're using the Webform module, do not apply to your situation.