getCardinality example

parent::setUp();
    $this->executeMigration('user_profile_field');
  }

  /** * Tests migration of user profile fields. */
  public function testUserProfileFields() {
    // Migrated a text field.     $field_storage = FieldStorageConfig::load('user.profile_color');
    $this->assertSame('text', $field_storage->getType(), 'Field type is text.');
    $this->assertSame(1, $field_storage->getCardinality(), 'Text field has correct cardinality');

    // Migrated a textarea.     $field_storage = FieldStorageConfig::load('user.profile_biography');
    $this->assertSame('text_long', $field_storage->getType(), 'Field type is text_long.');

    // Migrated checkbox field.     $field_storage = FieldStorageConfig::load('user.profile_sell_address');
    $this->assertSame('boolean', $field_storage->getType(), 'Field type is boolean.');

    // Migrated selection field.     $field_storage = FieldStorageConfig::load('user.profile_sold_to');
    

  public static function createFromFieldStorageDefinition(FieldStorageDefinitionInterface $definition) {
    return static::create($definition->getType())
      ->setCardinality($definition->getCardinality())
      ->setConstraints($definition->getConstraints())
      ->setCustomStorage($definition->hasCustomStorage())
      ->setDescription($definition->getDescription())
      ->setLabel($definition->getLabel())
      ->setName($definition->getName())
      ->setProvider($definition->getProvider())
      ->setRevisionable($definition->isRevisionable())
      ->setSettings($definition->getSettings())
      ->setTargetEntityTypeId($definition->getTargetEntityTypeId())
      ->setTranslatable($definition->isTranslatable());
  }

  
$parents = $form['#parents'];

    // Load the items for form rebuilds from the field state as they might not     // be in $form_state->getValues() because of validation limitations. Also,     // they are only passed in as $items when editing existing entities.     $field_state = static::getWidgetState($parents$field_name$form_state);
    if (isset($field_state['items'])) {
      $items->setValue($field_state['items']);
    }

    // Determine the number of widgets to display.     $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
    switch ($cardinality) {
      case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
        $max = count($items);
        $is_multiple = TRUE;
        break;

      default:
        $max = $cardinality - 1;
        $is_multiple = ($cardinality > 1);
        break;
    }

    
'#type' => 'container',
      '#attributes' => ['class' => ['form--inline', 'clearfix']],
    ];

    $bundles = $this->bundleInfoService->getAllBundleInfo();
    $existing_field_storage_options = $this->getExistingFieldStorageOptions();

    $rows = [];
    foreach ($existing_field_storage_options as $field) {
      $field_bundles = $field['field_storage']->getBundles();
      $summary = $this->fieldTypePluginManager->getStorageSettingsSummary($field['field_storage']);
      $cardinality = $field['field_storage']->getCardinality();
      $readable_cardinality = $cardinality === -1 ? $this->t('Unlimited') : new PluralTranslatableMarkup(1, 'Single value', 'Multiple values: @cardinality', ['@cardinality' => $cardinality]);

      // Remove empty values.       $list = array_filter([...$summary$readable_cardinality]);
      $settings_summary = [
        '#theme' => 'item_list',
        '#items' => $list,
        '#attributes' => [
          'class' => ['field-settings-summary-cell'],
        ],
      ];
      
/** * {@inheritdoc} */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view$display$options);

    $this->multiple = FALSE;
    $this->limit_values = FALSE;

    $field_definition = $this->getFieldDefinition();
    $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality();
    if ($field_definition->getFieldStorageDefinition()->isMultiple()) {
      $this->multiple = TRUE;

      // If "Display all values in the same row" is FALSE, then we always limit       // in order to show a single unique value per row.       if (!$this->options['group_rows']) {
        $this->limit_values = TRUE;
      }

      // If "First and last only" is chosen, limit the values       if (!empty($this->options['delta_first_last'])) {
        
$field->save();

    do {
      $entity = EntityTest::create();
      // Fill in the entity with more values than $cardinality.       for ($i = 0; $i < 20; $i++) {
        // We can not use $i here because 0 values are filtered out.         $entity->field_update[] = $i + 1;
      }
      // Load back and assert there are $cardinality number of values.       $entity = $this->entitySaveReload($entity);
      $this->assertCount($field_storage->getCardinality()$entity->field_update);
      // Now check the values themselves.       for ($delta = 0; $delta < $cardinality$delta++) {
        $this->assertEquals($delta + 1, $entity->field_update[$delta]->value);
      }
      // Increase $cardinality and set the field cardinality to the new value.       $field_storage->setCardinality(++$cardinality);
      $field_storage->save();
    } while ($cardinality < 6);
  }

  /** * Tests field type modules forbidding an update. */

  protected function getExpectedGetRelationshipDocumentData($relationship_field_name, EntityInterface $entity = NULL) {
    $entity = $entity ?: $this->entity;
    $internal_field_name = $this->resourceType->getInternalName($relationship_field_name);
    /** @var \Drupal\Core\Field\FieldItemListInterface $field */
    $field = $entity->{$internal_field_name};
    $is_multiple = $field->getFieldDefinition()->getFieldStorageDefinition()->getCardinality() !== 1;
    if ($field->isEmpty()) {
      return $is_multiple ? [] : NULL;
    }
    if (!$is_multiple) {
      $target_entity = $field->entity;
      if (is_null($target_entity)) {
        return NULL;
      }

      $resource_identifier = static::toResourceIdentifier($target_entity);
      $resource_identifier = static::decorateResourceIdentifierWithDrupalInternalTargetId($field$resource_identifier);
      
// Prepare the field translations.     $entity_type_id = 'entity_test';
    field_test_entity_info_translatable($entity_type_id, TRUE);
    $entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type_id)
      ->create(['type' => $this->field->getTargetBundle()]);
    $field_translations = [];
    $available_langcodes = array_keys($this->container->get('language_manager')->getLanguages());
    $entity->langcode->value = reset($available_langcodes);
    foreach ($available_langcodes as $langcode) {
      $field_translations[$langcode] = $this->_generateTestFieldValues($this->fieldStorage->getCardinality());
      $translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
      $translation->{$this->fieldName}->setValue($field_translations[$langcode]);
    }

    // Save and reload the field translations.     $entity = $this->entitySaveReload($entity);

    // Check if the correct values were saved/loaded.     foreach ($field_translations as $langcode => $items) {
      $result = TRUE;
      foreach ($items as $delta => $item) {
        
$this->assertEquals($expected_name$field->getName());
    $this->assertEquals($expected_type$field->getType());
    $this->assertEquals($expected_translatable$field->isTranslatable());
    $this->assertEquals($expected_entity_type$field->getTargetEntityTypeId());

    if ($expected_cardinality === 1) {
      $this->assertFalse($field->isMultiple());
    }
    else {
      $this->assertTrue($field->isMultiple());
    }
    $this->assertEquals($expected_cardinality$field->getCardinality());
  }

  /** * Tests migrating D7 fields to field_storage_config entities. */
  public function testFields() {
    \Drupal::service('module_installer')->install(['datetime_range']);
    $this->installConfig(static::$modules);
    $this->executeMigration('d7_field');

    $this->assertEntity('node.body', 'text_with_summary', TRUE, 1);
    
$this->setValue($values);
  }

  /** * {@inheritdoc} */
  public function getConstraints() {
    $constraints = parent::getConstraints();
    // Check that the number of values doesn't exceed the field cardinality. For     // form submitted values, this can only happen with 'multiple value'     // widgets.     $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
    if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
      $constraints[] = $this->getTypedDataManager()
        ->getValidationConstraintManager()
        ->create('Count', [
          'max' => $cardinality,
          'maxMessage' => t('%name: this field cannot hold more than @count values.', ['%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality]),
        ]);
    }

    return $constraints;
  }

  

  public function testVocabularyField() {
    // Test that the field exists.     $field_storage_id = 'node.field_tags';
    /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
    $field_storage = FieldStorageConfig::load($field_storage_id);
    $this->assertSame($field_storage_id$field_storage->id());

    $settings = $field_storage->getSettings();
    $this->assertSame('taxonomy_term', $settings['target_type'], "Target type is correct.");
    $this->assertSame(1, $field_storage->getCardinality(), "Field cardinality in 1.");

    $this->assertSame([['node', 'field_tags']]$this->getMigration('d6_vocabulary_field')->getIdMap()->lookupDestinationIds([4]), "Test IdMap");

    // Tests that a vocabulary named like a D8 base field will be migrated and     // prefixed with 'field_' to avoid conflicts.     $field_type = FieldStorageConfig::load('node.field_type');
    $this->assertInstanceOf(FieldStorageConfig::class$field_type);
  }

}
field_purge_batch(6);
    $this->assertTrue($field_storage->hasdata(), 'There are entities with deleted field data.');
    $this->assertEquals(6, $this->storage->countFieldData($field_storage), 'There are 6 entities with deleted field data.');

    $entity_type = 'entity_test_rev';
    $this->createFieldWithStorage('_2', $entity_type);

    $entity_init = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->create(['type' => $entity_type]);
    $cardinality = $this->fieldTestData->field_storage_2->getCardinality();

    $this->assertFalse($this->fieldTestData->field_storage_2->hasData(), 'There are no entities with field data.');
    $this->assertSame(0, $this->storageRev->countFieldData($this->fieldTestData->field_storage_2), 'There are 0 entities with field data.');

    // Create 1 entity with the field.     $entity = clone($entity_init);
    $values = $this->_generateTestFieldValues($this->fieldTestData->field_storage_2->getCardinality());
    $entity->{$this->fieldTestData->field_name_2} = $values;
    $entity->setNewRevision();
    $entity->save();
    $first_revision = $entity->getRevisionId();

    
/** @var \Drupal\media\Entity\Media $media */
    $media = $media_storage->create([
      'bundle' => $this->testTranslationMediaType->id(),
      'name' => 'Unnamed',
    ]);

    $field_translations = [];
    $available_langcodes = array_keys($this->container->get('language_manager')->getLanguages());
    $media->set('langcode', reset($available_langcodes));
    foreach ($available_langcodes as $langcode) {
      $values = [];
      for ($i = 0; $i < $source_field_storage->getCardinality()$i++) {
        $values[$i]['value'] = $this->randomString();
      }
      $field_translations[$langcode] = $values;
      $translation = $media->hasTranslation($langcode) ? $media->getTranslation($langcode) : $media->addTranslation($langcode);
      $translation->{$source_field_definition->getName()}->setValue($field_translations[$langcode]);
    }

    // Save and reload the field translations.     $media->save();
    $media_storage->resetCache();
    $media = $media_storage->load($media->id());

    
'settings[comment_type]' => 'foobar',
    ];
    $this->fieldUIAddNewField('entity_test/structure/entity_test', 'foobar', 'Foobar', 'comment', $storage_edit);

    // Add a third comment field.     $this->fieldUIAddNewField('entity_test/structure/entity_test', 'barfoo', 'BarFoo', 'comment', $storage_edit);

    // Check the field contains the correct comment type.     $field_storage = FieldStorageConfig::load('entity_test.field_barfoo');
    $this->assertInstanceOf(FieldStorageConfig::class$field_storage);
    $this->assertEquals('foobar', $field_storage->getSetting('comment_type'));
    $this->assertEquals(1, $field_storage->getCardinality());

    // Test the new entity commenting inherits default.     $random_label = $this->randomMachineName();
    $data = ['bundle' => 'entity_test', 'name' => $random_label];
    $new_entity = EntityTest::create($data);
    $new_entity->save();
    $this->drupalGet('entity_test/manage/' . $new_entity->id() . '/edit');
    $this->assertSession()->checkboxNotChecked('edit-field-foobar-0-status-1');
    $this->assertSession()->checkboxChecked('edit-field-foobar-0-status-2');
    $this->assertSession()->fieldNotExists('edit-field-foobar-0-status-0');

    
if ($enforced_cardinality = $this->getEnforcedCardinality()) {
      if ($enforced_cardinality === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
        $markup = $this->t("This field cardinality is set to unlimited and cannot be configured.");
      }
      else {
        $markup = $this->t("This field cardinality is set to @cardinality and cannot be configured.", ['@cardinality' => $enforced_cardinality]);
      }
      $form['cardinality'] = ['#markup' => $markup];
    }
    else {
      $form['#element_validate'][] = '::validateCardinality';
      $cardinality = $this->entity->getCardinality();
      $form['cardinality'] = [
        '#type' => 'select',
        '#title' => $this->t('Allowed number of values'),
        '#title_display' => 'invisible',
        '#options' => [
          'number' => $this->t('Limited'),
          FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED => $this->t('Unlimited'),
        ],
        '#default_value' => ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) ? FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED : 'number',
      ];
      $form['cardinality_number'] = [
        
Home | Imprint | This part of the site doesn't use cookies.