I am currently trying to use swiftmailer in my project. I am currently working on Sonata Admin and I wanted to know how I could retrieve the object displayed in a list to be able to retrieve the associated mail addresses and thus send an e-mail to all the addresses contained in this list. I want to go through the list displayed by sonata because their filter system works very well and I would use it to choose the people I want to send an email to. I saw on the symfony documentation that it was possible to send mail to an address table in this form:
$to = array('one@example.com', 'two@example.com', 'three@example.com');
$message = (new \Swift_Message('Hello Email'))
->setFrom('send@example.com')
->setTo(array($to))
->setBody('html content goes here', 'text/html');
$mailer->send($message);
But i don't know how to take back the object form the list. From this grid.
Ps : I just think putting a button down the list to send an email to all the people displayed in the list.
Thanks a lot.
Edit : I'm still searching and i found that the sql request was like 't0.id' and 'c0.id'. t0 and c0 are the name of the object ? Is it always that ? What is the difference between t0 and c0 ?
You can do this by adding an action to your admin list.
To do so, first create a new class in YourAdminBundle\Controller
folder, extending Sonata\AdminBundle\Controller\CRUDController
.
Your custom action could look like this for instance :
/** @property YourAdminClass $admin */
public function batchActionSendMail(ProxyQueryInterface $selectedModelQuery ,$type = 'sendMails') {
if (false === $this->admin->isGranted('EDIT')) {
throw new AccessDeniedException();
}
/* selected objects in your list !! */
$selectedModels = $selectedModelQuery->execute();
try{
foreach ($selectedModels as $selectedModel){
// your code to retrieve objects mails here (for instance)
}
//code to send your mails
}
catch(\Exception $e)
{
$this->addFlash('sonata_flash_error', "error");
}
$this->addFlash('sonata_flash_success', 'mails sent')
return new RedirectResponse($this->admin->generateUrl('list'));
}
To make this custom CRUD controller active, go to services.yml
, get to your class admin block, and complete the third param of arguments
property by referencing your custom CRUD controller:
arguments: [null, YourBundle\Entity\YourEntity,YourAdminBundle:CustomCRUD]
Finally, to allow you to use your custom action, go to your Admin Class and add this function :
public function getBatchActions()
{
if ($this->hasRoute('edit')) {
$actions['sendMails'] = array(
'label' => $this->trans('batch.sendMails.action'),
'ask_confirmation' => true, // by default always true
);
}
return $actions;
}
The action will be available in the dropdown list at the bottom of your admin list, next to the "Select all" checkbox.