You are here

function TmgmtEntityTestTrait::attachFields in Translation Management Tool 8

Creates fields of type text and text_with_summary of different cardinality.

It will attach created fields to provided entity name and bundle.

Field names will be stored in $this->field_names['entity']['bundle'] through which you can access them.

Parameters

string $entity_name: Entity name to which fields should be attached.

string $bundle: Bundle name to which fields should be attached.

bool|array $translatable: Flag or definition array to determine which or all fields should be translatable.

2 calls to TmgmtEntityTestTrait::attachFields()
TmgmtEntityTestTrait::createNodeType in tests/src/Functional/TmgmtEntityTestTrait.php
Creates node type with several text fields with different cardinality.
TmgmtEntityTestTrait::createTaxonomyVocab in tests/src/Functional/TmgmtEntityTestTrait.php
Creates taxonomy vocabulary with custom fields.

File

tests/src/Functional/TmgmtEntityTestTrait.php, line 111

Class

TmgmtEntityTestTrait
Utility test case class with helper methods to create entities and their fields with populated translatable content. Extend this class if you create tests in which you need Drupal entities and/or fields.

Namespace

Drupal\Tests\tmgmt\Functional

Code

function attachFields($entity_name, $bundle, $translatable = TRUE) {

  // Create several text fields.
  $field_types = array(
    'text',
    'text_with_summary',
  );
  for ($i = 0; $i <= 5; $i++) {
    $field_type = $field_types[array_rand($field_types, 1)];
    $field_name = mb_strtolower($this
      ->randomMachineName());

    // Create a field.
    $field_storage = FieldStorageConfig::create(array(
      'field_name' => $field_name,
      'entity_type' => $entity_name,
      'type' => $field_type,
      'cardinality' => mt_rand(1, 5),
      'translatable' => is_array($translatable) && isset($translatable[$i]) ? $translatable[$i] : (bool) $translatable,
    ));
    $field_storage
      ->save();

    // Create an instance of the previously created field.
    $field = FieldConfig::create(array(
      'field_name' => $field_name,
      'entity_type' => $entity_name,
      'bundle' => $bundle,
      'label' => $this
        ->randomMachineName(10),
      'description' => $this
        ->randomString(30),
      'widget' => array(
        'type' => $field_type == 'text' ? 'text_textfield' : 'text_textarea_with_summary',
        'label' => $this
          ->randomString(10),
      ),
    ));
    $field
      ->save();

    // Store field names in case there are needed outside this method.
    $this->field_names[$entity_name][$bundle][] = $field_name;
  }
}