You are here

public function ContentLoaderBase::assignFieldValue in YAML Content 8.2

Set or assign a field value based on field cardinality.

Parameters

\Drupal\Core\Entity\FieldableEntityInterface $entity: An entity object being assigned a field value.

string $field_name: The machine name of the field being populated.

mixed $value: The value being assigned into the entity field.

1 call to ContentLoaderBase::assignFieldValue()
ContentLoaderBase::importEntityField in src/ContentLoader/ContentLoaderBase.php
Process import data into an appropriate field value and assign it.

File

src/ContentLoader/ContentLoaderBase.php, line 324

Class

ContentLoaderBase
A base ContentLoader implementation to be extended by new content loaders.

Namespace

Drupal\yaml_content\ContentLoader

Code

public function assignFieldValue(FieldableEntityInterface $entity, $field_name, $value) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $field */
  $field = $entity->{$field_name};

  // Get the field cardinality to determine whether or not a value should be
  // 'set' or 'appended' to.
  $cardinality = $field
    ->getFieldDefinition()
    ->getFieldStorageDefinition()
    ->getCardinality();

  // If the cardinality is 0, throw an exception.
  if (!$cardinality) {
    throw new \InvalidArgumentException("'{$field->getName()}' cannot hold any values.");
  }

  // If the cardinality is set to 1, set the field value directly.
  if ($cardinality == 1) {
    $field
      ->setValue($value);
  }
  else {
    $field
      ->appendItem($value);
  }
}