Unable to save (A new entity was found through the relationship) - doctrine

Error Message:
"A new entity was found through the relationship
'AppBundle\Entity\Category#products' that was not configured to
cascade persist operations for entity:
AppBundle\Entity\Product#00000000133d712400000000104ed306. To solve
this issue: Either explicitly call EntityManager#persist() on this
unknown entity or configure cascade persist this association in the
mapping for example #ManyToOne(..,cascade={"persist"}). If you cannot
find out which entity causes the problem implement
'AppBundle\Entity\Product#__toString()' to get a clue."
/AppBundle/Entity/Product
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $name;
/**
* #ORM\Column(type="decimal", scale=2)
*/
private $price;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set category
*
* #param \AppBundle\Entity\Category $category
*
* #return Product
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
/AppBundle/Entity/Category
class Category
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add product
*
* #param \AppBundle\Entity\Product $product
*
* #return Category
*/
public function addProduct(\AppBundle\Entity\Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Product $product
*/
public function removeProduct(\AppBundle\Entity\Product $product)
{
$this->products->removeElement($product);
}
/**
* Get products
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
/AppBundle/Form/CategoryType
class CategoryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('products', CollectionType::class, array(
'entry_type' => ProductType::class
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Category'
));
}
public function getName()
{
return 'category';
}
}
/AppBundle/Form/ProductType
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('price')
->add('description');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product',
));
}
public function getName()
{
return 'app_bundle_product_type';
}
}
/AppBundle/Controller/CategoryController
class CategoryController extends Controller
{
/**
* #Route("/category/new", name="category_new")
*
*/
public function newAction(Request $request)
{
$category = new Category();
$product = new Product();
$category->getProducts()->add($product);
$form = $this->createForm(CategoryType::class, $category);
$form->handleRequest($request);
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
}
return $this->render('category/new.html.twig', array(
'form' => $form->createView(),
));
}
}
/category/new.html.twig
{% extends 'base.html.twig' %}
{% block body %}
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit" class="btn btn-primary">Save</button>
{{ form_end(form) }}
{% endblock %}

You should change association in order to tell doctrine to persist all new category products
...
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category", cascade={"persist", "remove"})
*/
protected $products;
...
or persist it manually
...
$em->persist($category);
$em->persist($product);
$em->flush();
...
Also set category for product
...
$product = new Product();
$product->setCategory($category);
...

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

Doctrine 2: cascade persist Oracle "IDENTITY" is returning 0 as last inserted ID

I am using doctrine 2 with oracle, the tables in the database has some triggers that generate the IDs, and my ID mapping of my tables is like the following:
/**
* #orm\Id
* #orm\Column(type="integer");
* #orm\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
and I have a OneToMany relation, with cascade={"persist"} but it is not working, I tried the same code with MySQL and it is working fine, but in oracle the last insert Id seems to always return 0 instead of the real id of the inserted row... and so the cascade persist is not working... is this a bug in doctrine or am I doing something wrong? any help?
After following the code it seems that the method
Doctrine\ORM\Id\IdentityGenerator::generate
is returning 0, I don't know why it is being invoked since the sequenceName is null (there is no sequence in the deffinition!
EDIT: Here are the entities:
The Client Entity:
/**
* #ORM\Entity
* #ORM\Table(name="clients")
**/
class Client {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(name="name",type="string",length=255,unique=true) */
protected $name;
/**
* #ORM\OneToMany(targetEntity="ContactInformation", mappedBy="client", cascade={"persist"})
**/
protected $contactInformations;
public function __construct() {
$this->contactInformations = new ArrayCollection();
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getContactInformations() {
return $this->contactInformations;
}
public function addContactInformations(Collection $contactInformations)
{
foreach ($contactInformations as $contactInformation) {
$contactInformation->setClient($this);
$this->contactInformations->add($contactInformation);
}
}
/**
* #param Collection $tags
*/
public function removeContactInformations(Collection $contactInformations)
{
foreach ($contactInformations as $contactInformation) {
$contactInformation->setClient(null);
$this->contactInformations->removeElement($contactInformation);
}
}
public function setContactInformations($contactInformations) {
$this->contactInformations = $contactInformations;
return $this;
}
}
The Contact Information Entity:
/**
* #ORM\Entity
* #ORM\Table(name="contact_informations")
**/
class ContactInformation {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="ContactInformationType")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
**/
protected $type;
/** #ORM\Column(type="text") */
protected $value;
/**
* #ORM\ManyToOne(targetEntity="Client", inversedBy="contact_informations")
* #ORM\JoinColumn(name="client_id", referencedColumnName="id")
**/
private $client;
public function getId() {
return $this->id;
}
public function getType() {
return $this->type;
}
public function setType($type) {
$this->type = $type;
return $this;
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
return $this;
}
public function getClient() {
return $this->client;
}
public function setClient($client = null) {
$this->client = $client;
return $this;
}
}
Oracle doesn't support auto incrementing, so you cannot use the "IDENTITY" strategy in Doctrine. You'll have to use the "SEQUENCE" (or "AUTO") strategy.
When specifying "AUTO", Doctrine will use "IDENTITY" for MySql and "SEQUENCE" for Oracle.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#identifier-generation-strategies

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 \.

Doctrine gives null while trying to access property of property

I am using Doctrine with CodeIgniter.
I can't access the category with this usage. $record is not null but $category is null.
$record_data = $this->getRepository('Entity\RecordData')->find($this->params['id']);
$record = $record_data->getRecord();
$category = $record->getCategory();
echo $category->getName();
Last line gives Fatal error: Call to a member function getName() on a non-object.
What am i doing wrong? Can you have a look please. Thanks.
Here is my entity classes.
Entity\RecordData:
<?php
namespace Entity;
/**
* #Entity(repositoryClass="RecordDataRepository")
* #Table(name="record_data")
*/
class RecordData {
/**
* #Id
* #Column(type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
protected $ID;
/**
* #ManyToOne(targetEntity="CategoryVariable")
* #JoinColumn(name="CategoryVariableID", referencedColumnName="ID")
*/
protected $CategoryVariable;
/**
* #ManyToOne(targetEntity="Record")
* #JoinColumn(name="RecordID", referencedColumnName="ID")
*/
protected $Record;
/**
* #ManyToOne(targetEntity="SkillLevel")
* #JoinColumn(name="SkillLevelID", referencedColumnName="ID")
*/
protected $SkillLevel = NULL;
/**
* #Column(type="string", length=255, nullable=true)
*/
protected $Value;
/**
* #Column(type="integer", nullable=false)
*/
protected $RecordDataOrder;
/**
* #Column(type="boolean", nullable=false)
*/
protected $Deleted = FALSE;
public function __construct(Record $record, CategoryVariable $category_variable)
{
$this->Record = $record;
$this->CategoryVariable = $category_variable;
}
public function getID()
{
return $this->ID;
}
public function getCategoryVariable()
{
return $this->CategoryVariable;
}
public function getRecord()
{
return $this->Record;
}
public function setSkillLevel($SkillLevel)
{
$this->SkillLevel = $SkillLevel;
}
public function getSkillLevel()
{
return $this->SkillLevel;
}
public function setValue($Value)
{
$this->Value = $Value;
}
public function getValue()
{
return $this->Value;
}
public function setRecordDataOrder($RecordDataOrder)
{
$this->RecordDataOrder = $RecordDataOrder;
}
public function getRecordDataOrder()
{
return $this->RecordDataOrder;
}
public function delete()
{
$this->Deleted = TRUE;
}
}
Entity\Record:
<?php
namespace Entity;
/**
* #Entity(repositoryClass="RecordRepository")
* #Table(name="record")
*/
class Record {
/**
* #Id
* #Column(type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
protected $ID;
/**
* #ManyToOne(targetEntity="Category")
* #JoinColumn(name="CategoryID", referencedColumnName="ID")
*/
protected $Category;
/**
* #Column(type="string", length=255, nullable=true)
*/
protected $Name;
/**
* #Column(type="integer", nullable=false)
*/
protected $RecordOrder;
/**
* #Column(type="string", length=255, nullable=true)
*/
protected $Description;
/**
* #Column(type="boolean", nullable=false)
*/
protected $Deleted = FALSE;
public function __construct(Category $category)
{
$this->Category = $category;
}
public function getID()
{
return $this->ID;
}
public function setCategory($Category)
{
$this->Category = $Category;
}
public function getCategory()
{
return $this->Category;
}
public function setName($Name)
{
$this->Name = $Name;
}
public function getName()
{
return $this->Name;
}
public function setRecordOrder($RecordOrder)
{
$this->RecordOrder = $RecordOrder;
}
public function getRecordOrder()
{
return $this->RecordOrder;
}
public function setDescription($Description)
{
$this->Description = $Description;
}
public function getDescription()
{
return $this->Description;
}
public function delete()
{
$this->Deleted = TRUE;
}
}
Entity\Category:
<?php
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity(repositoryClass="CategoryRepository")
* #Table(name="category")
*/
class Category {
/**
* #Id
* #Column(type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
protected $ID;
/**
* #Column(type="string", length=255)
*/
protected $Name;
/**
* #Column(type="string", length=255)
*/
protected $Description;
/**
* #Column(type="integer", nullable=false)
*/
protected $CategoryOrder;
/**
* #Column(type="boolean", nullable=false)
*/
protected $IsMultiple;
/**
* #Column(type="boolean", nullable=false)
*/
protected $Deleted = FALSE;
public function getID()
{
return $this->ID;
}
public function setName($Name)
{
$this->Name = $Name;
}
public function getName()
{
return $this->Name;
}
public function setDescription($Description)
{
$this->Description = $Description;
}
public function getDescription()
{
return $this->Description;
}
public function setCategoryOrder($CategoryOrder)
{
$this->CategoryOrder = $CategoryOrder;
}
public function getCategoryOrder()
{
return $this->CategoryOrder;
}
public function setIsMultiple($IsMultiple)
{
$this->IsMultiple = $IsMultiple;
}
public function getIsMultiple()
{
return $this->IsMultiple;
}
public function delete()
{
$this->Deleted = TRUE;
}
/**
* #var CategoryVariable[]
* #OneToMany(targetEntity="CategoryVariable", mappedBy="Category")
*/
protected $CategoryVariables = NULL;
/**
* #var Record[]
* #OneToMany(targetEntity="Record", mappedBy="Category")
*/
protected $Records = NULL;
public function setCategoryVariable(CategoryVariable $CategoryVariable)
{
$this->CategoryVariables[] = $CategoryVariable;
}
public function getCategoryVariables()
{
return $this->CategoryVariables;
}
public function setRecord(Record $Record)
{
$this->Records[] = $Record;
}
public function getRecords()
{
return $this->Records;
}
public function __construct()
{
$this->CategoryVariables = new ArrayCollection();
$this->Records = new ArrayCollection();
}
}
If your record doesn't have category then the category object that you retrieve it is null. So before echo its category you must to control if category is a real object or null object.
Like this:
$record_data = $this->getRepository('Entity\RecordData')->find($this->params['id']);
$record = $record_data->getRecord();}
$category = $record->getCategory();
echo ($category) ? $category->getName() : "Record doesn't have category";

Resources