setCardinality example


class EntityTestMultiValueBasefield extends EntityTest {

  /** * {@inheritdoc} */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields['name']->setCardinality(2);

    return $fields;
  }

}
->getStorage('file');

    // Add a file field.     $this->fieldStorage = FieldStorageConfig::create([
      'entity_type' => 'entity_test',
      'field_name' => 'field_rest_file_test',
      'type' => 'file',
      'settings' => [
        'uri_scheme' => 'public',
      ],
    ])
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->fieldStorage->save();

    $this->field = FieldConfig::create([
      'entity_type' => 'entity_test',
      'field_name' => 'field_rest_file_test',
      'bundle' => 'entity_test',
      'settings' => [
        'file_directory' => 'foobar',
        'file_extensions' => 'txt',
        'max_filesize' => '',
      ],
    ])
$view->setDisplay('rest_export_1');
    $this->executeView($view);

    // Test the raw 'created' value against each row.     foreach (Json::decode($this->drupalGet('test/serialize/node-field', ['query' => ['_format' => 'json']])) as $index => $values) {
      $this->assertSame($view->result[$index]->_entity->title->value, $values['title'], 'Expected raw title value found.');
    }

    // Test that multiple raw body fields are shown.     // Set the body field to unlimited cardinality.     $storage_definition = $node->getFieldDefinition('body')->getFieldStorageDefinition();
    $storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $storage_definition->save();

    $this->drupalGet($row_options);
    $this->submitForm(['row_options[field_options][body][raw_output]' => '1'], 'Apply');
    $this->submitForm([], 'Save');

    $node = $this->drupalCreateNode();

    $body = [
      'value' => '<script type="text/javascript">alert("node-body");</script>' . $this->randomMachineName(32),
      'format' => filter_default_format(),
    ];

  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());
  }

  
$this->fail('Using a field of a different type as initial value does not work.');
    }
    catch (FieldException $e) {
      $this->assertEquals('Illegal initial value definition on new_base_field: The field types do not match.', $e->getMessage());
    }

    try {
      // Add a base field that will not be stored in the shared tables.       $initial_field = BaseFieldDefinition::create('string')
        ->setName('initial_field')
        ->setLabel(t('An initial field'))
        ->setCardinality(2);
      $this->state->set('entity_test_update.additional_base_field_definitions', ['initial_field' => $initial_field]);
      $this->entityDefinitionUpdateManager->installFieldStorageDefinition('initial_field', 'entity_test_update', 'entity_test', $initial_field);

      // Now add the base field which will try to use the previously added field       // as the source of its initial values.       $new_base_field = BaseFieldDefinition::create('string')
        ->setName('new_base_field')
        ->setLabel(t('A new base field'))
        ->setInitialValueFromField('initial_field');
      $this->state->set('entity_test_update.additional_base_field_definitions', ['initial_field' => $initial_field, 'new_base_field' => $new_base_field]);
      $this->entityDefinitionUpdateManager->installFieldStorageDefinition('new_base_field', 'entity_test_update', 'entity_test', $new_base_field);
      
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['name']->setRevisionable(TRUE);
    $fields['user_id']->setRevisionable(TRUE);

    $fields['non_rev_field'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Non Revisionable Field'))
      ->setDescription(t('A non-revisionable test field.'))
      ->setRevisionable(FALSE)
      ->setTranslatable(TRUE)
      ->setCardinality(1)
      ->setReadOnly(TRUE);

    return $fields;
  }

}
->setLabel(new TranslatableMarkup('Field with a single property'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    $fields['test_multiple_properties'] = BaseFieldDefinition::create('multi_value_test')
      ->setLabel(new TranslatableMarkup('Field with multiple properties'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    $fields['test_single_property_multiple_values'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Field with a single property and multiple values'))
      ->setCardinality(2)
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    $fields['test_multiple_properties_multiple_values'] = BaseFieldDefinition::create('multi_value_test')
      ->setLabel(new TranslatableMarkup('Field with multiple properties and multiple values'))
      ->setCardinality(2)
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    $fields['test_non_rev_field'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Non Revisionable Field'))
      
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    // Setup some fields for entity_test_extra to create.     $definitions['multivalued_base_field'] = BaseFieldDefinition::create('string')
      ->setName('multivalued_base_field')
      ->setTargetEntityTypeId('entity_test_mulrev')
      ->setTargetBundle('entity_test_mulrev')
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      // Base fields are non-translatable and non-revisionable by default, but       // we explicitly set these values here for extra clarity.       ->setTranslatable(FALSE)
      ->setRevisionable(FALSE);
    $this->state->set('entity_test_mulrev.additional_base_field_definitions', $definitions);

    $this->tableMapping = $this->entityTypeManager->getStorage('entity_test_mulrev')->getTableMapping();

    // Ensure that the tables for the new field are created.     $this->applyEntityUpdates('entity_test_mulrev');
  }

  
->setDisplayOptions('view', [
        'type' => 'text_default',
        'weight' => 11,
      ])
      ->setDisplayOptions('form', [
        'type' => 'text_textfield',
        'weight' => 11,
      ]);

    $fields['test_display_multiple'] = BaseFieldDefinition::create('text')
      ->setLabel(t('A field with multiple values'))
      ->setCardinality(FieldStorageDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'weight' => 12,
      ])
      ->setDisplayOptions('form', [
        'type' => 'text_textfield',
        'weight' => 12,
      ]);

    return $fields;
  }

}
// Submit with valid data.     $value = rand(1, 255);
    $edit['test_user_field[0][value]'] = $value;
    $this->submitForm($edit, 'Create new account');
    // Check user fields.     $accounts = $this->container->get('entity_type.manager')->getStorage('user')
      ->loadByProperties(['name' => $name, 'mail' => $mail]);
    $new_user = reset($accounts);
    $this->assertEquals($value$new_user->test_user_field->value, 'The field value was correctly saved.');

    // Check that the 'add more' button works.     $field_storage->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $field_storage->save();
    $this->drupalGet('user/register');
    $this->assertRegistrationFormCacheTagsWithUserFields();
    // Add two inputs.     $value = rand(1, 255);
    $edit = [];
    $edit['test_user_field[0][value]'] = $value;
    $this->submitForm($edit, 'Add another item');
    $this->submitForm($edit, 'Add another item');
    // Submit with three values.     $edit['test_user_field[1][value]'] = $value + 1;
    
// Add a URL field; this example is from the Comment entity.     $this->commonBaseFields['homepage'] = BaseFieldDefinition::create('uri')
      ->setLabel('Homepage')
      ->setDescription("The comment author's home page address.")
      ->setTranslatable(TRUE)
      ->setSetting('max_length', 255);

    // A base field with cardinality > 1     $this->commonBaseFields['string'] = BaseFieldDefinition::create('string')
      ->setLabel('Strong')
      ->setTranslatable(TRUE)
      ->setCardinality(2);

    // Set up the basic 'entity_test' entity type. This is used by several     // tests; others customize it and the base fields.     $this->setUpEntityType($this->baseEntityType, $this->commonBaseFields);
  }

  /** * Mocks an entity type and its base fields. * * This works by: * - inserting the entity type definition into the entity type manager's cache * - setting the base fields on the ViewsTestEntity class as a static property * for its baseFieldsDefinitions() method to use. * * @param \Drupal\Core\Entity\EntityTypeInterface $definition * An entity type definition to add to the entity type manager. * @param \Drupal\Core\Field\BaseFieldDefinition[] $base_fields * An array of base field definitions */
->getStorage('file');

    // Add a file field.     $this->fieldStorage = FieldStorageConfig::create([
      'entity_type' => 'entity_test',
      'field_name' => 'field_rest_file_test',
      'type' => 'file',
      'settings' => [
        'uri_scheme' => 'public',
      ],
    ])
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->fieldStorage->save();

    $this->field = FieldConfig::create([
      'entity_type' => 'entity_test',
      'field_name' => 'field_rest_file_test',
      'bundle' => 'entity_test',
      'settings' => [
        'file_directory' => 'foobar',
        'file_extensions' => 'txt',
        'max_filesize' => '',
      ],
    ])
return $entity;
    }

    $entity_bundle = $entity->bundle();

    // Add access-protected field.     FieldStorageConfig::create([
      'entity_type' => static::$entityTypeId,
      'field_name' => 'field_rest_test',
      'type' => 'text',
    ])
      ->setCardinality(1)
      ->save();
    FieldConfig::create([
      'entity_type' => static::$entityTypeId,
      'field_name' => 'field_rest_test',
      'bundle' => $entity_bundle,
    ])
      ->setLabel('Test field')
      ->setTranslatable(FALSE)
      ->save();

    FieldStorageConfig::create([
      
->setLabel(t('Last login'))
      ->setDescription(t('The time that the user last logged in.'))
      ->setDefaultValue(0);

    $fields['init'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Initial email'))
      ->setDescription(t('The email address used for initial account creation.'))
      ->setDefaultValue('');

    $fields['roles'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Roles'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDescription(t('The roles the user has.'))
      ->setSetting('target_type', 'user_role');

    return $fields;
  }

  /** * Returns the role storage object. * * @return \Drupal\user\RoleStorageInterface * The role storage object. */
// Create an entity.     $this->entity = $this->createEntity();

    if ($this->entity instanceof FieldableEntityInterface) {
      // Add access-protected field.       FieldStorageConfig::create([
        'entity_type' => static::$entityTypeId,
        'field_name' => 'field_rest_test',
        'type' => 'text',
      ])
        ->setCardinality(1)
        ->save();
      FieldConfig::create([
        'entity_type' => static::$entityTypeId,
        'field_name' => 'field_rest_test',
        'bundle' => $this->entity->bundle(),
      ])
        ->setLabel('Test field')
        ->setTranslatable(FALSE)
        ->save();

      // Add multi-value field.
Home | Imprint | This part of the site doesn't use cookies.