InlineEdit.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Cms\Controller\Adminhtml\Block;
  7. use Magento\Backend\App\Action\Context;
  8. use Magento\Cms\Api\BlockRepositoryInterface as BlockRepository;
  9. use Magento\Framework\Controller\Result\JsonFactory;
  10. use Magento\Cms\Api\Data\BlockInterface;
  11. class InlineEdit extends \Magento\Backend\App\Action
  12. {
  13. /**
  14. * Authorization level of a basic admin session
  15. *
  16. * @see _isAllowed()
  17. */
  18. const ADMIN_RESOURCE = 'Magento_Cms::block';
  19. /**
  20. * @var \Magento\Cms\Api\BlockRepositoryInterface
  21. */
  22. protected $blockRepository;
  23. /**
  24. * @var \Magento\Framework\Controller\Result\JsonFactory
  25. */
  26. protected $jsonFactory;
  27. /**
  28. * @param Context $context
  29. * @param BlockRepository $blockRepository
  30. * @param JsonFactory $jsonFactory
  31. */
  32. public function __construct(
  33. Context $context,
  34. BlockRepository $blockRepository,
  35. JsonFactory $jsonFactory
  36. ) {
  37. parent::__construct($context);
  38. $this->blockRepository = $blockRepository;
  39. $this->jsonFactory = $jsonFactory;
  40. }
  41. /**
  42. * @return \Magento\Framework\Controller\ResultInterface
  43. * @throws \Magento\Framework\Exception\LocalizedException
  44. */
  45. public function execute()
  46. {
  47. /** @var \Magento\Framework\Controller\Result\Json $resultJson */
  48. $resultJson = $this->jsonFactory->create();
  49. $error = false;
  50. $messages = [];
  51. if ($this->getRequest()->getParam('isAjax')) {
  52. $postItems = $this->getRequest()->getParam('items', []);
  53. if (!count($postItems)) {
  54. $messages[] = __('Please correct the data sent.');
  55. $error = true;
  56. } else {
  57. foreach (array_keys($postItems) as $blockId) {
  58. /** @var \Magento\Cms\Model\Block $block */
  59. $block = $this->blockRepository->getById($blockId);
  60. try {
  61. $block->setData(array_merge($block->getData(), $postItems[$blockId]));
  62. $this->blockRepository->save($block);
  63. } catch (\Exception $e) {
  64. $messages[] = $this->getErrorWithBlockId(
  65. $block,
  66. __($e->getMessage())
  67. );
  68. $error = true;
  69. }
  70. }
  71. }
  72. }
  73. return $resultJson->setData([
  74. 'messages' => $messages,
  75. 'error' => $error
  76. ]);
  77. }
  78. /**
  79. * Add block title to error message
  80. *
  81. * @param BlockInterface $block
  82. * @param string $errorText
  83. * @return string
  84. */
  85. protected function getErrorWithBlockId(BlockInterface $block, $errorText)
  86. {
  87. return '[Block ID: ' . $block->getId() . '] ' . $errorText;
  88. }
  89. }