Skip to content

Instantly share code, notes, and snippets.

@ahmed-bhs
Last active March 31, 2018 22:07
Show Gist options
  • Save ahmed-bhs/81ea5bed4b16ebbe759133aaf756c487 to your computer and use it in GitHub Desktop.
Save ahmed-bhs/81ea5bed4b16ebbe759133aaf756c487 to your computer and use it in GitHub Desktop.
    /**
     * @param mixed  $entity
     * @param array  $parameters
     * @param string $method
     * @param array  $validationGroups
     *
     * @throws InvalidFormException
     *
     * @return mixed
     */
    protected function processForm($entity, array $parameters, $method = 'PUT', array $validationGroups = ['Default'])
    {
        $options = $this->mergeFormOptions([
            'method' => $method,
            'validation_groups' => $validationGroups,
        ]);

        $form = $this->formFactory->create($this->formType, $entity, $options);

        $form->submit($parameters, 'PATCH' !== $method);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->dispatchEvent($entity, 'success');

            if (null === $entity->getId()) {
                $this->dispatchEvent($entity, 'create');
                $this->om->persist($entity);
                $this->om->flush($entity);
                $this->dispatchEvent($entity, 'created');
            } else {
                $this->dispatchEvent($entity, 'update');
                $this->om->flush();
                $this->dispatchEvent($entity, 'updated');
            }

            $this->dispatchEvent($entity, 'completed');

            return $entity;
        }

        throw new InvalidFormException('Invalid submitted data', $form);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment