I'm helping re-write a module that has an admin settings page, and uses hook_form_alter to alter the core search form.
In the admin settings, there's a user-entered value I need to send to some JavaScript that'll then be used on the search form. I've worked out that I send the value to JS using the following: <?php drupal_add_js(array('customSearchBox' => array('default' => variable_get('custom_search_box_default', ''))), 'setting'); ?>. I have this code in the validate function for the admin settings form/function.
Is this the correct way to do it?
Secondly, I need to add the .js file that uses the above variable to any page that has the core search form on it.
What's the best way to do this? Can I just use drupal_add_js() in hook_form_alter(), or is there another way to do it?
Any and all help will be much appreciated!
Comments
Adding your value to
Adding your value to Drupal.settings using drupal_add_js is, IMHO, the correct way to send this kind of value from PHP to JavaScript.
I would also use drupal_add_js in hook_form_FORM_ID_alter() to add a .js file. Although I'm not sure it would work when the form is cached since the hook is only used when the form is build.
I've found adding CSS sheets
I've found adding CSS sheets to be more reliable when added in a preproccess function, or a theme function.
Contact me to contract me for D7 -> D10/11 migrations.