jsonFactory = $jsonFactory; $this->topicFactory = $topicFactory; parent::__construct($context); } /** * @return ResultInterface */ public function execute() { /** @var Json $resultJson */ $resultJson = $this->jsonFactory->create(); $error = false; $messages = []; $postItems = $this->getRequest()->getParam('items', []); if (!($this->getRequest()->getParam('isAjax') && !empty($postItems))) { return $resultJson->setData([ 'messages' => [__('Please correct the data sent.')], 'error' => true, ]); } $key = array_keys($postItems); $topicId = !empty($key) ? (int)$key[0] : ''; /** @var Topic $topic */ $topic = $this->topicFactory->create()->load($topicId); try { $topic->addData($postItems[$topicId]) ->save(); } catch (LocalizedException $e) { $messages[] = $this->getErrorWithTopicId($topic, $e->getMessage()); $error = true; } catch (RuntimeException $e) { $messages[] = $this->getErrorWithTopicId($topic, $e->getMessage()); $error = true; } catch (Exception $e) { $messages[] = $this->getErrorWithTopicId( $topic, __('Something went wrong while saving the Topic.') ); $error = true; } return $resultJson->setData([ 'messages' => $messages, 'error' => $error ]); } /** * Add Topic id to error message * * @param Topic $topic * @param string $errorText * * @return string */ public function getErrorWithTopicId(Topic $topic, $errorText) { return '[Topic ID: ' . $topic->getId() . '] ' . $errorText; } }