Commit 6fa5b693 authored by alexpott's avatar alexpott

Issue #1751234 by yched, amateescu, swentel, kotnik, webflo, pcambra |...

Issue #1751234 by yched, amateescu, swentel, kotnik, webflo, pcambra | tstoeckler: Convert option widgets to Plugin system.
parent 9c74b547
......@@ -63,6 +63,18 @@ function entity_reference_entity_field_info_alter(&$info, $entity_type) {
}
}
/**
* Implements hook_field_widget_info_alter().
*/
function entity_reference_field_widget_info_alter(&$info) {
if (isset($info['options_select'])) {
$info['options_select']['field_types'][] = 'entity_reference';
}
if (isset($info['options_buttons'])) {
$info['options_buttons']['field_types'][] = 'entity_reference';
}
}
/**
* Gets the selection handler for a given entity_reference field.
*
......
<?php
/**
* @file
* Contains \Drupal\options\Plugin\field\widget\ButtonsWidget.
*/
namespace Drupal\options\Plugin\field\widget;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
/**
* Plugin implementation of the 'options_buttons' widget.
*
* @Plugin(
* id = "options_buttons",
* module = "options",
* label = @Translation("Check boxes/radio buttons"),
* field_types = {
* "list_integer",
* "list_float",
* "list_text",
* "list_boolean"
* },
* multiple_values = TRUE
* )
*/
class ButtonsWidget extends OptionsWidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
$element = parent::formElement($items, $delta, $element, $langcode, $form, $form_state);
$options = $this->getOptions();
$selected = $this->getSelectedOptions($items);
// If required and there is one single option, preselect it.
if ($this->required && count($options) == 1) {
reset($options);
$selected = array(key($options));
}
if ($this->multiple) {
$element += array(
'#type' => 'checkboxes',
'#default_value' => $selected,
'#options' => $options,
);
}
else {
$element += array(
'#type' => 'radios',
// Radio buttons need a scalar value. Take the first default value, or
// default to NULL so that the form element is properly recognized as
// not having a default value.
'#default_value' => $selected ? reset($selected) : NULL,
'#options' => $options,
);
}
return $element;
}
/**
* {@inheritdoc}
*/
protected function getEmptyOption() {
if (!$this->required && !$this->multiple) {
return static::OPTIONS_EMPTY_NONE;
}
}
}
<?php
/**
* @file
* Contains \Drupal\options\Plugin\field\widget\OnOffWidget.
*/
namespace Drupal\options\Plugin\field\widget;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
/**
* Plugin implementation of the 'options_onoff' widget.
*
* @Plugin(
* id = "options_onoff",
* module = "options",
* label = @Translation("Single on/off checkbox"),
* field_types = {
* "list_boolean"
* },
* settings = {
* "display_label" = FALSE,
* },
* multiple_values = TRUE
* )
*/
class OnOffWidget extends OptionsWidgetBase {
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, array &$form_state) {
$element['display_label'] = array(
'#type' => 'checkbox',
'#title' => t('Use field label instead of the "On value" as label'),
'#default_value' => $this->getSetting('display_label'),
'#weight' => -1,
);
return $element;
}
/**
* {@inheritdoc}
*/
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
$element = parent::formElement($items, $delta, $element, $langcode, $form, $form_state);
$options = $this->getOptions();
$selected = $this->getSelectedOptions($items);
$element += array(
'#type' => 'checkbox',
'#default_value' => !empty($selected[0]),
);
// Override the title from the incoming $element.
if ($this->getSetting('display_label')) {
$element['#title'] = $this->instance['label'];
}
else {
$element['#title'] = isset($options[1]) ? $options[1] : '';
}
return $element;
}
}
<?php
/**
* @file
* Contains \Drupal\options\Plugin\field\widget\OptionsWidgetBase.
*/
namespace Drupal\options\Plugin\field\widget;
use Drupal\field\Plugin\Core\Entity\FieldInstance;
use Drupal\field\Plugin\Type\Widget\WidgetBase;
/**
* Base class for the 'options_*' widgets.
*/
abstract class OptionsWidgetBase extends WidgetBase {
/**
* Identifies a 'None' option.
*/
const OPTIONS_EMPTY_NONE = 'option_none';
/**
* Identifies a 'Select a value' option.
*/
const OPTIONS_EMPTY_SELECT = 'option_select';
/**
* Abstract over the actual field columns, to allow different field types to
* reuse those widgets.
*
* @var string
*/
protected $column;
/**
* {@inheritdoc}
*/
public function __construct($plugin_id, array $plugin_definition, FieldInstance $instance, array $settings, $weight) {
parent::__construct($plugin_id, $plugin_definition, $instance, $settings, $weight);
// Reset internal pointer since we're dealing with objects now.
reset($this->field['columns']);
$this->column = key($this->field['columns']);
}
/**
* {@inheritdoc}
*/
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;
}
/**
* Form validation handler for widget elements.
*
* @param array $element
* The form element.
* @param array $form_state
* The form state.
*/
public static function validateElement(array $element, array &$form_state) {
if ($element['#required'] && $element['#value'] == '_none') {
form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
}
// Massage submitted form values.
// Drupal\field\Plugin\Type\Widget\WidgetBase::submit() expects values as
// an array of values keyed by delta first, then by column, while our
// widgets return the opposite.
if (is_array($element['#value'])) {
$values = array_values($element['#value']);
}
else {
$values = array($element['#value']);
}
// Filter out the 'none' option. Use a strict comparison, because
// 0 == 'any string'.
$index = array_search('_none', $values, TRUE);
if ($index !== FALSE) {
unset($values[$index]);
}
// Transpose selections from field => delta to delta => field.
$items = array();
foreach ($values as $value) {
$items[] = array($element['#key_column'] => $value);
}
form_set_value($element, $items, $form_state);
}
/**
* Returns the array of options for the widget.
*
* @return array
* The array of options for the widget.
*/
protected function getOptions() {
if (!isset($this->options)) {
// Get the list of options from the field type module, and sanitize them.
$options = (array) module_invoke($this->field['module'], 'options_list', $this->field, $this->instance, $this->entity);
array_walk_recursive($options, array($this, 'sanitizeLabel'));
// Options might be nested ("optgroups"). If the widget does not support
// nested options, flatten the list.
if (!$this->supportsGroups()) {
$options = $this->flattenOptions($options);
}
// Add an empty option if the widget needs one.
if ($empty_option = $this->getEmptyOption()) {
$label = theme('options_none', array('option' => $empty_option, 'widget' => $this, 'instance' => $this->instance));
$options = array('_none' => $label) + $options;
}
$this->options = $options;
}
return $this->options;
}
/**
* Determines selected options from the incoming field values.
*
* @param array $items
* The field values.
*
* @return array
* The array of corresponding selected options.
*/
protected function getSelectedOptions(array $items) {
// We need to check against a flat list of options.
$flat_options = $this->flattenOptions($this->getOptions());
$selected_options = array();
foreach ($items as $item) {
$value = $item[$this->column];
// Keep the value if it actually is in the list of options (needs to be
// checked against the flat list).
if (isset($flat_options[$value])) {
$selected_options[] = $value;
}
}
return $selected_options;
}
/**
* Flattens an array of allowed values.
*
* @param array $array
* A single or multidimensional array.
*
* @return array
* The flattened array.
*/
protected function flattenOptions(array $array) {
$result = array();
array_walk_recursive($array, function($a, $b) use (&$result) { $result[$b] = $a; });
return $result;
}
/**
* Indicates whether the widgets support optgroups.
*
* @return bool
* TRUE if the widget supports optgroups, FALSE otherwise.
*/
protected function supportsGroups() {
return FALSE;
}
/**
* Sanitizes a string label to display as an option.
*
* @param string $label
* The label to sanitize.
*/
static protected function sanitizeLabel(&$label) {
// Allow a limited set of HTML tags.
$label = field_filter_xss($label);
}
/**
* Returns the empty option to add to the list of options, if any.
*
* @return string|null
* Either static::OPTIONS_EMPTY_NONE, static::OPTIONS_EMPTY_SELECT, or NULL.
*/
protected function getEmptyOption() { }
}
<?php
/**
* @file
* Contains \Drupal\options\Plugin\field\widget\SelectWidget.
*/
namespace Drupal\options\Plugin\field\widget;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
/**
* Plugin implementation of the 'options_select' widget.
*
* @Plugin(
* id = "options_select",
* module = "options",
* label = @Translation("Select list"),
* field_types = {
* "list_integer",
* "list_float",
* "list_text"
* },
* multiple_values = TRUE
* )
*/
class SelectWidget extends OptionsWidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
$element = parent::formElement($items, $delta, $element, $langcode, $form, $form_state);
$element += array(
'#type' => 'select',
'#options' => $this->getOptions(),
'#default_value' => $this->getSelectedOptions($items),
// Do not display a 'multiple' select box if there is only one option.
'#multiple' => $this->multiple && count($this->options) > 1,
);
return $element;
}
/**
* {@inheritdoc}
*/
static protected function sanitizeLabel(&$label) {
// Select form inputs allow unencoded HTML entities, but no HTML tags.
$label = strip_tags($label);
}
/**
* {@inheritdoc}
*/
protected function supportsGroups() {
return TRUE;
}
/**
* {@inheritdoc}
*/
protected function getEmptyOption() {
if ($this->multiple) {
// Multiple select: add a 'none' option for non-required fields.
if (!$this->required) {
return static::OPTIONS_EMPTY_NONE;
}
}
else {
// Single select: add a 'none' option for non-required fields,
// and a 'select a value' option for required fields that do not come
// with a value selected.
if (!$this->required) {
return static::OPTIONS_EMPTY_NONE;
}
if (!$this->has_value) {
return static::OPTIONS_EMPTY_SELECT;
}
}
}
}
......@@ -62,8 +62,7 @@ function setUp() {
'type' => 'list_boolean',
'cardinality' => 1,
'settings' => array(
// Make sure that 0 works as a 'on' value'.
'allowed_values' => array(1 => 'Zero', 0 => 'Some <script>dangerous</script> & unescaped <strong>markup</strong>'),
'allowed_values' => array(0 => 'Zero', 1 => 'Some <script>dangerous</script> & unescaped <strong>markup</strong>'),
),
);
$this->bool = field_create_field($this->bool);
......@@ -458,7 +457,7 @@ function testOnOffCheckbox() {
// Submit form: check the option.
$edit = array("bool[$langcode]" => TRUE);
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertFieldValues($entity_init, 'bool', $langcode, array(0));
$this->assertFieldValues($entity_init, 'bool', $langcode, array(1));
// Display form: check that the right options are selected.
$this->drupalGet('test-entity/manage/' . $entity->ftid . '/edit');
......@@ -467,7 +466,7 @@ function testOnOffCheckbox() {
// Submit form: uncheck the option.
$edit = array("bool[$langcode]" => FALSE);
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertFieldValues($entity_init, 'bool', $langcode, array(1));
$this->assertFieldValues($entity_init, 'bool', $langcode, array(0));
// Display form: with 'off' value, option is unchecked.
$this->drupalGet('test-entity/manage/' . $entity->ftid . '/edit');
......
......@@ -20,8 +20,7 @@
* properties to filter out values from a list defined by field level
* properties.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object the field is attached to, or NULL if no entity
* exists (e.g. in field settings page).
* The entity object the field is attached to.
*
* @return
* The array of options for the field. Array keys are the values to be
......
This diff is collapsed.
......@@ -1155,8 +1155,7 @@ function taxonomy_field_formatter_view(EntityInterface $entity, $field, $instanc
* properties to filter out values from a list defined by field level
* properties.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object the field is attached to, or NULL if no entity
* exists (e.g. in field settings page).
* The entity object the field is attached to.
*
* @return
* The array of valid terms for this field, keyed by term id.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment