Symfony2 Error: The options "value" do not exist in constraint - php

I have a Symfony FOSUserBundle which I am using with my Symfony2 application. I have run into a problem which I need help finding a solution to as I am not sure why it is showing up. After installation, I have tested the registration and login and they work but now when I try the resetting password, it gives me an error "The options "value" do not exist in constraint Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity". I have not modified the symfony2 vendor classes and I am sure I have not added anything else to FOSUserBundle to alter its behaviour. Here is my FOSUserBundle configuration:
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: Main\BundleName\Entity\User
service:
mailer: fos_user.mailer.twig_swift
registration:
confirmation:
enabled: true
from_email:
address: ....some email address here
sender_name: The senders name
Here is my Entity Class, I have truncated the setters and getters to reduce the length of this post:
namespace Main\BundleName\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* #ORM\Table(name="User")
* #ORM\Entity
* #UniqueEntity("email", message="A user with the specified email already exists")
* #UniqueEntity("username", message="A user with the specified username already exists")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
protected $password;
/**
* #var string
*/
protected $salt;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=200, nullable=true)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=200, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="thumbnail", type="string", length=200, nullable=true)
*/
// Getters and Setters ...truncated ....
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* 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;
}
}
Any ideas on how to fix this error?

I think the problem is on the uniqueEntity declaration
You should use #UniqueEntity(fields = "email", message="A message") instead of #UniqueEntity("email", message="A message").
When you pass more than one parameters to the UniqueEntity annotation you should declare each parameters. You can use #UniqueEntity("email") only if there is one parameters.
Hope it's helpful.
Best regard.

I faced a similar error when clearing the cache after i downgraded from Symfony 2.4 to 2.3.
[Symfony\Component\Validator\Exception\InvalidOptionsException]
The options "value" do not exist in constraint Symfony\Component\Validator\Constraints\Regex
#Benjamin Lazarecki answer helped me finding the solution
When i was in Symfony2.4 this annotation wasn't a problem:
#Assert\Regex("/^[0-9]{4}(?:-[0-9]{3})?$/", match=true, message="Format XXXX-XXX")
but after the downgrade it seems i need to be explicit when declaring the pattern like the annotation below:
#Assert\Regex(pattern="/^[0-9]{4}(?:-[0-9]{3})?$/", match=true, message="Format XXXX-XXX")

Related

Symfony $this->getUser() without doctrine associations (OneToMany)

In Symfony, we can get current logged-in user data using $this->getUser(), but my problem is when I access this statement, I am getting all the user-associated data set. which has OneToMany relationships with another entity, and it has a lot of data.
Example:
User Entity
`
class User implements UserInterface
{
/**
* #var string
* #ORM\Id
* #ORM\Column(type="string", length=10)
*
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string")
*/
protected $email;
/**
* #var array
* #ORM\Column(type="json")
*/
protected $roles;
/**
* One User has Many Posts.
* #ORM\OneToMany(targetEntity="App\Entity\Post", mappedBy="user", fetch="LAZY")
*
*
*/
private Collection $posts;
`
Post Entity
`
class Post
{
/**
* #var string
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", length=11)
*/
private $id;
/**
* Many posts have one user.
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="post", fetch="EXTRA_LAZY")
* #ORM\JoinColumn(name="userId", referencedColumnName="id")
*/
private $user;
`
I am looking to get rid of the user-associated data set or limit the associated data set to limit 1.
Thank you for the help in advance. :)
found solution after hours of search.
You will be required to add Symfony Serializer #Ignore attribute on the Entity class.
Example
use Symfony\Component\Serializer\Annotation\Ignore;
class User implements UserInterface
{
/**
* #var string
*
*/
#[ORM\Id]
#[ORM\Column(type: 'string', length: 10)]
protected $id;
/**
* #var string
*/
#[ORM\Column(type: 'string')]
protected $email;
/**
* #var array
*/
#[ORM\Column(type: 'json')]
protected $roles;
/**
* #var Post
*/
#[ORM\OneToMany(targetEntity: 'App\Entity\Post', mappedBy: 'user', fetch: 'LAZY')]
#[Ignore]
private Collection $posts;
I hope this help someone. Cheers!

Unrecognized id Field with Symfony 3 and FOSUserBundle

I keep getting the error in the title when I want to login using the FOSUserBundle on Symfony. The problem is, I already have an "id" for my User table from my database so I don't want to create an "id" field like they ask on the FOSUserBundle guide. I don't understand why it would give me this error when there is no more "id" field in my code.
Is this "id" field mandatory?
Here is the code of my User class (here called "Utilisateurs")`use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* Utilisateurs
*
* #ORM\Table(name="utilisateurs", indexes={#ORM\Index(name="FK_UTILISATEURS_id_sexe", columns={"id_sexe"}), #ORM\Index(name="FK_UTILISATEURS_id_niveau", columns={"id_niveau"})})
* #ORM\Entity
*/
class Utilisateurs extends BaseUser
{
public function __construct()
{
parent::__construct();
}
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=25, nullable=true)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=25, nullable=true)
*/
private $prenom;
/**
* #var \DateTime
*
* #ORM\Column(name="date_naissance", type="date", nullable=true)
*/
private $dateNaissance;
/**
* #var string
*
* #ORM\Column(name="url_photo", type="string", length=100, nullable=true)
*/
private $urlPhoto;
/**
* #var integer
*
* #ORM\Column(name="id_utilisateur", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idUtilisateur;
/**
* #var \Site\UserBundle\Entity\Sexes
*
* #ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\Sexes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_sexe", referencedColumnName="id_sexe")
* })
*/
private $idSexe;
/**
* #var \Site\UserBundle\Entity\Niveaux
*
* #ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\Niveaux")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_niveau", referencedColumnName="id_niveau")
* })
*/
private $idNiveau;`
As you can see I already have an "id_utilisateur" field which is the id of this entity.
And here is the code of the entity information in XML: The XML Code
Also here is a screenshot of the error I get when I try to log in: The Error
I think the problem is that per convention the id field is often called just id and in some places FOS UserBundle is expecting exactly that, e.g. in the UserProvider.
There are a few ways you can get around this. For instance you could just write your own UserProvder (using the one linked above as a reference) where you substitute the id with your field. You might have to do this in other places as well.
The easier solution would be to just change your entity to something like this:
/**
* #var integer
*
* #ORM\Column(name="id_utilisateur", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
public function getId() { return $this->id; }
Similarly in xml this would look like this:
<id name="id" column="id_utilisateur" type="integer">
<generator strategy="IDENTITY" />
</id>
This way in your entity you will use the expected property and accessor method, but in the background it will map to the database field id_utilisateur, so you you don't have to make any changes to your database.
This should already solve your problems. When a new user is generated Doctrine will take map $user->getId() to user_table.id_utilisateur automatically. If your existing code is making use of the old get-method you could just keep it around and mark it as deprecated:
/**
* #deprecated Use getId() instead.
*/
public function getIdUtilisateur()
{
return $this->getId();
}

Symfony 3 error : Case mismatch between loaded and declared class names

i've just got this error
Case mismatch between loaded and declared class names: MyApp\UserBundle\Entity\post vs MyApp\UserBundle\Entity\Post
i'm using two controllers to do a specific operation of delete and getting back to the old page
here is my button's code
<a href="{{ path('DeleteComment',{'idc':comment.id}) }}"> <i
class="icon-trash"></i>Delete</a>
here is my routing's code :
get_view_post:
path: /blog/get/one/post/{id}/
defaults: { _controller: "MyAppBlogBundle:Blog:getpost" }
DeleteComment:
path: /blog/post/comment/delete/{idc}/
defaults: { _controller: "MyAppBlogBundle:Blog:DeleteComment" }
here is my controllers code :
public function DeleteCommentAction($idc)
{
$em = $this->getDoctrine()->getManager();
$comment = $em->getRepository('MyAppUserBundle:PostComment')->find($idc);
$idPost =$comment->getIdPost();
$em->remove($comment);
$em->flush();
return $this->redirectToRoute("get_view_post", array('id' => $idPost));
}
public function getpostAction($id)
{
$user = $this->getUser();
$idu = $user->getId();
$em = $this->getDoctrine()->getManager();
$em1 = $this->getDoctrine()->getManager();
$post = $em->getRepository('MyAppUserBundle:Post')->find($id);
$idPost=$post->getId();
$comment = $em1->getRepository('MyAppUserBundle:PostComment')->findBy(array('idPost' => $idPost));
return $this->render('MyAppBlogBundle::afficherPostAvecComment.html.twig', array('posts' => $post,'comments'=>$comment,'idu'=>$idu));
}
i'm declaring my entities like this :
use MyApp\UserBundle\Entity\Post;
use MyApp\UserBundle\Entity\PostComment;
Here is my Entity
namespace MyApp\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var integer
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
* #ORM\Column(name="titre", type="string", length=100, nullable=false)
*/
private $titre;
/**
* #var string
* #ORM\Column(name="contenu", type="string", length=250, nullable=false)
*/
private $contenu;
/**
* #var \DateTime
* #ORM\Column(name="dateajout", type="datetime", nullable=true)
*/
private $dateajout ;
/**
* #var integer
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="id_utilisateur",referencedColumnName="id")
*/
private $idUser;
/**
* #var integer
* #ORM\Column(name="nbLike", type="integer", nullable=true)
*/
private $nbLike =0;
/**
* #var integer
* #ORM\Column(name="nbDislike", type="integer", nullable=true)
*/
private $nbDislike=0;
/**
* #var integer
* #ORM\Column(name="nbSignal", type="integer", nullable=true)
*/
private $nbSignal=0;
i did some changes in my code, as i see My IDE couldn't differentiate
between Post, PostComment and my array post or furthermore his own method of recuperation _POST.
you can see from the error above that it's based on hesitation between Post and post ,if you are using a latest version of Symfony, try to scan you whole project and change the names of your attributes or classes, believe it or not it creates some difficulties for the IDE when your project gets bigger
and here is what made the error gone:
old
/**
* #var integer
* #ORM\ManyToOne(targetEntity="post")
* #ORM\JoinColumn(name="id_post",referencedColumnName="id")
*/
private $idPost;
new
/**
* #var integer
* #ORM\ManyToOne(targetEntity="Post")
* #ORM\JoinColumn(name="id_post",referencedColumnName="id")
*/
private $idPost;
I was not giving the appropriate name of my Entity, so when I do any operation based on foreign keys, the IDE won't find any Entity of reference
if you are using and old version of Symfony, you have to add a line of code in some file's configuration
you can have a better explanation here:
Symfony2 error : Case mismatch between loaded and declared class names:
Once have look on the folder name of your userbundle file.
Since, you have mentioned UserBunlde in your namespace **(namespace MyApp\UserBundle\Entity;) then,
Your folder name must be UserBundle too.
If you have named as userBundle so that such error occurs.

PHP AppKernel Symfony Issue

Note People have marked this question as simmilar to others, but its not =- I am not using symfony and doctrine as a web framework, I am using symfony components with doctrine while using Slimphp as the actual web framework.
So while you might think I need an AppKernel I don't. I am using symfony components. The only issue here is that #UniqueEntity isn't working.
I have no idea what I am doing. I am getting the error:
Fatal error: Class 'doctrine.orm.validator.unique' not found in /var/www/html/image_upload_app/vendor/symfony/validator/ConstraintValidatorFactory.php on line 46
My AppKernel.php looks like:
namespace ImageUploader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel {
public function registerBundles() {
$bundles = array(
new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle()
);
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader) {}
}
From there I created a bootstrap.php with the following contents:
/** ---------------------------------------------------------------- **/
// Lets Setup Doctrine.
/** ---------------------------------------------------------------- **/
require_once 'vendor/autoload.php';
$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
/**
* Set up Doctrine.
*/
class DoctrineSetup {
/**
* #var array $paths - where the entities live.
*/
protected $paths = array(APP_MODELS);
/**
* #var bool $isDevMode - Are we considered "in development."
*/
protected $isDevMode = false;
/**
* #var array $dbParams - The database paramters.
*/
protected $dbParams = null;
/**
* Constructor to set some core values.
*/
public function __construct(){
if (!file_exists('db_config.ini')) {
throw new \Exception(
'Missing db_config.ini. You can create this from the db_config_sample.ini'
);
}
$this->dbParams = array(
'driver' => 'pdo_mysql',
'user' => parse_ini_file('db_config.ini')['DB_USER'],
'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
);
}
/**
* Get the entity manager for use through out the app.
*
* #return EntityManager
*/
public function getEntityManager() {
$config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
return EntityManager::create($this->dbParams, $config);
}
}
/**
* Function that can be called through out the app.
*
* #return EntityManager
*/
function getEntityManager() {
$ds = new DoctrineSetup();
return $ds->getEntityManager();
}
/**
* Function that returns the conection to the database.
*/
function getConnection() {
$ds = new DoctrineSetup();
return $ds->getEntityManager()->getConnection();
}
use \ImageUploader\AppKernel;
$kernel = new AppKernel();
$kernel->loadClassCache();
I am unsure why I keep getting this error, I have a model (entity) that looks as such:
namespace ImageUploader\Models;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #UniqueEntity(fields="userName")
* #UniqueEntity(fields="email")
*/
class User {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank(
* message = "Username cannot be blank"
* )
*/
protected $userName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank()
* #Assert\Email(
* message = "The email you entered is invalid.",
* checkMX = true
* )
*/
protected $email;
/**
* #ORM\Column(type="string", length=500, nullable=false)
* #Assert\NotBlank(
* message = "The password field cannot be empty."
* )
*/
protected $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $created_at;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $updated_at;
}
when I go to validate the model, I get the error listed above. I have installed doctrine bundle and I thought I set things up properly. But apparently not. Does any know know what I am doing wrong? Did I configure something wrong or not configure something at all?
You don't need to use the appkernel, I misunderstood your problem in your other question.
The problem is that you are using the UniqueValidator from the bridge. This is designed to work with the full-stack framework, not for standalone usage (only components are standalone).
This means you cannot use this constraint. Instead, you can use a pure Doctrine solution: #UniqueConstraint.

FOSUserBundle not applying User entity changes

I have just installed FosUserBundle in a Symfony version 2.3.3 application.
I'm able to manage users, login, register and whatnot but changes I make to my User class in MyApp\UserBundle\Entity aren't being applied when I run app/console doctrine:schema:update
The database structure contains:
id,
username,
username_canonical,
email,
email_canonical,
enabled,
salt,
password,
last_login,
locked,
expired,
expires_at,
confirmation_token,
password_requested_at,
roles,
credentials_expired,
credentials_expire_at
The field that I have added, rate, isnt being created in the database structure no matter what I do.
Inside /app/AppKernel.php
new MyApp\UserBundle\MyAppUserBundle(),
new FOS\UserBundle\FOSUserBundle(),
Inside /app/config/config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: MyApp\UserBundle\Entity\User
registration:
confirmation:
enabled: true
And inside /src/MyApp/UserBundle/Entity/User.php
<?php
namespace MyApp\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="fos_user")
* #ORM\Entity(repositoryClass="MyApp\UserBundle\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="token", type="string", length=255)
*/
private $token;
/**
* #var integer
*
* #ORM\Column(name="rate", type="integer")
*/
private $rate;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set token
*
* #param string $token
* #return User
*/
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* Get token
*
* #return string
*/
public function getToken()
{
return $this->token;
}
/**
* Set rate
*
* #param integer $rate
* #return User
*/
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
/**
* Get rate
*
* #return integer
*/
public function getRate()
{
return $this->rate;
}
}
Don't forget the constructor, clear the cache and try php app/console doctrine:schema:update --force
namespace Acme\UserBundle\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;
public function __construct()
{
parent::__construct();
// your own logic
}
}
Need to add MyUserBundle mappings to your config.yml file:
doctrine:
orm:
mappings:
FOSUserBundle: ~
MyUserBundle: ~

Categories