Fields from child entity don't show in symfony - php

I apologize in advance for a noob question. I just started learning symfony and I ran into a roadblock.
I created the RequestForEstimate entity and it may have multiple records associated under the RequestForEstimateDetail entity. Now, Im trying to create a form that not only displays fields from the first entity but also from the second one as well. Symfony doesn't return any errors however it doesn't render the "quantity" field from the RequestForEstimateDetail entity. I used the following tutorial to create this code: How to Embed a Collection of Forms
This is an example of my RequestForEstimate entity:
<?php
namespace SourcingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RequestForEstimate
*
* #ORM\Table(name="request_for_estimate")
* #ORM\Entity(repositoryClass="SourcingBundle\Repository\RequestForEstimateRepository")
*/
class RequestForEstimate
{
/**
* #var int
*
* #ORM\Column(name="requestId", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="createTime", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="updateTime", type="datetime")
*/
private $updateTime;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="RequestForEstimateDetail", mappedBy="detail", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $details;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set status
*
* #param integer $status
*
* #return RequestForEstimate
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return RequestForEstimate
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return RequestForEstimate
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
/**
* Set name
*
* #param string $name
*
* #return RequestForEstimate
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Constructor
*/
public function __construct()
{
$this->details = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add detail
*
* #param \SourcingBundle\Entity\RequestForEstimateDetail $detail
*
* #return RequestForEstimate
*/
public function addDetail(\SourcingBundle\Entity\RequestForEstimateDetail $detail)
{
$this->details[] = $detail;
return $this;
}
/**
* Remove detail
*
* #param \SourcingBundle\Entity\RequestForEstimateDetail $detail
*/
public function removeDetail(\SourcingBundle\Entity\RequestForEstimateDetail $detail)
{
$this->details->removeElement($detail);
}
/**
* Get details
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDetails()
{
return $this->details;
}
}
This is my RequestForEstimateDetail entity:
<?php
namespace SourcingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RequestForEstimateDetail
*
* #ORM\Table(name="request_for_estimate_detail")
* #ORM\Entity(repositoryClass="SourcingBundle\Repository\RequestForEstimateDetailRepository")
*/
class RequestForEstimateDetail
{
/**
* #var int
*
* #ORM\Column(name="requestDetailId", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="RequestForEstimate", inversedBy="details")
* #ORM\JoinColumn(name="requestId", referencedColumnName="requestId")
*/
private $detail;
/**
* #var int
*
* #ORM\Column(name="productId", type="integer")
*/
private $productId;
/**
* #var int
*
* #ORM\Column(name="quantity", type="integer")
*/
private $quantity;
/**
* #var string
*
* #ORM\Column(name="pricePerUnit", type="decimal", precision=2, scale=0)
*/
private $pricePerUnit;
/**
* #var string
*
* #ORM\Column(name="shippingCost", type="decimal", precision=2, scale=0)
*/
private $shippingCost;
/**
* #var string
*
* #ORM\Column(name="otherFees", type="decimal", precision=2, scale=0)
*/
private $otherFees;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set product
*
* #param integer $product
*
* #return RequestForEstimateDetail
*/
public function setProduct($product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return int
*/
public function getProduct()
{
return $this->product;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return RequestForEstimateDetail
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set pricePerUnit
*
* #param string $pricePerUnit
*
* #return RequestForEstimateDetail
*/
public function setPricePerUnit($pricePerUnit)
{
$this->pricePerUnit = $pricePerUnit;
return $this;
}
/**
* Get pricePerUnit
*
* #return string
*/
public function getPricePerUnit()
{
return $this->pricePerUnit;
}
/**
* Set shippingCost
*
* #param string $shippingCost
*
* #return RequestForEstimateDetail
*/
public function setShippingCost($shippingCost)
{
$this->shippingCost = $shippingCost;
return $this;
}
/**
* Get shippingCost
*
* #return string
*/
public function getShippingCost()
{
return $this->shippingCost;
}
/**
* Set otherFees
*
* #param string $otherFees
*
* #return RequestForEstimateDetail
*/
public function setOtherFees($otherFees)
{
$this->otherFees = $otherFees;
return $this;
}
/**
* Get otherFees
*
* #return string
*/
public function getOtherFees()
{
return $this->otherFees;
}
/**
* Set requestId
*
* #param \SourcingBundle\Entity\RequestForEstimate $requestId
*
* #return RequestForEstimateDetail
*/
public function setRequestId(\SourcingBundle\Entity\RequestForEstimate $requestId = null)
{
$this->requestId = $requestId;
return $this;
}
/**
* Get requestId
*
* #return \SourcingBundle\Entity\RequestForEstimate
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Set productId
*
* #param \SourcingBundle\Entity\Product $productId
*
* #return RequestForEstimateDetail
*/
public function setProductId(\SourcingBundle\Entity\Product $productId = null)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId
*
* #return \SourcingBundle\Entity\Product
*/
public function getProductId()
{
return $this->productId;
}
/**
* Set detail
*
* #param \SourcingBundle\Entity\RequestForEstimate $detail
*
* #return RequestForEstimateDetail
*/
public function setDetail(\SourcingBundle\Entity\RequestForEstimate $detail = null)
{
$this->detail = $detail;
return $this;
}
/**
* Get detail
*
* #return \SourcingBundle\Entity\RequestForEstimate
*/
public function getDetail()
{
return $this->detail;
}
}
This is my RequestForEstimateController:
<?php
namespace SourcingBundle\Controller;
use SourcingBundle\Entity\RequestForEstimate;
use SourcingBundle\Form\Type\RequestForEstimateType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class RequestForEstimateController extends Controller
{
/**
* #Route("sourcing/request-for-estimate", name="request_for_estimate")
*/
public function addRequest(Request $request)
{
$RequestForEstimate = new RequestForEstimate();
$form = $this->createForm(RequestForEstimateType::class, $RequestForEstimate);
return $this->render('sourcing/requestforestimate/create.html.twig', array(
'form' => $form->createView(),
));
}
}
These are my form classes:
RequestForEstimateType.php
<?php
namespace SourcingBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class RequestForEstimateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('details', CollectionType::class, array(
'entry_type' => RequestForEstimateDetailType::class
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SourcingBundle\Entity\RequestForEstimate',
));
}
}
RequestForEstimateDetailType.php:
<?php
namespace SourcingBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RequestForEstimateDetailType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('quantity',TextType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SourcingBundle\Entity\RequestForEstimateDetail',
));
}
}
Now my view:
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Create Request For Estimate</h5>
</div>
<div class="ibox-content">
{{ form_start(form) }}
{{ form_errors(form) }}
<div>
{{ form_widget(form) }}
</div>
{{ dump(form.details)}}
{% for detail in form.details %}
<li>{{ form_row(detail.quantity) }}</li>
{% endfor %}
{{ form_end(form) }}
</div>
</div>
</div>
</div>

You need to create some RequestForEstimateDetail entities in your controller class and add it to RequestForEstimate entity. Like this:
class RequestForEstimateController extends Controller
{
/**
* #Route("sourcing/request-for-estimate", name="request_for_estimate")
*/
public function addRequest(Request $request)
{
$RequestForEstimate = new RequestForEstimate();
$detail1 = new RequestForEstimateDetail();
$detail2 = new RequestForEstimateDetail();
$RequestForEstimate->addDetail($detail1);
$RequestForEstimate->addDetail($detail2);
$form = $this->createForm(RequestForEstimateType::class, $RequestForEstimate);
return $this->render('sourcing/requestforestimate/create.html.twig', array(
'form' => $form->createView(),
));
}
}
PS. U can read this doc http://symfony.com/doc/current/form/form_collections.html it's pretty clear =)

Related

Cannot get related entity field to save in Symfony Admin Form

I'm working my way through Symfony trying to learn how it all fits together and I'm working on the admin section.
Right now I'm putting together an admin form for a Show Entity which will reference a section entity (so this show belongs in that section, etc). Every other field in the form saves EXCEPT for the related entity choice field.
This is the ShowAdmin class
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Nelmio\ApiDocBundle\Tests\Fixtures\Form\EntityType;
class ShowAdmin extends AbstractAdmin {
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('title', 'text')
->add('shortname', 'text')
->add('section_id', EntityType::class, array(
'class' => 'AppBundle:SectionEntity',
'choice_label' => 'section_title',
))
->add('logo', 'text')
->add('description', 'textarea')
->add('status', 'integer');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add('title');
$datagridMapper->add('shortname');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->addIdentifier('title');
$listMapper->add('shortname', 'text');
}
}
This is the ShowEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="shows")
*/
class ShowEntity {
function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $title;
/**
* #ORM\Column(type="string", length=100)
*/
private $shortname;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SectionEntity")
*/
private $section;
/**
* #ORM\Column(type="string", length=255)
*/
private $logo;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="integer")
*/
private $status;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return ShowEntity
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set sectionId
*
* #param integer $sectionId
*
* #return ShowEntity
*/
public function setSectionId($sectionId)
{
$this->section_id = $sectionId;
return $this;
}
/**
* Get sectionId
*
* #return integer
*/
public function getSectionId()
{
return $this->section_id;
}
/**
* Set logo
*
* #param string $logo
*
* #return ShowEntity
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* #return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set description
*
* #param string $description
*
* #return ShowEntity
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set status
*
* #param integer $status
*
* #return ShowEntity
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set shortname
*
* #param string $shortname
*
* #return ShowEntity
*/
public function setShortname($shortname)
{
$this->shortname = $shortname;
return $this;
}
/**
* Get shortname
*
* #return string
*/
public function getShortname()
{
return $this->shortname;
}
}
And this is the SectionEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SectionEntity
*
* #ORM\Table(name="section_entity")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SectionEntityRepository")
*/
class SectionEntity
{
protected $section_id;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $section_title;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set sectionTitle
*
* #param string $sectionTitle
*
* #return SectionEntity
*/
public function setSectionTitle($sectionTitle)
{
$this->section_title = $sectionTitle;
return $this;
}
/**
* Get sectionTitle
*
* #return string
*/
public function getSectionTitle()
{
return $this->section_title;
}
/**
* Get string
*/
public function __toString() {
return $this->section_title;
}
function __construct() {
$this->section_id = new \Doctrine\Common\Collections\ArrayCollection();
}
}
Any help would be greatly appreciated, I know it's probably something super simple that I'm just not seeing.
Thanks.
(optional) Rename ShowEntity::$section into ShowEntity::$sections to highlight sections is a collection but not a single entity.
Set ShowEntity __construct method body to:
$this->sections = new \Doctrine\Common\Collections\ArrayCollection();
At ShowAdmin::configureFormFields rename
->add('section_id', EntityType::class, array(
into
->add('section', EntityType::class, array(
You should use direct reference to the relation instead of id.
Remove SectionEntity::__construct method, it has no sense.
Remove protected $section_id; from SectionEntity.
Change public function setSectionId($sectionId) into public function setSection(Section $section).
Perhaps you also need to rename section_title into sectionTitle or simply title, not sure about that.

Symfony One-To-One Unidirectional relationship How can I make Doctrine create a new Menu if a new Coffeeshop is made?

I have a bit of a problem figuring out the following:
How can I make Symfony insert a new menu when a new coffeeshop has been made with a form? (foreign key in menu is shopid)
Thanks in advance, code below.
Menu Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Menu
*
* #ORM\Table(name="menu")
* #ORM\Entity(repositoryClass="AppBundle\Repository\MenuRepository")
*
*/
class Menu
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="Coffeeshop")
* #ORM\JoinColumn(name="coffeeshop_id", referencedColumnName="id")
*/
private $shopId;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set shopId
*
* #param integer $shopId
*
* #return Menu
*/
public function setShopId($shopId)
{
$this->shopId = $shopId;
return $this;
}
/**
* Get shopId
*
* #return int
*/
public function getShopId()
{
return $this->shopId;
}
/**
* Set lastUpdated
*
* #param \DateTime $lastUpdated
*
* #return Menu
*/
public function setLastUpdated($lastUpdated)
{
$this->lastUpdated = $lastUpdated;
return $this;
}
/**
* Get lastUpdated
*
* #return \DateTime
*/
public function getLastUpdated()
{
return $this->lastUpdated;
}
/**
* Set updated
*
* #param \DateTime $updated
*
* #return Menu
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
}
Coffeeshop Entity:
<?php
/// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="coffeeshop")
*/
class Coffeeshop
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $phone;
/**
* #ORM\Column(type="string", length=50)
*/
private $streetName;
/**
* #ORM\Column(type="string", length=6)
*/
private $houseNumber;
/**
* #ORM\Column(type="string", length=7)
*/
private $zipcode;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Coffeeshop
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set phone
*
* #param string $phone
*
* #return Coffeeshop
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set streetName
*
* #param string $streetName
*
* #return Coffeeshop
*/
public function setStreetName($streetName)
{
$this->streetName = $streetName;
return $this;
}
/**
* Get streetName
*
* #return string
*/
public function getStreetName()
{
return $this->streetName;
}
/**
* Set houseNumber
*
* #param string $houseNumber
*
* #return Coffeeshop
*/
public function setHouseNumber($houseNumber)
{
$this->houseNumber = $houseNumber;
return $this;
}
/**
* Get houseNumber
*
* #return string
*/
public function getHouseNumber()
{
return $this->houseNumber;
}
/**
* Set description
*
* #param string $description
*
* #return Coffeeshop
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set zipcode
*
* #param string $zipcode
*
* #return Coffeeshop
*/
public function setZipcode($zipcode)
{
$this->zipcode = $zipcode;
return $this;
}
/**
* Get zipcode
*
* #return string
*/
public function getZipcode()
{
return $this->zipcode;
}
/**
* Set menu
*
* #param \AppBundle\Entity\Menu $menu
*
* #return Coffeeshop
*/
public function setMenu(\AppBundle\Entity\Menu $menu = null)
{
$this->menu = $menu;
return $this;
}
/**
* Get menu
*
* #return \AppBundle\Entity\Menu
*/
public function getMenu()
{
return $this->menu;
}
/**
* Set coffeeshopmenu
*
* #param \AppBundle\Entity\Menu $coffeeshopmenu
*
* #return Coffeeshop
*/
public function setCoffeeshopmenu(\AppBundle\Entity\Menu $coffeeshopmenu = null)
{
$this->coffeeshopmenu = $coffeeshopmenu;
return $this;
}
/**
* Get coffeeshopmenu
*
* #return \AppBundle\Entity\Menu
*/
public function getCoffeeshopmenu()
{
return $this->coffeeshopmenu;
}
}
Coffeeshop FormBuilder:
<?php
/**
* Created by PhpStorm.
* User:
* Date: 23-9-2016
* Time: 14:20
*/
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CoffeeshopType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('phone')
->add('streetName')
->add('houseNumber')
->add('zipcode')
->add('description')
->add('save', SubmitType::class, array('label' => 'Add shop'))
;
}
}
In many ways:
you can define Coffeeshoptypeas a service, then inject ManagerRegistry (#doctrine) to __construct() (or just EntityManager), set an event listener for event FormEvents::POST_SUBMIT. Something like that:
$this->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {/*...*/});
in controller, where you persist changes from Coffeeshoptype
use an event listener for Doctrine (or create an entity listener, feature from Doctrine). With doctrine events, you can find if entity (Coffeeshop) is persisting or updating and depends of situation, create new menu.
All of above methods can have access to Doctrine (thanks to Dependency Injection), also some of these methods are bad approaches. I suggest to attach EventListener (or EventSubscriber) to one of Doctrine Events and then do persisting for new menu. But if you need to create a new menu only when Coffeeshop is submitted by form, create event listener in form type.

Display specific fields from database in value and text fields of a combobox in Symfony2

I have a table named company which is having one to many relationship with a department table. I have created both the entities using Doctrine generator by specifying the relationships. I also have generated the schema and everything went fine
Please take a look at both my entities
Company.php
<?php
namespace Benerite\CompanyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Company
*
* #ORM\Table("companies")
* #ORM\Entity(repositoryClass="Benerite\CompanyBundle\Entity\CompanyRepository")
*/
class Company
{
/**
* #var departments
* #ORM\OneToMany(targetEntity="Department", mappedBy="company")
*/
protected $departments;
/**
* #var divisions
* #ORM\OneToMany(targetEntity="Division", mappedBy="company")
*/
protected $divisions;
/**
* #var employmentStatuses
* #ORM\OneToMany(targetEntity="EmploymentStatus", mappedBy="company")
*/
protected $employmentStatuses;
/**
* #var jobTitles
* #ORM\OneToMany(targetEntity="JobTitle", mappedBy="company")
*/
protected $jobTitles;
/**
* #var companyLocations
* #ORM\OneToMany(targetEntity="Location", mappedBy="company")
*/
protected $companyLocations;
/**
* #var remunerationChangeReasons
* #ORM\OneToMany(targetEntity="RemunerationChangeReason", mappedBy="company")
*/
protected $remunerationChangeReasons;
/**
* #var roles
* #ORM\OneToMany(targetEntity="Role", mappedBy="company")
*/
protected $roles;
/**
* #var subscriptionDetails
*
* #ORM\OneToMany(targetEntity="SubscriptionDetail", mappedBy="company")
*/
protected $subscriptionDetails;
/**
* #var employeeBasicInfo
*
* #ORM\OneToMany(targetEntity="Benerite\EmployeeBundle\Entity\EmployeeBasicInfo", mappedBy="companies")
*/
protected $employeeBasicInfo;
public function __construct() {
$this->departments = new ArrayCollection();
$this->divisions = new ArrayCollection();
$this->employmentStatuses = new ArrayCollection();
$this->jobTitles = new ArrayCollection();
$this->companyLocations = new ArrayCollection();
$this->remunerationChangeReasons = new ArrayCollection();
$this->roles = new ArrayCollection();
$this->subscriptionDetails = new ArrayCollection();
$this->employeeBasicInfo = new ArrayCollection();
}
function getDepartments() {
return $this->departments;
}
function getDivisions() {
return $this->divisions;
}
function getEmploymentStatuses() {
return $this->employmentStatuses;
}
function getJobTitles() {
return $this->jobTitles;
}
function getCompanyLocations() {
return $this->companyLocations;
}
function getRemunerationChangeReasons() {
return $this->remunerationChangeReasons;
}
function getRoles() {
return $this->roles;
}
function getSubscriptionDetails() {
return $this->subscriptionDetails;
}
function setDepartments(Department $departments) {
$this->departments = $departments;
}
function setDivisions(Division $divisions) {
$this->divisions = $divisions;
}
function setEmploymentStatuses(\Benerite\EmployeeBundle\Entity\EmployeeEmploymentStatus $employmentStatuses) {
$this->employmentStatuses = $employmentStatuses;
}
function setJobTitles(JobTitle $jobTitles) {
$this->jobTitles = $jobTitles;
}
function setCompanyLocations(Location $companyLocations) {
$this->companyLocations = $companyLocations;
}
function setRemunerationChangeReasons(RemunerationChangeReason $remunerationChangeReasons) {
$this->remunerationChangeReasons = $remunerationChangeReasons;
}
function setRoles(Role $roles) {
$this->roles = $roles;
}
function setSubscriptionDetails(SubscriptionDetail $subscriptionDetails) {
$this->subscriptionDetails = $subscriptionDetails;
}
function getEmployeeBasicInfo() {
return $this->employeeBasicInfo;
}
function setEmployeeBasicInfo(\Benerite\EmployeeBundle\Entity\EmployeeBasicInfo $employeeBasicInfo) {
$this->employeeBasicInfo = $employeeBasicInfo;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="company_name", type="string", length=255)
*/
private $companyName;
/**
* #var string
*
* #ORM\Column(name="company_reg_code", type="string", length=255)
*/
private $companyRegCode;
/**
* #var string
*
* #ORM\Column(name="account_owner", type="string", length=255)
*/
private $accountOwner;
/**
* #var string
*
* #ORM\Column(name="account_email", type="string", length=255)
*/
private $accountEmail;
/**
* #var string
*
* #ORM\Column(name="company_url", type="string", length=255)
*/
private $companyUrl;
/**
* #var string
*
* #ORM\Column(name="company_status", type="string", length=255)
*/
private $companyStatus;
/**
* #var \DateTime
*
* #ORM\Column(name="created_date", type="datetime")
*/
private $createdDate;
/**
* #var \DateTime
*
* #ORM\Column(name="last_updated_date", type="datetime")
*/
private $lastUpdatedDate;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set companyName
*
* #param string $companyName
*
* #return Company
*/
public function setCompanyName($companyName)
{
$this->companyName = $companyName;
return $this;
}
/**
* Get companyName
*
* #return string
*/
public function getCompanyName()
{
return $this->companyName;
}
/**
* Set companyRegCode
*
* #param string $companyRegCode
*
* #return Company
*/
public function setCompanyRegCode($companyRegCode)
{
$this->companyRegCode = $companyRegCode;
return $this;
}
/**
* Get companyRegCode
*
* #return string
*/
public function getCompanyRegCode()
{
return $this->companyRegCode;
}
/**
* Set accountOwner
*
* #param string $accountOwner
*
* #return Company
*/
public function setAccountOwner($accountOwner)
{
$this->accountOwner = $accountOwner;
return $this;
}
/**
* Get accountOwner
*
* #return string
*/
public function getAccountOwner()
{
return $this->accountOwner;
}
/**
* Set accountEmail
*
* #param string $accountEmail
*
* #return Company
*/
public function setAccountEmail($accountEmail)
{
$this->accountEmail = $accountEmail;
return $this;
}
/**
* Get accountEmail
*
* #return string
*/
public function getAccountEmail()
{
return $this->accountEmail;
}
/**
* Set companyUrl
*
* #param string $companyUrl
*
* #return Company
*/
public function setCompanyUrl($companyUrl)
{
$this->companyUrl = $companyUrl;
return $this;
}
/**
* Get companyUrl
*
* #return string
*/
public function getCompanyUrl()
{
return $this->companyUrl;
}
/**
* Set companyStatus
*
* #param string $companyStatus
*
* #return Company
*/
public function setCompanyStatus($companyStatus)
{
$this->companyStatus = $companyStatus;
return $this;
}
/**
* Get companyStatus
*
* #return string
*/
public function getCompanyStatus()
{
return $this->companyStatus;
}
/**
* Set createdDate
*
* #param \DateTime $createdDate
*
* #return Company
*/
public function setCreatedDate($createdDate)
{
$this->createdDate = $createdDate;
return $this;
}
/**
* Get createdDate
*
* #return \DateTime
*/
public function getCreatedDate()
{
return $this->createdDate;
}
/**
* Set lastUpdatedDate
*
* #param \DateTime $lastUpdatedDate
*
* #return Company
*/
public function setLastUpdatedDate($lastUpdatedDate)
{
$this->lastUpdatedDate = $lastUpdatedDate;
return $this;
}
/**
* Get lastUpdatedDate
*
* #return \DateTime
*/
public function getLastUpdatedDate()
{
return $this->lastUpdatedDate;
}
public function __toString()
{
return (string)$this->getId();
}
}
Department.php
<?php
namespace Benerite\CompanyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Department
*
* #ORM\Table("departments")
* #ORM\Entity(repositoryClass="Benerite\CompanyBundle\Entity\DepartmentRepository")
*/
class Department
{
/**
* #ORM\ManyToOne(targetEntity="Company", inversedBy="departments")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
protected $company;
/**
* #var employeeJobInfo
*
* #ORM\OneToMany(targetEntity="Benerite\EmployeeBundle\Entity\EmployeeJobInfo", mappedBy="department")
*/
protected $employeeJobInfo;
public function __construct()
{
$this->employeeJobInfo = new ArrayCollection();
}
function getCompany() {
return $this->company;
}
function getEmployeeJobInfo() {
return $this->employeeJobInfo;
}
function setCompany(Company $company) {
$this->company = $company;
}
function setEmployeeJobInfo(\Benerite\EmployeeBundle\Entity\EmployeeJobInfo $employeeJobInfo) {
$this->employeeJobInfo = $employeeJobInfo;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="company_id", type="integer" , nullable = false)
*/
private $companyId;
/**
* #var string
*
* #ORM\Column(name="department_name", type="string", length=255)
*/
private $departmentName;
/**
* #var string
*
* #ORM\Column(name="department_status", type="string", length=255)
*/
private $departmentStatus;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set companyId
*
* #param integer $companyId
*
* #return Department
*/
public function setCompanyId($companyId)
{
$this->companyId = $companyId;
return $this;
}
/**
* Get companyId
*
* #return integer
*/
public function getCompanyId()
{
return $this->companyId;
}
/**
* Set departmentName
*
* #param string $departmentName
*
* #return Department
*/
public function setDepartmentName($departmentName)
{
$this->departmentName = $departmentName;
return $this;
}
/**
* Get departmentName
*
* #return string
*/
public function getDepartmentName()
{
return $this->departmentName;
}
/**
* Set departmentStatus
*
* #param string $departmentStatus
*
* #return Department
*/
public function setDepartmentStatus($departmentStatus)
{
$this->departmentStatus = $departmentStatus;
return $this;
}
/**
* Get departmentStatus
*
* #return string
*/
public function getDepartmentStatus()
{
return $this->departmentStatus;
}
}
As a next step, I have generated CRUD forms for my Department entity and Company Entity. Now I can make CRUD operations on both the entities and everything goes fine. That's also OK for me
Please take a look at my CompanyType.php and DepartmentType.php
CompanyType.php
<?php
namespace Benerite\CompanyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CompanyType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('companyName')
->add('companyRegCode')
->add('accountOwner')
->add('accountEmail')
->add('companyUrl')
->add('companyStatus')
->add('createdDate')
->add('lastUpdatedDate')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Benerite\CompanyBundle\Entity\Company'
));
}
/**
* #return string
*/
public function getName()
{
return 'benerite_companybundle_company';
}
}
DepartmentType.php
<?php
namespace Benerite\CompanyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class DepartmentType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('company')
->add('departmentName')
->add('departmentStatus')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Benerite\CompanyBundle\Entity\Department'
));
}
/**
* #return string
*/
public function getName()
{
return 'benerite_companybundle_department';
}
}
I can now create Company. For these created companies, I want to create departments that's also goes fine
When rendering the departments "create" and "edit" forms, the company labelled combobox items are showing company ID in its text and value. I want to show the company name in text field and company ID in value property.
Here is my company creation TWIG file
new.html.ywig
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Department creation</h1>
{{ form_start(form) }}
<div>
{{ form_label(form.company) }}
{{ form_widget(form.company) }}
</div>
<div>
{{ form_label(form.departmentStatus) }}
{{ form_widget(form.departmentStatus) }}
</div>
<div>
{{ form_label(form.departmentName) }}
{{ form_widget(form.departmentName) }}
</div>
{{ form_end(form) }}
<ul class="record_actions">
<li>
<a href="{{ path('department') }}">
Back to the list
</a>
</li>
</ul>
{% endblock %}
Is there any option to customize this from the twig file or from the DepartmentType.php file?
How can I accomplish this?
To display company name instead of its id, use the property option (for Symfony 2.6 and bellow) or the choice_label option (for Symfony 2.7+) :
For Symfony 2.6 and bellow :
<?php
namespace Benerite\CompanyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class DepartmentType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('company', 'entity', array(
'class' => 'CompanyBundle:Company',
'property' => 'companyName',
))
->add('departmentName')
->add('departmentStatus')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Benerite\CompanyBundle\Entity\Department'
));
}
/**
* #return string
*/
public function getName()
{
return 'benerite_companybundle_department';
}
}
For Symfony 2.7 and next :
<?php
namespace Benerite\CompanyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class DepartmentType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('company', 'entity', array(
'class' => 'CompanyBundle:Company',
'choice_label' => 'companyName',
))
->add('departmentName')
->add('departmentStatus')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Benerite\CompanyBundle\Entity\Department'
));
}
/**
* #return string
*/
public function getName()
{
return 'benerite_companybundle_department';
}
}
And by the way, in your Twig instead of
{{ form_label(form.company) }}
{{ form_widget(form.company) }}
you can write form_row(form.company).
You have two solution. Th most simple with your current solution :
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Department creation</h1>
{{ form_start(form) }}
<div>
{{ form_label(form.company, form.company.companyName) }}
{{ form_widget(form.company) }}
</div>
<div>
{{ form_label(form.departmentStatus) }}
{{ form_widget(form.departmentStatus) }}
</div>
<div>
{{ form_label(form.departmentName) }}
{{ form_widget(form.departmentName) }}
</div>
{{ form_end(form) }}
<ul class="record_actions">
<li>
<a href="{{ path('department') }}">
Back to the list
</a>
</li>
</ul>
{% endblock %}
Im' not sure of how to access to the companyName (maybe you have to give the index in the vars of forms.company.vars. You can try it
Or you can do it in your form_builder :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('company', 'entity', array(
'class' => 'AppBundle:Company',
'choice_label' => 'companyName',
'expanded' => true,
'multiple' => true
));)
->add('departmentName')
->add('departmentStatus')
;
}

Data Transformer for Collection Field Type

I am creating a Chat system. I have two entities Chat and ChatThread.
namespace Acme\UitBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Chat
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\UitBundle\Entity\ChatRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Chat
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="chats")
* #ORM\JoinColumn(name="uid", referencedColumnName="id")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="msg", type="text")
*/
private $msg;
/**
* #ORM\ManyToOne(targetEntity="ChatThread", inversedBy="chats")
* #ORM\JoinColumn(name="tid", referencedColumnName="id")
*/
private $thread;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param \stdClass $user
* #return Chat
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \stdClass
*/
public function getUser()
{
return $this->user;
}
/**
* Set msg
*
* #param string $msg
* #return Chat
*/
public function setMsg($msg)
{
$this->msg = $msg;
return $this;
}
/**
* Get msg
*
* #return string
*/
public function getMsg()
{
return $this->msg;
}
/**
* Set date
*
* #param \DateTime $date
* #return Chat
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* #ORM\PrePersist
*/
public function setDateValue()
{
$this->date = new \DateTime();
}
/**
* Set thread
*
* #param \Acme\UitBundle\Entity\ChatThread $thread
* #return Chat
*/
public function setThread(\Acme\UitBundle\Entity\ChatThread $thread = null)
{
$this->thread = $thread;
return $this;
}
/**
* Get thread
*
* #return \Acme\UitBundle\Entity\ChatThread
*/
public function getThread()
{
return $this->thread;
}
}
Entity ChatThread :
namespace Acme\UitBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\OrderBy;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ChatThread
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\UitBundle\Entity\ChatThreadRepository")
*/
class ChatThread
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="inside")
*/
private $inside;
/**
* #ORM\OneToMany(targetEntity="Chat", mappedBy="thread")
* #OrderBy({"date" = "DESC"})
*/
private $chats;
public function __construct()
{
$this->chats=new ArrayCollection();
$this->inside=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set inside
*
* #param array $inside
* #return ChatThread
*/
public function setInside($inside)
{
$this->inside = $inside;
return $this;
}
/**
* Get inside
*
* #return array
*/
public function getInside()
{
return $this->inside;
}
/**
* Add inside
*
* #param \Acme\UitBundle\Entity\User $inside
* #return ChatThread
*/
public function addInside(\Acme\UitBundle\Entity\User $inside)
{
$this->inside[] = $inside;
return $this;
}
/**
* Remove inside
*
* #param \Acme\UitBundle\Entity\User $inside
*/
public function removeInside(\Acme\UitBundle\Entity\User $inside)
{
$this->inside->removeElement($inside);
}
/**
* Add chats
*
* #param \Acme\UitBundle\Entity\Chat $chats
* #return ChatThread
*/
public function addChat(\Acme\UitBundle\Entity\Chat $chats)
{
$this->chats[] = $chats;
return $this;
}
/**
* Remove chats
*
* #param \Acme\UitBundle\Entity\Chat $chats
*/
public function removeChat(\Acme\UitBundle\Entity\Chat $chats)
{
$this->chats->removeElement($chats);
}
/**
* Get chats
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChats()
{
return $this->chats;
}
}
What I want to do is Take users to be added in inside and create a ChatThread and add a msg in Chat.
I have a form of chatType which takes user id's as collection with name thread. I have used a data transformer to transform inside into ChatThread.
namespace Acme\UitBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Acme\UitBundle\Form\DataTransformer\ThreadToInsideTransformer;
class ChatType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$entityManager = $options['em'];
$transformer = new ThreadToInsideTransformer($entityManager);
$builder->add(
$builder->create('thread', 'collection' ,array('allow_add' => true,'label' => false))->addModelTransformer($transformer)
);
$builder->add('msg','textarea');
/* $builder->add('inside','collection',array(
'allow_add' => true,
'allow_delete' => true)); */
$builder->add('hook', 'submit');
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'Acme\UitBundle\Entity\Chat'
))
->setRequired(array(
'em',
))
->setAllowedTypes(array(
'em' => 'Doctrine\Common\Persistence\ObjectManager',
));
}
public function getName() {
return 'chat';
}
}
data transformer
namespace Acme\UitBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\UitBundle\Entity\ChatThread;
class ThreadToInsideTransformer implements DataTransformerInterface
{
/**
* #var ObjectManager
*/
private $om;
/**
* #param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
/**
* Transforms an object (thread) to an array (inside).
*
* #param Thread $thread
* #return array
*/
public function transform($thread)
{
if (null === $thread) {
return "";
}
return $thread->getInside();
}
/**
* Transforms a array (inside) to an object (thread).
*
* #param array $inside
*
* #return Thread
*
* #throws Create new Thread if object (thread) is not found.
*/
public function reverseTransform($inside)
{
if (!is_array($inside)) {
return null;
}
$a=$this->om
->getRepository('AcmeUitBundle:User')
->findById($inside);
if (null === $a) {
throw new TransformationFailedException(sprintf(
'Error. . .'
));
}
$thread = $this->om
->getRepository('AcmeUitBundle:ChatThread')
->findByInsideChat($a)
;
if (null === $thread) {
$thread=new ChatThread();
$thread->setInside($inside);
$this->om->persist($thread);
$this->om->flush();
}
return $thread;
}
}
When I submit form, I get this error Expected argument of type "object, array or empty", "string" given.

Symfony2 FosRestBundle Expose Properties at runtime

I have following entity class and controller class. I have exposed selected properties.
In my "getAlbumsAction()" the output is the way i want.
But in "getAlbumAction($id)" i want to expose all the properties of the album class. How can i achive it? Have been searching around for a while but can't get it.
<?php
namespace MyBundle\RestApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
/**
* Album
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\RestApiBundle\Entity\AlbumRepository")
* #ExclusionPolicy("all")
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #expose
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #expose
*/
private $name;
/**
*
* #ORM\OneToMany(targetEntity="Track", mappedBy="album")
*
*/
private $tracks;
/**
*
* #ORM\Column(name="likes", type="integer")
*
*
*/
private $likes;
/**
* #var \DateTime
*
* #ORM\Column(name="released", type="date")
*
*
*/
private $released;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="date")
*/
private $updated;
/**
* #ORM\ManyToOne(targetEntity="Language", inversedBy="albums")
* #ORM\JoinColumn(name="language_id", referencedColumnName="id")
*
*
*/
private $language;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Album
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set released
*
* #param \DateTime $released
* #return Album
*/
public function setReleased($released)
{
$this->released = $released;
return $this;
}
/**
* Get released
*
* #return \DateTime
*/
public function getReleased()
{
return $this->released;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Album
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set language
*
* #param integer $language
* #return Album
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* #return integer
*/
public function getLanguage()
{
return $this->language;
}
/**
* Constructor
*/
public function __construct()
{
$this->tracks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
* #return Album
*/
public function addTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks[] = $tracks;
return $this;
}
/**
* Remove tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
*/
public function removeTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks->removeElement($tracks);
}
/**
* Get tracks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTracks()
{
return $this->tracks;
}
/**
* Set likes
*
* #param integer $likes
* #return Album
*/
public function setLikes($likes)
{
$this->likes = $likes;
return $this;
}
/**
* Get likes
*
* #return integer
*/
public function getLikes()
{
return $this->likes;
}
}
<?php
namespace MyBundle\RestApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
class AlbumController extends Controller {
public function getAlbumsAction() {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyBundleRestApiBundle:Album')->findAll();
return array(
'albums' => $entities,
);
}
private function getEntity($id) {
$entityName = 'MyBundleRestApiBundle:Album';
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($entityName)->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find organisation entity');
}
return $entity;
}
public function getAlbumAction($id) {
$entity = $this->getEntity($id);
return array(
'album' => $entity,
);
}
}
you have a typo:
'album' => $entities but must be 'album' => $entity
also if you want to return different fields/formats for one object check this out
http://jmsyst.com/libs/serializer/master/reference/annotations#groups

Categories