How to set flash message in sonata admin Admin Controller

Lasith picture Lasith · Jul 30, 2013 · Viewed 11.8k times · Source

im looking for a way to set flash message in admin controller of sonata admin bundle, they allow to set flash messages in CRUDController as

$this->get('session')->setFlash('sonata_flash_error', 'flash_batch_merge_error');

but not in the Admin Controller,

this is my admin contrller

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 

}

}

appreciate your help

Answer

Guillermo Gutiérrez picture Guillermo Gutiérrez · Mar 6, 2014

Yes, you can set a flash message in an admin class. First, you can define a custom flash message type for the SonataCoreBundle. For example, if you want a success flash message type, add this in the app/config/config.yml file:

sonata_core:
    flashmessage:
        success:
            types:
                - { type: mytodo_success, domain: MyToDoBundle }

Then, you need to know when to set the message. For example, if you want to set the message after creating a new entity, you can do so overriding the postPersist function in your admin class, and adding the message in the Symfony flash bag:

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

This way, the message will be displayed whenever you create a new entity at the admin class.

You can also use the default type success:

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