You are here

public function ContactFormCloneForm::save in Contact Storage 8

Form submission handler for the 'save' action.

Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.

Overrides ContactFormEditForm::save

File

src/Form/ContactFormCloneForm.php, line 91

Class

ContactFormCloneForm
Defines a class for cloning a contact form.

Namespace

Drupal\contact_storage\Form

Code

public function save(array $form, FormStateInterface $form_state) {

  /** @var \Drupal\contact\ContactFormInterface $contact_form */
  $contact_form = $this->entity;

  // Get the original ID.
  $original_id = $contact_form
    ->getOriginalId();
  $new_id = $contact_form
    ->id();

  // Create the new form.
  $contact_form = $contact_form
    ->createDuplicate();
  $contact_form
    ->set('id', $new_id);
  $contact_form
    ->save();

  // Clone configurable fields.
  foreach ($this->fieldManager
    ->getFieldDefinitions('contact_message', $original_id) as $field) {
    if ($field instanceof BaseFieldDefinition) {
      continue;
    }
    if ($this->moduleHandler
      ->moduleExists('field')) {
      if ($config = $field
        ->getConfig($original_id)) {
        $new_config = FieldConfig::create([
          'bundle' => $contact_form
            ->id(),
          'uuid' => NULL,
        ] + $config
          ->toArray());
        $new_config
          ->save();
      }
    }
  }

  // Clone the entity form display.
  $display = EntityFormDisplay::load('contact_message.' . $original_id . '.default');
  EntityFormDisplay::create([
    'bundle' => $contact_form
      ->id(),
    'uuid' => NULL,
  ] + $display
    ->toArray())
    ->save();

  // Clone the entity view display.
  $display = EntityViewDisplay::load('contact_message.' . $original_id . '.default');
  EntityViewDisplay::create([
    'bundle' => $contact_form
      ->id(),
    'uuid' => NULL,
  ] + $display
    ->toArray())
    ->save();

  // Redirect and show messge.
  $form_state
    ->setRedirect('entity.contact_form.edit_form', [
    'contact_form' => $contact_form
      ->id(),
  ]);
  $edit_link = $this->entity
    ->toLink($this
    ->t('Edit'))
    ->toString();
  $this
    ->messenger()
    ->addStatus($this
    ->t('Contact form %label has been added.', [
    '%label' => $contact_form
      ->label(),
  ]));
  $this
    ->logger('contact')
    ->notice('Contact form %label has been added.', [
    '%label' => $contact_form
      ->label(),
    'link' => $edit_link,
  ]);
}