BlockContentForm.php 2.52 KB
Newer Older
1 2
<?php

3
namespace Drupal\block_content;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Core\Entity\ContentEntityForm;
7
use Drupal\Core\Form\FormStateInterface;
8 9

/**
10
 * Form handler for the custom block edit forms.
11 12
 *
 * @internal
13
 */
14
class BlockContentForm extends ContentEntityForm {
15

16 17 18 19 20 21 22
  /**
   * The block content entity.
   *
   * @var \Drupal\block_content\BlockContentInterface
   */
  protected $entity;

23
  /**
24
   * {@inheritdoc}
25
   */
26
  public function form(array $form, FormStateInterface $form_state) {
27
    $block = $this->entity;
28 29

    $form = parent::form($form, $form_state);
30 31

    if ($this->operation == 'edit') {
32
      $form['#title'] = $this->t('Edit custom block %label', ['%label' => $block->label()]);
33
    }
34 35 36
    // Override the default CSS class name, since the user-defined custom block
    // type name in 'TYPE-block-form' potentially clashes with third-party class
    // names.
37
    $form['#attributes']['class'][0] = 'block-' . Html::getClass($block->bundle()) . '-form';
38

39
    return $form;
40 41 42
  }

  /**
43
   * {@inheritdoc}
44
   */
45 46
  public function save(array $form, FormStateInterface $form_state) {
    $block = $this->entity;
47

48
    $insert = $block->isNew();
49
    $block->save();
50
    $context = ['@type' => $block->bundle(), '%info' => $block->label()];
51
    $logger = $this->logger('block_content');
52
    $block_type = $this->getBundleEntity();
53
    $t_args = ['@type' => $block_type->label(), '%info' => $block->label()];
54 55

    if ($insert) {
56
      $logger->notice('@type: added %info.', $context);
57
      $this->messenger()->addStatus($this->t('@type %info has been created.', $t_args));
58 59
    }
    else {
60
      $logger->notice('@type: updated %info.', $context);
61
      $this->messenger()->addStatus($this->t('@type %info has been updated.', $t_args));
62 63
    }

64
    if ($block->id()) {
65
      $form_state->setValue('id', $block->id());
66
      $form_state->set('id', $block->id());
67
      if ($insert) {
68 69
        if (!$theme = $block->getTheme()) {
          $theme = $this->config('system.theme')->get('default');
70
        }
71 72
        $form_state->setRedirect(
          'block.admin_add',
73
          [
74
            'plugin_id' => 'block_content:' . $block->uuid(),
75
            'theme' => $theme,
76
          ]
77
        );
78 79
      }
      else {
80
        $form_state->setRedirectUrl($block->urlInfo('collection'));
81 82 83 84 85
      }
    }
    else {
      // In the unlikely case something went wrong on save, the block will be
      // rebuilt and block form redisplayed.
86
      $this->messenger()->addError($this->t('The block could not be saved.'));
87
      $form_state->setRebuild();
88 89 90 91
    }
  }

}