You have requested a non-existent service \"user.handler\" - symfony

I have an error in my service restuser.handler, other services work, what's the problem please
services:
# rest_user.example:
# class: %rest_user.example.class%
# arguments: [#service_id, "plain_value", %parameter%]
restuser.form.register:
class: REST\UserBundle\Form\RegisterType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: rest_user_register}
restuser.form.profile:
class: REST\UserBundle\Form\ProfileType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: rest_user_profile }
restuser.handler:
class: REST\UserBundle\Handler\UserHandler
arguments: [#doctrine.orm.entity_manager, #form.factory, #security.encoder_factory]
my controller is as follows:
class UserController extends FOSRestController{
/**
* #QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing pages.")
* #QueryParam(name="limit", requirements="\d+", nullable=true, default="20", description="How many pages to return.")
*
* #View()
*
* #param Request $request the request object
* #param ParamFetcherInterface $paramFetcher param fetcher service
*
* #return array
*/
public function getUsersAction(Request $request, ParamFetcherInterface $paramFetcher)
{
$offset = $paramFetcher->get('offset');
$offset = null == $offset ? 0 : $offset;
$limit = $paramFetcher->get('limit');
return $this->container->get('user.handler')->all($limit, $offset);
}
/**
* #param User $user
*
* #View()
* #return array
*/
public function getUserAction($id)
{
$user=$this->getOr404($id);
return $user;
}
/**
*
* #View()
*
* #param Request $request
* #param int $id
*
* #return View
*
* #throws NotFoundHttpException when user not exist
*/
public function putUserAction(Request $request, $id)
{
try {
if (!($user = $this->container->get('user.handler')->get($id))) {
$statusCode = Codes::HTTP_CREATED;
$user = $this->container->get('user.handler')->post($request);
} else {
$statusCode = Codes::HTTP_NO_CONTENT;
$user = $this->container->get('user.handler')->put($user, $request);
}
$response = new Response('El usuario ha sido guardado con éxito', $statusCode);
return $response;
} catch (\Exception $exception) {
return $exception->getMessage();
}
}
/**
*
* #View()
*
* #param Request $request
* #param int $id
*
* #return FormTypeInterface|View
*
* #throws NotFoundHttpException when user not exist
*/
public function patchUserAction(Request $request, $id)
{
try {
if (($user = $this->getOr404($id))) {
$statusCode = Codes::HTTP_ACCEPTED;
$user = $this->container->get('user.handler')->patch($user, $request);
} else {
$statusCode = Codes::HTTP_NO_CONTENT;
}
$response = new Response('El usuario ha sido guardado con éxito', $statusCode);
return $response;
} catch (NotFoundHttpException $exception) {
return $exception->getMessage();
}
}
/**
*
* #View()
*
* #param Request $request
* #param int $id
*
* #return FormTypeInterface|View
*
* #throws NotFoundHttpException when user not exist
*/
public function deleteUserAction(Request $request, $id)
{
if (($user = $this->container->get('user.handler')->get($id))) {
$statusCode = Codes::HTTP_ACCEPTED;
$user = $this->container->get('user.handler')->delete($user);
} else {
$statusCode = Codes::HTTP_NO_CONTENT;
}
$response = new Response('El usuario se ha eliminado', $statusCode);
return $response;
}
/**
* Fetch the Page or throw a 404 exception.
*
* #param mixed $id
*
* #return PageInterface
*
* #throws NotFoundHttpException
*/
protected function getOr404($id)
{
if (!($page = $this->container->get('user.handler')->get($id))) {
throw new NotFoundHttpException(sprintf('The User \'%s\' was not found.',$id));
}
return $page;
}
}
my class user handler is a s follows:
public function __construct(EntityManager $em, FormFactoryInterface $formFactory, EncoderFactory $encoderFactory)
{
$this->em = $em;
$this->factory = $formFactory;
$this->encoderFactory = $encoderFactory;
}
public function get($id = null, $email = null)
{
if ($email) {
return $this->em->getRepository('UserBundle:User')->findOneBy(array('email' => $email));
}
return $this->em->getRepository('UserBundle:User')->find($id);
}
/**
* #param int $limit the limit of the result
* #param int $offset starting from the offset
*
* #return array
*/
public function all($limit = 20, $offset = 0, $orderby = null)
{
return $this->em->getRepository('UserBundle:User')->findBy(array(), $orderby, $limit, $offset);
}
/**
* Create a new User.
*
* #param $request
*
* #return User
*/
public function post(Request $request)
{
$user = new User();
return $this->processForm($user, $request, 'POST');
}
/**
* #param User $user
* #param $request
*
* #return User
*/
public function put(User $entity, $request)
{
return $this->processForm($entity, $request);
}
/**
* #param User $user
* #param $request
*
* #return User
*/
public function patch(User $entity, $request)
{
return $this->processForm($entity, $request, 'PATCH');
}
/**
* #param User $user
*
* #return User
*/
public function delete(User $entity)
{
$this->em->remove($entity);
$this->em->flush($entity);
}
/**
* Processes the form.
*
* #param User $user
* #param array $parameters
* #param String $method
*
* #return User
*
* #throws \Exception
*/
private function processForm(User $entity, Request $request, $method = "PUT")
{
$form = $this->factory->create(new AppUserType(), $entity, array('method' => $method));
$form->handleRequest($request);
if ($form->isValid()) {
$req = $request->request->get('user');
if (!$req) {
$req = $request->request->get('user');
}
if ($req['password']!= "") {
$entity->setPassword($req['password']);
}
$this->em->persist($entity);
$this->em->flush($entity);
return $entity;
}
return View::create($form, 400);
}
I tried to clear the cache and change name of service but still not work, please help me

Related

Symfony4 double entity on create

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');
}
}

ManyToOne many Posts for one User -> creates new User by creating a Post

I am using Symfony and Doctrine.
I have two Entities, User and Pots.
Every logged User can create as many Post he want to.
Every Post is associated to one User.
Thats the Workflow: I log in with an User, this user create a Post. A New Post is saved in the Database with a foreigkey on the User wo create it.
Problem: when the User create the Post, the post ist create, but a new User is created too. The new Post is asssociate to the new Users and not to the logged User.
USER ENTITY:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Post;
/**
* #ORM\Entity
* #ORM\Table(name= "User")
*/
class User
{
/**
* #ORM\Column(type = "integer")
* #ORM\Id
* #ORM\GeneratedValue("AUTO")
*/
private $id;
/**
* #ORM\Column(type = "string", length = 50)
*/
private $account;
/**
* #ORM\Column(type = "string", length = 22)
*/
private $password;
/**
* #ORM\Column(type = "string", length = 100)
*/
private $email;
/**
* #ORM\Column(type = "integer", length = 1)
*/
private $type;
/**
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="user")
*/
private $posts;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set account
*
* #param string $account
*
* #return User
*/
public function setAccount($account)
{
$this->account = $account;
return $this;
}
/**
* Get account
*
* #return string
*/
public function getAccount()
{
return $this->account;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set mail
*
* #param string $mail
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get mail
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set type
*
* #param integer $type
*
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType()
{
return $this->type;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add post
*
* #param \AppBundle\Entity\Post $post
*
* #return User
*/
public function addPost(\AppBundle\Entity\Post $post)
{
$this->posts[] = $post;
return $this;
}
/**
* Remove post
*
* #param \AppBundle\Entity\Post $post
*/
public function removePost(\AppBundle\Entity\Post $post)
{
$this->posts->removeElement($post);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
POST ENTITY:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\User;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
* #ORM\Table(name = "Post")
* #Vich\Uploadable
*/
class Post
{
/**
* #ORM\Column(type = "integer")
* #ORM\Id
* #ORM\GeneratedValue("AUTO")
*/
private $id;
/**
* #ORM\Column(type = "string", length = 25)
*/
private $title;
/**
* #ORM\Column(type = "string", length = 255)
*/
private $text;
/**
* #ORM\Column(type= "string", length = 250)
*/
private $pic;
/**
* #Vich\UploadableField(mapping="post_file", fileNameProperty="pic")
*
*/
private $picFile;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="posts", cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
public function getPicFile(){
return $this->picFile;
}
public function setPicFile(File $picFile = null){
$this->picFile = $picFile;
return $this;
}
/**
* Set user
*
* #param \AppBundle\Entity\User $user
*
* #return Coach
*/
public function setUser(\AppBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \AppBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set title
*
* #param string $title
*
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
*
* #return Post
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set pic
*
* #param string $pic
*
* #return Post
*/
public function setPic($pic)
{
$this->pic = $pic;
return $this;
}
/**
* Get pic
*
* #return string
*/
public function getPic()
{
return $this->pic;
}
/**
* Set id
*
* #param integer $id
*
* #return Post
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
CONTROLLER:
NOTE: Here is take the logged User from the SESSION. This works, i output the id from the User i use and it was the correct id.
public function FrameCoachNewAction(Request $request)
{
$session = $request->getSession();
$session->start();
$user = $session->get('user');
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$post = $form->getData();
$post->setUser($user);
$doct = $this->getDoctrine()->getManager();
$doct->persist($post);
$doct->flush();
//return New Response($post->getUser()->getId());
return $this->RedirectToRoute('app_frame_coach');
}else{
return $this->render('/frame/frame_coach_new.html.twig', array('form' => $form->createView(), 'user' => $user));
}
}
I left the Entity like you said, but i changed the Controller to. The Session User Object dind't work to associate it to the Post. So I just toke the ID from the Session and then search the user object again throw that id in the database and used this instade.
public function FrameCoachNewAction(Request $request)
{
$session = $request->getSession();
$session->start();
$users = $session->get('user');
$repo = $this->getDoctrine()->getRepository(User::class);
$user = $repo->find($users->getId());
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$doct = $this->getDoctrine()->getManager();
$post = $form->getData();
$post->setUser($user);
$doct->persist($post);
$doct->flush();
//return New Response($post->getUser()->getId());
return $this->RedirectToRoute('app_frame_coach');
}else{
return $this->render('/frame/frame_coach_new.html.twig', array('form' => $form->createView(), 'user' => $user));
}
}
The user is the strong side so you should move the cascade={"persist"} option to user, then the user can save the post not the other way. It seems the cascade={"persist"} option is rewriting the setUser method. When you use the cascade={"persist"} option that entity would create the targetEntity.
In addition to #Juan I. Morales Pestana
class User
{
// ...
/**
*
* #ORM\OneToMany(
* targetEntity="Post",
* mappedBy="user",
* cascade={"persist"}
* )
*/
private $posts;
// ...
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add post
*
* #param \AppBundle\Entity\Post $post
*
* #return User
*/
public function addPost(\AppBundle\Entity\Post $post)
{
$this->posts[] = $post;
$post->setUser($this);
return $this;
}

Setters and getters aren't accessible from custom user entity in Symfony2

I'm trying to implement the hwioauthbundle for connecting with Google.
However, I'm facing the problem that symfony can't seem to find the method declared in the User entity - I believe it has something to do with the FOSUserBundle that I'm also using.
Here is my GoogleProvider.php:
<?php
namespace AppBundle\Security\User\Provider;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
class GoogleProvider extends BaseClass
{
/**
* {#inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
$property = $this->getProperty($response);
$username = $response->getUsername();
//on connect - get the access token and the user ID
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
//we "disconnect" previously connected users
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
$previousUser->$setter_id(null);
$previousUser->$setter_token(null);
$this->userManager->updateUser($previousUser);
}
//we connect current user
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
$this->userManager->updateUser($user);
}
/**
* {#inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
//when the user is registrating
if (null === $user) {
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
// create new user here
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
}
And here is FOSUBUserProvider.php:
<?php
namespace HWI\Bundle\OAuthBundle\Security\Core\User;
use FOS\UserBundle\Model\User;
use FOS\UserBundle\Model\UserManagerInterface;
use HWI\Bundle\OAuthBundle\Connect\AccountConnectorInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class FOSUBUserProvider implements UserProviderInterface, AccountConnectorInterface, OAuthAwareUserProviderInterface
{
/**
* #var UserManagerInterface
*/
protected $userManager;
/**
* #var array
*/
protected $properties = array(
'identifier' => 'id',
);
/**
* #var PropertyAccessor
*/
protected $accessor;
/**
* Constructor.
*
* #param UserManagerInterface $userManager FOSUB user provider.
* #param array $properties Property mapping.
*/
public function __construct(UserManagerInterface $userManager, array $properties)
{
$this->userManager = $userManager;
$this->properties = array_merge($this->properties, $properties);
$this->accessor = PropertyAccess::createPropertyAccessor();
}
/**
* {#inheritDoc}
*/
public function loadUserByUsername($username)
{
// Compatibility with FOSUserBundle < 2.0
if (class_exists('FOS\UserBundle\Form\Handler\RegistrationFormHandler')) {
return $this->userManager->loadUserByUsername($username);
}
return $this->userManager->findUserByUsername($username);
}
/**
* {#inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
if (null === $user || null === $username) {
throw new AccountNotLinkedException(sprintf("User '%s' not found.", $username));
}
return $user;
}
/**
* {#inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Expected an instance of FOS\UserBundle\Model\User, but got "%s".', get_class($user)));
}
$property = $this->getProperty($response);
if (!$this->accessor->isWritable($user, $property)) {
throw new \RuntimeException(sprintf("Class '%s' must have defined setter method for property: '%s'.", get_class($user), $property));
}
$username = $response->getUsername();
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
$this->accessor->setValue($previousUser, $property, null);
$this->userManager->updateUser($previousUser);
}
$this->accessor->setValue($user, $property, $username);
$this->userManager->updateUser($user);
}
/**
* {#inheritDoc}
*/
public function refreshUser(UserInterface $user)
{
// Compatibility with FOSUserBundle < 2.0
if (class_exists('FOS\UserBundle\Form\Handler\RegistrationFormHandler')) {
return $this->userManager->refreshUser($user);
}
$identifier = $this->properties['identifier'];
if (!$user instanceof User || !$this->accessor->isReadable($user, $identifier)) {
throw new UnsupportedUserException(sprintf('Expected an instance of FOS\UserBundle\Model\User, but got "%s".', get_class($user)));
}
$userId = $this->accessor->getValue($user, $identifier);
if (null === $user = $this->userManager->findUserBy(array($identifier => $userId))) {
throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $userId));
}
return $user;
}
/**
* {#inheritDoc}
*/
public function supportsClass($class)
{
$userClass = $this->userManager->getClass();
return $userClass === $class || is_subclass_of($class, $userClass);
}
/**
* Gets the property for the response.
*
* #param UserResponseInterface $response
*
* #return string
*
* #throws \RuntimeException
*/
protected function getProperty(UserResponseInterface $response)
{
$resourceOwnerName = $response->getResourceOwner()->getName();
if (!isset($this->properties[$resourceOwnerName])) {
throw new \RuntimeException(sprintf("No property defined for entity for resource owner '%s'.", $resourceOwnerName));
}
return $this->properties[$resourceOwnerName];
}
}
And here is my service:
parameters:
my_user_provider.class: AppBundle\Security\User\Provider\GoogleProvider
services:
my_user_provider:
class: "%my_user_provider.class%"
#this is the place where the properties are passed to the UserProvider - see config.yml
arguments: [#fos_user.user_manager,{facebook: facebook_id, google: google_id}]
Here is my User entity:
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*/
private $name;
/**
* #var integer
*/
private $facebook_id;
/**
* #var string
*/
private $facebookAccessToken;
/**
* #var integer
*/
private $google_id;
/**
* #var string
*/
private $googleAccessToken;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $keyword;
/**
* Constructor
*/
public function __construct()
{
$this->keyword = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set facebook_id
*
* #param integer $facebookId
* #return User
*/
public function setFacebookId($facebookId)
{
$this->facebook_id = $facebookId;
return $this;
}
/**
* Get facebook_id
*
* #return integer
*/
public function getFacebookId()
{
return $this->facebook_id;
}
/**
* Set facebookAccessToken
*
* #param string $facebookAccessToken
* #return User
*/
public function setFacebookAccessToken($facebookAccessToken)
{
$this->facebookAccessToken = $facebookAccessToken;
return $this;
}
/**
* Get facebookAccessToken
*
* #return string
*/
public function getFacebookAccessToken()
{
return $this->facebookAccessToken;
}
/**
* Set google_id
*
* #param integer $googleId
* #return User
*/
public function setGoogleId($googleId)
{
$this->google_id = $googleId;
return $this;
}
/**
* Get google_id
*
* #return integer
*/
public function getGoogleId()
{
return $this->google_id;
}
/**
* Set googleAccessToken
*
* #param string $googleAccessToken
* #return User
*/
public function setGoogleAccessToken($googleAccessToken)
{
$this->googleAccessToken = $googleAccessToken;
return $this;
}
/**
* Get googleAccessToken
*
* #return string
*/
public function getGoogleAccessToken()
{
return $this->googleAccessToken;
}
/**
* Add keyword
*
* #param \AppBundle\Entity\Keyword $keyword
* #return User
*/
public function addKeyword(\AppBundle\Entity\Keyword $keyword)
{
$this->keyword[] = $keyword;
return $this;
}
/**
* Remove keyword
*
* #param \AppBundle\Entity\Keyword $keyword
*/
public function removeKeyword(\AppBundle\Entity\Keyword $keyword)
{
$this->keyword->removeElement($keyword);
}
/**
* Get keyword
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getKeyword()
{
return $this->keyword;
}
}
Does anyone have any idea what I'm doing wrong?
I works when I do:
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
$user->setEnabled(true);
But for instance I can't do:
$user->setGoogleId(123);
but I guess it is because they are not in my User entity, but in FOSUserBundle.
It seems like it doesn't extend my User entity.
I appreciate all kinds of help!
You need to add every method you expect to work in your User entity. There is no magic. So, add a setFacebookId(), setFacebookAccessToken(), etc. Indeed, you could even add a setGoogleId(), but there is no property called $googleId in your entity.

Symfony2 DQL on Fos Userbundle entity

I'm implementing a search on a website and for simplicity i've decided to create a class that does the hard work.
Basically my class takes the EntityManager and the Entities in which i want to search and creates the DQL and executes the query. For normal entities this works totally fine but when i pass the User entity (Extended from fos user bundle entity) i get this error :
[Semantical Error] line 0, col 139 near 'last_login LIKE': Error: Class Soundmerger\UserBundle\Entity\User has no field or association named last_login
The dql query generated seems fine and as it works for the other entities i doubt it comes form there.
Here is my Search class :
use Doctrine\Common\Util\Debug;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query;
class Search {
private $em;
private $searchables;
public function __construct(EntityManager $em, ArrayCollection $searchables){
$this->em = $em;
$this->searchables = $searchables;
}
public function search($query){
$words = explode("+", $query);
$qb = array();
$results = array();
foreach($this->searchables as $qNumber => $searchable){
$qb[$qNumber] = "SELECT s FROM $searchable s ";
$columns = $this->em->getClassMetadata($searchable)->getColumnNames();
foreach($words as $i => $word){
foreach($columns as $k => $column){
$string = "s.$column LIKE '%$word%'";
if($i == 0 && $k == 0){
$qb[$qNumber] .= "WHERE $string";
} else {
$qb[$qNumber] .= "OR $string";
}
}
}
$res[] = $this->em->createQuery($qb[$qNumber])->getResult(Query::HYDRATE_SIMPLEOBJECT);
}
return $this->formatSearch($res);
}
private function formatSearch($results){
$formatedResult = array();
foreach($results as $k => $result){
if(!empty($result)){
$formatedResult[$k]["type"] = get_class($result[0]);
$formatedResult[$k]["data"] = $result[0];
}
}
return $formatedResult;
}
}
And my Controller for the search :
/**
* #Route("/search/{query}")
* #Template()
*/
public function indexAction($query)
{
$em = $this->getDoctrine()->getManager();
$searchables = new ArrayCollection(
array(
"SoundmergerUserBundle:Professional",
"SoundmergerFaqBundle:Faq",
"SoundmergerUserBundle:User",
));
$search = new Search($em, $searchables);
return array('search' => $search->search($query));
}
And finally my user entity :
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #AttributeOverrides({
* #AttributeOverride(name="emailCanonical",
* column=#ORM\Column(
* name = "emailCanonical",
* type = "string",
* length = 255,
* nullable = true
* )
* ),
* #AttributeOverride(name="email",
* column=#ORM\Column(
* name = "email",
* type = "string",
* length = 255,
* nullable = true
* )
* ),
* #AttributeOverride(name="username",
* column=#ORM\Column(
* name = "username",
* type = "string",
* length = 255,
* unique = false
* )
* ),
* #AttributeOverride(name="usernameCanonical",
* column=#ORM\Column(
* name = "usernameCanonical",
* type = "string",
* length = 255,
* unique = false
* )
* ),
* })
*/
class User extends BaseUser
{
const STRUCTURE_SOLO = "solo";
const STRUCTURE_GROUP = "group";
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $nomProfile = null;
/**
* #ORM\Column(type="text", nullable=true)
* #var string
*/
protected $description = null;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $type = null;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $structure = self::STRUCTURE_SOLO;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $tel = null;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $site = null;
/**
* #ORM\Column(type="boolean")
* #var bool
*/
protected $firstLogin = true;
/**
* #ORM\OneToOne(targetEntity="Soundmerger\MainBundle\Entity\Address", cascade={"persist"})
*/
protected $address;
/**
* #ORM\OneToMany(targetEntity="Soundmerger\MainBundle\Entity\Style", mappedBy="user", cascade={"persist"})
*/
protected $styles;
/**
* #ORM\OneToMany(targetEntity="Soundmerger\UserBundle\Entity\Member", mappedBy="user")
* #ORM\JoinColumn(nullable=true)
*/
protected $members;
/** #ORM\Column(name="discogs_id", type="string", length=255, nullable=true) */
protected $discogs_id;
/** #ORM\Column(name="discogs_access_token", type="string", length=255, nullable=true) */
protected $discogs_access_token;
public function __construct()
{
parent::__construct();
$this->members = new ArrayCollection();
$this->styles = new ArrayCollection();
}
/**
* Get id
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* Get NomProfile
* #return string
*/
public function getNomProfile()
{
return $this->nomProfile;
}
/**
* Get type
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Get structure
* #return string
*/
public function getStructure()
{
return $this->structure;
}
/**
* Get tel
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Get site
* #return string
*/
public function getSite()
{
return $this->site;
}
/**
* Get description
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set nomProfile
* #param string $nomProfile
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setNomProfile($nomProfile)
{
$this->nomProfile = $nomProfile;
return $this;
}
/**
* Set type
* #param string $type
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set structure
* #param string $structure
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setStructure($structure)
{
if (!in_array($structure, array(self::STRUCTURE_SOLO, self::STRUCTURE_GROUP))) {
throw new \InvalidArgumentException("Invalid structure");
}
$this->structure = $structure;
return $this;
}
/**
* Set tel
* #param string $tel
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Set site
* #param string $site
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Set description
* #param type $description
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Set the first login
* #param bool $firstLogin
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setFirstLogin($firstLogin)
{
$this->firstLogin = $firstLogin;
return $this;
}
/**
* Is it the first login
* #return bool returns true if its the first login, false otherwise
*/
public function isFirstLogin()
{
return $this->firstLogin;
}
/**
* Set address
*
* #param Address $address
* #return $this
*/
public function setAddress(Address $address)
{
$this->address = $address;
return $this;
}
/**
* Get adress
*
* #return mixed
*/
public function getAddress()
{
return $this->address;
}
/**
* #return Style
*/
public function getStyles()
{
return $this->styles;
}
/**
* #param Style $style
* #return $this
*/
public function addStyle(Style $style)
{
if (!$this->styles->contains($style)) {
$style->setUser($this);
$this->styles->add($style);
}
return $this;
}
public function setStyles(PersistentCollection $styles)
{
foreach ($styles as $style) {
$this->addStyle($style);
}
}
/**
* #return ArrayCollection
*/
public function getMembers()
{
return $this->members;
}
/**
* #param Member $members
*/
public function addMember(Member $member)
{
if (!$this->members->contains($member)) {
$this->members->add($member);
}
return $this;
}
public function setDiscogsId($discogs_id)
{
$this->discogs_id = $discogs_id;
return $this;
}
public function getDiscogsId()
{
return $this->discogs_id;
}
public function setDiscogsAccessToken($discogs_access_token)
{
$this->discogs_access_token = $discogs_access_token;
return $this;
}
public function getDiscogsAccessToken()
{
return $this->discogs_access_token;
}
public function isRegisteredWithDiscogs(){
return $this->discogs_id != null;
}
}
Any ideas on why this is only happening with the user entity (it must be due to the inheritance but i can't seem to find a way round it)
btw : its a university project so the idea of using an external bundle for the search is not really possible.
Thanks for any help
Dan

Symfony2 stof doctrine uploadable with 1..1 or n..1 relations

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.

Resources