<?php
use Drupal\field\FieldUpdateForbiddenException;
use Drupal\Core\Entity\Query\QueryFactory;
function options_help($path, $arg) {
switch ($path) {
case 'admin/help#options':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Options module defines various fields for storing a list of items, for use with the Field module. Usually these items are entered through a select list, checkboxes, or radio buttons. See the <a href="@field-help">Field module help page</a> for more information about fields.', array(
'@field-help' => url('admin/help/field'),
)) . '</p>';
return $output;
}
}
function options_theme() {
return array(
'options_none' => array(
'variables' => array(
'instance' => NULL,
'option' => NULL,
),
),
);
}
function options_field_info() {
return array(
'list_integer' => array(
'label' => t('List (integer)'),
'description' => t("This field stores integer values from a list of allowed 'value => label' pairs, i.e. 'Lifetime in days': 1 => 1 day, 7 => 1 week, 31 => 1 month."),
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => '',
),
'default_widget' => 'options_select',
'default_formatter' => 'list_default',
),
'list_float' => array(
'label' => t('List (float)'),
'description' => t("This field stores float values from a list of allowed 'value => label' pairs, i.e. 'Fraction': 0 => 0, .25 => 1/4, .75 => 3/4, 1 => 1."),
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => '',
),
'default_widget' => 'options_select',
'default_formatter' => 'list_default',
),
'list_text' => array(
'label' => t('List (text)'),
'description' => t("This field stores text values from a list of allowed 'value => label' pairs, i.e. 'US States': IL => Illinois, IA => Iowa, IN => Indiana."),
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => '',
),
'default_widget' => 'options_select',
'default_formatter' => 'list_default',
),
'list_boolean' => array(
'label' => t('Boolean'),
'description' => t('This field stores simple on/off or yes/no options.'),
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => '',
),
'default_widget' => 'options_buttons',
'default_formatter' => 'list_default',
),
);
}
function options_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
switch ($field['type']) {
case 'list_integer':
case 'list_float':
case 'list_text':
$form['allowed_values'] = array(
'#type' => 'textarea',
'#title' => t('Allowed values list'),
'#default_value' => options_allowed_values_string($settings['allowed_values']),
'#rows' => 10,
'#element_validate' => array(
'options_field_settings_form_validate_allowed_values',
),
'#field_has_data' => $has_data,
'#field' => $field,
'#field_type' => $field['type'],
'#access' => empty($settings['allowed_values_function']),
);
$description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
if ($field['type'] == 'list_integer' || $field['type'] == 'list_float') {
$description .= '<br/>' . t('The key is the stored value, and must be numeric. The label will be used in displayed values and edit forms.');
$description .= '<br/>' . t('The label is optional: if a line contains a single number, it will be used as key and label.');
$description .= '<br/>' . t('Lists of labels are also accepted (one label per line), only if the field does not hold any values yet. Numeric keys will be automatically generated from the positions in the list.');
}
else {
$description .= '<br/>' . t('The key is the stored value. The label will be used in displayed values and edit forms.');
$description .= '<br/>' . t('The label is optional: if a line contains a single string, it will be used as key and label.');
}
$description .= '</p>';
$form['allowed_values']['#description'] = $description;
break;
case 'list_boolean':
$values = $settings['allowed_values'];
$off_value = array_shift($values);
$on_value = array_shift($values);
$form['allowed_values'] = array(
'#type' => 'value',
'#description' => '',
'#value_callback' => 'options_field_settings_form_value_boolean_allowed_values',
'#access' => empty($settings['allowed_values_function']),
);
$form['allowed_values']['on'] = array(
'#type' => 'textfield',
'#title' => t('On value'),
'#default_value' => $on_value,
'#required' => FALSE,
'#description' => t('If left empty, "1" will be used.'),
'#parents' => array(
'on',
),
);
$form['allowed_values']['off'] = array(
'#type' => 'textfield',
'#title' => t('Off value'),
'#default_value' => $off_value,
'#required' => FALSE,
'#description' => t('If left empty, "0" will be used.'),
'#parents' => array(
'off',
),
);
$form['allowed_values']['#on_parents'] =& $form['allowed_values']['on']['#parents'];
$form['allowed_values']['#off_parents'] =& $form['allowed_values']['off']['#parents'];
break;
}
if ($instance['widget']['type'] == 'options_onoff') {
$form['allowed_values']['#description'] .= '<p>' . t("For a 'single on/off checkbox' widget, define the 'off' value first, then the 'on' value in the <strong>Allowed values</strong> section. Note that the checkbox will be labeled with the label of the 'on' value.") . '</p>';
}
elseif ($instance['widget']['type'] == 'options_buttons') {
$form['allowed_values']['#description'] .= '<p>' . t("The 'checkboxes/radio buttons' widget will display checkboxes if the <em>Number of values</em> option is greater than 1 for this field, otherwise radios will be displayed.") . '</p>';
}
$form['allowed_values']['#description'] .= '<p>' . t('Allowed HTML tags in labels: @tags', array(
'@tags' => _field_filter_xss_display_allowed_tags(),
)) . '</p>';
$form['allowed_values_function'] = array(
'#type' => 'value',
'#value' => $settings['allowed_values_function'],
);
$form['allowed_values_function_display'] = array(
'#type' => 'item',
'#title' => t('Allowed values list'),
'#markup' => t('The value of this field is being determined by the %function function and may not be changed.', array(
'%function' => $settings['allowed_values_function'],
)),
'#access' => !empty($settings['allowed_values_function']),
);
return $form;
}
function options_field_settings_form_validate_allowed_values($element, &$form_state) {
$field = $element['#field'];
$has_data = $element['#field_has_data'];
$field_type = $field['type'];
$generate_keys = ($field_type == 'list_integer' || $field_type == 'list_float') && !$has_data;
$values = options_extract_allowed_values($element['#value'], $field['type'], $generate_keys);
if (!is_array($values)) {
form_error($element, t('Allowed values list: invalid input.'));
}
else {
foreach ($values as $key => $value) {
if ($field_type == 'list_integer' && !preg_match('/^-?\\d+$/', $key)) {
form_error($element, t('Allowed values list: keys must be integers.'));
break;
}
if ($field_type == 'list_float' && !is_numeric($key)) {
form_error($element, t('Allowed values list: each key must be a valid integer or decimal.'));
break;
}
elseif ($field_type == 'list_text' && drupal_strlen($key) > 255) {
form_error($element, t('Allowed values list: each key must be a string at most 255 characters long.'));
break;
}
}
if ($has_data) {
$lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($values));
if (_options_values_in_use($field, $lost_keys)) {
form_error($element, t('Allowed values list: some values are being removed while currently in use.'));
}
}
form_set_value($element, $values, $form_state);
}
}
function options_field_settings_form_value_boolean_allowed_values($element, $input, $form_state) {
$on = drupal_array_get_nested_value($form_state['input'], $element['#on_parents']);
$off = drupal_array_get_nested_value($form_state['input'], $element['#off_parents']);
return array(
$off,
$on,
);
}
function options_field_update_field($field, $prior_field, $has_data) {
drupal_static_reset('options_allowed_values');
}
function options_allowed_values($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$allowed_values =& drupal_static(__FUNCTION__, array());
if (!isset($allowed_values[$field['id']])) {
$function = $field['settings']['allowed_values_function'];
$cacheable = TRUE;
if (!empty($function)) {
$values = $function($field, $instance, $entity_type, $entity, $cacheable);
}
else {
$values = $field['settings']['allowed_values'];
}
if ($cacheable) {
$allowed_values[$field['id']] = $values;
}
else {
return $values;
}
}
return $allowed_values[$field['id']];
}
function options_extract_allowed_values($string, $field_type, $generate_keys) {
$values = array();
$list = explode("\n", $string);
$list = array_map('trim', $list);
$list = array_filter($list, 'strlen');
$generated_keys = $explicit_keys = FALSE;
foreach ($list as $position => $text) {
$value = $key = FALSE;
$matches = array();
if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {
$key = $matches[1];
$value = $matches[2];
$explicit_keys = TRUE;
}
elseif ($field_type == 'list_text' || $field_type == 'list_float' && is_numeric($text) || $field_type == 'list_integer' && is_numeric($text) && (double) $text == intval($text)) {
$key = $value = $text;
$explicit_keys = TRUE;
}
elseif ($generate_keys) {
$key = (string) $position;
$value = $text;
$generated_keys = TRUE;
}
else {
return;
}
if ($field_type == 'list_float' && is_numeric($key)) {
$key = (string) (double) $key;
}
$values[$key] = $value;
}
if ($explicit_keys && $generated_keys) {
return;
}
return $values;
}
function options_allowed_values_string($values) {
$lines = array();
foreach ($values as $key => $value) {
$lines[] = "{$key}|{$value}";
}
return implode("\n", $lines);
}
function options_field_update_forbid($field, $prior_field, $has_data) {
if ($field['module'] == 'options' && $has_data) {
$lost_keys = array_diff(array_keys($prior_field['settings']['allowed_values']), array_keys($field['settings']['allowed_values']));
if (_options_values_in_use($field, $lost_keys)) {
throw new FieldUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', array(
'@field_name' => $field['field_name'],
)));
}
}
}
function _options_values_in_use($field, $values) {
if ($values) {
$field = field_info_field_by_id($field['id']);
$factory = drupal_container()
->get('entity.query');
foreach ($field['bundles'] as $entity_type => $bundle) {
$result = $factory
->get($entity_type)
->condition($field['field_name'] . '.value', $values)
->count()
->accessCheck(FALSE)
->range(0, 1)
->execute();
if ($result) {
return TRUE;
}
}
}
return FALSE;
}
function options_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
$allowed_values = options_allowed_values($field, $instance, $entity_type, $entity);
foreach ($items as $delta => $item) {
if (!empty($item['value'])) {
if (!empty($allowed_values) && !isset($allowed_values[$item['value']])) {
$errors[$field['field_name']][$langcode][$delta][] = array(
'error' => 'list_illegal_value',
'message' => t('%name: illegal value.', array(
'%name' => $instance['label'],
)),
);
}
}
}
}
function options_field_is_empty($item, $field) {
if (empty($item['value']) && (string) $item['value'] !== '0') {
return TRUE;
}
return FALSE;
}
function options_field_widget_info() {
return array(
'options_select' => array(
'label' => t('Select list'),
'field types' => array(
'list_integer',
'list_float',
'list_text',
),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
),
'options_buttons' => array(
'label' => t('Check boxes/radio buttons'),
'field types' => array(
'list_integer',
'list_float',
'list_text',
'list_boolean',
),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
),
'options_onoff' => array(
'label' => t('Single on/off checkbox'),
'field types' => array(
'list_boolean',
),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
'settings' => array(
'display_label' => 0,
),
),
);
}
function options_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$value_key = key($field['columns']);
$type = str_replace('options_', '', $instance['widget']['type']);
$multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
$required = $element['#required'];
$has_value = isset($items[0][$value_key]);
$properties = _options_properties($type, $multiple, $required, $has_value);
$entity_type = $element['#entity_type'];
$entity = $element['#entity'];
$options = _options_get_options($field, $instance, $properties, $entity_type, $entity);
$default_value = _options_storage_to_form($items, $options, $value_key, $properties);
switch ($type) {
case 'select':
$element += array(
'#type' => 'select',
'#default_value' => $default_value,
'#multiple' => $multiple && count($options) > 1,
'#options' => $options,
);
break;
case 'buttons':
if ($required && count($options) == 1) {
reset($options);
$default_value = array(
key($options),
);
}
if (!$multiple) {
$default_value = $default_value ? reset($default_value) : NULL;
}
$element += array(
'#type' => $multiple ? 'checkboxes' : 'radios',
'#default_value' => $default_value,
'#options' => $options,
);
break;
case 'onoff':
$keys = array_keys($options);
$off_value = array_shift($keys);
$on_value = array_shift($keys);
$element += array(
'#type' => 'checkbox',
'#default_value' => isset($default_value[0]) && $default_value[0] == $on_value ? 1 : 0,
'#on_value' => $on_value,
'#off_value' => $off_value,
);
$element['#title'] = isset($options[$on_value]) ? $options[$on_value] : '';
if ($instance['widget']['settings']['display_label']) {
$element['#title'] = $instance['label'];
}
break;
}
$element += array(
'#value_key' => $value_key,
'#element_validate' => array(
'options_field_widget_validate',
),
'#properties' => $properties,
);
return $element;
}
function options_field_widget_settings_form($field, $instance) {
$form = array();
if ($instance['widget']['type'] == 'options_onoff') {
$form['display_label'] = array(
'#type' => 'checkbox',
'#title' => t('Use field label instead of the "On value" as label'),
'#default_value' => $instance['widget']['settings']['display_label'],
'#weight' => -1,
);
}
return $form;
}
function options_field_widget_validate($element, &$form_state) {
if ($element['#required'] && $element['#value'] == '_none') {
form_error($element, t('!name field is required.', array(
'!name' => $element['#title'],
)));
}
$items = _options_form_to_storage($element);
form_set_value($element, $items, $form_state);
}
function _options_properties($type, $multiple, $required, $has_value) {
$base = array(
'filter_xss' => FALSE,
'strip_tags' => FALSE,
'empty_option' => FALSE,
'optgroups' => FALSE,
);
$properties = array();
switch ($type) {
case 'select':
$properties = array(
'strip_tags' => TRUE,
'optgroups' => TRUE,
);
if ($multiple) {
if (!$required) {
$properties['empty_option'] = 'option_none';
}
}
else {
if (!$required) {
$properties['empty_option'] = 'option_none';
}
elseif (!$has_value) {
$properties['empty_option'] = 'option_select';
}
}
break;
case 'buttons':
$properties = array(
'filter_xss' => TRUE,
);
if (!$required && !$multiple) {
$properties['empty_option'] = 'option_none';
}
break;
case 'onoff':
$properties = array(
'filter_xss' => TRUE,
);
break;
}
return $properties + $base;
}
function _options_get_options($field, $instance, $properties, $entity_type, $entity) {
$options = (array) module_invoke($field['module'], 'options_list', $field, $instance, $entity_type, $entity);
_options_prepare_options($options, $properties);
if (!$properties['optgroups']) {
$options = options_array_flatten($options);
}
if ($properties['empty_option']) {
$label = theme('options_none', array(
'instance' => $instance,
'option' => $properties['empty_option'],
));
$options = array(
'_none' => $label,
) + $options;
}
return $options;
}
function _options_prepare_options(&$options, $properties) {
foreach ($options as $value => $label) {
if (is_array($label)) {
_options_prepare_options($options[$value], $properties);
}
else {
if ($properties['strip_tags']) {
$options[$value] = strip_tags($label);
}
if ($properties['filter_xss']) {
$options[$value] = field_filter_xss($label);
}
}
}
}
function _options_storage_to_form($items, $options, $column, $properties) {
$items_transposed = options_array_transpose($items);
$values = isset($items_transposed[$column]) && is_array($items_transposed[$column]) ? $items_transposed[$column] : array();
if ($properties['optgroups']) {
$options = options_array_flatten($options);
}
$values = array_values(array_intersect($values, array_keys($options)));
return $values;
}
function _options_form_to_storage($element) {
$values = array_values((array) $element['#value']);
$properties = $element['#properties'];
if ($element['#type'] == 'checkbox') {
$values = array(
$values[0] ? $element['#on_value'] : $element['#off_value'],
);
}
if ($properties['empty_option']) {
$index = array_search('_none', $values, TRUE);
if ($index !== FALSE) {
unset($values[$index]);
}
}
if (empty($values)) {
$values = array(
NULL,
);
}
$result = options_array_transpose(array(
$element['#value_key'] => $values,
));
return $result;
}
function options_array_transpose($array) {
$result = array();
if (is_array($array)) {
foreach ($array as $key1 => $value1) {
if (is_array($value1)) {
foreach ($value1 as $key2 => $value2) {
if (!isset($result[$key2])) {
$result[$key2] = array();
}
$result[$key2][$key1] = $value2;
}
}
}
}
return $result;
}
function options_array_flatten($array) {
$result = array();
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$result += options_array_flatten($value);
}
else {
$result[$key] = $value;
}
}
}
return $result;
}
function options_field_widget_error($element, $error, $form, &$form_state) {
form_error($element, $error['message']);
}
function options_options_list($field, $instance, $entity_type, $entity) {
return options_allowed_values($field, $instance, $entity_type, $entity);
}
function theme_options_none($variables) {
$instance = $variables['instance'];
$option = $variables['option'];
$output = '';
switch ($instance['widget']['type']) {
case 'options_buttons':
$output = t('N/A');
break;
case 'options_select':
$output = $option == 'option_none' ? t('- None -') : t('- Select a value -');
break;
}
return $output;
}
function options_field_formatter_info() {
return array(
'list_default' => array(
'label' => t('Default'),
'field types' => array(
'list_integer',
'list_float',
'list_text',
'list_boolean',
),
),
'list_key' => array(
'label' => t('Key'),
'field types' => array(
'list_integer',
'list_float',
'list_text',
'list_boolean',
),
),
);
}
function options_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
switch ($display['type']) {
case 'list_default':
$allowed_values = options_allowed_values($field, $instance, $entity_type, $entity);
foreach ($items as $delta => $item) {
if (isset($allowed_values[$item['value']])) {
$output = field_filter_xss($allowed_values[$item['value']]);
}
else {
$output = field_filter_xss($item['value']);
}
$element[$delta] = array(
'#markup' => $output,
);
}
break;
case 'list_key':
foreach ($items as $delta => $item) {
$element[$delta] = array(
'#markup' => field_filter_xss($item['value']),
);
}
break;
}
return $element;
}