replace-8.x-1.0/src/Form/ReplaceContentForm.php

src/Form/ReplaceContentForm.php
<?php

/**
 * @file
 * Contains \Drupal\replace\Form\ReplaceContentForm.
 */

namespace Drupal\replace\Form;

use Drupal\Console\Bootstrap\Drupal;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class ReplaceContentForm extends FormBase
{

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


  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $node_type = null)
  {
    $form['search'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Search'),
      '#default_value' => '',
    ];
    $form['replace'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Replace'),
      '#default_value' => '',
    ];
    $form['node_type_show'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Node type'),
      '#default_value' => $node_type->get('name'),
      '#attributes' => ['disabled' => 'disabled']
    ];
    $form['node_type'] = [
      '#type' => 'hidden',
      '#title' => $this->t('Node type'),
      '#default_value' => $node_type->get('type'),
      '#attributes' => ['disabled' => 'disabled']
    ];
    $form['show'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if (strlen($form_state->getValue('search')) < 2) {
      $form_state->setErrorByName('search', $this->t('Search element must not be less than 2 characters.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $type = $form['node_type']['#value'];
    $search = $form['search']['#value'];
    $replace = $form['replace']['#value'];
    $query = \Drupal::entityQuery('node');
    $group = $query
      ->orConditionGroup()
      ->condition('title', '%' . $search . '%', 'like')
      ->condition('body', '%' . $search . '%', 'like');
    $ids = $query->condition('type', $type)->condition($group)->execute();
    $num = count($ids);
    if ($num > 0) {
      foreach ($ids as $id) {
        $node = Node::load($id);
        $title = $node->get('title')->value;
        $body = $node->get('body')->value;
        $summary = $node->get('body')->summary;
        $node->get('title')->value = str_replace($search, $replace, $title);
        $node->get('body')->value = str_replace($search, $replace, $body);
        $node->get('body')->summary = str_replace($search, $replace, $summary);
        $node->save();
      }
      \Drupal::messenger()->addMessage($num . ' nodes modified!');
    } else {
      \Drupal::messenger()->addError('No data found!');
    }

    //return parent::submitForm($form, $form_state);
  }

}

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

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