I am creating a simple mailer..
First you need to create a MailTemplate (Entity).
This exists of a subject, mailFrom and a Message.
Then you create the mail: This happens in two steps.
First you choose your account(s) to send to and your MailTemplate.
Then you redirect to another route where i set the subject, message and mailfrom, so i can adjust things.
When i send (Save the mail). it saved the mail but makes a copy of my MailTemplate and saved the Mailtemplate to.
So i got 1 mail and 2 Templates.
My Template entity
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 26-6-2018
* Time: 20:13
*/
namespace App\Project\MailBundle\Entity;
use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class MailTemplates
* #package App\Project\MailBundle\Entity
*/
/**
* #ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\MailTemplatesRepository")
*/
class MailTemplate extends BaseEntity
{
public function __construct()
{
parent::__construct();
$this->active = true;
$this->bulkmails = new ArrayCollection();
$this->mails = new ArrayCollection();
}
/**
* #var string $template
*
* #ORM\Column(name="template", type="string", length=191, nullable=false)
*
*
*/
private $template;
/**
* #var string $mailFrom
*
* #ORM\Column(type="string", length=191, nullable=false, options={"default": "noreply#nachtpost.be"})
* #Assert\NotBlank()
*
*/
private $mailFrom;
/**
* #var string $mailSubject
*
* #ORM\Column(type="string", length=191, nullable=false)
* #Assert\NotBlank()
*
*/
private $mailSubject;
/**
* #var string $mailMessage
*
* #ORM\Column(type="text", nullable=false)
* #Assert\NotBlank()
*
*/
private $mailMessage;
/**
* #ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\Mail", mappedBy="mailTemplate", orphanRemoval=true)
*/
private $mails;
/**
* #ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\BulkMail", mappedBy="mailTemplate", orphanRemoval=true)
*/
private $bulkmails;
/**
* #return string
*/
public function getTemplate(): ? string
{
return $this->template;
}
/**
* #param string $template
*/
public function setTemplate(string $template): void
{
$this->template = $template;
}
/**
* #return mixed
*/
public function getMailFrom()
{
return $this->mailFrom;
}
/**
* #param mixed $mailFrom
*/
public function setMailFrom($mailFrom): void
{
$this->mailFrom = $mailFrom;
}
/**
* #return mixed
*/
public function getMailSubject()
{
return $this->mailSubject;
}
/**
* #param mixed $mailSubject
*/
public function setMailSubject($mailSubject): void
{
$this->mailSubject = $mailSubject;
}
/**
* #return mixed
*/
public function getMailMessage()
{
return $this->mailMessage;
}
/**
* #param mixed $mailMessage
*/
public function setMailMessage($mailMessage): void
{
$this->mailMessage = $mailMessage;
}
/**
* #return mixed
*/
public function getMails(): collection
{
return $this->mails;
}
/**
* #param mixed $mails
*/
public function setMails($mails)
{
$this->mails = $mails;
}
/**
* #return mixed
*/
public function getBulkmails(): collection
{
return $this->bulkmails;
}
/**
* #param mixed $bulkmails
*/
public function setBulkmails($bulkmails)
{
$this->bulkmails = $bulkmails;
}
public function __toString()
{
return $this->getTemplate();
}
}
My mailEntity
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 26-6-2018
* Time: 20:13
*/
namespace App\Project\MailBundle\Entity;
use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Class BulkMail
* #package App\Project\MailBundle\Entity
*/
/**
* #ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\BulkMailRepository")
*/
class BulkMail extends BaseEntity
{
public function __construct()
{
parent::__construct();
$this->mailTo = new ArrayCollection();
$this->active = true;
}
/**
* #ORM\ManyToOne(targetEntity="App\Project\MailBundle\Entity\MailTemplate", inversedBy="mails", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="bulkMail_id", referencedColumnName="id", nullable=false)
*/
private $mailTemplate;
/**
* #ORM\ManyToMany(targetEntity="App\Project\AccountBundle\Entity\Account")
* #ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false)
* #Assert\NotBlank()
*/
private $mailTo;
/**
* #var string $mailFrom
*
* #ORM\Column(type="string", length=191, nullable=true)
*
*/
private $mailFrom;
/**
* #var string $mailSubject
*
* #ORM\Column(type="string", length=191, nullable=true)
*
*/
private $mailSubject;
/**
* #var string $mailMessage
*
* #ORM\Column(type="text", nullable=true)
*
*/
private $mailMessage;
/**
* #return mixed
*/
public function getMailTo()
{
return $this->mailTo;
}
/**
* #param mixed $mailTo
*/
public function setMailTo($mailTo): void
{
$this->mailTo = $mailTo;
}
/**
* #return mixed
*/
public function getMailFrom()
{
return $this->mailFrom;
}
/**
* #param mixed $mailFrom
*/
public function setMailFrom($mailFrom): void
{
$this->mailFrom = $mailFrom;
}
/**
* #return mixed
*/
public function getMailSubject()
{
return $this->mailSubject;
}
/**
* #param mixed $mailSubject
*/
public function setMailSubject($mailSubject): void
{
$this->mailSubject = $mailSubject;
}
/**
* #return mixed
*/
public function getMailMessage()
{
return $this->mailMessage;
}
/**
* #param mixed $mailMessage
*/
public function setMailMessage($mailMessage): void
{
$this->mailMessage = $mailMessage;
}
/**
* #param mixed $accountId
*/
public function setMail($account): void
{
$this->account = $account;
}
/**
* #return mixed
*/
public function getMailTemplate()
{
return $this->mailTemplate;
}
/**
* #param mixed $mailTemplate
*/
public function setMailTemplate($mailTemplate)
{
$this->mailTemplate = $mailTemplate;
}
public function __toString()
{
return $this->mailSubject;
}
}
My controller
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 5-7-2018
* Time: 22:41
*/
namespace App\Project\MailBundle\Controller;
use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
class BulkMailController extends BaseController
{
public function BulkMailIndexAction()
{
$MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
$items = $MailRepository->findAll();
return $this->render('#ProjectMail/mails/bulk/index.html.twig', array(
'items' => $items
));
}
public function bulkSelectAction(Request $request) {
$mail = new BulkMail();
$form = $this->createForm(BulkSelectmailAdminType::class, $mail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$TemplateRepository = $this->getDoctrine()->getRepository(MailTemplate::class);
$tId = $mail->getMailTemplate()->getId();
$template = $TemplateRepository->findOneBy(array('id' => $tId));
$mail->setMailSubject($template->getMailSubject());
$mail->setMailFrom($template->getMailFrom());
$mail->setMailMessage($template->getMailMessage());
$mail->setMailTemplate($template);
$this->container->get('session')->set('Bmail', $mail);
$response = $this->redirectToRoute('mailBulkSend');
return $response;
}
}
$label = "Email opmaken";
$response = $this->render('#ProjectMail/mails/bulk/addBulk_select.html.twig', array(
'form' => $form->createView(),
'label' => $label
));
return $response;
}
/**
* #param Request $request
* #param \Swift_Mailer $mailer
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {
$Bmail = $this->container->get('session')->get('Bmail');
if ($Bmail) {
$accounts = array();
$AccountRepository = $this->getDoctrine()->getRepository(Account::class);
$count = 0;
foreach ($Bmail->getMailTo() as $key => $account) {
$accounts[] = $AccountRepository->findOneById($account->getId());
$count ++;
}
$form = $this->createForm(BulkAddMailAdminType::class, $Bmail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$Bmail->setMailTo($accounts);
//dump($Bmail->getMailTemplate()); die;
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($Bmail);
$entityManager->flush();
// Get account emails in array
foreach($accounts as $key => $acc){
$persons[$acc->getEmail()] = $acc->getEmail();
}
$message = (new \Swift_Message($Bmail->getMailSubject()))
->setContentType("text/html")
->setFrom($Bmail->getMailFrom())
->setTo($persons)
->setBody(
$this->renderView(
'#ProjectTemplate/_templates/base_mail.html.twig', array(
'type' => 'emailDefault',
'template' => $Bmail
)
)
)
;
// $mailer->send($message);
$response = $this->redirectToRoute('mailsBulkList');
return $response;
}
}
$label = "Email verzenden";
$response = $this->render('#ProjectMail/mails/bulk/addMail.html.twig', array(
'form' => $form->createView(),
'mail' => $Bmail,
'accounts' => $accounts,
'label' => $label
));
} else {
$response = $this->redirectToRoute('mailBulkAdd');
}
return $response;
}
public function deleteAction(BulkMail $mail)
{
$em = $this->getDoctrine()->getManager();
$em->remove($mail);
$em->flush();
return $this->redirectToRoute('mailsBulkList');
}
}
I dont know why this happens and how to handle this right..
Suggestions? Ty in advance!!
Thanks for the help guys, really appreciated!
After some debugging i came out with this..
Not sure if its the way it should be but it works..
I save my mail in the first action and pass the id in my session, in the second action i pass the mail thru the form, (Can make changes if i need to) and send(Save it again).
Did some cleanup to :)
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 5-7-2018
* Time: 22:41
*/
namespace App\Project\MailBundle\Controller;
use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
class BulkMailController extends BaseController
{
public function BulkMailIndexAction()
{
$MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
$items = $MailRepository->findAll();
return $this->render('#ProjectMail/mails/bulk/index.html.twig', array(
'items' => $items
));
}
public function bulkSelectAction(Request $request) {
$mail = new BulkMail();
$form = $this->createForm(BulkSelectmailAdminType::class, $mail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$template = $mail->getMailTemplate();
$mail->setMailSubject($template->getMailSubject());
$mail->setMailFrom($template->getMailFrom());
$mail->setMailMessage($template->getMailMessage());
$entityManager->persist($mail);
$entityManager->flush();
$this->container->get('session')->set('Bmail', $mail->getId());
$response = $this->redirectToRoute('mailBulkSend');
return $response;
}
}
$label = "Email opmaken";
$response = $this->render('#ProjectMail/mails/bulk/addBulk_select.html.twig', array(
'form' => $form->createView(),
'label' => $label
));
return $response;
}
/**
* #param Request $request
* #param \Swift_Mailer $mailer
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {
$BmailId = $this->container->get('session')->get('Bmail');
if ($BmailId) {
$entityManager = $this->getDoctrine()->getManager();
$mailRepo = $this->getDoctrine()->getRepository(BulkMail::class);
$Bmail = $mailRepo->find($BmailId);
$accounts = array();
$AccountRepository = $this->getDoctrine()->getRepository(Account::class);
$count = 0;
foreach ($Bmail->getMailTo() as $key => $account) {
$accounts[] = $AccountRepository->findOneById($account->getId());
$count ++;
}
$form = $this->createForm(BulkAddMailAdminType::class, $Bmail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$Bmail->setMailTo($accounts);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($Bmail);
$entityManager->flush();
// Get account emails in array
foreach($accounts as $key => $acc){
$persons[$acc->getEmail()] = $acc->getEmail();
}
$message = (new \Swift_Message($Bmail->getMailSubject()))
->setContentType("text/html")
->setFrom($Bmail->getMailFrom())
->setTo($persons)
->setBody(
$this->renderView(
'#ProjectTemplate/_templates/base_mail.html.twig', array(
'type' => 'emailDefault',
'template' => $Bmail
)
)
)
;
// $mailer->send($message);
$response = $this->redirectToRoute('mailsBulkList');
return $response;
}
}
$label = "Email verzenden";
$response = $this->render('#ProjectMail/mails/bulk/addMail.html.twig', array(
'form' => $form->createView(),
'mail' => $Bmail,
'accounts' => $accounts,
'label' => $label
));
} else {
$response = $this->redirectToRoute('mailBulkAdd');
}
return $response;
}
public function deleteAction(BulkMail $mail)
{
$em = $this->getDoctrine()->getManager();
$em->remove($mail);
$em->flush();
return $this->redirectToRoute('mailsBulkList');
}
}
Related
I have create a form with 2 fields, (name and file). I have follow this guide https://symfony.com/doc/current/controller/upload_file.html
I have create my CRUD. My addAction is ok. But my edit action is not ok. When i valid the form for juste change the name and not the file (no file on input file) the form send an error "there is no file". How can I do to make editAction working without new file if no change on file ?
I add my project files
ProductController.php EditAction()
/**
* Displays a form to edit an existing product entity.
*
* #Route("/{id}/edit", name="product_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Product $product)
{
$deleteForm = $this->createDeleteForm($product);
$editForm = $this->createForm('AppBundle\Form\ProductType', $product);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('product_edit', array('id' => $product->getId()));
}
return $this->render('product/edit.html.twig', array(
'product' => $product,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
ProductControlle newAction()
/**
* Creates a new product entity.
*
* #Route("/new", name="product_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$product = new Product();
$form = $this->createForm(
'AppBundle\Form\ProductType',
$product,
array(
'validation_groups' => array('add')
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirectToRoute('product_show', array('id' => $product->getId()));
}
return $this->render('product/new.html.twig', array(
'product' => $product,
'form' => $form->createView(),
));
}
My product entity
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\Type(type="string")
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Please, upload the product brochure as a PDF file.", groups={"add"})
* #Assert\File(mimeTypes={ "application/pdf" }, groups={"add"})
*/
private $brochure;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set brochure
*
* #param string $brochure
*
* #return Product
*/
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
/**
* Get brochure
*
* #return string
*/
public function getBrochure()
{
return $this->brochure;
}
My FileUploder (service)
private $targetDir;
public function __construct($targetDir)
{
$this->targetDir = $targetDir;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$file->move($this->getTargetDir(), $fileName);
return $fileName;
}
public function getTargetDir()
{
return $this->targetDir;
}
And my BrochureUploadListener.php
private $uploader;
private $fileName;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Product) {
return;
}
if ($fileName = $entity->getBrochure()) {
$entity->setBrochure(new File($this->uploader->getTargetDir().'/'.$fileName));
}
}
private function uploadFile($entity)
{
// upload only works for Product entities
if (!$entity instanceof Product) {
return;
}
$file = $entity->getBrochure();
// only upload new files
if ($file instanceof UploadedFile) {
$fileName = $this->uploader->upload($file);
$entity->setBrochure($fileName);
}
}
And my services.yml
AppBundle\Service\FileUploader:
arguments:
$targetDir: '%brochures_directory%'
AppBundle\EventListener\BrochureUploadListener:
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }
- { name: doctrine.event_listener, event: postLoad }
The problem is that when you use
$form->isValid()
it actually validates
#Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
#Assert\File(mimeTypes={ "application/pdf" })
but you providing string instead of instance of UploadedFile. What you could do is to create validation group to ensure that this assertions would work only when you create new entity:
#Assert\NotBlank(message="Please, upload the product brochure as a PDF file.", groups={"add"})
#Assert\File(mimeTypes={ "application/pdf" }, groups={"add"})
And then add to your form options inside your addAction following line:
'validation_groups' => array('add')
So, your form instantiation inside addAction should look like like this:
$form = $this->createForm(YourFormType::class, null, array(
'validation_groups' => array('add')
));
I have use vichuploader bundle and it's more simply and ok.
I'm very new to Symfony.
As a User I only want to see the entities I've created.
A User may login and create games but I only want to see the game entities I've created.
It's a ManyToMany relation for User and Games, where User is the owning side.
Example: the game "Game for user Joop1" can only be viewed by user
Joop1. The game with title "Game for Joop2" may only be viewed by
Joop2.
If Joop1 is logged as the current user, how can I only show the games he has created with DQL/querybuilder?
I use FOSUserBundle.
Update: I've changed the relation to:
User->Game: many-to-many.
Question: what is the dql/querybuilder script for this sql statement:
SELECT * FROM game,users_games WHERE users_games.user_id = 1
This is my current querybuilder script based on Manuel DUVERNON answer:
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository( Game::class )->createQueryBuilder( 'game_t' );
$qb->join( 'users_games.user_id', 'ug' )
->where( 'ug.user_id = :userId' )
->setParameter( 'userId', 1);
return $qb->getQuery()->getResult();
But this is not working because I get the following error:
[Semantical Error] line 0, col 70 near '.user_id ug WHERE': Error:
Identification Variable users_games used in join path expression but
was not defined before.
GameController
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Game;
use AppBundle\Entity\PlayLog;
use AppBundle\Entity\User;
use AppBundle\Form\GameType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\HttpFoundation\Request;
/**
* Game controller.
*
* #Route("game")
*/
class GameController extends Controller
{
/**
* Lists all game entities.
*
* #Route("/", name="game_index")
* #Method("GET")
*/
public function indexAction(Request $request)
{
//get user_id
//
$usr = $this->getUser();
$id = $usr->getId();
//
// $em = $this->getDoctrine()->getManager();
//// $dql="SELECT g FROM AppBundle\Entity\Game g Join g.users u WHERE u.id := user_id";
// $dql = "SELECT game FROM AppBundle:Game game ";
// $query = $em->createQuery($dql);
// $query->setParameter('user_id', $id);
// $current_games = $query->getResult();
// $paginator = $this->get('knp_paginator');
// $result = $paginator->paginate(
//
// $request->query->getInt('page', 1),
// $request->query->getInt('limit', 25)
// );
// dump(get_class($paginator));
// $em = $this->getDoctrine()->getManager();
//
// $current_games = $em->getRepository('AppBundle:Game')->findAll();
// $em = $this->getDoctrine()->getManager();
//
// $current_games = $em->getRepository('AppBundle:Game')->findAllOrdered($id);
//
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository( Game::class )->createQueryBuilder( 'game_t' );
$qb->join( 'users_games.user_id', 'ug' )
->where( 'ug.user_id = :userId' )
->setParameter( 'userId', $id);
return $qb->getQuery()->getResult();
return $this->render('game/index.html.twig', array(
'games' => $current_games,
'max_limit_error' => 25
));
}
/**
* Creates a new game entity.
*
* #Route("/new", name="game_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$game = new Game();
$form = $this->createForm('AppBundle\Form\GameType', $game);
$form->handleRequest($request);
$game->setUser($this->getUser());
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($game);
$em->flush($game);
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/new.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Finds and displays a game entity.
*
* #Route("/{id}", name="game_show")
* #Method("GET")
*/
public function showAction(Game $game)
{
$deleteForm = $this->createDeleteForm($game);
return $this->render('game/show.html.twig', array(
'game' => $game,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/edit", name="game_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Game $game)
{
$deleteForm = $this->createDeleteForm($game);
$editForm = $this->createForm('AppBundle\Form\GameType', $game);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/edit.html.twig', array(
'game' => $game,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/log", name="game_log")
* #Method({"GET", "POST"})
*/
public function addLogAction(Request $request, Game $game)
{
$playlog = new PlayLog();
$form = $this->createForm(GameType::class, $game);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
//Save playLog
$em = $this->getDoctrine()->getManager();
$em->persist($playlog);
$em->flush();
}
// Render / return view incl. formulier.
return $this->render('game/log.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Deletes a game entity.
*
* #Route("/{id}", name="game_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Game $game)
{
$form = $this->createDeleteForm($game);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($game);
$em->flush($game);
}
return $this->redirectToRoute('game_index');
}
/**
* Creates a form to delete a game entity.
*
* #param Game $game The game entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Game $game)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('game_delete', array('id' => $game->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
Game Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Game
*
* #ORM\Table(name="game")
* #ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
*/
class Game
{
/**
* #ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
* #ORM\OrderBy({"date" = "DESC"})
*
*/
private $playlogs;
public function __construct()
{
$this->playlogs = new ArrayCollection();
}
/**
* #ORM\ManyToOne(targetEntity="Type", inversedBy="games")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="games")
*/
private $user;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(
* min = "3",
* max = "100"
* )
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* #param mixed $user
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* Set name
*
* #param string $name
*
* #return Game
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
}
You can just get the current logged user, then request your dql query using that user id .
Take a look :
$usr= $this->getUser();
$id=$usr->getId();
$em=$this->getDoctrine()->getManager();
$dql="SELECT * games FROM Game WHERE Game.user_id := user_id";
$query = $em->createQuery($dql);
$query->setParameter('user_id',$id);
$current_games = $query->getResult();
Hi and thank you for taking the time reading this.
English is not my first language so I hope you'll excuse me for any errors.
Currently I'm doing a project to get familiar with Symfony 3.
This is what I'm trying to do:
I have a oneToMany relation, Game to PlayLog.
The relation is established and I can view a list of dates in my games.
I want to create a new PlayLog and be associated with the Game so I can access all my related PlayLogs via Game.
A view is shown with the id of the game (log.html.twig)
My question:
How do I create a new PlayLog with a form and date formField(dateType), and add it to an existing game?
Update: with the current code I now get this error:
An exception occurred while executing 'INSERT INTO play_log (date,
game_id) VALUES (?, ?)' with params ["2017-03-04", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'game_id'
cannot be null
This is my code:
--- entity/Game.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Game
*
* #ORM\Table(name="game")
* #ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
*/
class Game
{
/**
* #ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
*/
private $playlogs;
public function __construct()
{
$this->playlogs = new ArrayCollection();
}
/**
* #ORM\ManyToOne(targetEntity="Type", inversedBy="games")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(
* min = "3",
* max = "100"
* )
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Game
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #ORM\Column (options={"default" = none})
* #param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
}
--- entity/PlayLog.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PlayLog
*
* #ORM\Table(name="play_log")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PlayLogRepository")
*/
class PlayLog
{
/**
* #ORM\ManyToOne(targetEntity="Game", inversedBy="playlogs")
* #ORM\JoinColumn(name="game_id", referencedColumnName="id")
*/
private $game;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var int
*
* #ORM\Column(name="game_id", type="integer")
*/
private $gameId;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return PlayLog
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set gameId
*
* #param integer $gameId
*
* #return PlayLog
*/
public function setGameId($gameId)
{
$this->gameId = $gameId;
return $this;
}
/**
* Get gameId
*
* #return int
*/
public function getGameId()
{
return $this->gameId;
}
public function addGame(Game $game)
{
$this->games->add($game);
$game->setType($this);
}
public function removeGame(Game $game)
{
$this->games->removeElement($game);
}
}
--- GameController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Game;
use AppBundle\Entity\PlayLog;
use AppBundle\Entity\Type;
use AppBundle\Form\GameType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\HttpFoundation\Request;
/**
* Game controller.
*
* #Route("game")
*/
class GameController extends Controller
{
/**
* Lists all game entities.
*
* #Route("/", name="game_index")
* #Method("GET")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
// $games = $em->getRepository('AppBundle:Game')->findAll();
$dql = "SELECT game FROM AppBundle:Game game JOIN game.type type ORDER BY game.name";
$query = $em->createQuery($dql);
/*
* #var $paginator \Knp\Component\Pager\Paginator
*/
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$query,
$request->query->getInt('page', 1),
$request->query->getInt('limit', 25)
);
// dump(get_class($paginator));
return $this->render('game/index.html.twig', array(
'games' => $result,
'max_limit_error' => 25
));
}
/**
* Creates a new game entity.
*
* #Route("/new", name="game_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$game = new Game();
$form = $this->createForm('AppBundle\Form\GameType', $game);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($game);
$em->flush($game);
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/new.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Finds and displays a game entity.
*
* #Route("/{id}", name="game_show")
* #Method("GET")
*/
public function showAction(Game $game)
{
$deleteForm = $this->createDeleteForm($game);
return $this->render('game/show.html.twig', array(
'game' => $game,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/edit", name="game_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Game $game)
{
$deleteForm = $this->createDeleteForm($game);
$editForm = $this->createForm('AppBundle\Form\GameType', $game);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/edit.html.twig', array(
'game' => $game,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/log", name="game_log")
* #Method({"GET", "POST"})
*/
public function addLogAction(Request $request, Game $game)
{
$playlog = new PlayLog();
$form = $this->createForm(GameType::class, $game);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
//Save playLog
$em = $this->getDoctrine()->getManager();
$em->persist($playlog);
$em->flush();
}
// Render / return view incl. formulier.
return $this->render('game/log.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Deletes a game entity.
*
* #Route("/{id}", name="game_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Game $game)
{
$form = $this->createDeleteForm($game);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($game);
$em->flush($game);
}
return $this->redirectToRoute('game_index');
}
/**
* Creates a form to delete a game entity.
*
* #param Game $game The game entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Game $game)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('game_delete', array('id' => $game->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
--- PlayLogController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\PlayLog;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;
/**
* Playlog controller.
*
* #Route("playlog")
*/
class PlayLogController extends Controller
{
/**
* Lists all playLog entities.
*
* #Route("/", name="playlog_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$playLogs = $em->getRepository('AppBundle:PlayLog')->findAll();
return $this->render('playlog/index.html.twig', array(
'playLogs' => $playLogs,
));
}
/**
* Creates a new playLog entity.
*
* #Route("/{gameId}/new", name="playlog_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request, $gameId)
{
$playlog = new PlayLog();
$form = $this->createForm('AppBundle\Form\PlayLogType', $playlog);
$form->handleRequest($request);
$playlog->setGameId($gameId);
echo $playlog->getGameId()."!";
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($playlog);
$em->flush();
// return $this->redirectToRoute('game_show', array('id' => $gameId));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playlog,
'form' => $form->createView(),
));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playLog,
'form' => $form->createView(),
));
}
/**
* Finds and displays a playLog entity.
*
* #Route("/{id}", name="playlog_show")
* #Method("GET")
*/
public function showAction(PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
return $this->render('playlog/show.html.twig', array(
'playLog' => $playLog,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing playLog entity.
*
* #Route("/{id}/edit", name="playlog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
$editForm = $this->createForm('AppBundle\Form\PlayLogType', $playLog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('playlog_edit', array('id' => $playLog->getId()));
}
return $this->render('playlog/edit.html.twig', array(
'playLog' => $playLog,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a playLog entity.
*
* #Route("/{id}", name="playlog_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, PlayLog $playLog)
{
$form = $this->createDeleteForm($playLog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($playLog);
$em->flush();
}
return $this->redirectToRoute('playlog_index');
}
/**
* Creates a form to delete a playLog entity.
*
* #param PlayLog $playLog The playLog entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(PlayLog $playLog)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('playlog_delete', array('id' => $playLog->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
--- game/log.html.twig
{% extends 'base.html.twig' %}
{% block content %}
Adding log for {{ game.name }}
{{ form_widget(form.playlogs) }}
<input type="submit" value="Create" class="btn btn-default pull-left" />
{% endblock content %}
--- PlayLogType.php
<?php
namespace AppBundle\Form;
use AppBundle\Entity\PlayLog;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PlayLogType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('date');
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => PlayLog::class
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_playlog';
}
}
--- GameType.php
<?php
namespace AppBundle\Form;
use AppBundle\Entity\PlayLog;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class GameType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'form-control',
],
]);
$builder
->add('type', EntityType::class, [
'class' => 'AppBundle:Type',
'choice_label' => function ($type) {
return $type->getName();
},
'multiple' => false,
'expanded' => false,
'attr' => [
'class' => 'form-control',
],
]);
$builder->add('playlogs', CollectionType::class, array(
'entry_type' => PlayLogType::class,
'label' => false
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Game'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_game';
}
}
Not sure if this is the answer you looking for..
You can tweek your newAction and his Route annotation in the Playlog controller a bit so that you add the gameId in the route
/**
* Creates a new playLog entity.
*
* #Route("/{gameId}/new", name="playlog_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request, $gameId)
{
$em = $this->getDoctrine()->getManager();
$game = $em->getRepository('AppBundle:Game')->find($gameId);
if(null === $game) {
throw $this->createNotFoundException('The game with id ' . $gameId . ' does not exist.');
}
$playLog = new Playlog();
$playLog->SetGame($game);
$form = $this->createForm('AppBundle\Form\PlayLogType', $playLog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($playLog);
$em->flush($playLog);
return $this->redirectToRoute('playlog_show', array('id' => $playLog->getId()));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playLog,
'form' => $form->createView(),
));
}
I've figured it out, I tried to persist with just an ID ($gameId) but it expected the entire Game object. (1) So I first had to get the actual repository object with the ID and after that I can persist this object:
public function newAction(Request $request, $gameId)
{
$playlog = new PlayLog();
$em = $this->getDoctrine()->getManager();
// (1) Get Game object with given gameId:
$game = $em ->getRepository(Game::class)->find($gameId);
//Set the Game object
$playlog->setGame($game);
$form = $this->createForm('AppBundle\Form\PlayLogType', $playlog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* #var $playLog PlayLog */
$playlog = $form->getData();
$em->persist($playlog);
$em->flush();
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playlog,
'form' => $form->createView(),
));
}
i'm having trouble to use the uploadable extension of stofdoctrinebundle
i've a File entity :
<?php
namespace my\TestBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* File
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="my\TestBundle\Entity\FileRepository")
* #Gedmo\Uploadable(path="uploads", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Column(name="path", type="string")
* #Gedmo\UploadableFilePath
*/
private $path;
/**
* #ORM\Column(name="name", type="string")
* #Gedmo\UploadableFileName
*/
private $name;
/**
* #ORM\Column(name="mime_type", type="string")
* #Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* #ORM\Column(name="size", type="decimal")
* #Gedmo\UploadableFileSize
*/
private $size;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set mimeType
*
* #param string $mimeType
* #return File
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* Get mimeType
*
* #return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* Set size
*
* #param string $size
* #return File
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* #return string
*/
public function getSize()
{
return $this->size;
}
}
in my controller, when i use a form directly on this entity :
$document = new File();
$form = $this->createFormBuilder($document)
->add('name')
->add('path','file',array(
'data_class' => null ))
->add('submit','submit')
->getForm()
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($club);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($club, $club->getLogo()->getPath());
$em->flush();
}
}
my file is well uploaded and my entity correctly filled
But i want to use it in another entity :
class Company {
/**
* #ORM\ManyToOne(targetEntity="my\TestBundle\Entity\File", cascade={"persist"})
* #ORM\JoinColumn(name="logo", nullable=true)
*/
private $logo;
/**
* Get logo
*
* #return \my\TestBundle\Entity\File
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set comments
*
* #param string $comments
* #return Club
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
And in my controller :
$company = new Company();
$form = $this->createFormBuilder($company)
->add('name')
->add('logo', new \my\TestBundle\Form\FileType, array(
'data_class' => 'my\TestBundle\Entity\File' ))
->add('submit','submit')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($club);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($company, $company->getLogo()->getPath());
$em->flush();
}
}
My FileType :
/**
*
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('path', 'file', array(
'required' => false,
))
;
}
And when i submit, it tells me that all field of dile entity (mimetype, size, name) cannot be null.
But normally they are filled with the extension (like in 1st case)
How can i manage this?
Thanks
i think i solve my problem,
here what i've done :
$company = new Company();
$form = $this->createFormBuilder($company)
->add('name')
->add('logo', new \cM\ManagementBundle\Form\FileType, array(
'data_class' => 'cM\ManagementBundle\Entity\File' ))
->add('submit','submit')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($club->getLogo(), $club->getLogo()->getPath());
$em->flush();
}
}
I don't think the name is handled. Check documentation, name is asked in every demo form.
I have an Entity in Symfony called Ip and I save my IP address as integer - I use the IP as primary key, too.
But when I display and enter the IP in a form or list I want to convert it to a IP, e.g. 127.0.0.1 is saved as 2130706433.
I created the forms with the CRUD generator.
My entity comes here:
<?php
namespace IS\ClearanceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* IS\ClearanceBundle\Entity\Ip
*/
class Ip
{
/**
* #var bigint $ip
*/
private $ip;
/**
* #var integer $high
*/
private $high;
/**
* #var string $hoster
*/
private $hoster;
/**
* #var datetime $scandate
*/
private $scandate;
/**
* #var integer $id
*/
private $id;
/**
* #var IS\ClearanceBundle\Entity\Clearance
*/
private $clearance;
public function __construct()
{
$this->clearance = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set ip
*
* #param bigint $ip
*/
public function setIp($ip)
{
$this->ip = $ip;
}
/**
* Get ip
*
* #return bigint
*/
public function getIp()
{
return $this->ip;
}
/**
* Set high
*
* #param integer $high
*/
public function setHigh($high)
{
$this->high = $high;
}
/**
* Get high
*
* #return integer
*/
public function getHigh()
{
return $this->high;
}
/**
* Set hoster
*
* #param string $hoster
*/
public function setHoster($hoster)
{
$this->hoster = $hoster;
}
/**
* Get hoster
*
* #return string
*/
public function getHoster()
{
return $this->hoster;
}
/**
* Set scandate
*
* #param datetime $scandate
*/
public function setScandate($scandate)
{
$this->scandate = $scandate;
}
/**
* Get scandate
*
* #return datetime
*/
public function getScandate()
{
return $this->scandate;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add clearance
*
* #param IS\ClearanceBundle\Entity\Clearance $clearance
*/
public function addClearance(\IS\ClearanceBundle\Entity\Clearance $clearance)
{
$this->clearance[] = $clearance;
}
/**
* Get clearance
*
* #return Doctrine\Common\Collections\Collection
*/
public function getClearance()
{
return $this->clearance;
}
}
And here is my Controller:
<?php
namespace IS\ClearanceBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use IS\ClearanceBundle\Entity\Ip;
use IS\ClearanceBundle\Form\IpType;
/**
* Ip controller.
*
* #Route("/ip")
*/
class IpController extends Controller
{
/**
* Lists all Ip entities.
*
* #Route("/", name="ip")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entities = $em->getRepository('ISClearanceBundle:Ip')->findAll();
return array('entities' => $entities);
}
/**
* Finds and displays a Ip entity.
*
* #Route("/{id}/show", name="ip_show")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), );
}
/**
* Displays a form to create a new Ip entity.
*
* #Route("/new", name="ip_new")
* #Template()
*/
public function newAction()
{
$entity = new Ip();
$form = $this->createForm(new IpType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a new Ip entity.
*
* #Route("/create", name="ip_create")
* #Method("post")
* #Template("ISClearanceBundle:Ip:new.html.twig")
*/
public function createAction()
{
$entity = new Ip();
$request = $this->getRequest();
$form = $this->createForm(new IpType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('ip_show', array('id' => $ entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Displays a form to edit an existing Ip entity.
*
* #Route("/{id}/edit", name="ip_edit")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$editForm = $this->createForm(new IpType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing Ip entity.
*
* #Route("/{id}/update", name="ip_update")
* #Method("post")
* #Template("ISClearanceBundle:Ip:edit.html.twig")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$editForm = $this->createForm(new IpType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('ip_edit', array('id' => $ id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Ip entity.
*
* #Route("/{id}/delete", name="ip_delete")
* #Method("post")
*/
public function deleteAction($id)
{
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.' );
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('ip'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
And here the form:
<?php
namespace IS\ClearanceBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class IpType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('ip')
->add('high')
->add('hoster')
->add('scandate')
->add('clearance','entity', array('class'=>'IS\ClearanceBundle\Entity\Clearance', 'property'=>'id','required'=>false, 'multiple'=>true))
;
}
public function getName()
{
return 'is_clearancebundle_iptype';
}
}
Thanks for any help!
IMO if you want do it, you should use data transformer http://symfony.com/doc/current/cookbook/form/data_transformers.html and implement __toString for your entity IP.
EDIT:
Created sample at gist: https://gist.github.com/3086241