vendor/nambu-private/pimcore-form/src/FormBundle/Service/ObjectFormHandler.php line 42

Open in your IDE?
  1. <?php
  2. namespace FormBundle\Service;
  3. use FormBundle\Event\FormBundleEvents;
  4. use Pimcore\Log\Simple;
  5. use Pimcore\Model\DataObject;
  6. use Pimcore\Translation\Translator;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Symfony\Component\DependencyInjection\ServiceLocator;
  9. use Symfony\Component\EventDispatcher\GenericEvent;
  10. use Symfony\Component\Form;
  11. use Symfony\Component\Form\Extension\Core\Type;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  14. class ObjectFormHandler {
  15.     private $successMessage;
  16.     private $failMessage;
  17.     private $invalidMessage;
  18.     protected Translator $translator;
  19.     protected ContainerInterface $container;
  20.     protected ObjectFormService $formService;
  21.     protected Form\FormBuilderInterface $builder;
  22.     protected Form\FormFactoryInterface $formfactory;
  23.     private $disableTranslation false;
  24.     private DataObject\Concrete $object;
  25.     private $submitted false;
  26.     private $success false;
  27.     private Form\Form $form;
  28.     private $formview;
  29.     private array $formOptions = [];
  30.     private Request $request;
  31.     public function __construct(ContainerInterface $container) {
  32.         $this->container $container;
  33.         $this->formService $this->container->get('form.formservice');
  34.         $this->formfactory $this->container->get('form.factory');
  35.         $this->translator $this->container->get("translator");
  36.         $this->successMessage $this->translator->trans("form.submit.success");
  37.         $this->failMessage $this->translator->trans("form.submit.error");
  38.         $this->invalidMessage $this->translator->trans("form.submit.error.invalid");
  39.     }
  40.     public function setRequest(Request $request) {
  41.         $this->request $request;
  42.     }
  43.     public function disableTranslation() {
  44.         $this->disableTranslation true;
  45.     }
  46.     /**
  47.      * @var DataObject\Concrete $object  = null Insert object to save if not already provided in constructor
  48.      * @var array               $options = []
  49.      */
  50.     public function createForm(DataObject\Concrete $object null, array $options = []) {
  51.         $eventSuffix = (isset($options["eventSuffix"]) ? ".".$options["eventSuffix"] : '');
  52.         $customLayoutId $options["customLayoutId"] ?? null;
  53.         $this->object $object;
  54.         $formAttr = ["enctype" => "multipart/form-data"];
  55.         if (isset($options["formAttrs"]) && is_array($options["formAttrs"])) {
  56.             $formAttr array_merge($options["formAttrs"], $formAttr);
  57.         }
  58.         $object->setValues($_REQUEST);
  59.         $hasTranslation = !$this->disableTranslation && count(\Pimcore\Tool::getValidLanguages()) > 1;
  60.         $config = [
  61.             "method"             => "POST",
  62.             "attr"               => $formAttr,
  63.             "translation_domain" => $hasTranslation || array_key_exists("translationDomain"$options) ? ($options["translationDomain"] ?? 'messages') : false,
  64.             "allow_extra_fields" => true,
  65.         ];
  66.         if (isset($options["action"])) {
  67.             $config["action"] = $options["action"];
  68.         } else {
  69.             $config["action"] = $this->request->getPathInfo();
  70.         }
  71.         $this->builder $this->formfactory->createBuilder(Type\FormType::class, $object$config);
  72.         $this->form $this->formService->getForm($this->builder$customLayoutId);
  73.         $this->form->handleRequest($this->request);
  74.         if (strtolower($object->getClassName()) == strtolower($_POST["form_id"] ?? "-")) {
  75.             if ($this->form->isSubmitted()) {
  76.                 $eventData = new GenericEvent($object, [
  77.                     "request"     => $this->request,
  78.                     "formHandler" => $this,
  79.                 ]);
  80.                 \Pimcore::getEventDispatcher()->dispatch(
  81.                     $eventData,
  82.                     FormBundleEvents::REQUESTLISTENER_VALIDATION_EVENT.$eventSuffix
  83.                 );
  84.                 if (array_key_exists("validationEvent"$options)) {
  85.                     \Pimcore::getEventDispatcher()->dispatch(
  86.                         $eventData,
  87.                         $options["validationEvent"]
  88.                     );
  89.                 }
  90.                 $this->formService->validateFields($object$this->form);
  91.                 if (method_exists($this->object"validateForm")) {
  92.                     $this->object->validateForm($this->form$this->container);
  93.                 }
  94.             }
  95.         }
  96.         $this->formview $this->form->createView();
  97.         $this->formview->customLayoutId $customLayoutId;
  98.     }
  99.     public function handleRequest($addSuccessMessage true) {
  100.         /** @var $bag FlashBag */
  101.         $bag $this->container->get('session')->getFlashBag();
  102.         if ($this->form->isSubmitted()) {
  103.             $this->submitted true;
  104.             if ($this->form->isValid()) {
  105.                 try {
  106.                     $this->object->save();
  107.                     if ($addSuccessMessage && $this->successMessage) {
  108.                         $bag->add("success"$this->successMessage);
  109.                     }
  110.                     $this->success true;
  111.                 } catch (\Exception $e) {
  112.                     $this->success false;
  113.                     $bag->add("error"$this->invalidMessage);
  114.                     if (\Pimcore::inDebugMode()) {
  115.                         $bag->add("error"$e->getMessage());
  116.                     }
  117.                     if (stripos($e->getMessage(), "fieldname=") !== false) {
  118.                         $m = [];
  119.                         preg_match('/(.+)\sfieldname=(.+)/'$e->getMessage(), $m);
  120.                         $this->addFormError($m[2], $m[1]);
  121. //                    } else {
  122. //                        $this->addFormError("General", $e->getMessage());
  123.                     }
  124.                     if (\Pimcore::inDebugMode()) {
  125.                         $this->form->addError(new Form\FormError($e->getMessage()));
  126.                     }
  127. //                    Simple::log(date("Ym")."-WebFormularError", $e->getMessage().PHP_EOL.$e->getTraceAsString());
  128.                 }
  129.             } else {
  130.                 if (!$this->request || !$this->request->isXmlHttpRequest()) {
  131.                     $bag->add("error"$this->failMessage);
  132.                     if (\Pimcore::inDebugMode()) {
  133.                         $debugMessage = ['<strong>Only Visible in Debugmode:</strong>'];
  134.                         foreach ($this->getFormErrors() as $error) {
  135.                             $debugMessage[] = $error->getOrigin()->getName().": ".$error->getMessage();
  136.                         }
  137.                         $bag->add("warning"join("<br/>"$debugMessage));
  138.                     }
  139.                 }
  140.             }
  141.         }
  142.     }
  143.     public function getFormOptions(): array {
  144.         return $this->formOptions;
  145.     }
  146.     public function getObject() {
  147.         return $this->object;
  148.     }
  149.     public function getContainer() {
  150.         return $this->container;
  151.     }
  152.     public function getForm(): Form\FormView {
  153.         return $this->formview;
  154.     }
  155.     public function getSymfonyForm(): Form\FormInterface {
  156.         return $this->form;
  157.     }
  158.     public function addFormError($fieldName$message null) {
  159.         if (empty($message)) {
  160.             $message $this->translator->trans("form.validation.fieldempty");
  161.         }
  162.         if ($this->form == null) {
  163.             var_dump($message);
  164.             return;
  165.         }
  166.         if ($this->form->get($fieldName) == null) {
  167.             $this->form->addError(new Form\FormError($message." (".$fieldName.")"));
  168.         }
  169.         return $this->form->get($fieldName)->addError(new Form\FormError($message));
  170.     }
  171.     public function getFormErrors(): Form\FormErrorIterator {
  172.         return $this->form->getErrors(true);
  173.     }
  174.     public function isSuccess() {
  175.         return $this->success;
  176.     }
  177.     public function isSubmitted() {
  178.         return $this->form->isSubmitted();
  179.     }
  180. }