Instantly share code, notes, and snippets.

Embed
What would you like to do?
Override CRUDController to add custom form elements to list template for batch action usage in SonataAdminBundle
# config/admin.yml
services:
sonata.admin.electrical_equipment:
class: Acme\DemoBundle\Admin\ElectricalEquipmentAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: "Internal", label_catalogue: "messages", label: "Electrical Equipment" }
arguments:
- ~
- Acme\DemoBundle\Entity\ElectricalEquipment
- Acme\DemoBundle:ElectricalEquipmentAdmin
calls:
- [ addChild, [ @sonata.admin.electrical_equipment_test ] ]
- [ setSecurityContext, [@security.context]]
<?php
namespace Acme\DemoBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
class ElectricalEquipmentAdmin extends Admin
{
public function getTemplate($name)
{
switch ($name) {
case 'list':
return 'AcmeDemoBundle:ElectricalEquipmentAdmin:list.html.twig';
break;
default:
return parent::getTemplate($name);
break;
}
}
public function getBatchActions()
{
$actions = parent::getBatchActions();
if ($this->hasRoute('edit') && $this->isGranted('TEST')) {
$actions['test'] = array(
'label' => 'Test',
'ask_confirmation' => false
);
}
return $actions;
}
}
<?php
namespace Acme\DemoBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery as ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Acme\DemoBundle\Entity\ElectricalEquipmentTest;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\NotBlank;
class ElectricalEquipmentAdminController extends Controller
{
public function listAction()
{
if (false === $this->admin->isGranted('LIST')) {
throw new AccessDeniedException();
}
$datagrid = $this->admin->getDatagrid();
$formView = $datagrid->getForm()->createView();
$actionForm = $this->get('form.factory')->createNamedBuilder('', 'form')
->add('testedAt', 'sonata_type_date_picker', array('label' => 'zum'))
->getForm();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
return $this->render($this->admin->getTemplate('list'), array(
'action' => 'list',
'form' => $formView,
'actionForm' => $actionForm->createView(),
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
));
}
public function batchActionTestIsRelevant(array $selectedIds, $allEntitiesSelected)
{
if (count($selectedIds) === 0) return false;
$parameterBag = $this->get('request')->request;
// check that a target has been chosen
if (!$parameterBag->has('testedAt')) {
return 'flash_batch_test_no_tested_at';
}
$testedAt = $parameterBag->get('testedAt');
$dateConstraint = new Date();
$dateConstraint->message = 'flash_batch_test_no_tested_at';
$constraint = new Collection(array(
'testedAt' => array(
new NotBlank(),
$dateConstraint
)
));
$errorList = $this->get('validator')->validateValue(array('testedAt' => $testedAt), $constraint);
if (!count($errorList) == 0) {
return $errorList[0]->getMessage();
}
return true;
}
public function batchActionTest(ProxyQueryInterface $query)
{
if (false === $this->admin->isGranted('TEST')) {
throw new AccessDeniedException();
}
$parameterBag = $this->get('request')->request;
$testedAt = new \DateTime($parameterBag->get('testedAt'));
$user = $this->container->get('security.context')->getToken()->getUser();
$modelManager = $this->admin->getModelManager();
try {
foreach ($query->execute() as $entity) {
$test = new ElectricalEquipmentTest();
$test->setTestedAt($testedAt);
$test->setUser($user);
$entity->addTest($test);
// Model Manager missing flush() method.
$modelManager->update($entity);
}
$this->addFlash('sonata_flash_success', 'flash_batch_activation_success');
} catch (ModelManagerException $e) {
$this->addFlash('sonata_flash_error', 'flash_batch_activation_error');
}
return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
}
}
{% extends 'SonataAdminBundle:CRUD:base_list.html.twig' %}
{% block batch_actions %}
<label class="checkbox" for="{{ admin.uniqid }}_all_elements">
<input type="checkbox" name="all_elements" id="{{ admin.uniqid }}_all_elements">
{{ 'all_elements'|trans({}, 'SonataAdminBundle') }}
({{ admin.datagrid.pager.nbresults }})
</label>
{{ form_label(actionForm.testedAt) }} {{ form_widget(actionForm.testedAt) }}
<select name="action" style="width: auto; height: auto" class="form-control">
{% for action, options in batchactions %}
<option value="{{ action }}">{{ options.label }}</option>
{% endfor %}
</select>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment