Nelmio API doc bundle post request with boolean always returns true - rest

I'm developping a Symfony 4 API REST app with Nelmio Api Doc Bundle v3.
I am sending this request :
curl -X POST "http://dev.api_events.jessie/api/event-types" -H "accept: application/json" -H "Authorization: Bearer ZmU1MTgxNzNkZjM5ZTU2NzdiODVkODgxMmE2ZmE2OWUyMjY1ZWIxYzgxMjdlOTA3NjBiODM5Yzg1NTEzNjFlYw" -H "Content-Type: application/x-www-form-urlencoded" -d "fullName=aaaaaaaaaaa&shortName=aaaaaaaaaaa&dns=aaaaaaaaaa**&mandatoryRegistration=false"**
This is the response body :
{
"id": 19,
"full_name": "aaaaaaaaaaa",
"short_name": "aaaaaaaaaaa",
"dns": "aaaaaaaaaa",
**"mandatory_registration": true,**
"places": [],
"participation_types": []
}
I have absolutely no idea why i send mandatoryRegistration=false and my response have "mandatory_registration": true.
I paste my Controller, Form, Entity code below. And the nelmio api doc and fos_rest configuration code.
Controller :
/**
* Creates a new eventType entity.
*
* #Route("/event-types", methods="POST")
* #Operation(
* tags={"event_type"},
* summary="Creates a new event type entity",
* consumes={"application/x-www-form-urlencoded"},
* #SWG\Parameter(
* name="Authorization",
* in="header",
* description="Bearer",
* required=true,
* type="string"
* ),
* #SWG\Parameter(
* name="fullName",
* in="formData",
* description="event type full name",
* required=true,
* type="string"
* ),
* #SWG\Parameter(
* name="shortName",
* in="formData",
* description="event name",
* required=true,
* type="string"
* ),
* #SWG\Parameter(
* name="dns",
* in="formData",
* description="event type dns",
* required=true,
* type="string"
* ),
* #SWG\Parameter(
* name="mandatoryRegistration",
* in="formData",
* description="is the registration mandatory?",
* required=true,
* type="boolean"
* ),
* #SWG\Response(
* response=Response::HTTP_CREATED,
* description="Event Type created",
* #Model(type=EventType::class, groups={"event_type"})
* )
* )
*
*/
public function postEventTypeAction(Request $request, EntityManagerInterface $em)
{
$event_type = new EventType();
$form = $this->createForm(EventTypeType::class, $event_type);
$form->submit($request->request->all()); // Validation des données
if ($form->isValid()) {
$em->persist($event_type);
$em->flush();
return View::create($event_type, Response::HTTP_CREATED , []);
}
else{
return View::create($form, Response::HTTP_BAD_REQUEST , []);
}
}
EventType form :
class EventTypeType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('fullName'
)
->add('shortName')
->add('dns')
->add('mandatoryRegistration')
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => EventType::class
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'event_type';
}
}
EventType entity :
class EventType
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Groups({"event_type","place"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="full_name", type="string", length=255, unique=true)
* #Groups({"event_type","place","event_type_form_data"})
*/
private $fullName;
/**
* #var string
*
* #ORM\Column(type="string", length=255, unique=true)
* #Groups({"event_type","place","event_type_form_data"})
*/
private $shortName;
/**
* #var string
*
* #ORM\Column(name="dns", type="string", length=255, unique=true)
* #Groups({"event_type","event_type_form_data"})
*/
private $dns;
/**
* #var bool
*
* #ORM\Column(name="mandatory_registration", type="boolean", nullable=true)
*
* #Groups({"event_type","event_type_form_data"})
*/
private $mandatoryRegistration;
/**
* #ORM\OneToMany(targetEntity="Place", mappedBy="eventType", cascade={"persist"})
*/
private $places;
/**
* #ORM\OneToMany(targetEntity="EventTypeParticipationType", mappedBy="eventType", cascade={"persist"})
*/
private $participationTypes;
Config :
nelmio_api_doc:
documentation:
info:
title: Api Events
description: L4M Admin Events access point.
version: 1.0.0
security_definitions:
api_key:
type: apiKey
name: authorization
in: header
security:
api_key: []
sandbox:
request_format:
method: accept_header
accept_type: application/json
body_format:
formats: [ form, json ] # array of enabled body formats,
# remove all elements to disable the selectbox
default_format: form
areas: # to filter documented routes
path_patterns:
- ^/api(?!/doc$) # Accepts routes under /api except /api/doc
- ^/oauth/v2/token
fos_rest:
param_fetcher_listener: true
body_listener: true
#allowed_methods_listener: true
routing_loader: true
view:
view_response_listener: true
formats:
json: true
# exception:
# codes:
# App\Exception\MyException: 403
# messages:
# App\Exception\MyException: Forbidden area.
format_listener:
enabled: true
rules:
- { path: ^/, prefer_extension: false, fallback_format: json, priorities: [ json, xml, html ] }

I tried some debug and find out i was trying to put a string in a boolean field which always returns true ...
Here's my solution : do not send "false" in the request, instead send 0 or 1 :
Controller edit :
/* #SWG\Parameter(
* name="mandatoryRegistration",
* in="formData",
* description="is the registration mandatory?",
* required=true,
* type="integer",
* enum={0,1}
* ),

Related

symfony3 entity form validation not working

even doing copy/paste of this constraits, nothing hapens, i have disabled the html validations also, this is the code : twig:
{{form_start(form, {'action':'', 'method':'POST'})}}
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
{{form_end(form)}}
here the class:
class Curso {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\MaxLength(15)
* #ORM\Column(name="titulo", type="string", length=255)
*/
private $titulo;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(
* min = 2,
* max = 50,
* minMessage = "Your first name must be at least {{ limit }} characters long",
* maxMessage = "Your first name cannot be longer than {{ limit }} characters"
* )
* #Assert\Type("string")
* #ORM\Column(name="descripcion", type="string", length=255)
*/
private $descripcion;
/**
* #var float
* #Assert\NotBlank()
* #ORM\Column(name="precio", type="float")
*/
private $precio;
/**
* Get id
* #Assert\NotBlank()
* #return int
*/
public function getId() {
return $this->id;
}
/**
* Set titulo
*
* #param string $titulo
*
* #return Curso
*/
public function setTitulo($titulo) {
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo() {
return $this->titulo;
}
/**
* Set descripcion
*
* #param string $descripcion
*
* #return Curso
*/
public function setDescripcion($descripcion) {
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* #return string
*/
public function getDescripcion() {
return $this->descripcion;
}
/**
* Set precio
*
* #param float $precio
*
* #return Curso
*/
public function setPrecio($precio) {
$this->precio = $precio;
return $this;
}
/**
* Get precio
*
* #return float
*/
public function getPrecio() {
return $this->precio;
}
}
can you tell me what is wrong? sorry about my english, i'm a little rusty :)!!!
You may want to check your app/config.yml and make sure that the you have annotations enabled for validation
framework:
...
validation: { enable_annotations: true }

I get error when I created one form with 2 entities mapped

I have 2 entities, Topic.php and Post.php I would like to have this:
TopicType.php :
<?php
namespace BISSAP\ForumBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TopicType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text', array(
'label' => 'Titre'))
->add('subForm', new PostType())
->add('save', 'submit', array(
'attr' => array(
'class' => 'btn right-flt')))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BISSAP\ForumBundle\Entity\Topic'
));
}
/**
* #return string
*/
public function getName()
{
return 'bissap_forumbundle_topic';
}
}
PostType.php :
<?php
namespace BISSAP\ForumBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PostType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', 'ckeditor', array(
'label' => 'Votre message',
'config_name' => 'my_custom_config',
'config' => array('language' => 'fr')))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BISSAP\ForumBundle\Entity\Post'
));
}
/**
* #return string
*/
public function getName()
{
return 'bissap_forumbundle_post';
}
}
Topic.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/*use BISSAP\BodyConcept\Entity\Forum;
*/
/**
* Topic
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\TopicRepository")
*/
class Topic
{
/**
* #ORM\ManyToOne(targetEntity="Forum", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $forum;
/**
* #var ArrayCollection $Posts
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="Topic", cascade={"persist", "remove", "merge"})
*/
private $posts;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var integer
*
* #ORM\Column(name="view_count", type="integer")
*/
private $viewCount;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var integer
*
* #ORM\Column(name="reply_count", type="integer")
*/
private $replyCount;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="genre", type="string", length=255)
*/
private $genre;
/**
* #var integer
*
* #ORM\Column(name="last_post", type="integer")
*/
private $lastPost;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Topic
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user
*
* #param integer $user
* #return Topic
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUser()
{
return $this->user;
}
/**
* Set viewCount
*
* #param integer $viewCount
* #return Topic
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* Get viewCount
*
* #return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Topic
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set replyCount
*
* #param integer $replyCount
* #return Topic
*/
public function setReplyCount($replyCount)
{
$this->replyCount = $replyCount;
return $this;
}
/**
* Get replyCount
*
* #return integer
*/
public function getReplyCount()
{
return $this->replyCount;
}
/**
* Set slug
*
* #param string $slug
* #return Topic
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set genre
*
* #param string $genre
* #return Topic
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* #return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* Set lastPost
*
* #param integer $lastPost
* #return Topic
*/
public function setLastPost($lastPost)
{
$this->lastPost = $lastPost;
return $this;
}
/**
* Get lastPost
*
* #return integer
*/
public function getLastPost()
{
return $this->lastPost;
}
/**
* Set content
*
* #param string $content
* #return Topic
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set forum
*
* #param Forum $forum
* #return Topic
*/
/*public function setForum(\BISSAP\BodyConceptBundle\Entity\Forum $forum)*/
public function setForum(Forum $forum)
{
$this->forum = $forum;
return $this;
}
/**
* Get forum
*
* #return \BISSAP\BodyConceptBundle\Entity\Forum
*/
public function getForum()
{
return $this->forum;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime();
}
/**
* Add posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
* #return Topic
*/
public function addPost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
*/
public function removePost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
Post.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modif", type="datetime")
*/
private $dateModif;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #ORM\ManyToOne(targetEntity="Topic", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $topic;
/**
* Constructor
*/
public function __construct()
{
$this->dateCreation = new \DateTime();
$this->dateModif = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* #param string $content
* #return Post
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Post
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set dateModif
*
* #param \DateTime $dateModif
* #return Post
*/
public function setDateModif($dateModif)
{
$this->dateModif = $dateModif;
return $this;
}
/**
* Get dateModif
*
* #return \DateTime
*/
public function getDateModif()
{
return $this->dateModif;
}
/**
* Set slug
*
* #param string $slug
* #return Post
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set Topic
*
* #param Topic $topic
* #return Post
*/
/*public function setTopic(\BISSAP\ForumBundle\Entity\Topic $topic)*/
public function setTopic(Topic $topic)
{
$this->topic = $topic;
return $this;
}
/**
* Get Topic
*
* #return \BISSAP\ForumBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
/**
* Set user
*
* #param \BISSAP\ForumBundle\Entity\User $user
* #return Post
*/
public function setUser(\BISSAP\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \BISSAP\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
And this is my part of my controller, here i call and use the form:
public function categoryAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$topic = new \BISSAP\ForumBundle\Entity\Topic();
$form = $this->createForm(new TopicType(), $topic);
$user = $this->getUser();
$forum = $em->getRepository('BISSAPForumBundle:Forum')->find(1);
if ($form->handleRequest($request)->isValid()) {
$topic->setUser($user);
$topic->setForum($forum);
$topic->setViewCount(23);
$topic->setReplyCount(123);
$topic->setLastPost(25);
$topic->setSlug('slug_sluggg');
$topic->setGenre('genre');
$em->persist($topic);
$em->flush();
return $this->render('BISSAPForumBundle:F:topic-forum.html.twig', array('user' => $user, 'topic' => $topic));
}
return $this->render('BISSAPForumBundle:F:category-forum.html.twig', array('listTopics' => $listTopics, 'catId' => $catId, 'form' => $form->createView(), 'user' => $user));
}
I have this error : Neither the property "subForm" nor one of the methods "getSubForm()", "isSubForm()", "hasSubForm()", "__get()" exist and have public access in class "BISSAP\ForumBundle\Entity\Topic".
Sur the way is wrong, cause i think, I need to give "$topic objexct" and "$post object" when i used :
$form = $this->createForm(new TopicType(), $topic);
And I had tried, with add(collection) i get similar error!
Thanks U.
The error you get is because you don't have "subform" attribute in your topic class. That name should correspond to the name of the attribute in your topic class.
So this:
->add('subForm', new PostType())
Should be changed to
$builder->add('posts','collection', array( 'type' => new PostType()))
This would be helpful.

Symfony2 REST API, always returns false validating the form

I'm following the Web API REST with Symfony2 to build a REST API in symfony2 using Fosrestbundle and JMS Serializer and for GET routes works perfectly but not with POST because when I'm validating the form always returns false and even I followed the flow of the functions and in the last step returns true in $form->isValid(), so I'm confused.
And even doesn't take in account the validations.yml file so, Is a lot of code but hope you can help me because for two days I've been trying to figure out the problem
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: doctrine_extensions.yml }
framework:
validation: { enable_annotations: true }
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
sensio_framework_extra:
view: { annotations: false }
router: { annotations: true }
request: { converters: true }
fos_rest:
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
json: true
xml: true
templating_formats:
html: true
format_listener:
rules:
- { path: ^/api, priorities: ['json', 'xml'], fallback_format: json, prefer_extension: false }
- { path: ^/, priorities: ['html', '*/*'], fallback_format: html, prefer_extension: false }
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
allowed_methods_listener: true
access_denied_listener:
json: true
body_listener: true
disable_csrf_role: ROLE_API
validations.yml
# src/Acme/MyBundle/Resources/config/validation.yml
Acme\MyBundle\Entity\Vendor:
properties:
name:
- NotBlank: ~
- NotNull: ~
- Length:
min: 2
max: 50
minMessage: "Your name must be at least {{ limit }} characters length"
maxMessage: "Your name cannot be longer than {{ limit }} characters length"
email:
- Email:
message: "The email {{ value }} is not a valid email"
checkMX: true
password:
- NotBlank: ~
- NotNull: ~
Vendor entity
<?php
namespace Acme\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\MyBundle\Model\VendorInterface;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer;
/**
* Vendor
*
* #ORM\Table(name="vendors")
* #ORM\Entity()
* #ExclusionPolicy("all")
*/
class Vendor implements VendorInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Expose
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50)
* #Expose
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=50)
* #Expose
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=200)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="picture", type="string", length=50)
* #Expose
*/
private $picture;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
* #Gedmo\Timestampable(on="create")
* #Expose
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
* #Gedmo\Timestampable(on="create")
* #Expose
*/
private $updatedAt;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Vendor
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* #param string $email
* #return Vendor
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
* #return Vendor
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set description
*
* #param string $description
* #return Vendor
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set picture
*
* #param string $picture
* #return Vendor
*/
public function setPicture($picture)
{
$this->picture = $picture;
return $this;
}
/**
* Get picture
*
* #return string
*/
public function getPicture()
{
return $this->picture;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Vendor
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Vendor
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
}
VendorController.php
<?php
namespace Acme\MyBundle\Controller;
.....
class VendorController extends FOSRestController
{
public function postVendorAction(Request $request)
{
try {
$form = new VendorType();
$newVendor = $this->container->get('acme_mybundle.vendor.handler')->post(
$request->request->all()
);
$routeOptions = array(
'id' => $newVendor->getId(),
'_format' => $request->get('_format')
);
return $this->routeRedirectView('api_get_vendor', $routeOptions, Codes::HTTP_CREATED);
} catch (InvalidFormException $exception) {
return $exception->getForm();
}
}
protected function getOr404($id)
{
if (!($vendor = $this->container->get('acme_mybundle.vendor.handler')->get($id))) {
throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$id));
}
return $vendor;
}
}
VendorType.php
namespace Acme\MyBundle\Form;
...
class VendorType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('password')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\MyBundle\Entity\Vendor',
));
}
/**
* #return string
*/
public function getName()
{
return '';
}
}
VendiorHandler.php
<?php
namespace Acme\MyBundle\Handler;
....
class VendorHandler implements VendorHandlerInterface
{
private $om;
private $entityClass;
private $repository;
private $formFactory;
public function __construct(ObjectManager $om, $entityClass, FormFactoryInterface $formFactory)
{
$this->om = $om;
$this->entityClass = $entityClass;
$this->repository = $this->om->getRepository($this->entityClass);
$this->formFactory = $formFactory;
}
/**
* Create a new Vendor.
*
* #param array $parameters
*
* #return VendorInterface
*/
public function post(array $parameters)
{
//die(var_dump("post handler"));
$vendor = $this->createVendor();
return $this->processForm($vendor, $parameters, 'POST');
}
/**
* Processes the form.
*
* #param VendorInterface $vendor
* #param array $parameters
* #param String $method
*
* #return VendorInterface
*
* #throws \Acme\MyBundle\Exception\InvalidFormException
*/
private function processForm(VendorInterface $vendor, array $parameters, $method = "PUT")
{
$form = $this->formFactory->create(new VendorType(), $vendor, array('method' => $method));
$form->submit($parameters, 'PATCH' !== $method);
if (!$form->isValid()) {
$vendor = $form->getData();
$this->om->persist($vendor);
$this->om->flush($vendor);
return $vendor;
}
throw new InvalidFormException('Invalid submitted data', $form);
}
private function createVendor()
{
return new $this->entityClass();
}
}
There seems to be two easy ways to set constraints for your entities.
validation.yml
Create an yml file in your Bundle:
# src/Acme/BlogBundle/Resources/config/validation.yml
Acme\BlogBundle\Entity\Author:
properties:
name:
- NotBlank: ~
For this to work automatically, it's important that the file has that very same name and is in that exact path. Then, you have enable validation and disable annotations.
# app/config/config.yml
framework:
validation: { enabled: true, enable_annotations: false }
Annotations
You don't need any special files for this. Just specify the constraints along the properties of your Entity:
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* #Assert\NotBlank()
*/
public $name;
}
Remember to enable the use of annotations:
# app/config/config.yml
framework:
validation: { enable_annotations: true }
Problems
If you want to use both validation.yml and annotations, or you want to use a different name or path for your validation file/s then you have to load them manually.
Take a look at this for further information: https://stackoverflow.com/a/24210501

How make query for findBy two users in relation ManyToMany

I have 3 tables Chat(id + info) User(id + some info) and relation table chat_invited(chatId+userId)
I am using ZF2 and Doctrine2
I have Entity chat:
<?php
namespace Chat\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Chat
*
* #ORM\Table(name="chat")
* #ORM\Entity
*/
class Chat
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=256, nullable=true)
*/
private $title;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime", nullable=false)
*/
private $created;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Chat\Entity\User", inversedBy="chat")
* #ORM\JoinTable(name="chat_invited",
* joinColumns={
* #ORM\JoinColumn(name="chat", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="user", referencedColumnName="id")
* }
* )
*/
private $user;
/**
* #var \Chat\Entity\ChatCategory
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\ChatCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \Chat\Entity\User
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="owner", referencedColumnName="id")
* })
*/
private $owner;
/**
* #var \Chat\Entity\Building
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\Building")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="building", referencedColumnName="id")
* })
*/
private $building;
/**
* #var \Chat\Entity\Company
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\Company")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="company", referencedColumnName="id")
* })
*/
private $company;
/**
* Constructor
*/
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add user
*
* #param \Chat\Entity\User $user
* #return Chat
*/
public function addUser(\Chat\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \Chat\Entity\User $user
*/
public function removeUser(\Chat\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
........................................
}
How find chat which have invited User1 and User2 to him?
Its worked for me
$qb = $em->createQueryBuilder();
$query = $qb->select('chats, user')
->from('Chat\Entity\Chat', 'chats')
->join('chats.user', 'user')
->join('chats.user', 'user2')
->where('user.id = :user AND user2.id = :inv ')
->setParameter('user', <User1.id>)
->setParameter('inv',<User2.id>)
->setMaxResults(1)
->getQuery();

Symfony 2.1 : How to set default value based on my user in drop down list

I want to create a form with a drop-down list and text field.
My drop-down list contains values of my Agency Entity and my text field a week number.
I want to set default value based on my connected user but I don't know how.
I have modified my entity, my form and my controller:
I have an Entity Week with my Agency relation :
class Week
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="Agency", inversedBy="week", cascade={"persist"})
* #ORM\JoinColumn(name="agency_id", referencedColumnName="id")
*/
private $agency;
/**
* #var integer
*
* #ORM\Column(name="week_number", type="integer")
*/
private $week_number;
/**
* #var \DateTime
*
* #ORM\Column(name="week_start", type="datetime")
*/
private $week_start;
/**
* #var \DateTime
*
* #ORM\Column(name="week_end", type="datetime")
*/
private $week_end;
public function getAgency()
{
return $this->agency;
}
.... public function get.....
}
Then my Agency Entity :
class Agency
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50)
*/
private $name;
/**
* #var integer
*
* #ORM\Column(name="nb_team", type="integer")
*/
private $nb_team;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $date_creation;
/**
*
* #ORM\OneToMany(targetEntity="Week", mappedBy="agency", cascade={"persist"})
*/
private $week;
public function .....
}
My Form :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('agency', 'entity', array(
'class' => 'MyProjectBundle:Agency',
'property' => 'name',
/* 'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('a')->orderBy('a.name', 'ASC');
},*/
'attr' => array('onchange' => 'javascript:this.form.submit();')
))->add('week_number', 'text');
}
And my Controller :
$num_week = 4;
$id = 3;
$agency_id = $em->getRepository('MyProjectBundle:Agency')->find($id);
$week = $em->getRepository('MyProjectBundle:Week')->WeekExiste($num_week, $week_start, $agency_id);
$form2 = $this->createForm(new FormType(), $week);
if ($request->isMethod('POST')) {
$form2->bind($request);
$data = $form2->getData();
$agency = $data['agency'];
}
else {
$agency = $em->getRepository('MyProjectBundle:Agency')->find($id);
}
$week return a correct Entity.
My form works for the week_number field but my drop down list doesn't select my agency I set in my controller.
I had the same problem with the default option value, you can check it on my question.
I've shared a full code.
symfony2 selected option