2012-02-13 17 views
5

Quiero agregar title = "icons/icon_cart.gif" para cada una de las siguientes opciones en mi lista de selección que se representa con vistas.Agregar atributo al elemento de opción utilizando formularios api: drupal 7

Después de probar y leer muchos artículos parece que no encuentro la manera de agregar este html a mi formulario.

A continuación se muestra mi código.

function customchatter_form_alter(&$form, &$form_state, $form_id) { 

$form["tid"]["#options"][1]=t("nooo chatter"); 
// this works to change the label of the option but how do I add title="icons/icon- 
cart.gif" ? 

} 

Mi código html:

<select id="edit-tid" name="tid" class="form-select"> 
<option value="All">- Any -</option> 
<option value="1">nooo chatter</option> 
<option value="2">Complaints Complaints</option> 
<option value="3">Gear &amp; Gadgets</option> 
</select> 

Cheers, Vishal

ACTUALIZACIÓN traté de actualizar el código según el consejo de Clive pero los valores aún no están subiendo derecha. A continuación está mi historia.

Así que a continuación es la salida html soy capaz de lograr, pero el título siempre parece ser el número 1.

<select id="edit-select" class="form-select" name="select"> 
<option value="1" title="1">One</option> 
<option value="2" title="1">Two</option> 
</select> 

Como se puede ver el título está ahí, pero el valor es incorrecto. A continuación está mi formulario y las funciones que escribí.

Mi forma:

$form['select'] = array(
'#type' => 'select', 
'#options' => array(1 => 'One', 2 => 'Two'), 
'#title' => array(1 => 'One', 2 => 'Two') 
// I tried many combinations but nothing seems to work. 
); 

Mis funciones temáticas.

function kt_vusers_select($variables) { 
$element = $variables['element']; 
element_set_attributes($element, array('id', 'name', 'size')); 
_form_set_class($element, array('form-select')); 

return '<select' . drupal_attributes($element['#attributes']) . '>' .  
kt_vusers_form_select_options($element) . '</select>'; 
} 


function kt_vusers_form_select_options($element, $choices = NULL) { 

if (!isset($choices)) { 
$choices = $element['#options']; 
} 
// array_key_exists() accommodates the rare event where $element['#value'] is NULL. 
// isset() fails in this situation. 
$value_valid = isset($element['#value']) || array_key_exists('#value', $element); 


// @vishal so there I have declared the variable to accept the values. 
$vtitle = isset($element['#title']) || array_key_exists('#title', $element); 


$value_is_array = $value_valid && is_array($element['#value']); 
$options = ''; 
foreach ($choices as $key => $choice) { 
if (is_array($choice)) { 
    $options .= '<optgroup label="' . $key . '">'; 
    $options .= form_select_options($element, $choice); 
    $options .= '</optgroup>'; 
} 
elseif (is_object($choice)) { 
    $options .= form_select_options($element, $choice->option); 
} 
else { 
    $key = (string) $key; 
    if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || 
($value_is_array && in_array($key, $element['#value'])))) { 
    $selected = ' selected="selected"'; 
    } 
    else { 
    $selected = ''; 
    } 

// @vishal this is where the variable is being used. 

$options .= '<option title="'.$vtitle.'" value="' . check_plain($key) . '"' . $selected . 
'>' . check_plain($choice) . '</option>'; 
} 
} 
return $options; 
} 

a continuación es el código correcto para la última función tema

function kt_vusers_form_select_options($element, $choices = NULL, $vtitles=NULL) { 
// Build up your own version of form_select_options here 
// that takes into account your extra attribute needs. 
// This will probably involve inspecting your custom FAPI property, 
// which we'll call #extra_option_attributes 

if (!isset($choices)) { 
$choices = $element['#options']; 
$vtitles = array(); 
$vtitles = $element['#title']; 
} 
// array_key_exists() accommodates the rare event where $element['#value'] is NULL. 
// isset() fails in this situation. 
$value_valid = isset($element['#value']) || array_key_exists('#value', $element); 

$value_is_array = $value_valid && is_array($element['#value']); 
$options = ''; 

// print_r($vtitles); 

mientras ( (lista (clave $, $ elección) = cada uno ($ opciones)) & & (lista ($ keytwo, $ vtitle) = each ($ vtitles)) ) { // printf ("% s =>% s,% s =>% s \ n", $ clave1, $ valor1, $ clave2, $ value2);

if (is_array($choice)) { 
    $options .= '<optgroup label="' . $key . '">'; 
    $options .= kt_vusers_form_select_options($element, $choice); 
    $i++; 
    // $options .= form_select_options($element, $vtitle); 
    $options .= '</optgroup>'; 
    } // end if if is_array 

elseif(is_object($choice)) { 
    $options .= form_select_options($element, $choice->option); 
    } // end of else if 



else { 
     $key = (string) $key; 
    if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || 
($value_is_array  && in_array($key, $element['#value'])))) { 
    $selected = ' selected="selected"'; 
    } 
    else { 
    $selected = ''; 
    } 
    // $options .= '<option title="'.$vtitle.'" value="' . check_plain($key) . '"' . 
    $selected . '>' . check_plain($choice) . '</option>'; 


} 

$options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected 
.'>'. check_plain($choice) .'</option>'; 



} // end of choice 



return $options; 


} // end of function 
+0

Su es un problema abierto sobre eso https://drupal.org/node/342316 – gagarine

Respuesta

11

Me temo que tendrá que cavar bastante lejos para hacer esto, la matriz #options se aplana en form_select_options() y actualmente no incluye ninguna forma de agregar atributos.Este es el código:

$options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>'; 

Como puede ver, simplemente no hay ningún alcance para los atributos que existen. Sin embargo, podrá anular esto, pero implicará implementar su propia versión de theme_select() y su propia propiedad FAPI.

no he tenido tiempo para dar cuerpo a toda la cosa, pero en su archivo de tema que estaría haciendo algo como esto:

function MYTHEME_select($variables) { 
    $element = $variables['element']; 
    element_set_attributes($element, array('id', 'name', 'size')); 
    _form_set_class($element, array('form-select')); 

    return '<select' . drupal_attributes($element['#attributes']) . '>' . MYTHEME_form_select_options($element) . '</select>'; 
} 


function MYTHEME_form_select_options($element) { 
    // Build up your own version of form_select_options here 
    // that takes into account your extra attribute needs. 
    // This will probably involve inspecting your custom FAPI property, 
    // which we'll call #extra_option_attributes 
} 

Consulte form_select_options para la construcción de MYTHEME_form_select_options

Y su código de la forma sería algo así como:

$form['select'] = array(
    '#type' => 'select', 
    '#options' => array(1 => 'One', 2 => 'Two'), 
    '#extra_option_attributes' => array(
    1 => array('title' => 'Test title'), // Attributes for option with key "1", 
    2 => array('title' => 'Test title'), // Attributes for option with key "2", 
) 
); 

En MYTHEME_form_select_options() a continuación, puede inspeccionar el elemento deClave(si existe) para ver si necesita agregar físicamente más atributos en el código HTML que crea.

Espero que ayude, sé que parece una manera enloquecida de hacer lo que necesita, pero hasta donde yo sé, es la única manera.

+0

Usted gana esta ronda @Clive. Tú ganas esta ronda. +1 por esfuerzo. – SpaceBeers

+0

gracias clive. Le daré una oportunidad y volveré atrás. –

+0

clive He actualizado la publicación. Puedo obtener el título allí en html pero el valor siempre parece ser uno. –

0

No comprobado, pero has:

$form["tid"]["#options"][1]['#attributes'] = array('title' => t('YOUR NEW TITLE')); 

puede que tenga que perder el tiempo con el nombre del elemento, etc, pero la etiqueta #attributes debería funcionar.

EDIT: Como se señala en la respuesta de Clive, esto no funcionará, pero lo dejaré en caso de que alguien quiera saber cómo agregar atributos a otros campos (cuadros de texto, etc.).

+0

gracias por intentarlo. ¡salud, –

+2

+1 porque no creo que tener una respuesta negativa en una respuesta que fue de buena fe sea justo! –

+0

Eres un caballero. – SpaceBeers

0

Probado

Probar:

$form["tid"][1]['#attributes'] = array('title' => t('nooo chatter')); 

en lugar de:

$form["tid"]['#options'][1]['#attributes'] = array('title' => t('nooo chatter'));

Es posible añadir atributos arbitrarios a los elementos de esta forma. Lo descubrí después de realizar algunas pruebas basadas en la respuesta this.

También se mencionó here y here.

+0

Esto no funcionó para mí, los agregó fuera de la matriz de opciones, por lo que no se procesó nada para cada elemento. – Collins

Cuestiones relacionadas