cbr-1.0.0/src/Form/ReuseForm.php

src/Form/ReuseForm.php
<?

namespace Drupal\cbr\Form;

use Drupal\cbr\Plugin\Field\FieldType\CBRCaseStatus;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\node\Entity\Node;
use Symfony\Component\DependencyInjection\ContainerInterface;

/** @file 
 *  Contains Drupal\cbr\Form\MergeForm
 */

class ReuseForm extends ConfigFormBase
{

    protected RendererInterface $renderer;
    protected EntityTypeManagerInterface $entityTypeManager;


    /**
     * {@inheritdoc}
     */
    protected function getEditableConfigNames()
    {
        return [
            'cbr.reuse_form',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFormId()
    {
        return 'cbr_reuse_form';
    }

    /* Constructs a new ReuseForm object.
     *
     * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
     *   The factory for configuration objects.
     * @param \Drupal\Core\Render\RendererInterface $renderer
     *  The renderer.
     */
    public function __construct(ConfigFactoryInterface $config_factory, RendererInterface $renderer, EntityTypeManagerInterface $entity_type_manager)
    {
        parent::__construct($config_factory);
        $this->renderer = $renderer;
        $this->entityTypeManager = $entity_type_manager;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container)
    {
        return new static(
            $container->get('config.factory'),
            $container->get('renderer'),
            $container->get('entity_type.manager')
        );
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, Node $source = NULL, Node $target = NULL)
    {
        //check if source and target are the same node type and if not so, raise an exception
        if ($source->getType() != $target->getType()) {
            throw new \Exception('Source and target node types are not the same');
        }

        $form['merge_form']['table'] = [
            '#type' => 'table',
            '#header' => [
                'label' => t('Field'),
                'source_field' => t('Source value'),
                'target_field' => t('Target value'),
                'action' => t('Reuse'),
            ],
            '#empty' => t('No fields to continue'),
        ];

        //loop through all fields on the target node
        $source_fields = $source->getFields();
        foreach ($source_fields as $field_name => $field_value) {
            //skip fields of type "cbr_case_status" and "cbr_solution_reference" or fields, that are deleted
            if ($field_value->getFieldDefinition()->getType() == 'cbr_case_status' || $field_value->getFieldDefinition()->getType() == 'cbr_solution_reference' || $field_value->getFieldDefinition()->getConfig($source->bundle())->get('deleted') !== false) {
                continue;
            }
            $form['merge_form']['table'][$field_name]['label'] = [
                '#type' => 'label',
                '#title' => $source->get($field_name)->getFieldDefinition()->getLabel(),
            ];
            $form['merge_form']['table'][$field_name]['source_field'] = [
                '#type' => 'markup',
                '#markup' => $this->renderField($source->get($field_name)),
            ];
            $form['merge_form']['table'][$field_name]['target_field'] = [
                '#type' => 'markup',
                '#markup' => $this->renderField($target->get($field_name)),
            ];
            $form['merge_form']['table'][$field_name]['action'] = [
                '#type' => 'checkbox',
                '#default_value' => !empty($source->get($field_name)->getValue()) && empty($target->get($field_name)->getValue()),
            ];
        }

        //add source and targe node id to hidden fields
        $form['merge_form']['source_node_id'] = [
            '#type' => 'hidden',
            '#value' => $source->id(),
        ];
        $form['merge_form']['target_node_id'] = [
            '#type' => 'hidden',
            '#value' => $target->id(),
        ];

        //form actions
        $form['actions'] = [
            '#type' => 'actions',
        ];
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => t('Continue'),
            '#button_type' => 'primary',
        ];

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $source_node_id = $form_state->getValue('source_node_id');
        $target_node_id = $form_state->getValue('target_node_id');

        $source_node = $this->entityTypeManager->getStorage('node')->load($source_node_id);
        $target_node = $this->entityTypeManager->getStorage('node')->load($target_node_id);

        $fields = $form_state->getValue('table');

        foreach ($fields as $field_name => $field_values) {
            if ($field_values['action']) {
                $target_node->set($field_name, $source_node->get($field_name)->getValue());
            }
        }
        foreach ($target_node->getFieldDefinitions() as $field_item) {
            if ($field_item->getType() == 'cbr_case_status') {
                $target_node->get($field_item->getName())->setValue(CBRCaseStatus::CASE_STATUS_TESTING_SOLUTION);
            } else if ($field_item->getType() == 'cbr_solution_reference') {
                //add solution reference to the target node
                $target_node->get($field_item->getName())->appendItem(['target_id' => $source_node->id()]);
            }
        }
        $target_node->save();

        $this->messenger()->deleteAll();
        $this->messenger()->addMessage('Case status is now "Testing solution". You can edit the solution further, if needed.');

        //go to edit form of target node
        $form_state->setRedirect('entity.node.edit_form', ['node' => $target_node_id]);
    }


    private function renderField($field)
    {
        $view = $field->view([
            'label' => 'hidden',
            'type' => 'default_formatter'
        ]);
        return $this->renderer->renderPlain($view);
    }
}

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

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