如何在sonata admin Admin Controller中设置flash消息

Las*_*ith 8 php admin symfony flash-message sonata-admin

我正在寻找一种在sonata管理包的管理控制器中设置flash消息的方法,它们允许在CRUDController中设置flash消息

$this->get('session')->setFlash('sonata_flash_error', 'flash_batch_merge_error');
Run Code Online (Sandbox Code Playgroud)

但不在管理控制器中,

这是我的管理员控制器

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;

class ConfigAdmin extends Admin
{

protected function configureFormFields(FormMapper $formMapper)
{   

    $formMapper
        ->with('System Settings')
            ->add('Name','text', array('label' => "Configuration Name"))
            ->add('Language', 'choice', array(
                'label' => 'System Language',
                'choices' => array(0 => 'English', 1 => 'Swedish'),
                'preferred_choices' => array(0),
                ))
            ->add('commonmail','text', array('label' => "Common e-Mail"))
            ->add('dateformat','text', array('label' => "Date format"))
            ->add('currencyformat','text', array('label' => "Currency format"))
        ->end()
}

public function postUpdate($object) {

      // here i need to perform some validations and set flash message if there is an errror 

}

}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Gui*_*rez 16

是的,您可以在管理类中设置Flash消息.首先,您可以为SonataCoreBundle定义自定义Flash消息类型.例如,如果您想要成功的flash消息类型,请在app/config/config.yml文件中添加:

sonata_core:
    flashmessage:
        success:
            types:
                - { type: mytodo_success, domain: MyToDoBundle }
Run Code Online (Sandbox Code Playgroud)

然后,您需要知道何时设置消息.例如,如果要在创建新实体后设置消息,可以覆盖postPersist管理类中的功能,并在Symfony闪存包中添加消息:

public function postPersist($object) {
    $this->getRequest()->getSession()->getFlashBag()->add("mytodo_success", "My To-Do custom success message");
}
Run Code Online (Sandbox Code Playgroud)

这样,只要在admin类中创建新实体,就会显示该消息.

您还可以使用默认类型成功:

public function postPersist($object) {
    $this->getRequest()->getSession()->getFlashBag()->add("success", "My To-Do custom success message");
}
Run Code Online (Sandbox Code Playgroud)

  • 奏鸣曲似乎支持"成功","警告"和"错误"类型 (4认同)

Bab*_*aga 3

您正在谈论管理类,而不是控制器。

默认情况下这是不可能的。最好的方法是编写一个自定义 CRUDController(从默认的 CRUDController 扩展)并在那里处理它。

  • 不应该被接受的错误答案:如其他答案中所述,您可以注入会话服务以在任何可以注入服务的类中使用 flashbag,包括 Sonata 管理类。 (9认同)