3 namespace Drupal\Core\Field;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Entity\FieldableEntityInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Language\LanguageInterface;
9 use Drupal\Core\Session\AccountInterface;
10 use Drupal\Core\TypedData\Plugin\DataType\ItemList;
13 * Represents an entity field; that is, a list of field item objects.
15 * An entity field is a list of field items, each containing a set of
16 * properties. Note that even single-valued entity fields are represented as
17 * list of field items, however for easy access to the contained item the entity
18 * field delegates __get() and __set() calls directly to the first item.
20 class FieldItemList extends ItemList implements FieldItemListInterface {
23 * Numerically indexed array of field items.
25 * @var \Drupal\Core\Field\FieldItemInterface[]
30 * The langcode of the field values held in the object.
34 protected $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
39 protected function createItem($offset = 0, $value = NULL) {
40 return \Drupal::service('plugin.manager.field.field_type')->createFieldItem($this, $offset, $value);
46 public function getEntity() {
47 // The "parent" is the TypedData object for the entity, we need to unwrap
49 return $this->getParent()->getValue();
55 public function setLangcode($langcode) {
56 $this->langcode = $langcode;
62 public function getLangcode() {
63 return $this->langcode;
69 public function getFieldDefinition() {
70 return $this->definition;
76 public function getSettings() {
77 return $this->definition->getSettings();
83 public function getSetting($setting_name) {
84 return $this->definition->getSetting($setting_name);
90 public function filterEmptyItems() {
91 $this->filter(function ($item) {
92 return !$item->isEmpty();
99 * @todo Revisit the need when all entity types are converted to NG entities.
101 public function getValue($include_computed = FALSE) {
103 foreach ($this->list as $delta => $item) {
104 $values[$delta] = $item->getValue($include_computed);
112 public function setValue($values, $notify = TRUE) {
113 // Support passing in only the value of the first item, either as a literal
114 // (value of the first property) or as an array of properties.
115 if (isset($values) && (!is_array($values) || (!empty($values) && !is_numeric(current(array_keys($values)))))) {
116 $values = [0 => $values];
118 parent::setValue($values, $notify);
124 public function __get($property_name) {
125 // For empty fields, $entity->field->property is NULL.
126 if ($item = $this->first()) {
127 return $item->__get($property_name);
134 public function __set($property_name, $value) {
135 // For empty fields, $entity->field->property = $value automatically
136 // creates the item before assigning the value.
137 $item = $this->first() ?: $this->appendItem();
138 $item->__set($property_name, $value);
144 public function __isset($property_name) {
145 if ($item = $this->first()) {
146 return $item->__isset($property_name);
154 public function __unset($property_name) {
155 if ($item = $this->first()) {
156 $item->__unset($property_name);
163 public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
164 $access_control_handler = \Drupal::entityManager()->getAccessControlHandler($this->getEntity()->getEntityTypeId());
165 return $access_control_handler->fieldAccess($operation, $this->getFieldDefinition(), $account, $this, $return_as_object);
171 public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {
172 // Grant access per default.
173 return AccessResult::allowed();
179 public function applyDefaultValue($notify = TRUE) {
180 if ($value = $this->getFieldDefinition()->getDefaultValue($this->getEntity())) {
181 $this->setValue($value, $notify);
184 // Create one field item and give it a chance to apply its defaults.
185 // Remove it if this ended up doing nothing.
186 // @todo Having to create an item in case it wants to set a value is
187 // absurd. Remove that in https://www.drupal.org/node/2356623.
188 $item = $this->first() ?: $this->appendItem();
189 $item->applyDefaultValue(FALSE);
190 $this->filterEmptyItems();
198 public function preSave() {
199 // Filter out empty items.
200 $this->filterEmptyItems();
202 $this->delegateMethod('preSave');
208 public function postSave($update) {
209 $result = $this->delegateMethod('postSave', $update);
210 return (bool) array_filter($result);
216 public function delete() {
217 $this->delegateMethod('delete');
223 public function deleteRevision() {
224 $this->delegateMethod('deleteRevision');
228 * Calls a method on each FieldItem.
230 * Any argument passed will be forwarded to the invoked method.
232 * @param string $method
233 * The name of the method to be invoked.
236 * An array of results keyed by delta.
238 protected function delegateMethod($method) {
240 $args = array_slice(func_get_args(), 1);
241 foreach ($this->list as $delta => $item) {
242 // call_user_func_array() is way slower than a direct call so we avoid
243 // using it if have no parameters.
244 $result[$delta] = $args ? call_user_func_array([$item, $method], $args) : $item->{$method}();
252 public function view($display_options = []) {
253 $view_builder = \Drupal::entityManager()->getViewBuilder($this->getEntity()->getEntityTypeId());
254 return $view_builder->viewField($this, $display_options);
260 public function generateSampleItems($count = 1) {
261 $field_definition = $this->getFieldDefinition();
262 $field_type_class = \Drupal::service('plugin.manager.field.field_type')->getPluginClass($field_definition->getType());
263 for ($delta = 0; $delta < $count; $delta++) {
264 $values[$delta] = $field_type_class::generateSampleValue($field_definition);
266 $this->setValue($values);
272 public function getConstraints() {
273 $constraints = parent::getConstraints();
274 // Check that the number of values doesn't exceed the field cardinality. For
275 // form submitted values, this can only happen with 'multiple value'
277 $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
278 if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
279 $constraints[] = $this->getTypedDataManager()
280 ->getValidationConstraintManager()
282 'max' => $cardinality,
283 'maxMessage' => t('%name: this field cannot hold more than @count values.', ['%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality]),
293 public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
294 if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
295 if ($widget = $this->defaultValueWidget($form_state)) {
296 // Place the input in a separate place in the submitted values tree.
297 $element = ['#parents' => ['default_value_input']];
298 $element += $widget->form($this, $element, $form_state);
303 return ['#markup' => $this->t('No widget available for: %type.', ['%type' => $this->getFieldDefinition()->getType()])];
311 public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) {
312 // Extract the submitted value, and validate it.
313 if ($widget = $this->defaultValueWidget($form_state)) {
314 $widget->extractFormValues($this, $element, $form_state);
315 // Force a non-required field definition.
316 // @see self::defaultValueWidget().
317 $this->getFieldDefinition()->setRequired(FALSE);
318 $violations = $this->validate();
320 // Assign reported errors to the correct form element.
321 if (count($violations)) {
322 $widget->flagErrors($this, $violations, $element, $form_state);
330 public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
331 // Extract the submitted value, and return it as an array.
332 if ($widget = $this->defaultValueWidget($form_state)) {
333 $widget->extractFormValues($this, $element, $form_state);
334 return $this->getValue();
341 public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
342 return $default_value;
346 * Returns the widget object used in default value form.
348 * @param \Drupal\Core\Form\FormStateInterface $form_state
349 * The form state of the (entire) configuration form.
351 * @return \Drupal\Core\Field\WidgetInterface|null
352 * A Widget object or NULL if no widget is available.
354 protected function defaultValueWidget(FormStateInterface $form_state) {
355 if (!$form_state->has('default_value_widget')) {
356 $entity = $this->getEntity();
358 // Force a non-required widget.
359 $definition = $this->getFieldDefinition();
360 $definition->setRequired(FALSE);
361 $definition->setDescription('');
363 // Use the widget currently configured for the 'default' form mode, or
364 // fallback to the default widget for the field type.
365 $entity_form_display = entity_get_form_display($entity->getEntityTypeId(), $entity->bundle(), 'default');
366 $widget = $entity_form_display->getRenderer($this->getFieldDefinition()->getName());
368 $widget = \Drupal::service('plugin.manager.field.widget')->getInstance(['field_definition' => $this->getFieldDefinition()]);
371 $form_state->set('default_value_widget', $widget);
374 return $form_state->get('default_value_widget');
380 public function equals(FieldItemListInterface $list_to_compare) {
381 $columns = $this->getFieldDefinition()->getFieldStorageDefinition()->getColumns();
382 $count1 = count($this);
383 $count2 = count($list_to_compare);
384 if ($count1 === 0 && $count2 === 0) {
385 // Both are empty we can safely assume that it did not change.
388 if ($count1 !== $count2) {
389 // One of them is empty but not the other one so the value changed.
392 $value1 = $this->getValue();
393 $value2 = $list_to_compare->getValue();
394 if ($value1 === $value2) {
397 // If the values are not equal ensure a consistent order of field item
398 // properties and remove properties which will not be saved.
399 $callback = function (&$value) use ($columns) {
400 if (is_array($value)) {
401 $value = array_intersect_key($value, $columns);
405 array_walk($value1, $callback);
406 array_walk($value2, $callback);
408 return $value1 == $value2;