Returns the form for a single field widget.
Field widget form elements should be based on the passed-in $element, which contains the base form element properties derived from the field configuration.
The BaseWidget methods will set the weight, field name and delta values for each form element. If there are multiple values for this field, the formElement() method will be called as many times as needed.
Note that, depending on the context in which the widget is being included (regular entity form, field configuration form, advanced search form...), the values for $field and $instance might be different from the "official" definitions returned by field_info_field() and field_info_instance(). Examples: mono-value widget even if the field is multi-valued, non-required widget even if the field is 'required'...
Therefore, the FAPI element callbacks (such as #process, #element_validate, #value_callback...) used by the widget cannot use the field_info_field() or field_info_instance() functions to retrieve the $field or $instance definitions they should operate on. The field_widget_field() and field_widget_instance() functions should be used instead to fetch the current working definitions from $form_state, where Field API stores them.
Alternatively, hook_field_widget_form() can extract the needed specific properties from $field and $instance and set them as ad-hoc $element['#custom'] properties, for later use by its element callbacks.
Other modules may alter the form element provided by this function using hook_field_widget_form_alter().
array $items: Array of default values for this field.
int $delta: The order of this item in the array of subelements (0, 1, 2, etc).
array $element: A form element array containing basic properties for the widget:
string $langcode: The language associated with $items.
string $form: The form structure where widgets are being attached to. This might be a full form structure, or a sub-element of a larger form.
string $form_state: An associative array containing the current state of the form.
array The form elements for a single widget for this field.
Overrides WidgetInterface::formElement
hook_field_widget_form_alter()
hook_field_widget_WIDGET_TYPE_form_alter()
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
// Prepare some properties for the child methods to build the actual form
// element.
$this->entity = $element['#entity'];
$this->required = $element['#required'];
$this->multiple = $this->field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $this->field['cardinality'] > 1;
$this->has_value = isset($items[0][$this->column]);
// Add our custom validator.
$element['#element_validate'][] = array(
get_class($this),
'validateElement',
);
$element['#key_column'] = $this->column;
// The rest of the $element is built by child method implementations.
return $element;
}