Crear un campo de fields, cuyo widget muestre dos elementos de formulario.

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
oskar_calvo's picture

Buenas, lo que quiero es crear un campo de node reference, pero que antes se pueda seleccionar un campo select con un listado de taxonomías, de tal forma que a la hora de buscar la búsqueda en el node-reference este condicioniada por el select anterior.

Trasteando con widget solo he conseguido sacar el select primero, nada más.

Mi código.

<?php

/**************************************************************************
* Código de ejemplo de examples
* From field_examples.module
* Field Type API: Widget
*
* The widget is the form element used to receive input from the user
* when the field is being populated.
**************************************************************************/

/**
* Implements hook_field_widget_info().
*
* Three widgets are provided.
* - A simple text-only widget where the user enters the '#ffffff'.
* - A 3-textfield widget that gathers the red, green, and blue values
*   separately.
* - A farbtastic colorpicker widget that chooses the value graphically.
*/

function tados_field_widget_info() {
 
//definie de new widtet
 
return array(
   
'node_reference_filtered' => array(
     
'label' => t('Node references filtered by vocabulary'),
     
'field types' => array('node_reference'),
     
'settings'    => array(
       
'size' => 60
     
),
    ),
  );
}

/**
*
* From field_example.module
*
* Implements hook_field_widget_form().
*
* hook_widget_form() is where Drupal tells us to create form elements for
* our field's widget.
*
* We provide one of three different forms, depending on the widget type of
* the Form API item provided.
*
* The 'field_example_colorpicker' and 'field_example_text' are essentially
* the same, but field_example_colorpicker adds a javascript colorpicker
* helper.
*
* field_example_3text displays three text fields, one each for red, green,
* and blue. However, the field type defines a single text column,
* rgb, which needs an HTML color spec. Define an element validate
* handler that converts our r, g, and b fields into a simulated single
* 'rgb' form element.
*/
function tados_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  switch (
$instance['widget']['type']) {
   case
'node_reference_filtered':
     
     
$terms = taxonomy_get_tree(1, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
     
$termlist = array();
      foreach (
$terms as $term){
       
$termlist[$term->tid] = $term->name;
      }
     
$options_first = drupal_map_assoc($termlist);
     
$selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);
     
     
$element += array(
       
'#type' => 'select',
       
'#title' => 'Instrument Type',
       
'#options' => $options_first,
       
'#default_value' => $selected,
       
// Bind an ajax callback to the change event (which is the default for the
        // select form type) of the first dropdown. It will replace the second
        // dropdown when rebuilt
       
'#ajax' => array(
         
// When 'event' occurs, Drupal will perform an ajax request in the
          // background. Usually the default value is sufficient (eg. change for
          // select elements), but valid values include any jQuery event,
          // most notably 'mousedown', 'blur', and 'submit'.
          // 'event' => 'change',
         
'callback' => 'tados_dependent_dropdown_callback',
         
'wrapper' => 'dropdown-second-replace',
        )
      );
     
     
$element += array(
       
'#type' => 'textfield',
       
'#title' => $options_first[$selected] . ' ' . t('Instruments'),
       
// The entire enclosing div created here gets replaced when dropdown_first
        // is changed.
       
'#prefix' => '<div id="dropdown-second-replace">',
       
'#suffix' => '</div>',
       
// when the form is rebuilt during ajax processing, the $selected variable
        // will now have the new value and so the options will change
       
'#options' => _tados_get_second_dropdown_options($selected),
       
'#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : ''
      );
    break; 
     
  }

  return array(
'nid' => $element);
}

/**
* Selects just the second dropdown to be returned for re-rendering
*
* Since the controlling logic for populating the form is in the form builder
* function, all we do here is select the element and return it to be updated.
*
* @return renderable array (the second dropdown)
*/
function tados_dependent_dropdown_callback($form, $form_state) {
  return
$form['dropdown_second'];
}

/**
* Helper function to populate the second dropdown. This would normally be
* pulling data from the database.
*
* @param $key
*   This will determine which set of options is returned.
*
* @return array of options
*/
function _tados_get_second_dropdown_options($key = '') {
 
$options = array(
   
t('1') => drupal_map_assoc(array(t('Violin'), t('Viola'), t('Cello'), t('Double Bass'))),
   
t('2') => drupal_map_assoc(array(t('Flute'), t('Clarinet'), t('Oboe'), t('Bassoon'))),
   
t('3') => drupal_map_assoc(array(t('Trumpet'), t('Trombone'), t('French Horn'), t('Euphonium'))),
   
t('4') => drupal_map_assoc(array(t('Bass Drum'), t('Timpani'), t('Snare Drum'), t('Tambourine'))),
  );
  if (isset(
$options[$key])) {
    return
$options[$key];
  }
  else {
    return array();
  }
}

?>

Gracias

Oskar

Comments

Buenas, no sé si lo que te

rafinskipg's picture

Buenas, no sé si lo que te voy a decir tiene mucho sentido ya que no lo he probado.

¿Que tal hacer un form_alter del formulario de creación de contenido, añadir un select por taxonomías que haga una petición ajax a una alteración del query de la vista (references) del node reference?, o que le mande argumentos, si la vista está preparada.

Saludos

@rafinskipg porque eso no es

oskar_calvo's picture

@rafinskipg porque eso no es reusable, con eso puedes hacer una cosa concreta.

La idea es crear un widget que se pueda reutilizar para más proyectos sin necesidad de tener que reprogramar todo el rato.

Oskar

Ojo, se que el código no esta

oskar_calvo's picture

Ojo, se que el código no esta completado, pero como no termino de sacar el segundo elemento del widget, creo que es innecesario terminar de depurar el campo que será el node-reference.

Oskar

Dos o mas elemento en el mismo widget

cmfeliz's picture

Hola tengo varios problemas con esto igual que tu. No se si lo has resuelto, pero mi problema es que quiero un campo con 5 elementos, siendo el quinto un campo que recibe un valor.

Tengo un formulario con 5 columnas
donde la primero columna es un codigo, la segundo un enuciado, la tercera un rango de valores posible para cada campo, un valor ingresado por el usuario y por ultimo un checkboxes con el tipo de usaurario que ha respondido.

He decido hacer un campo personalizado, pues mi formulario es largo, la cuestion es que aunque puedo asignar el campo a un tipo d contenido, no me salen los elementos en el formulario.
Hice debuger de la variable $form y mi tipo de campo esta alli, pero no muestra los elementos.
Alguna idea con esto?

Gracias

Madrid

Group organizers

Group events

Add to calendar

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: