Submit a form.

In case you would like to perform actions after the post is stored in the database,
you could create an EventListener that listens to the `Events::POST_FORM_SUBMIT` event.

@param Request $request
@param int     $id

@return Response
198989
public function submitAction(Request $request, $id)
    {
        $form = $this->get('opifer.form.form_manager')->getRepository()->find($id);

        if (!$form) {
            throw $this->createNotFoundException('The form could not be found');
        }

        $post = $this->get('opifer.eav.eav_manager')->initializeEntity($form->getSchema());
        $post->setForm($form);

        $postForm = $this->createForm(PostType::class, $post, ['form_id' => $id]);
        $postForm->handleRequest($request);

        if ($postForm->isSubmitted() && $postForm->isValid()) {
            $this->get('opifer.form.post_manager')->save($post);

            $event = new FormSubmitEvent($post);
            $this->get('event_dispatcher')->dispatch(Events::POST_FORM_SUBMIT, $event);
            
            if ($form->getRedirectUrl()) {
                return $this->redirect($form->getRedirectUrl());
            }
        }

        return $this->redirect($request->headers->get('referer'));
    }
248526
public function editAction(Request $request, $id)
    {
        $this->checkIfUserHasPermission(Permission::EDIT);

        list($parentEntity) = $this->getParentEntityDefinition($request);

        $entity = $this->getEntity($id);

        $entityBefore = clone $entity;

        $this->getEventDispatcher()->dispatch(
            Events::PRE_CRUD_CONTROLLER_ACTION,
            new CrudControllerActionEvent($this->meta, __FUNCTION__)
        );

        $form = $this->getAdminFormFactory()->createEntityForm(
            $this->meta,
            $entity,
            'edit',
            $this->getAdminRouter()->generate($entity, $this->entityClass, AdminRouter::TYPE_EDIT),
            $this->getEntityFormSubmitButtons()
        )->handleRequest($request);

        if ($this->getFormHandler()->handleEntityForm($form, 'action.edit.success')) {
            $this->getEventDispatcher()->dispatch(CrudEvents::UPDATED, new UpdatedEvent($this->getUser(), $entityBefore, $entity));

            return $this->successRedirect($form, $entity);
        }

        return $this->renderResponse('edit', [
            'entity'        => $entity,
            'form'          => $form->createView(),
            'meta'          => $this->meta,
            'parent_entity' => $parentEntity,
        ]);
    }
550047
public function updateAction(Request $request, $id)
    {
        $title = $request->get('title');
        $rawCriteria = json_decode($request->get('criteria'), true);

        $filterManager = $this->get('phlexible_message.filter_manager');

        $filter = $filterManager->find($id);
        $filter->setTitle($title);

        $criteria = new Criteria();
        $criteria->setMode(Criteria::MODE_OR);
        foreach ($rawCriteria as $group) {
            $criteriaGroup = new Criteria();
            $criteriaGroup->setMode(Criteria::MODE_AND);
            foreach ($group as $row) {
                if (!strlen($row['value'])) {
                    continue;
                }

                $criterium = new Criterium($row['key'], $row['value']);
                $criteriaGroup->add($criterium);
            }
            if ($criteriaGroup->count()) {
                $criteria->addCriteria($criteriaGroup);
            }
        }
        $filter->setCriteria($criteria);

        $filterManager->updateFilter($filter);

        return new ResultResponse(true, 'Filter updated');
    }
1218410
public function putAction(Request $request, $id)
    {
        try {
            $this->checkArguments($request);
            $locale = $this->getRequestParameter($request, 'locale', true);
            $user = $this->getUserManager()->save($request->request->all(), $locale, $id);
            $view = $this->view($user, 200);
        } catch (EntityNotFoundException $exc) {
            $view = $this->view($exc->toArray(), 404);
        } catch (UsernameNotUniqueException $exc) {
            $view = $this->view($exc->toArray(), 409);
        } catch (EmailNotUniqueException $exc) {
            $view = $this->view($exc->toArray(), 409);
        } catch (RestException $exc) {
            $view = $this->view($exc->toArray(), 400);
        }

        $this->addSerializationGroups($view);

        return $this->handleView($view);
    }
1034350
public function deleteAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $submission = $em->getRepository('KunstmaanFormBundle:FormSubmission')->find($id);

        $node = $em->getRepository('KunstmaanNodeBundle:Node')->find($submission->getNode());
        $nt = $node->getNodeTranslation($request->getLocale());

        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_DELETE, $node);

        $url = $this->get('router')->generate(
            'KunstmaanFormBundle_formsubmissions_list',
            ['nodeTranslationId' => $nt->getId()]
        );

        $fields = $em->getRepository('KunstmaanFormBundle:FormSubmissionField')->findBy(['formSubmission' => $submission]);

        try {
            foreach ($fields as $field) {
                $em->remove($field);
            }

            $em->remove($submission);
            $em->flush();

            $this->addFlash(
                FlashTypes::SUCCESS,
                $this->get('translator')->trans('formsubmissions.delete.flash.success')
            );
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());
            $this->addFlash(
                FlashTypes::ERROR,
                $this->get('translator')->trans('formsubmissions.delete.flash.error')
            );
        }

        $response = new RedirectResponse($url);

        return $response;
    }
1132373
public function putAction(Request $request, $id)
    {
        $locale = $this->getProductLocaleManager()->retrieveLocale($this->getUser(), $request->get('locale'));

        try {
            $attribute = $this->getManager()->save(
                $request->request->all(),
                $locale,
                $this->getUser()->getId(),
                $id
            );
            $view = $this->view($attribute, 200);
        } catch (AttributeDependencyNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 400);
        } catch (AttributeNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 404);
        } catch (MissingAttributeException $exc) {
            $exception = new MissingArgumentException(self::$entityName, $exc->getAttribute());
            $view = $this->view($exception->toArray(), 400);
        }

        return $this->handleView($view);
    }
592345
public function publishAction(Request $request, $id = null)
    {
        $id = $request->get($this->admin->getIdParameter());

        $object = $this->admin->getObject($id);

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('PUBLISH', $object)) {
            throw new AccessDeniedException();
        }

        $this->admin->setSubject($object);

        $form = $this->admin->getForm();

        $object->setStatus(PageInterface::STATUS_PUBLISHED);

        // persist if the form was valid and if in preview mode the preview was approved
        $this->admin->update($object);

        if ($object->getStatus() == PageInterface::STATUS_PUBLISHED) {
            $this->makeSnapshot($object);
        }

        $request->getSession()->getFlashBag()->add(
            'sonata_flash_success',
            $this->translate('flash_publish_success')
        );

        return $this->redirect($this->admin->generateObjectUrl('edit', $object));
    }
549349
public function postEdit(PostRequest $request, $id)
    {
        $command = new EditPostCommand($request->all());

        try 
        {
            $this->bus->execute($command);
        }
        catch(ValidationException $e)
        {
            return Redirect::to(\OogleeBConfig::get('laravelblog::routes.base_uri_admin').'/post/{$id}/edit')->withErrors($e->getErrors());
        }
        catch(\DomainException $e)
        {
            return Redirect::to(\OogleeBConfig::get('laravelblog::routes.base_uri_admin').'/post/{$id}/edit')->withErrors($e->getErrors());
        }

        return Redirect::to(\OogleeBConfig::get('laravelblog::routes.base_uri_admin').'/posts')->with(['message' => 'success!']);
    }
963392
public function crudUpdate(Request $request, $id)
    {
        try{
            $entity = $this->throwEntityNotFoundException($this->getRepository()->find($id));

            $form = $this->createForm($this->getEntityType(), $entity);
            $form->submit($request);
            
            $page = static::EDIT_VIEW;
            
            if ($form->isValid()) {
                $page = static::SHOW_VIEW;
                $this->saveEntity($entity);
                $form = $this->createDeleteForm($id)->createView();
                return $this->render($page, $this->commonsResponseVars(compact('entity','form')));
            }
            
            $form = $form->createView();
            $delete_form = $this->createDeleteForm($id)->createView();
            return $this->success($page, $this->commonsResponseVars(compact('entity','form','delete_form')));
            
        }catch(\Exception $e){
            return $this->failure($e);
        }
    }
1071163
public function deleteAction(Request $request, $id)
    {
        $this->checkIfUserHasPermission(Permission::CREATE_DELETE);

        $this->getParentEntityDefinition($request);

        $entity = $this->getEntity($id);

        $this->getEventDispatcher()->dispatch(
            Events::PRE_CRUD_CONTROLLER_ACTION,
            new CrudControllerActionEvent($this->meta, __FUNCTION__)
        );

        $form = $this->getAdminFormFactory()->createDeleteForm($entity, $this->entityClass)->handleRequest($request);

        if ($this->getFormHandler()->handleDeleteForm($form, $entity)) {
            $this->getEventDispatcher()->dispatch(CrudEvents::DELETED, new DeletedEvent($this->getUser(), $entity));

            return $this->redirect($this->getAdminRouter()->generate($entity, $this->entityClass, AdminRouter::TYPE_INDEX));
        }

        $url = $request->headers->get(
            'referer',
            $this->getAdminRouter()->generate($entity, $this->entityClass, AdminRouter::TYPE_INDEX)
        );

        return $this->redirect($url);
    }
696407
public function update($id, Request $request)
    {
        $entity = $this->getEntityById($id);

        if (!$entity) {
            return $this->response(null, Response::HTTP_NOT_FOUND);
        }

        $params = $request->only($this->fillable);

        $result = $this->manager->update($entity, $params);

        if (!$result->ok()) {
            return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
        }

        return $this->response($this->serialize($result->getResource(), $request), Response::HTTP_OK);
    }
549804
public function postUpdate(ModelConfigurationInterface $model, Request $request, $id)
    {
        /** @var FormInterface $editForm */
        $editForm = $model->fireEdit($id);
        $item = $editForm->getModel();

        if (is_null($item) || ! $model->isEditable($item)) {
            abort(404);
        }

        $nextAction = $request->input('next_action');

        $backUrl = $this->getBackUrl($request);

        if ($editForm instanceof FormInterface) {
            try {
                $editForm->validateForm($request, $model);

                if ($editForm->saveForm($request, $model) === false) {
                    return redirect()->back()->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
                }
            } catch (ValidationException $exception) {
                return redirect()->back()
                    ->withErrors($exception->validator)
                    ->withInput()
                    ->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
            }
        }

        $redirectPolicy = $model->getRedirect();

        if ($nextAction == 'save_and_continue') {
            $response = redirect()->back()->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);

            if ($redirectPolicy->get('edit') == 'display') {
                $response = redirect()->to(
                    $model->getDisplayUrl()
                )->with([
                    '_redirectBack'       => $backUrl,
                    'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                ]);
            }
        } elseif ($nextAction == 'save_and_create') {
            $response = redirect()->to($model->getCreateUrl($request->except([
                '_redirectBack',
                '_token',
                'url',
                'next_action',
            ])))->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);
        } else {
            $response = redirect()->to($request->input('_redirectBack', $model->getDisplayUrl()));
        }

        return $response->with('success_message', $model->getMessageOnUpdate());
    }
432289
public function postAction($id, Request $request)
    {
        return $this->addMediaToEntity($this->getContactEntityName(), $id, $request->get('mediaId', ''));
    }
1161017
protected function handleWriteContext($request, $id = null)
    {
        $context = $id ? $this->getContext($id) : null;

        $form = $this->formFactory->createNamed(null, 'sonata_classification_api_form_context', $context, [
            'csrf_protection' => false,
        ]);

        FormHelper::removeFields($request->request->all(), $form);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $context = $form->getData();
            $this->contextManager->save($context);

            $context = new Context();
            $context->setGroups(['sonata_api_read']);

            $view = FOSRestView::create($context);
            $view->setContext($context);

            return $view;
        }

        return $form;
    }
413144
public function putAction(Request $request, $id)
    {
        $jsonData = $request->getContent();
        $data = json_decode($jsonData, true);

        // Id should be taken of request uri.
        $data['id'] = $id;

        $targetGroup = $this->deserializeData(json_encode($data));
        $targetGroup = $this->getTargetGroupRepository()->save($targetGroup);
        $this->getEntityManager()->flush();

        return $this->handleView($this->view($targetGroup));
    }
209835
public function editAction(Request $request, $id)
    {
        /** @var Config $data */
        $data = $this->manager->find($id);

        if (!$data) {
            throw $this->createNotFoundException();
        }

        try {
            $adapter = $this->registry->getAdapter($data->getAdapter());
        } catch (Exception $e) {
            throw $this->createNotFoundException('Not Found', $e);
        }

        $event = new GetResponseConfigEvent($data, $request);

        if ($this->dispatcher->dispatch(IntegratedChannelEvents::CONFIG_EDIT_REQUEST, $event)->getResponse()) {
            return $event->getResponse();
        }

        $form = $this->createEditForm($data, $adapter);
        $form->handleRequest($request);

        if ($form->get('actions')->getData() == 'cancel') {
            return $this->redirect($this->generateUrl('integrated_channel_config_index'));
        }

        if ($form->isSubmitted() && $form->isValid()) {
            $event = $this->dispatcher->dispatch(
                IntegratedChannelEvents::CONFIG_EDIT_SUBMITTED,
                new FormConfigEvent($data, $request, $form)
            );

            $this->manager->persist($data);

            if (!$response = $event->getResponse()) {
                if ($message = $this->getFlashMessage()) {
                    $message->success(sprintf('The changes to the config %s are saved', $data->getName()));
                }

                $response = $this->redirect($this->generateUrl('integrated_channel_config_index'));
            }

            $this->dispatcher->dispatch(
                IntegratedChannelEvents::CONFIG_EDIT_RESPONSE,
                new FilterResponseConfigEvent($data, $request, $response)
            );

            return $response;
        }

        return $this->render('IntegratedChannelBundle:Config:edit.html.twig', [
            'adapter' => $adapter,
            'data'    => $data,
            'form'    => $form->createView()
        ]);
    }
56408
public function update(Request $request, $id)
    {
        // Validate the form data
        $result = $this->validate($request, [
            'email' => 'required|email|max:255|unique:users,email,'.$id,
            'password' => 'nullable|confirmed|min:6',
        ]);

        // Assemble the updated attributes
        $attributes = [
            'email' => trim($request->get('email')),
            'first_name' => $request->get('first_name', null),
            'last_name' => $request->get('last_name', null)
        ];

        // Do we need to update the password as well?
        if ($request->has('password')) {
            $attributes['password'] = $request->get('password');
        }

        // Fetch the user object
        $user = $this->userRepository->findById($id);
        if (!$user) {
            if ($request->expectsJson()) {
                return response()->json("Invalid user.", 422);
            }
            session()->flash('error', 'Invalid user.');
            return redirect()->back()->withInput();
        }

        // Update the user
        $user = $this->userRepository->update($user, $attributes);

        // Update role assignments
        $roleIds = array_values($request->get('roles', []));
        $user->roles()->sync($roleIds);

        // All done
        if ($request->expectsJson()) {
            return response()->json(['user' => $user], 200);
        }

        session()->flash('success', "{$user->email} has been updated.");
        return redirect()->route('users.index');
    }