Two records in database on 1 form - php

I have an entity Page with fields:
pageID (PK) and tag.
I have an entity PageLocale with fields:
pagelocaleid (PK), description, content, locale, translated and pageID (FK).
My Database Structure:
My entity PageLocale:
<?php
namespace DX\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Pagelocale
*
* #ORM\Table(name="pageLocale", indexes={#ORM\Index(name="fk_pageLocale_page1_idx", columns={"pageID"})})
* #ORM\Entity(repositoryClass="DX\MyBundle\Repository\PagelocaleRepository")
* #ORM\HasLifecycleCallbacks
*/
class Pagelocale
{
/**
* #var string
*
* #ORM\Column(name="description", type="text", length=65535, nullable=true)
*/
private $description;
/**
* #var string
*/
private $descriptionEN;
/**
* #var string
*
* #ORM\Column(name="content", type="text", length=65535, nullable=true)
*/
private $content;
/**
* #var string
*/
private $contentEN;
/**
* #var string
*
* #ORM\Column(name="locale", type="string", length=5, nullable=true)
*/
private $locale;
/**
* #var boolean
*
* #ORM\Column(name="translated", type="boolean", nullable=true)
*/
private $translated;
/**
* #var integer
*
* #ORM\Column(name="pageLocaleID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $pagelocaleid;
/**
* #var \DX\MyBundle\Entity\Page
*
* #ORM\ManyToOne(targetEntity="DX\MyBundle\Entity\Page")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="pageID", referencedColumnName="pageID")
* })
*/
private $pageid;
/**
* #var string
*/
private $tag;
/**
* Set tag
*
* #param string $tag
* #return Articlelocale
*/
public function setTag($tag)
{
if($this->pageid)
{
$this->pageid->setTag($tag);
}
else
{
$this->tag = $tag;
}
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
if($this->pageid)
{
return $this->pageid->getTag();
}
else
{
return $this->tag;
}
}
/**
* Set description
*
* #param string $description
* #return Pagelocale
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set descriptionEN
*
* #param string $descriptionEN
* #return Pagelocale
*/
public function setDescriptionEN($descriptionEN)
{
$this->descriptionEN = $descriptionEN;
return $this;
}
/**
* Get descriptionEN
*
* #return string
*/
public function getDescriptionEN()
{
return $this->descriptionEN;
}
/**
* Set content
*
* #param string $content
* #return Pagelocale
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set contentEN
*
* #param string $contentEN
* #return Pagelocale
*/
public function setContentEN($contentEN)
{
$this->contentEN = $contentEN;
return $this;
}
/**
* Get contentEN
*
* #return string
*/
public function getContentEN()
{
return $this->contentEN;
}
/**
* Set locale
*
* #param string $locale
* #return Pagelocale
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Get locale
*
* #return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* Set translated
*
* #param boolean $translated
* #return Pagelocale
*/
public function setTranslated($translated)
{
$this->translated = $translated;
return $this;
}
/**
* Get translated
*
* #return boolean
*/
public function getTranslated()
{
return $this->translated;
}
/**
* Get pagelocaleid
*
* #return integer
*/
public function getPagelocaleid()
{
return $this->pagelocaleid;
}
/**
* Set pageid
*
* #param \DX\MyBundle\Entity\Page $pageid
* #return Pagelocale
*/
public function setPageid(\DX\MyBundle\Entity\Page $pageid = null)
{
$this->pageid = $pageid;
return $this;
}
}
I'm using the Sonata Admin Bundle but that doesn't really matter in this case.
As you can see in my entity I've manually added contentEN and descriptionEN because I want the content & description in 2 languages.
And I want to be able to do this in one form and not in 2 steps (create for each language content).
Now I have in my form:
$formMapper
->add('tag', 'text', array('label' => 'Tag'))
->add('description', 'text', array('label' => 'Beschrijving'))
->add('descriptionEN', 'text', array('label' => 'Beschrijving Engels'))
->add('content', 'textarea', array('label' => 'Tekst', 'attr' => array('class' => 'ckeditor'), 'help' =>
'My help text.'))
->add('contentEN', 'textarea', array('label' => 'Tekst Engels', 'attr' => array('class' => 'ckeditor'), 'help' =>
'My help text.'))
;
I can create 2 different entities and set the locale, that's no problem. But when I want to edit them the contentEN & descriptionEN are logically not filled in. How can I make sure I get the description and content where locale = .. ?
I know the contentEN & descriptionEN are not the way to do this. But I just wanted to clarify the problem.

If you want to retrieve some specific content based on the locale, you need to create an array where you set your fields ordered by locale and create a query that uses this array.
You could do it this way :
class PageLocaleManager
{
public function getParametersLocale()
{
// retrieve the current locale.
$locale = $this->get('request')->getLocale();
// set the fields you want retrieve based on the locale, you have to set an alias before the name for the query.
$parameters = array(
'fr' => array('pl.description', 'pl.content'),
'en' => array('pl.descriptionEN', 'pl.contentEN')
);
// if the locale is set return the parameters related to it, else return the default parameters (in this case default = fr)
return (isset($parameters[$locale]) ? $parameters[$locale] : $parameters['fr'];
}
}
class PageLocaleRepository
{
public function findLocalePageById($parameters, $pageId)
{
return $this->createQueryBuilder('pl')
->select($parameters)
->where('pl.page = :pageId')
->setParameter('pageId', $id)
->getQuery()
->getResult();
}
}
Then when you want to retrieve the page content for a specific locale you have to do :
$pageId = 1;
$parameters = $this->get('page_locale.manager')->getParametersLocale();
$pageLocaleEntity = $this->getDoctrine()->getRepository('TestBundle:PageLocale')->findLocalePageById($parameters, $pageId);
Also you shouldn't use this schema in your project in my opinion, if you want to add more languages, you will have to duplicate fields.
Update
You have to use events prePersist / preUpdate if you want to create / update 2 entity from the data of the same form.
You can add in your Sonata Admin a prePersist method (http://sonata-project.org/bundles/admin/master/doc/reference/saving_hooks.html) and create a new Entity based on the data of your form.
class PageLocaleAdmin extends Admin
{
public function prePersist($object)
{
$pageLocaleEnEntity = new PageLocale();
$pageLocaleEnEntity->setDescriptionEN($object->getDescriptionEN());
$pageLocaleEnEntity->setContentEN($object->getContentEN());
$this->getConfigurationPool()->getContainer()->get('doctrine')->persist($pageLocaleEnEntity);
}
}
Update 2
Ok, i didn't see that the field descriptionEN and contentEN are not in your model.
To fill the descriptionEN and contentEN on Edit you have to retrieve the related PageLocale and set the locale value, you could do :
class PageLocaleAdmin extends Admin
{
public function configureFormFields(FormMapper $formMapper)
{
$locale = 'en';
if ($this->subject->getId() !== null) {
$pageLocaleEntity = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository('DXMyBundle:PageLocale')->findOneby($this->subject->getId(), $locale);
$descriptionEN = $pageLocaleEntity->getDescriptionEN();
$contentEN = $pageLocaleEntity->getContentEN();
} else {
$pageLocaleEntity = null;
$descriptionEN = null;
$contentEN = null;
}
$formMapper
->add('description', 'text', array('label' => 'Beschrijving'))
->add('descriptionEN', 'text', array('label' => 'Beschrijving Engels', 'data' => $descriptionEN))
->add('content', 'textarea', array('label' => 'Tekst', 'attr' => array('class' => 'ckeditor'), 'help' => 'My help text.'))
->add('contentEN', 'textarea', array('label' => 'Tekst Engels', 'attr' => array('class' => 'ckeditor'), 'help' => 'My help text.', 'data' => $contentEN));
}
}

Related

Load choices into form choice field from entity method

I have symfony form with choice field. I want to load choices from my entity class static method. can i use data or CallbackChoiceLoader? what is the best practise?
this is my field:
class CarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, [
// This choices I would like to load from:
// 'choices' => $car::getTypes(),
'choices' => [
'Critical' => 'critical',
'Medium' => 'medium',
'Info' => 'info',
],
'label' => 'Type'
])
->add('name', TextType::class, [
'label' => 'Name'
])
->add('save', SubmitType::class, [
'label' => 'Save'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Car'
]);
}
public function getName()
{
return 'car';
}
}
This is my entity:
/**
* #ORM\Entity
* #ORM\Table(name="car")
*/
class Car
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $type
*
* #Assert\NotBlank()
* #ORM\Column(name="type")
*/
private $type;
/**
* #var string $name
*
* #Assert\NotBlank()
* #ORM\Column(name="name")
*/
private $name;
/**
* #var \DateTime $created
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
private static $types = ['main', 'custom'];
public function __construct()
{
$this->created = new \DateTime('now', new \DateTimeZone('Europe/Ljubljana'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get types
*
* #return array
*/
public function getTypes()
{
return self::$types;
}
/**
* Set type
*
* #param string $type
*
* #return Car
*/
public function setType($type)
{
if (in_array($type, $this->getTypes())) {
$this->type = $type;
}
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set name
*
* #param string $name
*
* #return Car
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Car
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
How and what can i use to load choices from $car::getTypes() method like i commented in form so that the choices are loaded dynamicly based on values in getTypes entity method?
Edit: This is option 1. Option 2 below more directly answers the question.
The preferred method of creating a choice form field from an entity is to use the EntityType field. Here is an example from an application that requires an ethnicity field. Below that is the Ethnicity entity.
form field:
->add('ethnicity', EntityType::class, array(
'label' => 'Ethnicity:',
'class' => 'AppBundle:Ethnicity',
'choice_label' => 'abbreviation',
'expanded' => false,
'placeholder' => 'Select ethnicity',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.abbreviation', 'ASC')
;
},
))
Ethnicity entity:
/**
* Ethnicity.
*
* #ORM\Table(name="ethnicity")
* #ORM\Entity
*/
class Ethnicity
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="ethnicity", type="string", length=45, nullable=true)
*/
protected $ethnicity;
/**
* #var string
*
* #ORM\Column(name="abbr", type="string", length=45, nullable=true)
*/
protected $abbreviation;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Member", mappedBy="ethnicity", cascade={"persist"})
*/
protected $members;
/**
* Constructor.
*/
public function __construct()
{
$this->members = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set ethnicity.
*
* #param string $ethnicity
*
* #return Ethnicity
*/
public function setEthnicity($ethnicity)
{
$this->ethnicity = $ethnicity;
return $this;
}
/**
* Get ethnicity.
*
* #return string
*/
public function getEthnicity()
{
return $this->ethnicity;
}
/**
* Set abbreviation.
*
* #param string $abbreviation
*
* #return Ethnicity
*/
public function setAbbreviation($abbreviation)
{
$this->abbreviation = $abbreviation;
return $this;
}
/**
* Get abbreviation.
*
* #return string
*/
public function getAbbreviation()
{
return $this->abbreviation;
}
/**
* Add members.
*
* #param \AppBundle\Entity\Member $members
*
* #return Ethnicity
*/
public function addMember(\AppBundle\Entity\Member $members)
{
$this->members[] = $members;
return $this;
}
/**
* Remove members.
*
* #param \AppBundle\Entity\Member $members
*/
public function removeMember(\Truckee\ProjectmanaBundle\Entity\Member $members)
{
$this->members->removeElement($members);
}
/**
* Get members.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMembers()
{
return $this->members;
}
/**
* #var bool
*
* #ORM\Column(name="enabled", type="boolean", nullable=true)
*/
protected $enabled;
/**
* Set enabled.
*
* #param bool $enabled
*
* #return enabled
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled.
*
* #return bool
*/
public function getEnabled()
{
return $this->enabled;
}
}
Option 2:
If you really want to do that, then here's an approach:
Modify your static property $types such that the choices are values in an array, e.g., $types = array(1 => 'main', 2 => 'custom')
In your controller, add a use statement for the Car entity.
In controller action:
$car = new Car();
$types = $car->getTypes;
Use the answer to Passing data to buildForm() in Symfony 2.8/3.0 to see how to pass $types to your form.

OneToOne Unidirectional Collection not persisting data

I'm attempting to create a OneToOne Undirectional relationship between two entities. I've created the schema but when I submit the form it does not persist the data to the collection. Based off all my research I suspect it's because I don't have the owning entity set up correctly but I've tried everything I can to figure it out with no luck.
Entity - Products.php (Owning Side)
<?php
namespace SCWDesignsBundle\Entity\Products;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Mapping\ClassMetaData;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="SCWDesignsBundle\Entity\Repository\Products\ProductRespository")
* #ORM\Table(name="products")
*/
class Products {
/**
* #ORM\ID
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="ProductCategories")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $category_id;
/**
* #ORM\Column(type="boolean", options={"default" = 0})
*/
protected $featured;
/**
* #ORM\Column(type="boolean", options={"default" = 1})
*/
protected $enabled;
/**
* #ORM\Column(type="boolean", options={"default" = 0})
*/
protected $free_shipping;
/**
* #ORM\OneToOne(targetEntity="ProductSales")
* #ORM\JoinColumn(name="participate_sale", referencedColumnName="id")
*/
protected $participate_sale;
/**
* #ORM\Column(type="decimal")
*/
protected $price;
/**
* #ORM\Column(type="integer")
*/
protected $sku;
/**
* #ORM\Column(type="datetime")
*/
protected $arrival_date;
/**
* #ORM\Column(type="datetime")
*/
protected $update_date;
/*
* ArrayCollection for ProductDescription
* #ORM\OneToOne(targetEntity="ProductDescription", mappedBy="product_id", cascade={"persist"})
* #ORM\JoinColumn(name="description", referencedColumnName="product_id")
*/
protected $description;
public function __construct() {
$this->setArrivalDate(new \DateTime());
$this->description = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set featured
*
* #param boolean $featured
* #return Products
*/
public function setFeatured($featured) {
$this->featured = $featured;
return $this;
}
/**
* Get featured
*
* #return boolean
*/
public function getFeatured() {
return $this->featured;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Products
*/
public function setEnabled($enabled) {
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled() {
return $this->enabled;
}
/**
* Set free_shipping
*
* #param boolean $freeShipping
* #return Products
*/
public function setFreeShipping($freeShipping) {
$this->free_shipping = $freeShipping;
return $this;
}
/**
* Get free_shipping
*
* #return boolean
*/
public function getFreeShipping() {
return $this->free_shipping;
}
/**
* Set price
*
* #param string $price
* #return Products
*/
public function setPrice($price) {
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice() {
return $this->price;
}
/**
* Set sku
*
* #param integer $sku
* #return Products
*/
public function setSku($sku) {
$this->sku = $sku;
return $this;
}
/**
* Get sku
*
* #return integer
*/
public function getSku() {
return $this->sku;
}
/**
* Set arrival_date
*
* #param \DateTime $arrivalDate
* #return Products
*/
public function setArrivalDate($arrivalDate) {
$this->arrival_date = $arrivalDate;
return $this;
}
/**
* Get arrival_date
*
* #return \DateTime
*/
public function getArrivalDate() {
return $this->arrival_date;
}
/**
* Set update_date
*
* #param \DateTime $updateDate
* #return Products
*/
public function setUpdateDate($updateDate) {
$this->update_date = $updateDate;
return $this;
}
/**
* Get update_date
*
* #return \DateTime
*/
public function getUpdateDate() {
return $this->update_date;
}
/**
* Set category_id
*
* #param \SCWDesignsBundle\Entity\Products\ProductCategories $categoryId
* #return Products
*/
public function setCategoryId(\SCWDesignsBundle\Entity\Products\ProductCategories $categoryId = null) {
$this->category_id = $categoryId;
return $this;
}
/**
* Get category_id
*
* #return \SCWDesignsBundle\Entity\Products\ProductCategories
*/
public function getCategoryId() {
return $this->category_id;
}
/**
* Set participate_sale
*
* #param \SCWDesignsBundle\Entity\Products\ProductSales $participateSale
* #return Products
*/
public function setParticipateSale(\SCWDesignsBundle\Entity\Products\ProductSales $participateSale = null) {
$this->participate_sale = $participateSale;
return $this;
}
/**
* Get participate_sale
*
* #return \SCWDesignsBundle\Entity\Products\ProductSales
*/
public function getParticipateSale() {
return $this->participate_sale;
}
/**
* Set description
*
* #param \SCWDesignsBundle\Entity\Products\ProductDescrition $description
* #return Products
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
}
Entity - ProductDescription.php
<?php
namespace SCWDesignsBundle\Entity\Products;
use Doctrine\ORM\Mapping as ORM;
use SCWDesignsBundle\Entity\BaseEntity;
use Symfony\Component\Validator\Mapping\ClassMetaData;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="product_description")
*/
class ProductDescription extends BaseEntity {
/**
* #ORM\ManyToOne(targetEntity="Products")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $product_id;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The item name must be at least {{ limit }} characters long.",
* maxMessage = "The item name cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $name;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $brief_description;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $full_description;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The tags characters must be at least {{ limit }} characters long.",
* maxMessage = "The tags characters cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $meta_tags;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The tags title must be at least {{ limit }} characters long.",
* maxMessage = "The tags title cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $meta_title;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $meta_description;
/**
* Set name
*
* #param string $name
* #return ProductDescription
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set brief_description
*
* #param string $briefDescription
* #return ProductDescription
*/
public function setBriefDescription($briefDescription) {
$this->brief_description = $briefDescription;
return $this;
}
/**
* Get brief_description
*
* #return string
*/
public function getBriefDescription() {
return $this->brief_description;
}
/**
* Set full_description
*
* #param string $fullDescription
* #return ProductDescription
*/
public function setFullDescription($fullDescription) {
$this->full_description = $fullDescription;
return $this;
}
/**
* Get full_description
*
* #return string
*/
public function getFullDescription() {
return $this->full_description;
}
/**
* Set meta_tags
*
* #param string $metaTags
* #return ProductDescription
*/
public function setMetaTags($metaTags) {
$this->meta_tags = $metaTags;
return $this;
}
/**
* Get meta_tags
*
* #return string
*/
public function getMetaTags() {
return $this->meta_tags;
}
/**
* Set meta_title
*
* #param string $metaTitle
* #return ProductDescription
*/
public function setMetaTitle($metaTitle) {
$this->meta_title = $metaTitle;
return $this;
}
/**
* Get meta_title
*
* #return string
*/
public function getMetaTitle() {
return $this->meta_title;
}
/**
* Set meta_description
*
* #param string $metaDescription
* #return ProductDescription
*/
public function setMetaDescription($metaDescription) {
$this->meta_description = $metaDescription;
return $this;
}
/**
* Get meta_description
*
* #return string
*/
public function getMetaDescription() {
return $this->meta_description;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set product_id
*
* #param \SCWDesignsBundle\Entity\Products\Products $productId
* #return ProductDescription
*/
public function setProductId(\SCWDesignsBundle\Entity\Products\Products $productId = null) {
$this->product_id = $productId;
return $this;
}
/**
* Get product_id
*
* #return \SCWDesignsBundle\Entity\Products\Products
*/
public function getProductId() {
return $this->product_id;
}
}
FormType - NewProductFormType.php
<?php
namespace SCWDesignsBundle\Form\Admin;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use SCWDesignsBundle\Form\Types\ProductDescriptionType;
class NewProductFormType extends AbstractType {
private $entityManager;
public function __construct($entityManager) {
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('featured', 'checkbox', array('label' => 'Featured', 'required' => false))
->add('enabled', 'checkbox', array('label' => 'Enabled', 'required' => false))
->add('freeshipping', 'checkbox', array('label' => 'Free Shipping', 'required' => false))
// ->add('participate_sale', 'checkbox', array('label' => 'Sale', 'required' => false))
->add('price', 'text', array('label' => 'Price', 'required' => true))
->add('sku', 'text', array('label' => 'Sku', 'required' => false))
->add('description', 'collection', array(
'type' => new ProductDescriptionType(),
'allow_add' => true,
'by_reference' => true
))
->add('category_id', 'entity', array(
'class' => 'SCWDesignsBundle:Products\ProductCategories',
'property' => 'name',
'placeholder' => false
));
}
public function getName() {
return 'product_new';
}
}
Type - ProductDescriptionType.php
<?php
namespace SCWDesignsBundle\Form\Types;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProductDescriptionType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', null, array('label' => 'Product Name', 'required' => true))
->add('full_description', 'textarea', array('label' => 'Full Description', 'required' => false))
->add('brief_description', 'textarea', array('label' => 'Brief Description', 'required' => false))
->add('meta_tags', null, array('label' => 'Meta Tags', 'required' => false))
->add('meta_title', null, array('label' => 'Meta Title', 'required' => false))
->add('meta_description', 'text', array('label' => 'Meta Description', 'required' => false));
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array('data_class' => '\SCWDesignsBundle\Entity\Products\ProductDescription'));
}
public function getName() {
return 'product_description';
}
}
Controller - ProductsController.php
public function addProductAction(Request $request) {
$categories = $this->getCategories();
$em = $this->getDoctrine()->getEntityManager();
$product = new Products();
$form = $this->createForm(new NewProductFormType($em), $product);
$form->handleRequest($request);
if ($form->isValid()) {
$date = new \DateTime('NOW');
$product->setUpdateDate($date);
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('scw_designs_admin_products'));
}
return $this->render('SCWDesignsBundle:Admin\Products\Actions:new.html.twig', array(
'active_page' => 'products',
'categories' => $categories,
'form' => $form->createView(),
'action' => $this->generateUrl('scw_designs_admin_products_new')
));
}
As this caused me quite a bit of grief I've decided to post my answers after working with sshaun and ddproxy in the official #symfony irc channel.
First, I did have the owning relationship wrong. Needed to switch the inversedby to the product.php. Second I needed to presist the data, so I added the below to the controller and voila, as if magic, it worked.
if ($form->isValid()) {
$date = new \DateTime('NOW');
$product->setUpdateDate($date);
$em->persist($product);
$em->flush();
$description = $product->getDescription()->first();
$description->setProductId($product);
$em->persist($description);
$em->flush();
return $this->redirect($this->generateUrl('scw_designs_admin_products'));
}

Symfony2 relationship between two entities

I want to make a relationship between two entities but for some reason I am getting NULL on one of the values...
So in my skin entity I have an email_registration_id field with the relationship :
/**
* #ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\Email")
* #ORM\JoinColumn(name="email_registration_id", referencedColumnName="id")
*/
protected $email_registration_id;
/**
* Set email_registration_id
*
* #param \Project\UserBundle\Entity\Email $email_registration_id
* #return Skin
*/
public function setEmailRegistrationId(\Project\UserBundle\Entity\Email $email_registration_id = null)
{
$this->email_registration_id = $email_registration_id;
return $this;
}
/**
* Get email_registration_id
*
* #return \Project\UserBundle\Entity\Email
*/
public function getEmailRegistrationId()
{
return $this->email_registration_id;
}
And this is the Email entity:
/**
* Project\UserBundle\Entity\Email
*
* #ORM\Entity
* #ORM\Table(name="email")
*/
class Email {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $title
*
* #ORM\Column(name="title", type="string")
*/
protected $title;
/**
* #var string $registration_content
*
* #ORM\Column(name="registration_content", type="string")
*/
protected $registration_content;
/**
* #var string $confirmation_apuestas
*
* #ORM\Column(name="confirmation_apuestas", type="string")
*/
protected $confirmation_apuestas;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function setId() {
$this->id = null;
}
/**
* Set title
*
* #param string $title
* #return Email
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set registration_content
*
* #param string $registration_content
* #return Email
*/
public function setRegistrationContent($registration_content)
{
$this->registration_content = $registration_content;
return $this;
}
/**
* Get registration_content
*
* #return string
*/
public function getRegistrationContent()
{
return $this->registration_content;
}
/**
* Set $confirmation_apuestas
*
* #param string $confirmation_apuestas
* #return Email
*/
public function setConfirmationApuestas($confirmation_apuestas)
{
$this->confirmation_apuestas = $confirmation_apuestas;
return $this;
}
/**
* Get $confirmation_apuestas
*
*
#return string
*/
public function getConfirmationApuestas()
{
return $this->confirmation_apuestas;
}
}
Now in my cms i create a new email like this:
/**
* #Route("/new", name="cms_email_new")
* #Method({"GET"})
* #Template()
*/
public function newAction() {
$item = new Email();
$form = $this->createForm(new EmailType($this->container->getParameter("langs")), $item);
return array('form' => $form->createView(), 'item' => $item);
}
The form:
public function buildForm(FormBuilderInterface $builder, array $option) {
$builder->add('title', 'text', array('label' => 'cms.Title'));
$builder->add('registration_content', 'textarea', array('label' => 'cms.registration.content'));
$builder->add('confirmation_apuestas', 'textarea', array('label' => 'cms.confirmation.apuestas'));
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'Project\UserBundle\Entity\Email',
);
}
This is how I persist the Email to the database:
/**
* #Route("/save", name="cms_email_save")
* #Template("ProjectUserBundle:EmailAdmin:new.html.twig")
* #Method({"POST"})
*/
public function saveAction(Request $request) {
$item = new Email();
$type = new EmailType($this->container->getParameter("langs"));
$form = $this->createForm($type, $item);
$form->bind($request);
$em = $this->getEntityManager();
if ($form->isValid()) {
$this->upload($form, $item);
$em->persist($item);
$em->flush();
return $this->redirect($this->generateUrl('cms_skin_email_list', array('skin_id' => $item->getId())));
}
return array('form' => $form->createView(), 'item' => $item);
}
The problem is that it creates an email, but in my skin entity, the email_registration_id is just NULL and not the same as emails Id... Maybe I missed something?
UPDATE
So this is what I made according to the responses I got:
class Email {
/**
* #ORM\OneToMany(targetEntity="Project\SkinBundle\Entity\Skin", mappedBy="email_registration_id")
*/
protected $skin;
/**
* Set skin
*
* #param string $skin
* #return Email
*/
public function setSkin(\Project\SkinBundle\Entity\Skin $skin = null)
{
$this->skin = $skin;
return $this;
}
/**
* Get skin
*
* #return string
*/
public function getSkin()
{
return $this->skin;
}
And the form:
public function buildForm(FormBuilderInterface $builder, array $option) {
$builder->add('title', 'text', array('label' => 'cms.Title'));
$builder->add('registration_content', 'textarea', array('label' => 'cms.registration.content'));
$builder->add('confirmation_apuestas', 'textarea', array('label' => 'cms.confirmation.apuestas'));
$builder->add('skin', 'entity', array(
'class' => 'ProjectSkinBundle:Skin',
'property' => 'id',
));
}
However when i am trying to flush to the database I get this error:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in C:\wamp\www\Company\front\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 528 and defined in C:\wamp\www\Company\front\vendor\doctrine\collections\lib\Doctrine\Common\Collections\ArrayCollection.php line 48
It's normal that the creation of a new email is not associated to a skin object. How could it ? The relation is unidirectional, and only works when you create a skin and you give it an email. To create an email and give it a skin, you have to make the relation bidirectional, and add it to your email form.
To do this, I'd do the following :
/*
* Class Project\UserBundle\Entity\Email
*/
class Email {
...
/**
* #ORM\OneToMany(targetEntity="Project\SkinBundle\Entity\Skin", mappedBy="email_registration_id")
*/
protected $skin;
and in your form :
public function buildForm(FormBuilderInterface $builder, array $option) {
$builder->add('title', 'text', array('label' => 'cms.Title'))
->add('registration_content', 'textarea', array('label' => 'cms.registration.content'))
->add('confirmation_apuestas', 'textarea', array('label' => 'cms.confirmation.apuestas'))
->add('skin')
;
}
And PS : You should not use the bind() method to handle the request, it is deprecated. Instead use :
$form->handleRequest($request);
UPDATE 1 : Don't forget to also update your ManyToOne annotation adding the inversedBy part :
#ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\Email", inversedBy="skin")
And also, of course, update your database.

Select categories related to current Store entity

I have two entities Store and Category and each Store has it's own categories.
I'd like that when a Store owner's try to add a new category and category_parent, just the categories related to current Store will be displayed.
Right now, all categories are displayed in the select-option.
I'm using Tree Gedmo extension to manage Category entity and I use getChildrenQueryBuilder method to select categories.
How can I modify this method and add my specific constraint ?
$store which is the constraint is declared in the controller action down.
I'd like te set current Category option disabled when he try to add a category_parent, so category and category parent must be differnt.
I hope it's clear
CategoryType.php
<?php
namespace Project\StoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
class CategoryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//..........
//..........
->add('category', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Entity/Category.php
<?php
namespace Project\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Category
* #Gedmo\Tree(type="nested")
* #ORM\Table()
* #ORM\Entity(repositoryClass="Project\StoreBundle\Entity\CategoryRepository")
* #ORM\HasLifeCycleCallbacks()
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*
*#Assert\NotBlank(message="Please enter the name of categorie.")
*/
private $name;
/**
* #Gedmo\slug(fields={"name"}, unique_base="uniqueBase")
* #ORM\Column(name="slug",length=255, unique=false)
*/
private $slug ;
/**
* #ORM\Column(name="uniqueBase", type="integer")
*/
private $uniqueBase ;
/**
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #ORM\Column(name="metaDescription", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaDescription;
/**
* #ORM\Column(name="metaKeywords", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaKeywords;
/**
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
private $enabled;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
*non mapped property
*/
private $indentedName;
/**
*non mapped property
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Project\StoreBundle\Entity\Store", inversedBy="categories", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $store ;
/**
* Constructor
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
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;
}
/**
* Set slug
*
* #param string $slug
* #return Category
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set uniqueBase
*
* #param integer $uniqueBase
* #return Category
*/
public function setUniqueBase($uniqueBase)
{
$this->uniqueBase = $uniqueBase;
return $this;
}
/**
* Get uniqueBase
*
* #return integer
*/
public function getUniqueBase()
{
return $this->uniqueBase;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set metaDescription
*
* #param string $metaDescription
* #return Category
*/
public function setMetaDescription($metaDescription)
{
$this->metaDescription = $metaDescription;
return $this;
}
/**
* Get metaDescription
*
* #return string
*/
public function getMetaDescription()
{
return $this->metaDescription;
}
/**
* Set metaKeywords
*
* #param string $metaKeywords
* #return Category
*/
public function setMetaKeywords($metaKeywords)
{
$this->metaKeywords = $metaKeywords;
return $this;
}
/**
* Get metaKeywords
*
* #return string
*/
public function getMetaKeywords()
{
return $this->metaKeywords;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Category
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set parent
*
* #param \Project\StoreBundle\Entity\Category $parent
* #return Category
*/
public function setParent(\Project\StoreBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \Project\StoreBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
/**
* Set lft
*
* #param integer $lft
* #return Category
*/
public function setLft($lft)
{
$this->lft = $lft;
return $this;
}
/**
* Get lft
*
* #return integer
*/
public function getLft()
{
return $this->lft;
}
/**
* Set lvl
*
* #param integer $lvl
* #return Category
*/
public function setLvl($lvl)
{
$this->lvl = $lvl;
return $this;
}
/**
* Get lvl
*
* #return integer
*/
public function getLvl()
{
return $this->lvl;
}
/**
* Set rgt
*
* #param integer $rgt
* #return Category
*/
public function setRgt($rgt)
{
$this->rgt = $rgt;
return $this;
}
/**
* Get rgt
*
* #return integer
*/
public function getRgt()
{
return $this->rgt;
}
/**
* Set root
*
* #param integer $root
* #return Category
*/
public function setRoot($root)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* #return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Add children
*
* #param \Project\StoreBundle\Entity\Category $children
* #return Category
*/
public function addChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children[] = $children;
return $this;
}
/**
* Remove children
*
* #param \Project\StoreBundle\Entity\Category $children
*/
public function removeChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children->removeElement($children);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Get IndentedName
*
*/
public function getIndentedName()
{
return str_repeat("-----", $this->lvl).$this->name;
}
/**
* Get category
*
*/
public function getCategory()
{
return $this->category;
}
/**
* Set store
*
* #param \Project\StoreBundle\Entity\Store $store
* #return Category
*/
public function setStore(\Project\StoreBundle\Entity\Store $store = null)
{
$this->store = $store;
return $this;
}
/**
* Get store
*
* #return \Project\StoreBundle\Entity\Store
*/
public function getStore()
{
return $this->store;
}
}
Controller
/**
* Create a new Category entity.
*
*/
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType(), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
I managed to pass the parameter $store to the form, but I don't know how to use it as a constraint in getChildrenQueryBuilder method.
Should I create a new custom method? I prefer to use getChildrenQueryBuilder if it is possible.
Here is the new code
CategoryType.php
class CategoryType extends AbstractType
{
private $store;
public function __construct($store)
{
$this->store = $store;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$store = $this->store;
$builder
//...........
//...........
->add('parent', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r) use ($store)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Controller
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType($store), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
You're not saying which Symfony2 version you're using, but generically speaking, you just need to find a way to pass the current store to your form builder and use it in the method that filters the possible categories.
Take a look at this one, or this one, basically you just need to inject the $store into your form builder, and then you (almost) have it :-)

How to upload image and display on edit of profile using sonata admin bundle

I am using sonata admin bundle and creating one employee form to save employee detail and I want to upload employee photo and display that photo on click of edit profile for that I am writing following code in location:
E:\xampp\htdocs\SymfonyStart\src\Sigma\EmployeeBundle\Admin\EmployeeAdmin
// src/Sigma/EmployeeBundle/Admin/PostAdmin.php
namespace Sigma\EmployeeBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class EmployeeAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', 'text', array('label' => 'Name'))
->add('designation', 'choice', array(
'choices' => array('pm' => 'PM', 'pl' => 'PL','pm' => 'PM', 'pc' => 'PC','pm' => 'PM', 'tl' => 'TL','sse' => 'SSE', 'se' => 'SE','others' => 'Others'),
'required' => true,
))
->add('lob', 'choice', array(
'choices' => array('ba' => 'BA', 'bi' => 'BI','java' => 'JAVA','qa' => 'QA', 'ob' => 'OB','web' => 'WEB'),
'required' => true,
))
->add('emp_id')
->add('experience', 'text', array('label' => 'Experience'))
->add('skills', 'textarea', array('label' => 'Skills'))
->add('email', 'email', array('label' => 'Email'))
->add('mobile', 'text', array('label' => 'Mobile'))
->add('attachment', 'file', array(
'required' => false,
'data_class' => null
)
);
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('designation')
->add('name')
->add('emp_id')
->add('lob')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('name')
->addIdentifier('designation')
->add('emp_id')
->add('lob')
->add('attachment')
;
}
}
and my entity class file location and code is -
E:\xampp\htdocs\SymfonyStart\src\Sigma\EmployeeBundle\Entity
namespace Sigma\EmployeeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Employee
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Sigma\EmployeeBundle\Entity\EmployeeRepository")
*/
class Employee
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="lob", type="string", length=255)
*/
private $lob;
/**
* #var string
*
* #ORM\Column(name="experience", type="string", length=255)
*/
private $experience;
/**
* #var string
*
* #ORM\Column(name="skills", type="string", length=255)
*/
private $skills;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="mobile", type="integer")
*/
private $mobile;
/**
* #var string
*
* #ORM\Column(name="emp_id", type="integer")
*/
private $emp_id;
/**
* #var string
*
* #ORM\Column(name="designation", type="string", length=255)
*/
private $designation;
/**
* #var string
*
* #ORM\Column(name="attachment", type="string", length=255)
*/
public $attachment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set designation
*
* #param string $designation
* #return Employee
*/
public function setDesignation($designation)
{
$this->designation = $designation;
return $this;
}
/**
* Get designation
*
* #return string
*/
public function getDesignation()
{
return $this->designation;
}
/**
* Set first_name
*
* #param string $firstName
* #return Employee
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set lob
*
* #param string $lob
* #return Employee
*/
public function setLob($lob)
{
$this->lob = $lob;
return $this;
}
/**
* Get lob
*
* #return string
*/
public function getLob()
{
return $this->lob;
}
/**
* Set experience
*
* #param string $experience
* #return Employee
*/
public function setExperience($experience)
{
$this->experience = $experience;
return $this;
}
/**
* Get experience
*
* #return string
*/
public function getexperience()
{
return $this->experience;
}
/**
* Set skills
*
* #param string $skills
* #return Employee
*/
public function setSkills($skills)
{
$this->skills = $skills;
return $this;
}
/**
* Get skills
*
* #return string
*/
public function getSkills()
{
return $this->skills;
}
/**
* Set email
*
* #param string $email
* #return Employee
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set mobile
*
* #param integer $mobile
* #return Employee
*/
public function setMobile($mobile)
{
$this->mobile = $mobile;
return $this;
}
/**
* Get mobile
*
* #return integer
*/
public function getMobile()
{
return $this->mobile;
}
/**
* Set attachment
*
* #param string $attachment
* #return Employee
*/
public function setAttachment($attachment)
{
$this->attachment = $attachment;
return $this;
}
/**
* Get attachment
*
* #return string
*/
public function getAttachment()
{
return $this->attachment;
}
/**
* Set emp_id
*
* #param integer $empId
* #return Employee
*/
public function setEmpId($empId)
{
$this->emp_id = $empId;
return $this;
}
/**
* Get emp_id
*
* #return integer
*/
public function getEmpId()
{
return $this->emp_id;
}
}
by this I am able to upload image but it saving in database like - "xampp/tmp/php6767.xt". How I can save this image properly and and display on edit profile? I followed the tutorial documentation but exactly I am not getting where and how to place code according to my code.
You should use SonataMediaAdmin with the SonataAdminBundle in order to store your employee profile pictures.
Using it, you could write in your EmployeeAdmin class (in the configureFormFields() method) something like that:
$formMapper->add('attachment', 'sonata_media_type', array(
'provider' => 'sonata.media.provider.image',
'context' => 'employee_pictures',
));
You should also create a specific context (named employee_pictures in my previous code block) in the SonataMediaBundle configuration to store them.

Categories