How to get all property for a custom entity in FOSUserBundle? - doctrine

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

Related

Doctrine in laravel, getting all user's roles

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

Symfony2: How to validate an input field is not-blank, only when checkbox is true?

Within Symfony2 how to validate an inputfield is not-blank, only when the value of a checkbox is 1 (True) - otherwise blank is allowed?
To be more precise, I have a form with a checkbox and an input field with type text. On the Entity in Symfony there should be a check that when the value of the checkbox is True (1) / checked, the value of the input can't be blank. I am using annotations within the Entity.
Any advise would be much appreciated.
UPDATE / SOLUTION - based on GeLo's remark:
<?php
// src/ZeroSpace/Invoicing/Entity/Customer.php
namespace ZeroSpace\InvoicingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="customers")
* #UniqueEntity("billing_id")
* #UniqueEntity("billing_name")
*/
class Customer {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer", length=6, unique=true)
* #Assert\Length(min="6", max="6")
*/
protected $billing_id;
/**
* #ORM\Column(type="string", length=100, unique=true)
*/
protected $billing_name;
/**
* #ORM\Column(type="string", nullable=true, length=100)
*/
protected $billing_consignee;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_street;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_address;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_zip;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_city;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_country;
/**
* #ORM\Column(type="string", length=100)
* #Assert\Email()
*/
protected $billing_email;
/**
* #ORM\Column(type="boolean")
*/
protected $billing_debit=false;
/**
* #ORM\Column(type="string", nullable=true, length=100)
* #Assert\NotBlank(groups={"iban_required"})
* #Assert\Iban(message = "This is not a valid International Bank Account Number (IBAN).")
*/
protected $billing_iban;
protected $locations;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set billing_id
*
* #param integer $billingId
* #return Customer
*/
public function setBillingId($billingId)
{
$this->billing_id = $billingId;
return $this;
}
/**
* Get billing_id
*
* #return integer
*/
public function getBillingId()
{
return $this->billing_id;
}
/**
* Set billing_name
*
* #param string $billingName
* #return Customer
*/
public function setBillingName($billingName)
{
$this->billing_name = $billingName;
return $this;
}
/**
* Get billing_name
*
* #return string
*/
public function getBillingName()
{
return $this->billing_name;
}
/**
* Set billing_consignee
*
* #param string $billingConsignee
* #return Customer
*/
public function setBillingConsignee($billingConsignee)
{
$this->billing_consignee = $billingConsignee;
return $this;
}
/**
* Get billing_consignee
*
* #return string
*/
public function getBillingConsignee()
{
return $this->billing_consignee;
}
/**
* Set billing_street
*
* #param string $billingStreet
* #return Customer
*/
public function setBillingStreet($billingStreet)
{
$this->billing_street = $billingStreet;
return $this;
}
/**
* Get billing_street
*
* #return string
*/
public function getBillingStreet()
{
return $this->billing_street;
}
/**
* Set billing_address
*
* #param string $billingAddress
* #return Customer
*/
public function setBillingAddress($billingAddress)
{
$this->billing_address = $billingAddress;
return $this;
}
/**
* Get billing_address
*
* #return string
*/
public function getBillingAddress()
{
return $this->billing_address;
}
/**
* Set billing_zip
*
* #param string $billingZip
* #return Customer
*/
public function setBillingZip($billingZip)
{
$this->billing_zip = $billingZip;
return $this;
}
/**
* Get billing_zip
*
* #return string
*/
public function getBillingZip()
{
return $this->billing_zip;
}
/**
* Set billing_city
*
* #param string $billingCity
* #return Customer
*/
public function setBillingCity($billingCity)
{
$this->billing_city = $billingCity;
return $this;
}
/**
* Get billing_city
*
* #return string
*/
public function getBillingCity()
{
return $this->billing_city;
}
/**
* Set billing_country
*
* #param string $billingCountry
* #return Customer
*/
public function setBillingCountry($billingCountry)
{
$this->billing_country = $billingCountry;
return $this;
}
/**
* Get billing_country
*
* #return string
*/
public function getBillingCountry()
{
return $this->billing_country;
}
/**
* Set billing_email
*
* #param string $billingEmail
* #return Customer
*/
public function setBillingEmail($billingEmail)
{
$this->billing_email = $billingEmail;
return $this;
}
/**
* Get billing_email
*
* #return string
*/
public function getBillingEmail()
{
return $this->billing_email;
}
/**
* Set billing_debit
*
* #param boolean $billingDebit
* #return Customer
*/
public function setBillingDebit($billingDebit)
{
$this->billing_debit = $billingDebit;
return $this;
}
/**
* Get billing_debit
*
* #return boolean
*/
public function getBillingDebit()
{
return $this->billing_debit;
}
/**
* Set billing_iban
*
* #param string $billingIban
* #return Customer
*/
public function setBillingIban($billingIban)
{
$this->billing_iban = $billingIban;
return $this;
}
/**
* Get billing_iban
*
* #return string
*/
public function getBillingIban() {
return $this->billing_iban;
}
}
<?php
// src/Blogger/BlogBundle/Form/CustomerType.php
namespace ZeroSpace\InvoicingBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
class CustomerType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('billing_id');
$builder->add('billing_name');
$builder->add('billing_consignee');
$builder->add('billing_street');
$builder->add('billing_address');
$builder->add('billing_zip');
$builder->add('billing_city');
$builder->add('billing_country');
$builder->add('billing_email', 'email');
$builder->add('billing_debit', 'checkbox');
$builder->add('billing_iban');
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
'validation_groups' => function(FormInterface $form) {
$data = $form->getData();
if($data->getBillingDebit() == 1) {
return array('Default', 'iban_required');
}
else {
return array('Default');
}
},
));
}
public function getName() {
return 'customer';
}
}
?>
<?php
namespace ZeroSpace\InvoicingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;
class CustomerController extends Controller {
public function createAction(Request $request) {
$form = $this->createForm(new CustomerType(), new Customer());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return $this->redirect($this->generateUrl('customer_list'));
// return $this->redirect($this->generateUrl('task_success'));
}
return $this->render('InvoicingBundle:Page:customers.html.twig', array(
'form' => $form->createView()
));
}
public function listAction() {
$customers = $this->getDoctrine()->getManager()
->createQuery('SELECT c FROM InvoicingBundle:Customer c')
->execute();
return $this->render(
'InvoicingBundle:Customer:list.html.twig',
array('customers' => $customers));
}
public function showAction($id) {
$customer = $this->get('doctrine')
->getManager()
->getRepository('InvoicingBundle:Customer')
->find($id);
if (!$post) {
// cause the 404 page not found to be displayed
throw $this->createNotFoundException();
}
return $this->render(
'InvoicingBundle:Page:customers.html.twig',
array('customer' => $customer)
);
}
}
?>
I think this is the solution:
<?php
namespace ZeroSpace\InvoicingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;
class CustomerController extends Controller {
public function createAction(Request $request) {
$form = $this->createForm(new CustomerType(), new Customer());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return $this->redirect($this->generateUrl('customer_list'));
// return $this->redirect($this->generateUrl('task_success'));
}
return $this->render('InvoicingBundle:Page:customers.html.twig', array(
'form' => $form->createView()
));
}
public function listAction() {
$customers = $this->getDoctrine()->getManager()
->createQuery('SELECT c FROM InvoicingBundle:Customer c')
->execute();
return $this->render(
'InvoicingBundle:Customer:list.html.twig',
array('customers' => $customers));
}
public function showAction($id) {
$customer = $this->get('doctrine')
->getManager()
->getRepository('InvoicingBundle:Customer')
->find($id);
if (!$post) {
// cause the 404 page not found to be displayed
throw $this->createNotFoundException();
}
return $this->render(
'InvoicingBundle:Page:customers.html.twig',
array('customer' => $customer)
);
}
}
?>
<?php
// src/Blogger/BlogBundle/Form/CustomerType.php
namespace ZeroSpace\InvoicingBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
class CustomerType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('billing_id');
$builder->add('billing_name');
$builder->add('billing_consignee');
$builder->add('billing_street');
$builder->add('billing_address');
$builder->add('billing_zip');
$builder->add('billing_city');
$builder->add('billing_country');
$builder->add('billing_email', 'email');
$builder->add('billing_debit', 'checkbox');
$builder->add('billing_iban');
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
'validation_groups' => function(FormInterface $form) {
$data = $form->getData();
if($data->getBillingDebit() == 1) {
return array('Default', 'iban_required');
}
else {
return array('Default');
}
},
));
}
public function getName() {
return 'customer';
}
}
?>
<?php
// src/ZeroSpace/Invoicing/Entity/Customer.php
namespace ZeroSpace\InvoicingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="customers")
* #UniqueEntity("billing_id")
* #UniqueEntity("billing_name")
*/
class Customer {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer", length=6, unique=true)
* #Assert\Length(min="6", max="6")
*/
protected $billing_id;
/**
* #ORM\Column(type="string", length=100, unique=true)
*/
protected $billing_name;
/**
* #ORM\Column(type="string", nullable=true, length=100)
*/
protected $billing_consignee;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_street;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_address;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_zip;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_city;
/**
* #ORM\Column(type="string", length=100)
*/
protected $billing_country;
/**
* #ORM\Column(type="string", length=100)
* #Assert\Email()
*/
protected $billing_email;
/**
* #ORM\Column(type="boolean")
*/
protected $billing_debit=false;
/**
* #ORM\Column(type="string", nullable=true, length=100)
* #Assert\NotBlank(groups={"iban_required"})
* #Assert\Iban(message = "This is not a valid International Bank Account Number (IBAN).")
*/
protected $billing_iban;
protected $locations;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set billing_id
*
* #param integer $billingId
* #return Customer
*/
public function setBillingId($billingId)
{
$this->billing_id = $billingId;
return $this;
}
/**
* Get billing_id
*
* #return integer
*/
public function getBillingId()
{
return $this->billing_id;
}
/**
* Set billing_name
*
* #param string $billingName
* #return Customer
*/
public function setBillingName($billingName)
{
$this->billing_name = $billingName;
return $this;
}
/**
* Get billing_name
*
* #return string
*/
public function getBillingName()
{
return $this->billing_name;
}
/**
* Set billing_consignee
*
* #param string $billingConsignee
* #return Customer
*/
public function setBillingConsignee($billingConsignee)
{
$this->billing_consignee = $billingConsignee;
return $this;
}
/**
* Get billing_consignee
*
* #return string
*/
public function getBillingConsignee()
{
return $this->billing_consignee;
}
/**
* Set billing_street
*
* #param string $billingStreet
* #return Customer
*/
public function setBillingStreet($billingStreet)
{
$this->billing_street = $billingStreet;
return $this;
}
/**
* Get billing_street
*
* #return string
*/
public function getBillingStreet()
{
return $this->billing_street;
}
/**
* Set billing_address
*
* #param string $billingAddress
* #return Customer
*/
public function setBillingAddress($billingAddress)
{
$this->billing_address = $billingAddress;
return $this;
}
/**
* Get billing_address
*
* #return string
*/
public function getBillingAddress()
{
return $this->billing_address;
}
/**
* Set billing_zip
*
* #param string $billingZip
* #return Customer
*/
public function setBillingZip($billingZip)
{
$this->billing_zip = $billingZip;
return $this;
}
/**
* Get billing_zip
*
* #return string
*/
public function getBillingZip()
{
return $this->billing_zip;
}
/**
* Set billing_city
*
* #param string $billingCity
* #return Customer
*/
public function setBillingCity($billingCity)
{
$this->billing_city = $billingCity;
return $this;
}
/**
* Get billing_city
*
* #return string
*/
public function getBillingCity()
{
return $this->billing_city;
}
/**
* Set billing_country
*
* #param string $billingCountry
* #return Customer
*/
public function setBillingCountry($billingCountry)
{
$this->billing_country = $billingCountry;
return $this;
}
/**
* Get billing_country
*
* #return string
*/
public function getBillingCountry()
{
return $this->billing_country;
}
/**
* Set billing_email
*
* #param string $billingEmail
* #return Customer
*/
public function setBillingEmail($billingEmail)
{
$this->billing_email = $billingEmail;
return $this;
}
/**
* Get billing_email
*
* #return string
*/
public function getBillingEmail()
{
return $this->billing_email;
}
/**
* Set billing_debit
*
* #param boolean $billingDebit
* #return Customer
*/
public function setBillingDebit($billingDebit)
{
$this->billing_debit = $billingDebit;
return $this;
}
/**
* Get billing_debit
*
* #return boolean
*/
public function getBillingDebit()
{
return $this->billing_debit;
}
/**
* Set billing_iban
*
* #param string $billingIban
* #return Customer
*/
public function setBillingIban($billingIban)
{
$this->billing_iban = $billingIban;
return $this;
}
/**
* Get billing_iban
*
* #return string
*/
public function getBillingIban() {
return $this->billing_iban;
}
}
An efficient approach can be to use the validation group which can be determined on the fly. Then, given the checkbox is not checked, you use the Default validation group whereas if the checkbox is checked, you use the Default group and a custom group which will check if your field is not empty.
See this part of the documentation for more details: http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data
could you do something like this ?
/**
* #Assert\True()
*/
public function customValidate()
{
return (!$this->checkboxField) or (strlen($this->inputField) > 0);
}

integrating doctrine 2 in codeignitier 2

Currently i am trying to integrate doctrine 2 in codeigniter 2 and i am doing all this by following the below tutorial.
http://www.joelverhagen.com/blog/2011/05/setting-up-codeigniter-2-with-doctrine-2-the-right-way/
According to the tutorial i had
1)Doctrine 2 in library
2)Doctrine.php file in library
3)doctrine-cli.php in root folder
4)yaml file inside applications/models/mappings and also entities and proxies inside the same location
According to the tutorial from the command prompt i had made the entities as
User entitiy
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Entities\User
*/
class User
{
/**
* #var integer $id
*/
private $id;
/**
* #var string $password
*/
private $password;
/**
* #var string $firstName
*/
private $firstName;
/**
* #var string $lastName
*/
private $lastName;
/**
* #var string $email
*/
private $email;
/**
* #var string $website
*/
private $website;
/**
* #var datetime $created
*/
private $created;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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 firstName
*
* #param string $firstName
* #return User
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
* #return User
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set website
*
* #param string $website
* #return User
*/
public function setWebsite($website)
{
$this->website = $website;
return $this;
}
/**
* Get website
*
* #return string
*/
public function getWebsite()
{
return $this->website;
}
/**
* Set created
*
* #param datetime $created
* #return User
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
}?>
also the article entitiy as
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Entities\Article
*/
class Article
{
/**
* #var integer $id
*/
private $id;
/**
* #var string $title
*/
private $title;
/**
* #var text $content
*/
private $content;
/**
* #var datetime $created
*/
private $created;
/**
* #var Entities\User
*/
private $user;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Article
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set content
*
* #param text $content
* #return Article
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return text
*/
public function getContent()
{
return $this->content;
}
/**
* Set created
*
* #param datetime $created
* #return Article
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set user
*
* #param Entities\User $user
* #return Article
*/
public function setUser(\Entities\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return Entities\User
*/
public function getUser()
{
return $this->user;
}
}
i had done every thing as explained in that tutorial but when i try to insert the value in database table i got the error as
Fatal error: Class 'Entities' not found in D:\xampp\htdocs\ci_doctrine\application\controllers\welcome.php on line 32
while i use welcome controller to insert the data and my controller is
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function __construct() {
parent::__construct();
// $this->load->library('Doctrine.php');
//$this->em = $this->doctrine->em;
}
public function index()
{
// create a new user object
$user = new Entities/User;
$user->setFirstName('Joel');
$user->setLastName('Verhagen');
$user->setPassword(md5('Emma Watson'));
$user->setEmail('joel#joelverhagen.com');
$user->setWebsite('http://www.joelverhagen.com');
$user->setCreated(new DateTime());
// standard way in CodeIgniter to access a library in a controller: $this->library_name->member->memberFunction()
// save the object to database, so that it can obtain its ID
$this->doctrine->em->persist($user);
// create a new article object
$article = new Entities/Article;
$article->setTitle('Emma Watson is extremely talented, no?');
$article->setContent('By talented, I mean good at lookin\' good.');
$article->setCreated(new DateTime());
// the user object you pass must be persisted first!
$article->setUser($user);
// save the article object to the database
$this->doctrine->em->persist($article);
$this->doctrine->em->flush();
echo "<b>Success!</b>";
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
what is going on i can't figure out .... any suggestion and help..??
You don't use the fully qualified namespace but a relative one.
http://php.net/manual/en/language.namespaces.basics.php
That's why.
Try
$article = new \Entities\Article;
in your controller.
EDIT: Oh even better. You were trying to divide Entities with Article.
You were using / instead of \.

symfony annotations validation override entities/models

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.

doctrine 2, how do get data from the inverse side (many to one)

I have two entities, entry and comments.
comments:
/**
* #Entity(repositoryClass="\Entities\Blog\CommentRepository")
* #Table(name="blog_comment")
* #HasLifecycleCallbacks
*/
class Comment extends \Entities\AbstractEntity
{
/**
* #Id #Column(name="id", type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ManyToOne(targetEntity="Entry", inversedBy="comments")
* #JoinColumn(name="entry_id", referencedColumnName="id")
*/
protected $entry;
/** #Column(name="approved", type="string", length=255) */
protected $approved;
/** #Column(name="title", type="string", length=255) */
protected $title;
/** #Column(name="content", type="text") */
protected $content;
/** #Column(name="pub_date", type="datetime") */
protected $pub_date;
/** #Column(type="datetime") */
private $created_at;
/** #Column(type="datetime") */
private $updated_at;
/** #PreUpdate */
public function updated()
{
$this->updated_at = new \DateTime("now");
}
public function __construct()
{
$this->created_at = $this->updated_at = new \DateTime("now");
}
}
class CommentRepository extends \Entities\PaginatedRepository
{
protected $_entityClassName = 'Entities\Blog\Comment';
}
and entry:
<?php
namespace Entities\Blog;
/**
* #Entity(repositoryClass="\Entities\Blog\EntryRepository")
* #Table(name="blog_entry")
* #HasLifecycleCallbacks
*/
class Entry extends \Entities\AbstractEntity
{
/**
* #Id #Column(name="id", type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/** #Column(name="permalink", type="string", length=255) */
protected $permalink;
/** #Column(name="title", type="string", length=255) */
protected $title;
/** #Column(name="pub_date", type="datetime") */
protected $pub_date;
/** #Column(name="content", type="text") */
protected $content;
/** #OneToMany(targetEntity="Comment", mappedBy="entry") */
protected $comments;
/** #Column(type="datetime") */
private $created_at;
/** #Column(type="datetime") */
private $updated_at;
/** #PreUpdate */
public function updated()
{
$this->updated_at = new \DateTime("now");
}
public function __construct()
{
$this->comments = new \Doctrine\Common\Collections\ArrayCollection();
}
I can get the collection of all comments belonging to each entry via:
foreach ($comments as $comment){
$comment-$commentId;
}
but how can I get the entry information from the comments side. for example, I would like to get the entry id from a specific comment
Each time you create a #OneToMany relation, you create a Collection of proxy objects in class on "One"-side of relation, and single proxy object in class on "Many"-side of relation. Proxy classes are automatically generated by Doctrine2 from your mapping information.
To allow Doctrine2 filling proxy object with real data from DB it's important to declare it protected or private. I'm not sure about that, but seems like Doctrine tracks down any requests to proxy objects inside your entity class and ensures that proxies are populated before first usage.
To access the associated object you have to define accessor function in your Comment class:
class Comment extends \Entities\AbstractEntity{
/** other definitions */
function getEntity(){
return $this->entity;
}
}
And use it like
$comment = $em->find("Entities\Comment",1);
$entity = $comment->getEntity();
Doctrine2 will automatically populate $comment->entity proxy with actual Entity object.
See "Workin with Objects" chapter of Doctrine documentation and "Can you explain me what is a Proxy in Doctrine 2?" on details of proxies.

Resources