问题
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
回答1:
You are talking about an admin class, not a controller.
And this is not possible by default. Best way to do this is to write a custom CRUDController (extend from default one) and handle it there.
回答2:
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");
}
回答3:
Because it is an Admin class I get the flashbag over the Session service:
protected function whereever()
{
$this->getFlashBag()->add(
'info',
'Your message'
);
}
...
protected function getFlashBag()
{
return $this->getConfigurationPool()->getContainer()->get('session')->getFlashBag();
}
Cheers
回答4:
You need to inject the session service into your admin class.
http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services
来源:https://stackoverflow.com/questions/17940448/how-to-set-flash-message-in-sonata-admin-admin-controller