I'm trying to create a field widget that is similar to the normal term reference widget with one key difference. The user needs to be able to add multiple new taxonomy terms at the same time, this may demonstrate it better:
I've got to a point where the functionality is similar to what the taxonomy/options/list modules provide (i.e. the checkboxes/radios are shown, saving etc.)
Here's important bit of the code I'm using in hook_field_widget_form()
:
$element += array(
'#type' => $multiple ? 'checkboxes' : 'radios',
'#default_value' => $multiple ? $default_value : reset($default_value),
'#options' => $options,
'#value_key' => $value_key,
'#element_validate' => array('options_field_widget_validate'),
'#properties' => $properties,
);
What's throwing me here is that $element isn't your usual form array so I'm not sure how to add the textfield and and button - especially as their values aren't meant to be saved. What's the best way to add these fields to my widget?
As for adding the Javascript needed, am I right in thinking I should use #ajax that calls a function that rebuilds the #options for the checkboxes?
Thanks in advance!
EDIT - My initial question was quite vague, here's some more details on what I've tried:
$element += array(
'#type' => 'fieldset',
'#delta' => $delta,
);
$element['value'] = array(
'#type' => $multiple ? 'checkboxes' : 'radios',
'#default_value' => $multiple ? $default_value : reset($default_value),
'#options' => $options,
'#value_key' => $value_key,
'#element_validate' => array('options_field_widget_validate'),
'#properties' => $properties,
);
$element['text'] = array(
'#type' => 'textfield',
'#title' => t('Add another'),
'#weight' => 5,
);
This a is an amalgamation of various examples I've seen, and seems to get me closer. The problem is when I submit the entity form I get the following error:
Notice: Undefined index: tid in taxonomy_field_is_empty() (line 1402 of modules\taxonomy\taxonomy.module).
I've taken a closer look at this function and it's expecting $item
to have the structure $item = array('tid', 2)
. When using the above code there seems to be a delta coming from somewhere and the structure of $item
ends up being $item = array(0, array('tid', 2)
. I can't work out where '0' is coming from?
ANOTHER EDIT
I've been able to fix the above error with the following code by altering $element like so:
$element += array(
'#type' => 'fieldset',
'#process' => array('taxonomy_free_entry_ignore_parent'),
);
and adding the function:
function taxonomy_free_entry_ignore_parent(&$form, &$form_state, $complete) {
array_pop($form['#parents']);
return $form;
}
When I save the entity I'm getting a message telling me it's been saved. When I check the table for the field, it isn't being saved. What am I doing wrong?