Search code examples
drupaldrupal-6drupal-forms

How can I get the title of a form element in Drupal?


For example, in the registration form, there is "Username" and the text field for it which has the input type="text" name="name" ....

I need to know how can I get the title from the input field's name.

I'm expecting a function like:

$title = get_title_for_element('name');

Result:

assert($title == 'Username'); // is true

Is there something like this in Drupal?

Thanks.


Solution

  • You can do it in two different ways as I see it. Let's create a module called mycustomvalidation.module (remember to create the mycustomvalidation.info file also).

    Note: The code below has not been tested, so you might have to do some minor adjustments. This is Drupal 6.x code by the way.

    1) Using hook_user()

    What you need is a custom module containing your own implementation of hook_user() http://api.drupal.org/api/function/hook_user/6.

    <?php
    function mycustomvalidation_user($op, &$edit, &$account, $category = NULL) {
      if ($op == 'validate') {
        // Checking for an empty 'profile_fullname' field here, but you should adjust it to your needs.
        if ($edit['profile_fullname'] != '') {
          form_set_error('profile_fullname', t("Field 'Fullname' must not be empty."));
        }
      }
    }
    ?>
    

    2) Using form_alter() and a custom validation function

    Personally, I would go for this option because I find it cleaner and more "correct". We're adding a custom validation function to our profile field here.

    <?php
    function mycustomvalidation_form_alter(&$form, $form_state, $form_id) {
      // Check if we are loading 'user_register' or 'user_edit' forms.
      if ($form_id == 'user_register' || $form_id == 'user_edit') {
        // Add a custom validation function to the element.
        $form['User information']['profile_fullname']['#element_validate'] = array('mycustomvalidation_profile_fullname_validate');
      }
    }
    
    function mycustomvalidation_profile_fullname_validate($field) {
      // Checking for an empty 'profile_fullname' field here, but you should adjust it to your needs.
      if ($field['#value'] != '') {
        form_set_error('profile_fullname', t("Field %title must not be empty.", array('%title' => $field['#title']));
      }
    }
    ?>