BlockContentForm.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Drupal\block_content;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Core\Entity\ContentEntityForm;
  5. use Drupal\Core\Form\FormStateInterface;
  6. /**
  7. * Form handler for the custom block edit forms.
  8. *
  9. * @internal
  10. */
  11. class BlockContentForm extends ContentEntityForm {
  12. /**
  13. * The block content entity.
  14. *
  15. * @var \Drupal\block_content\BlockContentInterface
  16. */
  17. protected $entity;
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function form(array $form, FormStateInterface $form_state) {
  22. $block = $this->entity;
  23. $form = parent::form($form, $form_state);
  24. if ($this->operation == 'edit') {
  25. $form['#title'] = $this->t('Edit custom block %label', ['%label' => $block->label()]);
  26. }
  27. // Override the default CSS class name, since the user-defined custom block
  28. // type name in 'TYPE-block-form' potentially clashes with third-party class
  29. // names.
  30. $form['#attributes']['class'][0] = 'block-' . Html::getClass($block->bundle()) . '-form';
  31. return $form;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function save(array $form, FormStateInterface $form_state) {
  37. $block = $this->entity;
  38. $insert = $block->isNew();
  39. $block->save();
  40. $context = ['@type' => $block->bundle(), '%info' => $block->label()];
  41. $logger = $this->logger('block_content');
  42. $block_type = $this->getBundleEntity();
  43. $t_args = ['@type' => $block_type->label(), '%info' => $block->label()];
  44. if ($insert) {
  45. $logger->notice('@type: added %info.', $context);
  46. $this->messenger()->addStatus($this->t('@type %info has been created.', $t_args));
  47. }
  48. else {
  49. $logger->notice('@type: updated %info.', $context);
  50. $this->messenger()->addStatus($this->t('@type %info has been updated.', $t_args));
  51. }
  52. if ($block->id()) {
  53. $form_state->setValue('id', $block->id());
  54. $form_state->set('id', $block->id());
  55. if ($insert) {
  56. if (!$theme = $block->getTheme()) {
  57. $theme = $this->config('system.theme')->get('default');
  58. }
  59. $form_state->setRedirect(
  60. 'block.admin_add',
  61. [
  62. 'plugin_id' => 'block_content:' . $block->uuid(),
  63. 'theme' => $theme,
  64. ]
  65. );
  66. }
  67. else {
  68. $form_state->setRedirectUrl($block->urlInfo('collection'));
  69. }
  70. }
  71. else {
  72. // In the unlikely case something went wrong on save, the block will be
  73. // rebuilt and block form redisplayed.
  74. $this->messenger()->addError($this->t('The block could not be saved.'));
  75. $form_state->setRebuild();
  76. }
  77. }
  78. }