Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 - input form readonly and apply style

I need to apply style and read-only property to an input element of a drupal form. I coded the following:

$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Precio'),
  '#default_value' => ''.$precio,
  '#size' => 20,
  '#required' => TRUE,
  '#attributes' => array($inputAtributo => 1),
  '#description' => t('Modifica el precio '),
);

And at '#attributes' => array($inputAtributo => 1),

Before create form, I check if this input should be readonly and apply some style:

if ($tarifa !='' & $tarifa=='N')
$inputAtributo=" readonly style=\"background: none repeat scroll 0 0 #EAEAEA;\" ";
else
$inputAtributo = "";

This works, but I think it's not coded correctly

The html code shows the following:

<input id="edit-precio" class="form-text required" type="text" maxlength="128" size="20" value="258" name="precio" ="1"="" style="background: none repeat scroll 0 0 #EAEAEA;" readonly="">

How I can do this better?

like image 569
Daniel Avatar asked Dec 19 '12 11:12

Daniel


2 Answers

#attributes must be an array of key-value-pairs.

so the array should look like

'#attributes' => array(
    'readonly'=>'readonly',
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;'
);
like image 161
mantish Avatar answered Oct 31 '22 19:10

mantish


#attributes is not intented to be used with styles. You must provide an array with key and values reproducing html attributes. And class and css is better than adding style directly into html.

'#attributes' = array(
  'class' => array('readonly-input'),
  'readonly' => 'readonly',
)

If you want to add it in an if, you can do this:

if ($tarifa !='' & $tarifa=='N') {
  $form['precio']['#attributes']['class'][] = 'readonly-input';
  $form['precio']['#attributes']['readonly'] = 'readonly';
}

Note that readonly attribute has also "readonly" as value, so it's xhtml compliant.

Now add a css rule in your stylesheet:

.readonly-input { background: none repeat scroll 0 0 #EAEAEA; }
like image 35
Alessandro Pezzato Avatar answered Oct 31 '22 18:10

Alessandro Pezzato