You are here

protected function ConfigFieldsExportToCodeForm::getBaseFieldCode in Field tools 8

1 call to ConfigFieldsExportToCodeForm::getBaseFieldCode()
ConfigFieldsExportToCodeForm::buildForm in src/Form/ConfigFieldsExportToCodeForm.php
Form constructor.

File

src/Form/ConfigFieldsExportToCodeForm.php, line 124

Class

ConfigFieldsExportToCodeForm
Provides a form to clone multiple fields from an entity bundle.

Namespace

Drupal\field_tools\Form

Code

protected function getBaseFieldCode(&$code, $field) {
  $code[] = sprintf("\$fields['%s'] = \\Drupal\\Core\\Field\\BaseFieldDefinition::create('%s')", $field
    ->getName(), $field
    ->getType());
  $code[] = sprintf("->setLabel(t('%s'))", $field
    ->getLabel());
  $code[] = sprintf("->setDescription(t('%s'))", $field
    ->getDescription());
  if ($field
    ->isRequired()) {
    $code[] = "  ->setRequired(TRUE)";
  }
  if ($field instanceof \Drupal\Core\Field\FieldStorageDefinitionInterface) {
    if ($field
      ->isRevisionable()) {
      $code[] = "  ->setRevisionable(TRUE)";
    }
  }
  if ($field
    ->isTranslatable()) {
    $code[] = "  ->setTranslatable(TRUE)";
  }
  foreach ($field
    ->getSettings() as $setting => $value) {
    if (is_string($value)) {
      $code[] = "  ->setSetting('{$setting}' => '{$value}')";
    }
    elseif (is_bool($value)) {
      $code[] = "  ->setSetting('{$setting}' => " . ($value ? 'TRUE' : 'FALSE') . ")";
    }
    else {

      // TODO: format the output code properly!
      $code[] = "  ->setSetting('{$setting}' => " . var_export($value, TRUE) . ")";
    }
  }
  foreach ([
    'form',
    'view',
  ] as $display_type) {
    $display = $this->entityTypeManager
      ->getStorage("entity_{$display_type}_display")
      ->load($this->entityTypeId . '.' . $this->bundle . '.' . 'default');
    if ($display) {
      $display_settings = $display
        ->getComponent($field
        ->getName());
      $code[] = "  ->setDisplayOptions('{$display_type}', [";
      $code[] = "    'type' => '{$display_settings['type']}',";
      $code[] = "    'weight' => '{$display_settings['weight']}',";
      if (!empty($display_settings['label'])) {
        $code[] = "    'label' => '{$display_settings['label']}',";
      }
      if (!empty($display_settings['settings'])) {
        $code[] = "    'settings' => [";
        foreach ($display_settings['settings'] as $key => $value) {
          $code[] = "      '{$key}' => '{$value}',";
        }
        $code[] = "    ],";
      }
      $code[] = "  ])";
      $code[] = "  ->setDisplayConfigurable('{$display_type}', TRUE)";
    }
  }
}