PHP AppKernel Symfony Issue - php

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.

Related

Class "App\Entities\Test" is not a valid entity or mapped super class. PHP, Doctrine

I catch this error
Class "App\Entities\Test" is not a valid entity or mapped super class
Path to entities is correct
Database's name is too correct. I have checked its about million times.
My entity:
namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Test
* #package App\Entities
* #ORM\Entity
* #ORM\Table(name="test")
*/
class Test
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="id")
*/
protected int $id;
/**
* #ORM\Column(type="string", name="name")
*/
protected string $name;
/**
* #ORM\Column(type="string", name="pass")
*/
protected string $password;
//Getters and setters
}
Initialization:
$test = new Test();
$test->setName('name');
$test->setPassword('123');
$entityManager = $this->container->get(EntityManager::class);
$entityManager->persist($test);
$entityManager->flush();
Where is my mistake? I re-readed documentations many times, googled it

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.

Symfony2 Session as Entity / Clearing old sessions without remember me

how i can use the $sessData, which is a blob?
Example entity
<?php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Session
*
* #ORM\Table(name="sessions")
* #ORM\Entity
*/
class Session
{
/**
* #var string
*
* #ORM\Column(name="sess_id", type="string", length=128)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $sessId;
/**
* #var string
*
* #ORM\Column(name="sess_data", type="blob", length=65535, nullable=false)
*/
private $sessData;
/**
* #var integer
*
* #ORM\Column(name="sess_time", type="integer", nullable=false, options={"unsigned"=true})
*/
private $sessTime;
/**
* #var integer
*
* #ORM\Column(name="sess_lifetime", type="integer", nullable=false)
*/
private $sessLifetime;
}
Example command.
<?php
namespace Acme\UserBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Acme\UserBundle\Entity\Session;
/**
* Class ClearSessionsCommand
* #package Acme\UserBundle\Command
*/
class ClearSessionsCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('acme:clear:sessions')
->setDescription('Deletes old sessions from database')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/** #var \Doctrine\Bundle\DoctrineBundle\Registry $doctrine */
$doctrine = $this->getContainer()->get('doctrine');
$repository = $doctrine->getManager()->getRepository('AcmeUserBundle:Session');
$sessions = $repository->findAll();
foreach($sessions as $session)
{
/** #var Session $session */
var_dump($session->getSessData());
}
}
}
And that's the output.
class Acme\UserBundle\Entity\Session#460 (4) {
private $sessId => string(26) "5v0as58i11vgikih7rb0b7fg41"
private $sessData => resource(419) of type (stream)
private $sessTime => int(1421508757)
private $sessLifetime => int(1440)
}
I'll hope you can help me.
I also tried to use "array", "simple_array" and "json_array".
But if i view the value in plain text i have a format like this.
_sf2_attributes|a:2:{s:18:"_csrf/authenticate";s:43:"esEvNzkJgkPN3JcgVWO71ArAHnoMxK_ChC1qdXT4bM4";s:14:"_security_main";s:691:"C:74:"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":603:{a:3:{i:0;N;i:1;s:4:"main";i:2;s:563:"a:4:{i:0;C:26:"Acme\UserBundle\Entity\User":227:{a:9:{i:0;s:88:"4T+akBl30pcGyIDl3MB64TT/o4izQZ/CA/JDHurok50o33g3L0bEgDYMj+itI5G6JWQmzH7gHTrDmLeE7I9yeQ==";i:1;s:31:"cljvnnze8jwo8ck4og8gcg08c4o0ww4";i:2;s:8:"max";i:3;s:8:"Max";i:4;b:0;i:5;b:0;i:6;b:0;i:7;b:1;i:8;i:1;}}i:1;b:1;i:2;a:2:{i:0;O:41:"Symfony\Component\Security\Core\Role\Role":1:{s:47:"
And i dont know whats this could be for a format.
If i remove _sf2_attributes| it might be serialized.
I would delete all sessions where older than one day and not logged in with remembered option.
Thanks in Advance!

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

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")

Symfony2 how to join on many-to-many relations using querybuilder?

Being new to symfony2 and querybuilder, I am trying to select all my containers but limiting the result to only those for which the logged-in user has access.
With the current code I get this error:
Notice: Undefined index: Container in /var/www/biztv_symfony/vendor/doctrine/lib/Doctrine/ORM/Query/SqlWalker.php line 746
Here is my attempt at the query (I have tried a couple of options from this and other forum sites and still can't seem to understand it right...)
public function indexAction()
{
//Get the requisits
$companyId = $this->container->get('security.context')->getToken()->getUser()->getCompany()->getId();
$em = $this->getDoctrine()->getEntityManager();
//Fetch the containers
$repository = $this->getDoctrine()->getRepository('BizTVContainerManagementBundle:Container');
$query = $repository->createQueryBuilder('c')
->innerJoin('c.users','u')
->where('c.company = :company')
->setParameter('company', $companyId)
->orderBy('c.name', 'ASC')
->getQuery();
$containers = $query->getResult();
I keep track of access with a many-to-many relation, this is my user entity...
<?php
// src/BizTV/UserBundle/Entity/User.php
namespace BizTV\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use BizTV\BackendBundle\Entity\company as company;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var object BizTV\BackendBundle\Entity\company
*
* #ORM\ManyToOne(targetEntity="BizTV\BackendBundle\Entity\company")
* #ORM\JoinColumn(name="company", referencedColumnName="id", nullable=false)
*/
protected $company;
/**
* #ORM\ManyToMany(targetEntity="BizTV\ContainerManagementBundle\Entity\Container", inversedBy="User")
* #ORM\JoinTable(name="access")
*/
private $access;
public function __construct()
{
parent::__construct();
$this->access = new \Doctrine\Common\Collections\ArrayCollection();
}
//getters and setters...
This is my container entity:
<?php
namespace BizTV\ContainerManagementBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use BizTV\UserBundle\Entity\User as user;
/**
* BizTV\ContainerManagementBundle\Entity\Container
*
* #ORM\Table(name="container")
* #ORM\Entity
*/
class Container
{
/**
* #var integer $id
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $name
* #Assert\NotBlank(message = "Du måste ange ett namn för området")
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
//TODO: form handler assuring no name is used twice in same company
/**
* #var object BizTV\BackendBundle\Entity\company
*
* #ORM\ManyToOne(targetEntity="BizTV\BackendBundle\Entity\company")
* #ORM\JoinColumn(name="company", referencedColumnName="id", nullable=false)
*/
protected $company;
/**
* #ORM\ManyToMany(targetEntity="BizTV\UserBundle\Entity\User", mappedBy="Container")
*/
private $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
In the Container entity, when you specify the $users property mapping, the value of mappedBy is important: you need to specify the name of the inverse property in the User class.
Here, we have, Container::$users <-> User::$access.
Change your annotations to:
class User
{
/**
* #ORM\ManyToMany(targetEntity="BizTV\ContainerManagementBundle\Entity\Container", inversedBy="users")
* #ORM\JoinTable(name="access")
*/
private $access;
}
class Container
{
/**
* #ORM\ManyToMany(targetEntity="BizTV\UserBundle\Entity\User", mappedBy="access")
*/
private $users;
}
I encourage you to read the doctrine orm documentation part about associations, and verify and fix this in all your associations.

Categories