1

I want to add HTML5 number type textfield in the form programmatically. I am building the form using hook_form(). I tried adding the code:-

$form['field_price']['#attributes']['type'] = 'number';

But it isnt working.

Is there any other work around for the same?

0

An alternative to using Element, and since theme_textfield() has a hardcoded value of type 'text', you may want to override theme_textfield() in your template.php. You can copy theme_textfield(), paste it in your theme's template.php and rename it, then make necessary changes. For example

(NB: I HAVEN'T tested this, so there may be some bugs):

function MYTHEME_textfield($variables) {
  $element = $variables['element'];
  if (isset($element['#attributes']['type'][0]) && $element['#attributes']['type'][0] == 'number'){
    $element['#attributes']['type'] = 'number';        
  } else {
    $element['#attributes']['type'] = 'text';
  };
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-text'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

This will hardcode as type text any element that does not specifically have a key $form['field_name']['#attributes']['type'] = array('number');

| improve this answer | |
1

Try Element module. it adds advance html5 elements to your form.

Similar question is asked here

| improve this answer | |

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.