I'm trying to override the entities validatation of a forum bundle.
I do it like this:
Category entity:
//src/MSD/ForoBundle/Entity/Category.php
namespace MSD\ForoBundle\Entity;
use Herzult\Bundle\ForumBundle\Entity\Category as BaseCategory;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="Herzult\Bundle\ForumBundle\Entity\CategoryRepository")
*/
class Category extends BaseCategory
{
}
Topic entity:
//src/MSD/ForoBundle/Entity/Topic.php
namespace MSD\ForoBundle\Entity;
use Herzult\Bundle\ForumBundle\Entity\Topic as BaseTopic;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Topic
*
* #ORM\Entity(repositoryClass="Herzult\Bundle\ForumBundle\Entity\TopicRepository")
*
*/
class Topic extends BaseTopic
{
/**
* #ORM\ManyToOne(targetEntity="Category")
*/
protected $category;
/**
* #Assert\NotBlank()
* #Assert\MinLength(limit=4, message="Just a little too short| ")
* #Assert\Regex(
* pattern="/^[a-zA-Z0-9\-_¿?!¡ ]{4,50}$/",
* message="El tema puede contener letras, números, guiones y espacios, interrogantes y exclamaciones. Entre 4 y 30 caracteres"
* )
*/
protected $subject;
/**
* {#inheritDoc}
*/
public function getAuthorName()
{
return $this->author;
}
/**
* #ORM\ManyToOne(targetEntity="User")
*/
private $author;
public function setAuthor(User $user)
{
$this->author = $user;
}
public function getAuthor()
{
return $this->author;
}
}
Post Entity:
//src/MSD/ForoBundle/Entity/Post.php
namespace MSD\ForoBundle\Entity;
use Herzult\Bundle\ForumBundle\Entity\Post as BasePost;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="Herzult\Bundle\ForumBundle\Entity\PostRepository")
*/
class Post extends BasePost
{
/**
* #ORM\ManyToOne(targetEntity="Topic")
*/
protected $topic;
/**
* #Assert\Regex(
* pattern="/^[^<>]{4,1000}$/",
* message="El mensaje no puede contener '<' ni '>'. Entre 4 y 1000 caracteres"
* )
*
*/
public $message;
public function getAuthorName()
{
return $this->author;
}
/**
* #ORM\ManyToOne(targetEntity="User")
*/
private $author;
public function setAuthor(User $user)
{
$this->author = $user;
}
public function getAuthor()
{
return $this->author;
}
}
And the validation works... except the message of the firt post!! that is created when a new topic is created.
I've tried many changes, but without success.
Any idea of why does it happend?
Thank you
Yeah! I got it. The solution was to add this in the Topic entity:
/**
* #Assert\NotBlank
* #Assert\Valid
*/
protected $firstPost;
Then, the message of the first post is validated.
Related
I have a simple project in laravel 5.4 with Doctrine 2.0. I have three tables: users, roles, user_roles. Screenshot from tables schemas from HEIDISQL I show below:
users:
roles:
user_roles:
I have three Entities classes for each table of course:
<?php
namespace TodoList\Http\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*
*/
private $id;
/**
*
* #ORM\Column(type="string")
*
*/
private $name;
/**
*
* #ORM\Column(type="string")
*
*/
private $email;
/**
* #ORM\OneToMany(targetEntity="Task", mappedBy="user", cascade={"persist"})
* #var ArrayCollection|Task[]
*/
private $tasks;
/**
* #ORM\OneToMany(targetEntity="UserRole", mappedBy="user")
*/
protected $user_roles;
/**
* User constructor
* #param #name
* #param #email
* #param $password
*/
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
$this->tasks = new ArrayCollection();
$this->user_roles = new ArrayCollection();
}
/**
*
* #return mixed
*
*
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* #return mixed
*/
public function getTasks()
{
return $this->tasks;
}
public function addTask(Task $task)
{
if(!$this->tasks->contains($task)) {
$task->setUser($this);
$this->tasks->add($task);
}
}
public function getId(){
return $this->id;
}
public function getUserRoles(){
return $this->user_roles;
}
}
<?php
namespace TodoList\Http\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="roles")
*
*/
class Role{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string")
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="UserRole", mappedBy="role",cascade={"persist"})
*/
protected $user_roles;
public function getId(){
return $this->id;
}
public function getName(){
return $this->name;
}
public function getDescription(){
return $this->description;
}
}
<?php
namespace TodoList\Http\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="user_roles")
*/
class UserRole
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="User", inversedBy="user_roles")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*
*/
private $user;
/**
*
* #ORM\ManyToOne(targetEntity="Role", inversedBy="user_roles")
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
*/
private $role;
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \NVC\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set recipe
*
* #param \NVC\RecipeBundle\Entity\Recipe $recipe
* #return UserRecipeAssociation
*/
public function setRole(Role $role)
{
$this->role = $role;
return $this;
}
/**
* Get recipe
*
* #return \NVC\RecipeBundle\Entity\Recipe
*/
public function getRole()
{
return $this->role;
}
}
I have a problem when I'm trying retrieve roles of particular user by doctrine Entity Managar. I'm trying to do that in that way:
public function showUserRoles(EntityManagerInterface $em){
$userRoles = $em->getRepository('\TodoList\Http\Entities\UserRole');
$userRoles->findBy(['user' => 2]);
//count($userRole);
}
There is an error from method findBy
Error message is:
(1/1) FatalErrorException
Doctrine\Common\Proxy\AbstractProxyFactory::getProxyDefinition():
Failed opening required
'C:\xampp\htdocs\Project\storage\proxies__CG__TodoListHttpEntitiesRole.php'
(include_path='C:\xampp\php\PEAR')
Is anything wrong with my Entities? I don't know how could I solve that problem. Could someone help me with that?
I would be very greateful
Best regards ;)
You need to set folder C:\xampp\htdocs\Project\storage\proxies\ as writable and then you need to generate proxies by console command:
doctrine:generate:proxies
I am using FOSUserBundle
I created a User entity that extents baseuser, and I added a protected property I called $apiKey. The registration form works fine.
then, I created a userController that extends controller, and in a methoid to edit my user I have:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')->find($id);
my $user has the apiKey property but this is empty (of course the field in the DB is not).
any idea?
thanks
UPDATE: user entity
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
/**
* #ORM\Column(type="string", unique=true, nullable=true)
*/
protected $apiKey;
/* public function __construct()
{
parent::__construct();
// your own logic
//$this->roles = array('ROLE_USER'); //default role for new users
}*/
public function __construct()
{
parent::__construct();
// your own logic
$this->groups = new ArrayCollection();
}
/**
* #return mixed
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param mixed $apiKey
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* #return mixed
*/
public function getGroups()
{
return $this->groups;
}
/**
* #param mixed $groups
*/
public function setGroups($groups)
{
$this->groups = $groups;
}
}
I have problem with translation of new inputs in the registration form in FOSUSER. Basicly I Extended the FOS user Entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Fill it", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="To short.",
* maxMessage="To long.",
* groups={"Registration", "Profile"}
* )
*/
protected $nameU;
public function getNameU() {
return $this->nameU;
}
public function setNameU($nameU) {
$this->nameU= $nameU;
}
Ovveride the registration FORM
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Gregwar\CaptchaBundle\Type\CaptchaType;
use FOS\UserBundle\Util\LegacyFormHelper;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nameU')
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
// For Symfony 2.x
public function getName()
{
return $this->getBlockPrefix();
}
}
In my registration view I have:
{{ form_label(form.nameU, null,{}) }}
Add to translation specific declaration for a locale of FOS USER BUNDLE in app/Resource/FosUser../translation/.....
form:
group_name: Gruppenname
username: Benutzername TEST <- this change OK
nameU: TESTS <- this not
The translation is not working and it's look like variable name nameU :(
Ok. I have found it. I forget to send it in the registration type:
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->
->add('numeU',null, array('label' => 'form.nameU', 'translation_domain' => 'FOSUserBundle'))
I am trying to make custom validator in symfony 2, but it loads from wrong namespace. Error says:
Attempted to load class "DateChecker" from namespace "Symfony\Component\Validator\Constraints\Errand\MainBundle\Validator\Constraints.
Here is my code:
MainBundle/Validator/Constraints/DateCheker.php:
<?php
namespace Errand\MainBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* #Annotation
*/
class DateChecker extends Constraint
{
/**
*
* #var string
*/
public $message = 'some message';
/**
*
* #return string
*/
public function validatedBy()
{
return get_class($this).'Validator';
}
/**
* Get class constraints and properties
*
* #return array
*/
public function getTargets()
{
return array(self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT);
}
}
MainBundle/Validator/Constraints/DateCheckerValidator.php:
namespace Errand\MainBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class DateCheckerValidator extends ConstraintValidator
{
/**
* Method to validate
*
* #param string $value Property value
*
*
* #return boolean
*/
public function validate($value, Constraint $constraint)
{
//validation
}
}
MainBundle/Resources/config/validation.yml:
Errand\MainBundle\Entity\Task:
constraints:
- Errand\MainBundle\Validator\Constraints\DateChecker: ~
My current Client-Entity has an unloading and a loading Area, which are both ClientArea-Entities.
namespace ACME\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sorien\DataGridBundle\Grid\Mapping as GRID;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ACME\DemoBundle\Entity\Client
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="ACME\DemoBundle\Entity\ClientRepository")
*/
class Client
{
/**
* #ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"})
*/
public $unloading_areas;
/**
* #ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"})
*/
public $loading_areas;
}
class ClientArea
{
/**
* #ORM\ManyToOne(targetEntity="Client")
*/
public $client;
}
This does not work because client can only map 1 association.
How can i map the relation properly?
To create entity relations you need to have keys to use when joining tables. Your Client class should have an id key defined and you need to initialize collections, like this:
class Client
{
//....
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"})
*/
public $unloading_areas;
/**
* #ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"})
*/
public $loading_areas;
public function __construct() {
// Initialize collections
$this->unloading_areas = new \Doctrine\Common\Collections\ArrayCollection();
$this->loading_areas = new \Doctrine\Common\Collections\ArrayCollection();
}
// ....
}
Your ClientArea class should then look something like this:
class ClientArea
{
// ....
/**
* #ORM\Column(name="client_id", type="int", nullable=false)
*/
private $clientId;
/**
* #ORM\ManyToOne(targetEntity="Client")
* #JoinColumn(name="client_id", referencedColumnName="id")
*/
public $client;
// ....
}
Now, those two entities should be mapped correctly.
To learn more about association mappings in Doctrine, read article here: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html
Hope this helps.