Add a component to WebForm in Drupal

3 Oct 2012

Remark: This is a clumsy way to add a component, as the component is integrated into WebForm's source. You can actually build an independent module that utitlizes WebForm's hooks in order to build a component.

Today I've successfully added a component (e.g. textbox) to WebForm module of Drupal.

The component is somewhat-very dynamic, so it requires Javascript and stuffs.

I cannot write about what it is, but I can say how I've built it (I guess). I am pretty new with the hightech workplace and stuffs. I've gotta be careful. Well, it's just a Drupal knowledge anyway.

So, here it is:

How to add a new component

  1. Create an `.incfile under ``webform/components`. You may just make a copy``
  2. Add your component block in the function `webform_webform_component_info()in ``webform/webform.module```. (There are several examples in that function)
  3. Now modify your `.inc`

Please note that all functions in your `.incmust be in the form of ``_webform_somehook_yourcomponentname()```.

Please see `webform/webform.api.php` for more description.

Drupal form building

The thing to understand is that Drupal has its own element generator (outside WebForm).

You can do download examples and look into `form_examples`. It's really helpful.

The problem that I've encountered is that I generate a `markup` element that has a div inside.

In that `div`, I add an input-text with javascript. But, then, the input-text value is not submitted with the form.

That is because when I generate the element, I didn't tell Drupal that this element would have a value being submitted from a user.

So, Drupal can be told with:

$element = array( '#type' => 'markup', '#input' => TRUE, // this line '#return_value' => TRUE, // and this line '#markup' => '<div style="display: none;">' . json_encode($data) . '</div>', );

How to link your element with your javascript

When you generate a `markup` element, you must leave a clue like this:

$element = array( '#type' => 'markup', '#input' => TRUE, // this line '#return_value' => TRUE, // and this line '#markup' => '<div class="some-weird-named-class" style="display: none;">' . json_encode($data) . '</div>', );

Then, you can add your javascript code in `webform/js/webform.js`. Here is how I added the code:

// // Some code above // Drupal.behaviors.webform.attach = function(context) { // Calendar datepicker behavior. Drupal.webform.datepicker(context); Drupal.webform.newComponenetJavascriptCode(context); }; Drupal.webform = Drupal.webform || {}; Drupal.webform.newComponenetJavascriptCode = function(context) { $('.some-weird-named-class').each(function() { }); }; // // Some code below //

Give it a kudos