niobi-8.x-2.0-alpha4/modules/niobi_form/src/Form/NiobiFormCloneForm.php

modules/niobi_form/src/Form/NiobiFormCloneForm.php
<?php

namespace Drupal\niobi_form\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\group\Entity\GroupContent;
use Drupal\niobi_form\Entity\NiobiForm;
use Drupal\webform\Entity\Webform;

/**
 * Form controller for Niobi Form edit form.
 *
 * @ingroup niobi_form
 */
class NiobiFormCloneForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    /* @var $entity \Drupal\niobi_form\Entity\NiobiForm */
    $form = parent::buildForm($form, $form_state);

    $entity = $this->entity;

    $form['name']['widget'][0]['value']['#default_value'] = t('Clone of ') . $entity->getName();

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $current_form = NiobiForm::load($this->entity->id());
    $current_form->setName($form_state->getValue('name'));

    $new_form = $current_form->createDuplicate();

    // If the Niobi Form has a webform already, clone that also.
    if ($current_form->get('field_form')->getValue()) {
      $current_webform_data = $current_form->get('field_form')->getValue()[0];
      $current_webform = Webform::load($current_webform_data['target_id']);
      $new_webform_data = $current_webform_data;
      $new_webform = $current_webform->createDuplicate();
      $new_webform_id = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);
      $new_webform->set('id', $new_webform_id);
      $new_webform->save();
      $new_webform_data['target_id'] = $new_webform_id;
      $new_form->set('field_form', [$new_webform_data]);
    }

    $new_form->save();

    // Create group content.
    $gcs = GroupContent::loadByEntity($current_form);
    if (!empty($gcs)) {
      $gc = array_shift($gcs);
      if ($gc && $group = $gc->getGroup()) {
        $new_gc = GroupContent::create(
          [
            'type' => 'group_content_type_0f5fe3baa72a1',
            'gid' => $group->id(),
            'entity_id' => $new_form->id(),
            'label' => $new_form->label(),
          ]
        );
        $new_gc->save();
      }
    }

    $form_state->setRedirect('entity.niobi_form.canonical', ['niobi_form' => $new_form->id()]);
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc