Save an inline edit form for a block

@param HTTPRequest $request
@return HTTPResponse|null JSON encoded string or null if an exception is thrown
@throws HTTPResponse_Exception
501509
public function apiSaveForm(HTTPRequest $request)
    {
        // Validate required input data
        if (!isset($this->urlParams['ID'])) {
            $this->jsonError(400);
            return null;
        }

        $data = Convert::json2array($request->getBody());
        if (empty($data)) {
            $this->jsonError(400);
            return null;
        }

        // Inject request body as request vars
        foreach ($data as $key => $value) {
            $request->offsetSet($key, $value);
        }

        // Check security token
        if (!SecurityToken::inst()->checkRequest($request)) {
            $this->jsonError(400);
            return null;
        }

        /** @var BaseElement $element */
        $element = BaseElement::get()->byID($this->urlParams['ID']);
        // Ensure the element can be edited by the current user
        if (!$element || !$element->canEdit()) {
            $this->jsonError(403);
            return null;
        }

        // Remove the pseudo namespaces that were added by the form factory
        $data = $this->removeNamespacesFromFields($data, $element->ID);

        try {
            $updated = false;

            $element->updateFromFormData($data);
            // Check if anything will actually be changed before writing
            if ($element->isChanged()) {
                $element->write();
                // Track changes so we can return to the client
                $updated = true;
            }
        } catch (Exception $ex) {
            Injector::inst()->get(LoggerInterface::class)->debug($ex->getMessage());

            $this->jsonError(500);
            return null;
        }

        $body = Convert::raw2json([
            'status' => 'success',
            'updated' => $updated,
        ]);
        return HTTPResponse::create($body)->addHeader('Content-Type', 'application/json');
    }
835973
public function fileEditorLinkForm($request = null)
    {
        // Get ID either from posted back value, or url parameter
        if (!$request) {
            $this->jsonError(400);
            return null;
        }
        $id = $request->param('ID');
        if (!$id) {
            $this->jsonError(400);
            return null;
        }
        return $this->getFileInsertForm($id);
    }
783356
public function edit(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {
            $connection = $request->get('conn', 'default');

            $manager = $this->manager();

            $variables = [
                'conn'        => $connection,
                'info'        => $manager->getInformation(),
                'connections' => $manager->getConnections(),
                'data'        => $manager->fetch($request->get('key')),
            ];

            if (empty($variables['data'])) {
                $view = 'laravel-admin-redis-manager::edit.nil';
            } else {
                $view = 'laravel-admin-redis-manager::edit.'.$variables['data']['type'];
            }

            $content->header('Redis manager');
            $content->description('Connections');
            $content->breadcrumb(
                ['text' => 'Redis manager', 'url' => route('redis-index', ['conn' => $connection])],
                ['text' => 'Edit']
            );
            $content->body(view($view, $variables));
        });
    }
96839
protected function generateResponseForRequest($request = null)
    {
        $leafClass = $this->getPresenterClassName();
        $leaf = new $leafClass();
        $leaf->itemIdentifier = $this->resourceIdentifier;

        $response = $leaf->generateResponse($request);

        if (is_string($response)) {
            $htmlResponse = new HtmlResponse($leaf);
            $htmlResponse->setContent($response);
            $response = $htmlResponse;
        }

        return $response;
    }
1176238
public function updateAction(Request $request)
    {
        $form = $this->buildForm(null, $this->find($action = 'update'));

        if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)
            && $this->submitForm($form, $request)->isValid()) {
            try {
                $this->getDomainManager()->update($form->getData());
            } catch (DomainException $e) {
                $this->processException($e);
            }
        }

        return $this->processAction($action, $form);
    }
901862
public function store(Request $request)
    {
        try {
            $blockType = $this->blockTypes->save($request);
        } catch (Exception $e) {
            return $this->handleException($e, trans('soda::errors.create', ['object' => trans('soda::terminology.block_type')]));
        }

        return redirect()->route('soda.block-types.edit', $blockType->getKey())->with('success', trans('soda::messages.created', ['object' => trans('soda::terminology.block_type')]));
    }
1119097
public function apiCreateFile(HTTPRequest $request)
    {
        $data = $request->postVars();

        // When creating new files, rename on conflict
        $upload = $this->getUpload();
        $upload->setReplaceFile(false);

        // CSRF check
        $token = SecurityToken::inst();
        if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
            $this->jsonError(400);
            return null;
        }

        // Check parent record
        /** @var Folder $parentRecord */
        $parentRecord = null;
        if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) {
            $parentRecord = Folder::get()->byID($data['ParentID']);
        }
        $data['Parent'] = $parentRecord;

        $tmpFile = $request->postVar('Upload');
        if (!$upload->validate($tmpFile)) {
            $errors = $upload->getErrors();
            $message = array_shift($errors);
            $this->jsonError(400, $message);
            return null;
        }

        // TODO Allow batch uploads
        $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name']));
        /** @var File $file */
        $file = Injector::inst()->create($fileClass);

        // check canCreate permissions
        if (!$file->canCreate(null, $data)) {
            $this->jsonError(
                403,
                _t(__CLASS__.'.CreatePermissionDenied', 'You do not have permission to add files')
            );
            return null;
        }

        $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/');
        if (!$uploadResult) {
            $this->jsonError(
                400,
                _t(__CLASS__.'.LoadIntoFileFailed', 'Failed to load file')
            );
            return null;
        }

        $file->ParentID = $parentRecord ? $parentRecord->ID : 0;
        $file->write();

        $result = [
            $this->getObjectFromData($file, false)
        ];

        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
681572
public function edit($request) {
        $controller=$this->getToplevelController();
        $form=$this->ItemEditForm($this->gridField, $request);
        
        
        return $controller->customise(array(
                                    'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())),
                                    'ItemEditForm'=>$form,
                                ))->renderWith($this->template);
    }
395662
public function edit(Request $request)
    {
        $post = $this->api('post.fetch', $request->route('post'))->get();

        event(new UserEditingPost($post));

        if ($post->trashed()) {
            return abort(404);
        }

        $this->authorize('edit', $post);

        $thread = $post->thread;
        $category = $post->thread->category;

        return view('forum::post.edit', compact('category', 'thread', 'post'));
    }
601770
public function savePositionAction(Request $request = null)
    {
        $this->admin->checkAccess('savePosition');

        try {
            $params = $request->get('disposition');

            if (!\is_array($params)) {
                throw new HttpException(400, 'wrong parameters');
            }

            $result = $this->get('sonata.page.block_interactor')->saveBlocksPosition($params, false);

            $status = 200;

            $pageAdmin = $this->get('sonata.page.admin.page');
            $pageAdmin->setRequest($request);
            $pageAdmin->update($pageAdmin->getSubject());
        } catch (HttpException $e) {
            $status = $e->getStatusCode();
            $result = [
                'exception' => \get_class($e),
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        } catch (\Exception $e) {
            $status = 500;
            $result = [
                'exception' => \get_class($e),
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        }

        $result = (true === $result) ? 'ok' : $result;

        return $this->renderJson(['result' => $result], $status);
    }
68962
public function layoutAction(Request $request)
    {
        $row = $this->findRowByRequest($request);

        $data = $request->request->get('data', []);

        try {
            $this->getEditor()->getLayoutAdapter()->updateRowLayout($row, $data);
        } catch (EditorExceptionInterface $e) {
            return $this->handleException($e);
        }

        $this->validate($row);
        $this->persist($row);

        $data = [
            'rows' => [$this->getViewBuilder()->buildRow($row)],
        ];

        return $this->buildResponse($data, self::SERIALIZE_LAYOUT);
    }
324552
public function createAction(Request $request): Response
    {
        $this->denyAccessUnlessGranted(new Attribute('section', 'edit'));
        $form = $this->formFactory->createSection(
            new SectionCreateData()
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            try {
                $sectionCreateStruct = $this->sectionCreateMapper->reverseMap($data);
                $section = $this->sectionService->createSection($sectionCreateStruct);

                $this->notificationHandler->success(
                    $this->translator->trans(
                        /** @Desc("Section '%name%' created.") */
                        'section.create.success',
                        ['%name%' => $section->name],
                        'section'
                    )
                );

                return new RedirectResponse($this->generateUrl('ezplatform.section.view', [
                    'sectionId' => $section->id,
                ]));
            } catch (Exception $e) {
                $this->notificationHandler->error($e->getMessage());
            }
        }

        return $this->render('@ezdesign/admin/section/create.html.twig', [
            'form_section_create' => $form->createView(),
        ]);
    }
375366
public function editInlineAction(Request $request, DataInterface $data)
    {
        $parameters = array_merge(
            $request->query->all(),
            [
                'familyCode' => $data->getFamilyCode(),
                'id' => $data->getId(),
            ]
        );

        return $this->redirectToAction('edit', $parameters);
    }
282793
public function suggest(HTTPRequest $request)
    {
        $responseBody = json_encode(
            ['items' => $this->getTags($request->getVar('term'))]
        );

        $response = HTTPResponse::create();
        $response->addHeader('Content-Type', 'application/json');
        $response->setBody($responseBody);

        return $response;
    }
197341
public function handle(HttpRequest $request)
    {
        $routeClass = Loader::load('route');

        $route = new $routeClass($this->route, $request->method());
        $controllerClassMethod = $route->resolve();
        if (false === $controllerClassMethod) {
            throw new Exception('Can\t resolve route.'); // TODO: Change to 404 response
        }

        $controllerClass = array_shift($controllerClassMethod);
        $controllerMethod = array_shift($controllerClassMethod);

        $controller = new $controllerClass($request);
        if (method_exists($controller, $controllerMethod)) {
            $output = call_user_func_array(array($controller, $controllerMethod), $route->get());
        } else {
            throw new ApplicationException(sprintf('Method "%s" doesn\'t exists in class "%s".', $method, $controllerClass)); // TODO: Change to 404 response
        }

        if ($request->isAjax()) {
            return json_encode($output);
        } else {
            return $output;
        }
    }
343974
protected static function supportsHTML(HTTPRequest $request = null)
    {
        // No HTML output in CLI
        if (Director::is_cli()) {
            return false;
        }

        // Get current request if registered
        if (!$request && Injector::inst()->has(HTTPRequest::class)) {
            $request = Injector::inst()->get(HTTPRequest::class);
        }
        if (!$request) {
            return false;
        }
        // Request must include text/html
        $accepted = $request->getAcceptMimetypes(false);

        // Explicit opt in
        if (in_array('text/html', $accepted)) {
            return true;
        };

        // Implicit opt-out
        if (in_array('application/json', $accepted)) {
            return false;
        }

        // Fallback to wildcard comparison
        if (in_array('*/*', $accepted)) {
            return true;
        }
        return false;
    }
802815
public function upload(HTTPRequest $request)
    {
        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // Protect against CSRF on destructive action
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $tmpfile = $request->postVar('Upload');

        // Check if the file has been uploaded into the temporary storage.
        if (!$tmpfile) {
            $return = [
                'error' => _t(
                    'SilverStripe\\AssetAdmin\\Forms\\UploadField.FIELDNOTSET',
                    'File information not found'
                )
            ];
        } else {
            $return = [
                'name' => $tmpfile['name'],
                'size' => $tmpfile['size'],
                'type' => $tmpfile['type'],
                'error' => $tmpfile['error']
            ];
        }

        if (!$return['error']) {
            // Get options for this import.
            $splitHeader = (int)$request->postVar('SplitHeader');
            $keepSource = (bool)$request->postVar('KeepSource');
            $chosenFolderID = (int)$request->postVar('ChosenFolderID');
            $publishPages = (bool)$request->postVar('PublishPages');
            $includeTOC = (bool)$request->postVar('IncludeTOC');

            // Process the document and write the page.
            $preservedDocument = null;
            if ($keepSource) {
                $preservedDocument = $this->preserveSourceDocument($tmpfile, $chosenFolderID);
            }

            $importResult = $this->importFromPOST($tmpfile, $splitHeader, $publishPages, $chosenFolderID);
            if (is_array($importResult) && isset($importResult['error'])) {
                $return['error'] = $importResult['error'];
            } elseif ($includeTOC) {
                $this->writeTOC($publishPages, $keepSource ? $preservedDocument : null);
            }
        }

        $response = HTTPResponse::create(Convert::raw2json([$return]));
        $response->addHeader('Content-Type', 'application/json');
        return $response;
    }