簡體   English   中英

Symfony 4替代Sonata Admin CRUD控制器

[英]Symfony 4 override Sonata Admin CRUD Controller

我在覆蓋Symfony 4上的Sonata Admin的editAction時遇到問題。我的問題是,我有此界面用於編輯帖子,如您所見,這是兩個圖片:

每次管理員更改內容格式化程序后,它都會更改,並且更改將保存在mysql中

但是當您嘗試再次編輯帖子時,默認情況下,管理員總是選擇“文本”

我想使默認選擇的選項成為保存在MySQL中的選項。 例如,如果管理員將其更改為rawhtml ,那么下次他要編輯此帖子時,他應該找到默認情況下選中的rawhtml (而不是圖像中的文本)。

這是Sonata editAction方法:

public function editAction($id = null)
{
    $request = $this->getRequest();
    // the key used to lookup the template
    $templateKey = 'edit';

    $id = $request->get($this->admin->getIdParameter());
    $existingObject = $this->admin->getObject($id);

    if (!$existingObject) {
        throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
    }

    $this->checkParentChildAssociation($request, $existingObject);

    $this->admin->checkAccess('edit', $existingObject);

    $preResponse = $this->preEdit($request, $existingObject);
    if (null !== $preResponse) {
        return $preResponse;
    }

    $this->admin->setSubject($existingObject);
    $objectId = $this->admin->getNormalizedIdentifier($existingObject);

    /** @var $form Form */
    $form = $this->admin->getForm();
    $form->setData($existingObject);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        $isFormValid = $form->isValid();

        // persist if the form was valid and if in preview mode the preview was approved
        if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
            $submittedObject = $form->getData();
            $this->admin->setSubject($submittedObject);

            try {
                $existingObject = $this->admin->update($submittedObject);

                if ($this->isXmlHttpRequest()) {
                    return $this->renderJson([
                        'result' => 'ok',
                        'objectId' => $objectId,
                        'objectName' => $this->escapeHtml($this->admin->toString($existingObject)),
                    ], 200, []);
                }

                $this->addFlash(
                    'sonata_flash_success',
                    $this->trans(
                        'flash_edit_success',
                        ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                        'SonataAdminBundle'
                    )
                );

                // redirect to edit mode
                return $this->redirectTo($existingObject);
            } catch (ModelManagerException $e) {
                $this->handleModelManagerException($e);

                $isFormValid = false;
            } catch (LockException $e) {
                $this->addFlash('sonata_flash_error', $this->trans('flash_lock_error', [
                    '%name%' => $this->escapeHtml($this->admin->toString($existingObject)),
                    '%link_start%' => '<a href="'.$this->admin->generateObjectUrl('edit', $existingObject).'">',
                    '%link_end%' => '</a>',
                ], 'SonataAdminBundle'));
            }
        }

        // show an error message if the form failed validation
        if (!$isFormValid) {
            if (!$this->isXmlHttpRequest()) {
                $this->addFlash(
                    'sonata_flash_error',
                    $this->trans(
                        'flash_edit_error',
                        ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                        'SonataAdminBundle'
                    )
                );
            }
        } elseif ($this->isPreviewRequested()) {
            // enable the preview template if the form was valid and preview was requested
            $templateKey = 'preview';
            $this->admin->getShow();
        }
    }

    $formView = $form->createView();
    // set the theme for the current Admin Form
    $this->setFormTheme($formView, $this->admin->getFormTheme());

    // NEXT_MAJOR: Remove this line and use commented line below it instead
    $template = $this->admin->getTemplate($templateKey);
    // $template = $this->templateRegistry->getTemplate($templateKey);

    return $this->renderWithExtraParams($template, [
        'action' => 'edit',
        'form' => $formView,
        'object' => $existingObject,
        'objectId' => $objectId,
    ], null);
}

這是我用於PostAdmin的configureFormFields方法:

        $isHorizontal = 'horizontal' == $this->getConfigurationPool()->getOption('form_type');
    $formMapper
        ->with('group_post', [
            'class' => 'col-md-8',
        ])
        ->add('author', ModelListType::class)
        ->add('title')
        ->add('abstract', TextareaType::class, [
            'attr' => ['rows' => 5],
        ])
        ->add('content', FormatterType::class, [
            'event_dispatcher' => $formMapper->getFormBuilder()->getEventDispatcher(),
            'format_field' => 'contentFormatter',
            'source_field' => 'rawContent',
            'source_field_options' => [
                'horizontal_input_wrapper_class' => $isHorizontal ? 'col-lg-12' : '',
                'attr' => ['class' => $isHorizontal ? 'span10 col-sm-10 col-md-10' : '', 'rows' => 20],
            ],
            'ckeditor_context' => 'news',
            'target_field' => 'content',
            'listener' => true,
        ])
        ->end()
        ->with('group_status', [
            'class' => 'col-md-4',
        ])
        ->add('enabled', CheckboxType::class, ['required' => false])
        ->add('image', ModelListType::class, ['required' => false], [
            'link_parameters' => [
                'context' => 'news',
                'hide_context' => true,
            ],
        ])

        ->add('publicationDateStart', DateTimePickerType::class, [
            'dp_side_by_side' => true,
        ])
        ->add('commentsCloseAt', DateTimePickerType::class, [
            'dp_side_by_side' => true,
            'required' => false,
        ])
        ->add('commentsEnabled', CheckboxType::class, [
            'required' => false,
        ])
        ->add('commentsDefaultStatus', CommentStatusType::class, [
            'expanded' => true,
        ])
        ->end()

        ->with('group_classification', [
            'class' => 'col-md-4',
        ])
        ->add('tags', ModelAutocompleteType::class, [
            'property' => 'name',
            'multiple' => 'true',
            'required' => false,
        ])
        ->add('collection', ModelListType::class, [
            'required' => false,
        ])->end();
    $options = $formMapper->get('content')->get('contentFormatter')->getOptions();
    $options = array_merge($options,array('choices'=>array('markdown'=>'markdown','text'=>'text','rawhtml'=>'rawhtml','richhtml'=>'richhtml')));
    $rawcontent = $formMapper->get('content')->get('rawContent');
    $formMapper->get('content')->remove('contentFormatter')->remove('rawContent')->add('contentFormatter',ChoiceType::class,$options)->add($rawcontent);

它仍然不采用默認的選定值。 無論如何,有沒有強迫它把mysql的真實值當作'數據'? 我找不到應該在哪里編輯表單以從對象獲取默認選定值的地方。 請您幫助我,我將非常高興。 我對Sonata捆綁包和表單管理不熟悉。

我認為根本不需要修改editAction或控制器。

我想使默認選擇的選項成為保存在MySQL中的選項。

這是一個經典用例,用於將值從表單保存回模型並在下次編輯時顯示。

相反,您應該修改您的管理類

我不知道您的模型,但例如在您的管理員configureFormFields方法中:

$formMapper->add('contentFormatter', 'choice', ['choices' => ['Text' => 'text', 'Raw HTML' => 'rawHtml']]);

因此,選擇的格式為“顯示值=>實體的值”。

因此,如果您來自實體的值返回“ rawHtml”,則表單將選擇“原始HTML”。 如果這不起作用,則說明您的管理員配置有誤。 仔細檢查從您的實體對象返回什么值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM