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.
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.
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;
}
}