Here I am try to use ResultSetMapping to map the result which generate by nativeQuery. But I have no idea about why the doctrine always throw Undefined index error. anyone can help me out from this problem?
Here is my code:
the PlaceMarkerRepository:
namespace Leo\FoodRadarBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
/**
* PlaceMarkerRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PlaceMarkerRepository extends EntityRepository
{
public function findNearBy($query,$lat, $lng, $radius){
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
// $rsm = new ResultSetMappingBuilder();
// $rsm->addRootEntityFromClassMetadata('LeoFoodRadarBundle:PlaceMarker', 'p');
// $rsm->addJoinedEntityFromClassMetadata('LeoFoodRadarBundle:Coordinate', 'c', 'p', 'coordinate', array('id' => 'coordinate_id'));
$rsm->addEntityResult('LeoFoodRadarBundle:PlaceMarker', 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addFieldResult('p', 'name', 'name');
$rsm->addJoinedEntityResult('LeoFoodRadarBundle:Coordinate' , 'c', 'p', 'coordinate');
$rsm->addFieldResult('c', 'coordinate_id', 'id');
$rsm->addFieldResult('c', 'latitude', 'latitude');
$rsm->addFieldResult('c', 'longitude', 'longitude');
$sql ="SELECT p.id, p.name, c.latitude, c.longitude, c.id as coordinate_id
FROM placeMarker p join coordinate c on p.coordinate_id = c.id
";
$this->getEntityManager()->createNativeQuery($sql, $rsm)->getResult();
}
}
and PlaceMark:
namespace Leo\FoodRadarBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Leo\FoodRadarBundle\Entity\PlaceMarker
*
* #ORM\Table(name="placeMarker")
* #ORM\Entity(repositoryClass="Leo\FoodRadarBundle\Entity\PlaceMarkerRepository")
*/
class PlaceMarker {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Coordinate coordinate
* #ORM\OneToOne(targetEntity="Coordinate")
* #ORM\JoinColumn(name="coordinate_id", referencedColumnName="id")
*/
private $coordinate;
/**
*
* #var Address address
* #ORM\OneToOne(targetEntity="Address")
* #ORM\JoinColumn(name="address_id", referencedColumnName="id")
*/
private $address;
/**
*
* #ORM\Column(name="name", type="string", length=100)
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set coordinate
*
* #param Leo\FoodRadarBundle\Entity\Coordinate $coordinate
* #return PlaceMarker
*/
public function setCoordinate(\Leo\FoodRadarBundle\Entity\Coordinate $coordinate = null) {
$this->coordinate = $coordinate;
return $this;
}
/**
* Get coordinate
*
* #return Leo\FoodRadarBundle\Entity\Coordinate
*/
public function getCoordinate() {
return $this->coordinate;
}
/**
* Set address
*
* #param Leo\FoodRadarBundle\Entity\Address $address
* #return PlaceMarker
*/
public function setAddress(\Leo\FoodRadarBundle\Entity\Address $address = null) {
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return Leo\FoodRadarBundle\Entity\Address
*/
public function getAddress() {
return $this->address;
}
/**
* Set name
*
* #param string $name
* #return PlaceMarker
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
The Coordinate:
<?php
namespace Leo\FoodRadarBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Leo\FoodRadarBundle\Entity\Coordinate
*
* #ORM\Table(name="coordinate")
* #ORM\Entity
*/
class Coordinate
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="float")
*/
private $longitude;
/**
* #ORM\Column(type="float")
*/
private $latitude;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get longitude
* #return float
*/
public function getLongitude() {
return $this->longitude;
}
/**
* Set longitude
*/
public function setLongitude($longitude) {
$this->longitude = $longitude;
}
/**
* Get Latitude
* #return float
*/
public function getLatitude() {
return $this->latitude;
}
/**
* Set Latitude
*/
public function setLatitude($latitude) {
$this->latitude = $latitude;
}
}
the error caused by this statement:
$targetClass = $this->_ce[$relation['targetEntity']];
the information about error is:
Notice: Undefined index: Leo\FoodRadarBundle\Entity\Coordinate in /Volumes/DATA/LEO/Sites/FoodRadar/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 427
ErrorHandler ->handle ('8', 'Undefined index: Leo\FoodRadarBundle\Entity\Coordinate', '/Volumes/DATA/LEO/Sites/FoodRadar/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php', '427', array('row' => array('id' => '1', 'name' => 'test', 'latitude' => '233.234342', 'longitude' => '-232.23232323232', 'coordinate_id' => '2'), 'cache' => array('id' => array('fieldName' => 'id', 'type' => object(IntegerType), 'isIdentifier' => true, 'dqlAlias' => 'p'), 'name' => array('fieldName' => 'name', 'type' => object(StringType), 'isIdentifier' => false, 'dqlAlias' => 'p'), 'latitude' => array('fieldName' => 'latitude', 'type' => object(FloatType), 'isIdentifier' => false, 'dqlAlias' => 'c'), 'longitude' => array('fieldName' => 'longitude', 'type' => object(FloatType), 'isIdentifier' => false, 'dqlAlias' => 'c'), 'coordinate_id' => array('fieldName' => 'id', 'type' => object(IntegerType), 'isIdentifier' => true, 'dqlAlias' => 'c')), 'result' => array(object(PlaceMarker)), 'id' => array('p' => '|1', 'c' => '|2'), 'nonemptyComponents' => array('p' => true, 'c' => true), 'rowData' => array('p' => array('id' => '1', 'name' => 'test'), 'c' => array('latitude' => '233.234342', 'longitude' => '-232.23232323232', 'id' => '2')), 'dqlAlias' => 'c', 'data' => array('latitude' => '233.234342', 'longitude' => '-232.23232323232', 'id' => '2'), 'entityName' => 'LeoFoodRadarBundle:Coordinate', 'parentAlias' => 'p', 'path' => 'p.c', 'parentObject' => object(PlaceMarker), 'parentClass' => object(ClassMetadata), 'oid' => '000000003e34db9d00000000492221b6', 'relationField' => 'coordinate', 'relation' => array('fieldName' => 'coordinate', 'targetEntity' => 'Leo\FoodRadarBundle\Entity\Coordinate', 'joinColumns' => array(array('name' => 'coordinate_id', 'unique' => true, 'nullable' => true, 'onDelete' => null, 'columnDefinition' => null, 'referencedColumnName' => 'id')), 'mappedBy' => null, 'inversedBy' => null, 'cascade' => array(), 'orphanRemoval' => false, 'fetch' => '2', 'type' => '1', 'isOwningSide' => true, 'sourceEntity' => 'Leo\FoodRadarBundle\Entity\PlaceMarker', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'sourceToTargetKeyColumns' => array(*DEEP NESTED ARRAY*), 'joinColumnFieldNames' => array(*DEEP NESTED ARRAY*), 'targetToSourceKeyColumns' => array(*DEEP NESTED ARRAY*)), 'reflField' => object(ReflectionProperty), 'reflFieldValue' => null, 'element' => object(Coordinate), 'entityKey' => '0', 'resultKey' => '0'))
in /Volumes/DATA/LEO/Sites/FoodRadar/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php at line 427 -+
Finally, I found the reason why caused this problem. I think this because resultsetmapping runs internally, So it can't understand the logic name which provide by Symfony. The solution for this problem is that changing logical name to full path name. then it will work.
Related
I tried display customer attribute on frontend from admin. But I dont know how to display it, because attribute is type "select" and when I got value of it I got value of option of source model.
My layout ArseniyInk/TaskTwo/view/frontend/layout/customer_account_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Customer\Block\Account\Dashboard\Info" name="customer_account_dashboard_info" as="info" template="Magento_Customer::account/dashboard/info.phtml" cacheable="false">
<container name="customer.account.dashboard.info.extra">
<block class="Magento\Customer\Block\Account\Dashboard\Info" name="customer.account.dashboard.info.extra.magento.username" template="ArseniyInk_TaskTwo::account/dashboard/info.phtml"/>
</container>
</block>
</referenceContainer>
</body>
My Source Model ArseniyInk/TaskTwo/Model/Customer/Attribute/Source/Employment.php
<?php
namespace ArseniyInk\TaskTwo\Model\Customer\Attribute\Source;
class Employment extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
public function getAllOptions()
{
if (!$this->_options) {
$this->_options = [
['label' => __('Unemployment'), 'value' => '1'],
['label' => __('Pupil'), 'value' => '2'],
['label' => __('Student'), 'value' => '3'],
['label' => __('Employee'), 'value' => '4']
];
}
return $this->_options;
}
}
My Attribute ArseniyInk/TaskTwo/Setup/Patch/Data/AddTestEmploymentAttribute.php
<?php declare(strict_types=1);
/**
* Patch to create Customer Attribute
*
*
*/
namespace ArseniyInk\TaskTwo\Setup\Patch\Data;
use Zend_Validate_Exception;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Eav\Model\Entity\Attribute\Source\Boolean;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
class AddTestEmploymentAttribute implements DataPatchInterface
{
/**
* #var Config
*/
private $eavConfig;
/**
* #var EavSetupFactory
*/
private $eavSetupFactory;
/**
* #var AttributeSetFactory
*/
private $attributeSetFactory;
/**
*
*
* #param Config $eavConfig
* #param EavSetupFactory $eavSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
Config $eavConfig,
EavSetupFactory $eavSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {#inheritdoc}
*/
public static function getDependencies(): array
{
return [];
}
/**
* Create account customer attribute
* #return void
* #throws LocalizedException
* #throws Zend_Validate_Exception
*/
public function apply(): void
{
$eavSetup = $this->eavSetupFactory->create();
$customerEntity = $this->eavConfig->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$eavSetup->addAttribute('customer', 'new_test_employment', [
'type' => 'int',
'input' => 'select',
'source' => 'ArseniyInk\TaskTwo\Model\Customer\Attribute\Source\Employment',
'label' => 'NEmployment',
'visible' => false,
'required' => false,
'user_defined' => true,
'system' => false,
'global' => true,
'default' => 0,
'visible_on_front' => false,
'sort_order' => 52,
'position' => 52
]);
$customAttribute = $this->eavConfig->getAttribute('customer', 'new_test_employment');
$customAttribute->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer', 'customer_account_edit', 'customer_account_create']
]);
$customAttribute->save();
}
/**
* {#inheritdoc}
*/
public function getAliases(): array
{
return [];
}
}
My Template ArseniyInk/TaskTwo/view/frontend/templates/account/dashboard/info.phtml
<p>
Employment =
<?= $block->escapeHtml($block->getCustomer()->getCustomAttribute('new_test_employment')->getValue()) ?><br>
</p>
Photo
I'm trying to create a customer attribute on magento 2.0.1. I have checked all the answered questions here but my code still does not work.
Here my InstallData.php located in Mymodule\Cus\Setup
namespace Mymodule\Cus\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* #codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* #var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* #param CustomerSetupFactory $customerSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {#inheritdoc}
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** #var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'test_att', [
'type' => 'varchar',
'label' => 'Test ATT',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'test_att')
->addData(['attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address','adminhtml_checkout'],
]);
$attribute->save();
}
}
When i run both :
php bin\magento setup:upgrade
php bin\magento setup:flush
the attribute is not created.
My module is registrated and i'm using for others things and it's working.
Try to locate Setup folder in the root of module also do not forget change namespace in the file
Try to clean row in the db setup_module table with your module version
Try to create attribute in this way:
$eavTable = $installer->getTable('needded table');
$columns = [
'column_name' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'nullable' => false,
'comment' => '',
],
];
$connection = $installer->getConnection();
foreach ($columns as $name => $definition) {
$connection->addColumn($eavTable, $name, $definition);
}
I'm having problems creating my form for creating a course. This is a part of my database scheme for which I'm trying to create a form:
So which I'm trying to do is create a course where I can create sessions and dates (moment) attached to that session. It should look something like this:
In my CourseAdmin class I have:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', 'text', array('label' => 'Naam'))
->add('description', 'textarea', array('label' => 'Beschrijving'))
->add('materials', 'textarea', array('label' => 'Benodigde materialen'))
->add('numberOfParticipants', 'number', array('label' => 'Aantal deelnembers'))
->add('numberOfDays', 'number', array('label' => 'Aantal dagen'))
->add('price', 'number', array('label' => 'Prijs'))
->add('priceKmo', 'number', array('label' => 'KMO-portefeuille Prijs'))
->add('location', 'sonata_type_model', array('expanded' => true, 'by_reference' => false, 'multiple' => true, 'btn_add' => false))
->add('session', 'sonata_type_collection', array(
'by_reference' => false,
'type_options' => array(
// Prevents the "Delete" option from being displayed
'delete' => false,
'delete_options' => array(
// You may otherwise choose to put the field but hide it
'type' => 'hidden',
// In that case, you need to fill in the options as well
'type_options' => array(
'mapped' => false,
'required' => false,
)
)
)
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position'
))
;
}
In my SessionAdmin class I have:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('type', 'text', array('label' => 'Type opleiding (Dag / Avond)'))
->add('moment', 'sonata_type_collection', array(
'by_reference' => false,
'type_options' => array(
// Prevents the "Delete" option from being displayed
'delete' => false,
'delete_options' => array(
// You may otherwise choose to put the field but hide it
'type' => 'hidden',
// In that case, you need to fill in the options as well
'type_options' => array(
'mapped' => false,
'required' => false,
)
)
)
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position'
))
;
}
And in my MomentAdmin class I have:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('time', 'date', array('label' => 'Datum'))
;
}
The problem in my form is when I try to add a moment (date) to my session I get the following error:
FatalErrorException: Error: Call to a member function getName() on null in /myproject/app/cache/dev/classes.php line 9772
So, I can add a session but when I try to add a moment to my session I'm getting the error ... .
When I look in the file classes.php on rule 9771 and 9772 there is:
$childFormBuilder = $this->getChildFormBuilder($formBuilder, $elementId);
$fieldDescription = $admin->getFormFieldDescription($childFormBuilder->getName());
The $childFormBuilder is null.
When I look at that function than I get this:
public function getChildFormBuilder(FormBuilder $formBuilder, $elementId)
{
foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
if ($name == $elementId) {
return $formBuilder;
}
}
return;
}
When I do a var_dump of $name and $elementId like this:
public function getChildFormBuilder(FormBuilder $formBuilder, $elementId)
{
foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
var_dump("name: " . $name);
var_dump("elementId: " . $elementId);
if ($name == $elementId) {
return $formBuilder;
}
}
die;
return;
}
And push on the Add new button like the following picture:
Then I get this output:
name: s56cda71d2daa0_name
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_description
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_materials
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_numberOfParticipants
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_numberOfDays
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_price
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_priceKmo
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_location
elementId: s56cda71d2daa0_session_0_moment
name: s56cda71d2daa0_session
elementId: s56cda71d2daa0_session_0_moment
In all my entities I have a __toString function. An example in my Course entity:
public function __toString()
{
if(!is_null($this->name))
{
return $this->name;
}
else{
return "";
}
}
What could be the problem here? I'm really stuck with this. I've also posted an issue on the github repo of Sonata Admin but no answers ...
My entities:
Course Entity:
<?php
namespace Studyx\EnrolmentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Course
*
* #ORM\Table(name="course")
* #ORM\Entity
*/
class Course
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="materials", type="text", nullable=true)
*/
private $materials;
/**
* #var integer
*
* #ORM\Column(name="number_of_participants", type="integer", nullable=true)
*/
private $numberOfParticipants;
/**
* #var integer
*
* #ORM\Column(name="number_of_days", type="integer", nullable=true)
*/
private $numberOfDays;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", nullable=true)
*/
private $price;
/**
* #var string
*
* #ORM\Column(name="price_kmo", type="decimal", nullable=true)
*/
private $priceKmo;
/**
* #var integer
*
* #ORM\Column(name="ID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Studyx\EnrolmentBundle\Entity\Location", inversedBy="course")
* #ORM\JoinTable(name="course_has_location",
* joinColumns={
* #ORM\JoinColumn(name="course_ID", referencedColumnName="ID")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="location_ID", referencedColumnName="ID")
* }
* )
*/
private $location;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="Studyx\EnrolmentBundle\Entity\Session", mappedBy="course")
*/
private $session;
/**
* Add session
*
* #param \Studyx\EnrolmentBundle\Entity\Session $session
* #return Session
*/
public function addSession(\Studyx\EnrolmentBundle\Entity\Session $session)
{
$this->session[] = $session;
return $this;
}
/**
* Remove session
*
* #param \Studyx\EnrolmentBundle\Entity\Session $session
*/
public function removeSession(\Studyx\EnrolmentBundle\Entity\Session $session)
{
$this->session->removeElement($session);
}
/**
* Get session
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSession()
{
return $this->session;
}
/**
* Constructor
*/
public function __construct()
{
$this->location = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
if(!is_null($this->name))
{
return $this->name;
}
else{
return "";
}
}
/**
* Set name
*
* #param string $name
* #return Course
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Course
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set materials
*
* #param string $materials
* #return Course
*/
public function setMaterials($materials)
{
$this->materials = $materials;
return $this;
}
/**
* Get materials
*
* #return string
*/
public function getMaterials()
{
return $this->materials;
}
/**
* Set numberOfParticipants
*
* #param integer $numberOfParticipants
* #return Course
*/
public function setNumberOfParticipants($numberOfParticipants)
{
$this->numberOfParticipants = $numberOfParticipants;
return $this;
}
/**
* Get numberOfParticipants
*
* #return integer
*/
public function getNumberOfParticipants()
{
return $this->numberOfParticipants;
}
/**
* Set numberOfDays
*
* #param integer $numberOfDays
* #return Course
*/
public function setNumberOfDays($numberOfDays)
{
$this->numberOfDays = $numberOfDays;
return $this;
}
/**
* Get numberOfDays
*
* #return integer
*/
public function getNumberOfDays()
{
return $this->numberOfDays;
}
/**
* Set price
*
* #param string $price
* #return Course
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set priceKmo
*
* #param string $priceKmo
* #return Course
*/
public function setPriceKmo($priceKmo)
{
$this->priceKmo = $priceKmo;
return $this;
}
/**
* Get priceKmo
*
* #return string
*/
public function getPriceKmo()
{
return $this->priceKmo;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add location
*
* #param \Studyx\EnrolmentBundle\Entity\Location $location
* #return Course
*/
public function addLocation(\Studyx\EnrolmentBundle\Entity\Location $location)
{
$this->location[] = $location;
return $this;
}
/**
* Remove location
*
* #param \Studyx\EnrolmentBundle\Entity\Location $location
*/
public function removeLocation(\Studyx\EnrolmentBundle\Entity\Location $location)
{
$this->location->removeElement($location);
}
/**
* Get location
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLocation()
{
return $this->location;
}
}
Session Entity:
<?php
namespace Studyx\EnrolmentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Session
*
* #ORM\Table(name="session")
* #ORM\Entity
*/
class Session
{
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=45, nullable=false)
*/
private $type;
/**
* #var integer
*
* #ORM\Column(name="ID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Studyx\EnrolmentBundle\Entity\Course
*
* #ORM\ManyToOne(targetEntity="Studyx\EnrolmentBundle\Entity\Course", inversedBy="session")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="course_ID", referencedColumnName="ID")
* })
*/
private $course;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="Studyx\EnrolmentBundle\Entity\Moment", mappedBy="session")
*/
private $moment;
/**
* Add moment
*
* #param \Studyx\EnrolmentBundle\Entity\Moment $moment
* #return Moment
*/
public function addMoment(\Studyx\EnrolmentBundle\Entity\Moment $moment)
{
$this->moment[] = $moment;
return $this;
}
/**
* Remove moment
*
* #param \Studyx\EnrolmentBundle\Entity\Moment $moment
*/
public function removeMoment(\Studyx\EnrolmentBundle\Entity\Moment $moment)
{
$this->moment->removeElement($moment);
}
/**
* Get moment
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMoment()
{
return $this->moment;
}
public function __toString()
{
if(!is_null($this->type))
{
return $this->type;
}
else{
return "";
}
}
/**
* Set type
*
* #param string $type
* #return Session
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set course
*
* #param \Studyx\EnrolmentBundle\Entity\Course $course
* #return Session
*/
public function setCourse(\Studyx\EnrolmentBundle\Entity\Course $course = null)
{
$this->course = $course;
return $this;
}
/**
* Get course
*
* #return \Studyx\EnrolmentBundle\Entity\Course
*/
public function getCourse()
{
return $this->course;
}
}
Moment Entity:
<?php
namespace Studyx\EnrolmentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Moment
*
* #ORM\Table(name="moment")
* #ORM\Entity
*/
class Moment
{
/**
* #var \DateTime
*
* #ORM\Column(name="time", type="datetime", nullable=false)
*/
private $time;
/**
* #var integer
*
* #ORM\Column(name="ID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Studyx\EnrolmentBundle\Entity\Session
*
* #ORM\ManyToOne(targetEntity="Studyx\EnrolmentBundle\Entity\Session")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="session_ID", referencedColumnName="ID")
* })
*/
private $session;
public function __toString()
{
if(!is_null($this->time))
{
return $this->time;
}
else{
return "";
}
}
/**
* Set time
*
* #param \DateTime $time
* #return Moment
*/
public function setTime($time)
{
$this->time = $time;
return $this;
}
/**
* Get time
*
* #return \DateTime
*/
public function getTime()
{
return $this->time;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set session
*
* #param \Studyx\EnrolmentBundle\Entity\Session $session
* #return Moment
*/
public function setSession(\Studyx\EnrolmentBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \Studyx\EnrolmentBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
}
UPDATE:
I've added some var_dumps to my function getChildFormBuilder like this:
public function getChildFormBuilder(FormBuilder $formBuilder, $elementId)
{
foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
if ($name == $elementId) {
return $formBuilder;
}
}
var_dump(__METHOD__);
var_dump($elementId);
var_dump(debug_backtrace());
return;
}
The result is this:
string 'Sonata\AdminBundle\Admin\AdminHelper::getChildFormBuilder' (length=57)
string 's56cdfa72c4dea_session_0_moment' (length=31)
array (size=8)
0 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/app/cache/dev/classes.php' (length=69)
'line' => int 9774
'function' => string 'getChildFormBuilder' (length=19)
'class' => string 'Sonata\AdminBundle\Admin\AdminHelper' (length=36)
'object' =>
object(Sonata\AdminBundle\Admin\AdminHelper)[339]
protected 'pool' =>
object(Sonata\AdminBundle\Admin\Pool)[104]
...
'type' => string '->' (length=2)
'args' =>
array (size=2)
0 =>
object(Symfony\Component\Form\FormBuilder)[436]
...
1 => &string 's56cdfa72c4dea_session_0_moment' (length=31)
1 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/vendor/sonata-project/admin-bundle/Controller/HelperController.php' (length=110)
'line' => int 95
'function' => string 'appendFormFieldElement' (length=22)
'class' => string 'Sonata\AdminBundle\Admin\AdminHelper' (length=36)
'object' =>
object(Sonata\AdminBundle\Admin\AdminHelper)[339]
protected 'pool' =>
object(Sonata\AdminBundle\Admin\Pool)[104]
...
'type' => string '->' (length=2)
'args' =>
array (size=3)
0 =>
object(Studyx\EnrolmentBundle\Admin\CourseAdmin)[370]
...
1 =>
object(Studyx\EnrolmentBundle\Entity\Course)[415]
...
2 => &string 's56cdfa72c4dea_session_0_moment' (length=31)
2 =>
array (size=5)
'function' => string 'appendFormFieldElementAction' (length=28)
'class' => string 'Sonata\AdminBundle\Controller\HelperController' (length=46)
'object' =>
object(Sonata\AdminBundle\Controller\HelperController)[244]
protected 'twig' =>
object(Twig_Environment)[220]
...
protected 'helper' =>
object(Sonata\AdminBundle\Admin\AdminHelper)[339]
...
protected 'pool' =>
object(Sonata\AdminBundle\Admin\Pool)[104]
...
protected 'validator' =>
object(Symfony\Component\Validator\Validator)[340]
...
'type' => string '->' (length=2)
'args' =>
array (size=1)
0 =>
object(Symfony\Component\HttpFoundation\Request)[6]
...
3 =>
array (size=4)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/app/bootstrap.php.cache' (length=67)
'line' => int 2957
'function' => string 'call_user_func_array' (length=20)
'args' =>
array (size=2)
0 => &
array (size=2)
...
1 => &
array (size=1)
...
4 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/app/bootstrap.php.cache' (length=67)
'line' => int 2931
'function' => string 'handleRaw' (length=9)
'class' => string 'Symfony\Component\HttpKernel\HttpKernel' (length=39)
'object' =>
object(Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel)[300]
protected 'container' =>
object(appDevDebugProjectContainer)[304]
...
protected 'dispatcher' =>
object(Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher)[299]
...
protected 'resolver' =>
object(Symfony\Component\HttpKernel\Controller\TraceableControllerResolver)[249]
...
'type' => string '->' (length=2)
'args' =>
array (size=2)
0 =>
object(Symfony\Component\HttpFoundation\Request)[6]
...
1 => &int 1
5 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/app/bootstrap.php.cache' (length=67)
'line' => int 3060
'function' => string 'handle' (length=6)
'class' => string 'Symfony\Component\HttpKernel\HttpKernel' (length=39)
'object' =>
object(Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel)[300]
protected 'container' =>
object(appDevDebugProjectContainer)[304]
...
protected 'dispatcher' =>
object(Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher)[299]
...
protected 'resolver' =>
object(Symfony\Component\HttpKernel\Controller\TraceableControllerResolver)[249]
...
'type' => string '->' (length=2)
'args' =>
array (size=3)
0 =>
object(Symfony\Component\HttpFoundation\Request)[6]
...
1 => &int 1
2 => &boolean true
6 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/app/bootstrap.php.cache' (length=67)
'line' => int 2333
'function' => string 'handle' (length=6)
'class' => string 'Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel' (length=73)
'object' =>
object(Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel)[300]
protected 'container' =>
object(appDevDebugProjectContainer)[304]
...
protected 'dispatcher' =>
object(Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher)[299]
...
protected 'resolver' =>
object(Symfony\Component\HttpKernel\Controller\TraceableControllerResolver)[249]
...
'type' => string '->' (length=2)
'args' =>
array (size=3)
0 =>
object(Symfony\Component\HttpFoundation\Request)[6]
...
1 => &int 1
2 => &boolean true
7 =>
array (size=7)
'file' => string '/Applications/MAMP/htdocs/studyx_enrolments/web/app_dev.php' (length=59)
'line' => int 29
'function' => string 'handle' (length=6)
'class' => string 'Symfony\Component\HttpKernel\Kernel' (length=35)
'object' =>
object(AppKernel)[5]
protected 'bundles' =>
array (size=22)
...
protected 'bundleMap' =>
array (size=22)
...
protected 'container' =>
object(appDevDebugProjectContainer)[304]
...
protected 'rootDir' => string '/Applications/MAMP/htdocs/studyx_enrolments/app' (length=47)
protected 'environment' => string 'dev' (length=3)
protected 'debug' => boolean true
protected 'booted' => boolean true
protected 'name' => string 'app' (length=3)
protected 'startTime' => float 1456339594.61
protected 'loadClassCache' =>
array (size=2)
...
'type' => string '->' (length=2)
'args' =>
array (size=1)
0 =>
object(Symfony\Component\HttpFoundation\Request)[6]
...
UPDATE 2:
I've changed the require in my composer.json to "sonata-project/admin-bundle": "^2.4#dev" and updated with composer. But now I'm getting this error:
ContextErrorException: Warning: Illegal string offset 'admin' in
app/cache/dev/classes.php line 10482
The error is in this function:
public function getDashboardGroups()
{
$groups = $this->adminGroups;
foreach ($this->adminGroups as $name => $adminGroup) {
if (isset($adminGroup['items'])) {
foreach ($adminGroup['items'] as $key => $item) {
if (''!= $item['admin']) {
$admin = $this->getInstance($item['admin']);
if ($admin->showIn(Admin::CONTEXT_DASHBOARD)) {
$groups[$name]['items'][$key] = $admin;
} else {
unset($groups[$name]['items'][$key]);
}
}
else {
unset($groups[$name]['items'][$key]);
}
}
}
if (empty($groups[$name]['items'])) {
unset($groups[$name]);
}
}
return $groups;
}
The errors in on line : if (''!= $item['admin']) { .
In my config.yml I have:
sonata_admin:
title: Studyx
title_logo: bundles/studyxenrolment/images/logo.png
templates:
layout: StudyxEnrolmentBundle:Admin:standard_layout.html.twig
edit: StudyxEnrolmentBundle:CRUD:edit.html.twig
user_block: StudyxEnrolmentBundle:Admin:user_block.html.twig
# search: SonataAdminBundle:Core:search.html.twig
# search_result_block: SonataAdminBundle:Block:block_search_result.html.twig
dashboard:
groups:
studyx.admin.group.inschrijvingen:
label: Inschrijvingen
items: ~
item_adds:
- sonata.admin.enrolment
studyx.admin.group.algemeen:
label: Algemeen
items: ~
item_adds:
- sonata.admin.course
- sonata.admin.student
studyx.admin.group.extra:
label: Extra
items: ~
item_adds:
- sonata.admin.location
blocks:
-
position: top
class: col-md-12
type: sonata.admin.block.admin_list
So I think the function getDashboardGroups is called there.
UPDATE 3:
In my composer.json I have now the following:
"sonata-project/block-bundle": "~2.3",
"sonata-project/admin-bundle": "^2.4#dev",
"sonata-project/doctrine-orm-admin-bundle": "2.3.*",
"sonata-project/formatter-bundle": "^2.3"
Should I update them all to ^2.4#dev ?
This error occurs because you have more than two level of nested collection forms, and it's currently not yet supported in any release of sonata-admin.
From #rande (owner) and sonata maintainers at issues #262, #1228, #1327 and #1971 :
This is still not supported for now ....
You can also look at this old PR #1971 which should solve the problem for some use cases only.
The solution I propose you is to implement the fix provided by the last opened PR #2985.
Because the PR is not merged, you need to tell composer to load it rather than the current (not-working as expected) version. (see composer and VCS).
Hope the PR is merged soon.
Until it is, feel free to fix your problem at the moment by using it directly, as several people do.
UPDATE
The Pull Request #3553 has been recently merged and fix the problem of the nested collections at > 2 levels (nested in nested).
To get the fixed release, you must use the dev-master tag of the bundle (at least from the commit 926f159 representing the merge of the PR).
I tried it and it works well with the following requirement:
// composer.json
"require": {
"sonata-project/admin-bundle": "^2.4#dev",
...
},
I hope you can easily upgrade the bundle in order to get the fix.
Update2
Apparently, your composer doesn't take the last changes of the branch.
The fix provided by the PR #2739 has been merged 6 days ago.
To fix this last one (hope), you need to change a very short code block in the AddDepencyCallsCompilerPass located in vendor/sonata-project/admin-bundle/DependencyInjection/Compiler/AddDependencyCallsCompilerPass.
At line 95, replace this line :
$groupDefaults[$resolvedGroupName]['items'][] = $id;
To those ones:
$groupDefaults[$resolvedGroupName]['items'][] = array(
'admin' => $id,
'label' => !empty($attributes['label']) ? $attributes['label'] : '',
'route' => '',
'route_params' => array(),
);
Like it's done by the PR (it's the only needed change to make it working).
I would make the fix manually because it's very new, and after some days/weeks, run the following commands:
composer clear-cache and composer update sonata-project/admin-bundle
You should try it now before adding the fix manually, maybe the changes will be added.
Also, you can use the link about composer and VCS I given at the begin of my answer and require the fix directly. It's at your own appreciation because of it's a solution at the moment.
And last, be patient, the fixes will be merged in stable releases soon.
public function getChildFormBuilder(FormBuilder $formBuilder, $elementId)
{
foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
if ($name == $elementId) {
return $formBuilder;
}
}
return;
}
Dumping the name and element id within the loop won't accomplish anything. Your application obviously crashes when there is nothing to iterate - it then walks through the loop, exits and goes to the last line where NULL is returned.
I suggest you dump the element id just after the loop, like the following. The use of debug_backtrace might also help:
public function getChildFormBuilder(FormBuilder $formBuilder, $elementId)
{
foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
if ($name == $elementId) {
return $formBuilder;
}
}
var_dump(__METHOD__);
var_dump($elementId);
var_dump(debug_backtrace());
return;
}
I am overriding the form type to register a user. All looks ok, but when I submit my form the new fields are not persisted in database.
I followed the documentation.
My ProfileType:
<?php
namespace Application\Sonata\UserBundle\Form\Type;
//use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
//use Sonata\UserBundle\Model\UserInterface;
use Sonata\UserBundle\Form\Type\ProfileType as BaseType;
class ProfileType extends BaseType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('username', null, array(
'label' => 'Pseudo',
'required' => false
))
->add('firstname', null, array(
'label' => 'Prénom'
))
->add('lastname', null, array(
'label' => 'Nom'
))
->add('email', 'email', array(
'label' => 'Email'
))
->add('dateOfBirth', 'birthday', array(
'label' => 'Date d\'anniversaire',
'required' => false,
'data' => new \DateTime("01/01/1980")
))
->add('plainPassword', 'password', array(
'label' => 'Password'
))
->add('phone', null, array(
'label' => 'Téléphone',
'required' => false
))
->add('adress', null, array(
'label' => 'Adresse',
'required' => false
))
->add('zip', null, array(
'label' => 'Code postale',
'required' => false
))
->add('city', null, array(
'label' => 'Ville',
'required' => false
))
->add('newsletter', 'checkbox', array(
'label' => 'newsletter',
'required' => false
))
#hidden
->add('website', 'hidden', array(
'label' => 'website',
'required' => false
))
->add('biography', 'hidden', array(
'label' => 'biography',
'required' => false
))
->add('locale', 'hidden', array(
'label' => 'locale',
'required' => false
))
->add('timezone', 'hidden', array(
'label' => 'Timezone',
'required' => false
))
->add('gender', 'hidden', array(
'label' => 'Civilité',
'required' => false
))
;
// var_dump($builder);
}
/**
* {#inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Application\Sonata\UserBundle\Entity\User',
'intention' => 'profile',
'label' => 'Edit Profile'
));
}
// public function getParent()
// {
// return 'fos_user_registration';
// }
/**
* {#inheritdoc}
*/
public function getName()
{
return 'application_sonata_user_profile';
}
}
My user class:
<?php
namespace Application\Sonata\UserBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
/**
* Application\Sonata\UserBundle\Entity\User
*
* #ORM\Table(name="fos_user_user", indexes={#ORM\Index(name="search_idx", columns={"username", "email"})}))
* #ORM\Entity()
* #DoctrineAssert\UniqueEntity(fields={"username"}, message="username.already.exist" )
* #DoctrineAssert\UniqueEntity(fields={"email"}, message="email.already.exist" )
*/
class User extends BaseUser
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="zip", type="string", length=255, nullable=true)
*/
protected $zip;
/**
* #var string
*
* #ORM\Column(name="adress", type="text", nullable=true)
*/
protected $adress;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255, nullable=true)
*/
protected $city;
/**
* #var boolean
*
* #ORM\Column(name="newsletter", type="boolean", nullable=true)
*/
private $newsletter;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* Set zip
*
* #param string $zip
* #return FosUserUser
*/
public function setZip($zip)
{
$this->zip = $zip;
return $this;
}
/**
* Get zip
*
* #return string
*/
public function getZip()
{
return $this->zip;
}
/**
* Set adress
*
* #param string $adress
* #return FosUserUser
*/
public function setAdress($adress)
{
$this->adress = $adress;
return $this;
}
/**
* Get adress
*
* #return string
*/
public function getAdress()
{
return $this->adress;
}
/**
* Set city
*
* #param string $city
* #return FosUserUser
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set Newsletter
*
* #param boolean $newsletter
* #return FosUserUser
*/
public function setNewsletter($newsletter)
{
$this->newsletter = $newsletter;
return $this;
}
/**
* Get Newsletter
*
* #return boolean
*/
public function getNewsletter()
{
return $this->newsletter;
}
}
Thank you for your help.
If you have a just created properties of the entity and you are using the metadata cache, the doctrine still doesn't aware about these new properties. Just try to clear the metadata cache.
I am using zendframework 2 and doctrine 2. My addAction doesn't work i don't have any error but when i valid my form no row created in my database !!
i think that i have problem in populating foreign key !
this is my Form:
<?php
// filename : module/Users/src/Users/Form/addForm.php
namespace Vehicules\Form;
use Zend\Form\Form;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
class VehiculeForm extends form implements ObjectManagerAwareInterface
{
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
//public function init()
public function __construct(ObjectManager $objectManager)
{
parent::__construct('add');
$this->objectManager = $objectManager;
$this->init();
}
public function init(){
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/formdata');
$this->add(array(
'name' => 'matricule',
'attributes' => array(
'type' => 'text',
'required' => true
),
'options' => array(
'label' => 'Matricule',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'carburant',
'options' => array(
'label' => 'Carburant',
'value_options' => array(
'0' => 'Essence',
'1' => 'Gasoil',
'2' => 'Hybride',
),
)
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'name' => 'option',
'options' => array(
'label' => 'Options Véhicule',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\optionsvehicule',
'property' => 'libellee',
)));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'categorie',
'options' => array(
'label' => 'categorie',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\categorie',
'property' => 'idcat',
)
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'modele',
'options' => array(
'label' => 'Modèle',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\modele',
'property' => 'nom',
)
));
/*$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'modele',
'options' => array(
'label' => 'Modèle',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\modele',
'property' => 'nom',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('active' => 1),
// Use key 'orderBy' if using ORM
'orderBy' => array('lastname' => 'ASC'),
// Use key 'sort' if using ODM
'sort' => array('lastname' => 'ASC')
),
),
),
));*/
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'marque',
'options' => array(
'label' => 'Marque',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\marque',
'property' => 'nom',
)
));
$this->add(array(
'name' => 'dateMiseCirculation',
'attributes' => array(
'type' => 'Zend\Form\Element\Date',
),
'options' => array(
'label' => 'Date de Mise en Circulation',
),
));
$this->add(array(
'name' => 'numChasis',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Numero de Chasis',
),
));
$this->add(array(
'name' => "Prix d'achat",
'attributes' => array(
'type' => 'int',
),
'options' => array(
'label' => "Prix d'achat",
),
));
$this->add(array(
'name' => 'concessionnaire',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'concessionnaire',
),
));
$this->add(array(
'name' => 'souslocation',
'attributes' => array(
'type' => 'string',
),
'options' => array(
'label' => 'Sous-location',
),
));
$this->add(array(
'name' => 'remarque',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'remarque',
),
));
$this->add(array(
'name' => 'puisfiscal',
'attributes' => array(
'type' => 'int',
),
'options' => array(
'label' => "puissance fiscale",
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'nbreport',
'options' => array(
'label' => 'Nombre de portes',
'value_options' => array(
'0' => '4',
'1' => '2',
'2' => '5',
'3' => '6',
'4' => '7',
'5' => '7',
),
)
));
$this->add(array(
'name' => 'dernierKm',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Dernier kilométrage',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Valider'
),
));
}}
and this is my Entity Vehicule:
<?php
namespace Vehicules\Entity;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\Factory as InputFactory;
use Doctrine\ORM\Mapping as ORM;
/**
* Vehicule
*
* #ORM\Table(name="vehicule", uniqueConstraints={#ORM\UniqueConstraint(name="VEHICULE_PK", columns={"idVeh"})}, indexes={#ORM\Index(name="ASSOCIATION11_FK", columns={"idCat"}), #ORM\Index(name="ASSOCIATION13_FK", columns={"idMod"})})
* #ORM\Entity
*/
class Vehicule
{ protected $inputFilter;
/**
* #var integer
*
* #ORM\Column(name="idVeh", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idveh;
/**
* #var string
*
* #ORM\Column(name="matricule", type="string", length=254, nullable=false)
*/
private $matricule;
/**
* #var string
*
* #ORM\Column(name="dateMiseCirculation", type="string", length=254, nullable=true)
*/
private $datemisecirculation;
/**
* #var string
*
* #ORM\Column(name="numChasis", type="string", length=254, nullable=false)
*/
private $numchasis;
/**
* #var string
*
* #ORM\Column(name="carburant", type="string", length=254, nullable=true)
*/
private $carburant;
/**
* #var string
*
* #ORM\Column(name="dernierKm", type="decimal", precision=10, scale=0, nullable=false)
*/
private $dernierkm;
/**
* #var integer
*
* #ORM\Column(name="prixachat", type="integer", precision=10, scale=0, nullable=false)
*/
private $prixachat;
/**
* #var string
*
* #ORM\Column(name="concessionnaire", type="string", length=254, nullable=true)
*/
private $concessionnaire;
/**
* #var integer
*
* #ORM\Column(name="sousLocation", type="smallint", nullable=true)
*/
private $souslocation;
/**
* #var string
*
* #ORM\Column(name="remarque", type="string", length=254, nullable=true)
*/
private $remarque;
/**
* #var integer
*
* #ORM\Column(name="puisFiscal", type="integer", nullable=true)
*/
private $puisfiscal;
/**
* #var integer
*
* #ORM\Column(name="nbrePort", type="integer", nullable=true)
*/
private $nbreport;
/**
* #var \Vehicules\Entity\Categorie
*
* #ORM\ManyToOne(targetEntity="Vehicules\Entity\Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idCat", referencedColumnName="idCat")
* })
*/
private $idcat;
/**
* #var \Vehicules\Entity\Modele
*
* #ORM\ManyToOne(targetEntity="Vehicules\Entity\Modele")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idMod", referencedColumnName="idMod")
* })
*/
private $idmod;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Vehicules\Entity\Optionsvehicule", inversedBy="idveh")
* #ORM\JoinTable(name="veh_option",
* joinColumns={
* #ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="idOptVeh", referencedColumnName="idOptVeh")
* }
* )
*/
private $idoptveh;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Vehicules\Entity\Vehiculestatut", inversedBy="idveh")
* #ORM\JoinTable(name="veh_status",
* joinColumns={
* #ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="idStatut", referencedColumnName="idStatut")
* }
* )
*/
private $idstatut;
/**
* Constructor
*/
public function __construct()
{
$this->idoptveh = new \Doctrine\Common\Collections\ArrayCollection();
$this->idstatut = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get idveh
*
* #return integer
*/
public function getIdveh()
{
return $this->idveh;
}
/**
* Set matricule
*
* #param string $matricule
* #return Vehicule
*/
public function setMatricule($matricule)
{
$this->matricule = $matricule;
return $this;
}
/**
* Get matricule
*
* #return string
*/
public function getMatricule()
{
return $this->matricule;
}
/**
* Set datemisecirculation
*
* #param string $datemisecirculation
* #return Vehicule
*/
public function setDatemisecirculation($datemisecirculation)
{
$this->datemisecirculation = $datemisecirculation;
return $this;
}
/**
* Get datemisecirculation
*
* #return string
*/
public function getDatemisecirculation()
{
return $this->datemisecirculation;
}
/**
* Set numchasis
*
* #param string $numchasis
* #return Vehicule
*/
public function setNumchasis($numchasis)
{
$this->numchasis = $numchasis;
return $this;
}
/**
* Get numchasis
*
* #return string
*/
public function getNumchasis()
{
return $this->numchasis;
}
/**
* Set carburant
*
* #param string $carburant
* #return Vehicule
*/
public function setCarburant($carburant)
{
$this->carburant = $carburant;
return $this;
}
/**
* Get carburant
*
* #return string
*/
public function getCarburant()
{
return $this->carburant;
}
/**
* Set dernierkm
*
* #param string $dernierkm
* #return Vehicule
*/
public function setDernierkm($dernierkm)
{
$this->dernierkm = $dernierkm;
return $this;
}
/**
* Get dernierkm
*
* #return string
*/
public function getDernierkm()
{
return $this->dernierkm;
}
/**
* Set prixachat
*
* #param integer $prixachat
* #return Vehicule
*/
public function setPrixachat($prixachat)
{
$this->prixachat = $prixachat;
return $this;
}
/**
* Get prixachat
*
* #return integer
*/
public function getPrixachat()
{
return $this->prixachat;
}
/**
* Set concessionnaire
*
* #param string $concessionnaire
* #return Vehicule
*/
public function setConcessionnaire($concessionnaire)
{
$this->concessionnaire = $concessionnaire;
return $this;
}
/**
* Get concessionnaire
*
* #return string
*/
public function getConcessionnaire()
{
return $this->concessionnaire;
}
/**
* Set souslocation
*
* #param integer $souslocation
* #return Vehicule
*/
public function setSouslocation($souslocation)
{
$this->souslocation = $souslocation;
return $this;
}
/**
* Get souslocation
*
* #return integer
*/
public function getSouslocation()
{
return $this->souslocation;
}
/**
* Set remarque
*
* #param string $remarque
* #return Vehicule
*/
public function setRemarque($remarque)
{
$this->remarque = $remarque;
return $this;
}
/**
* Get remarque
*
* #return string
*/
public function getRemarque()
{
return $this->remarque;
}
/**
* Set puisfiscal
*
* #param integer $puisfiscal
* #return Vehicule
*/
public function setPuisfiscal($puisfiscal)
{
$this->puisfiscal = $puisfiscal;
return $this;
}
/**
* Get puisfiscal
*
* #return integer
*/
public function getPuisfiscal()
{
return $this->puisfiscal;
}
/**
* Set nbreport
*
* #param integer $nbreport
* #return Vehicule
*/
public function setNbreport($nbreport)
{
$this->nbreport = $nbreport;
return $this;
}
/**
* Get nbreport
*
* #return integer
*/
public function getNbreport()
{
return $this->nbreport;
}
/**
* Set idcat
*
* #param \Vehicules\Entity\Categorie $idcat
* #return Vehicule
*/
public function setIdcat(\Vehicules\Entity\Categorie $idcat = null)
{
$this->idcat = $idcat;
return $this;
}
/**
* Get idcat
*
* #return \Vehicules\Entity\Categorie
*/
public function getIdcat()
{
return $this->idcat;
}
/**
* Set idmod
*
* #param \Vehicules\Entity\Modele $idmod
* #return Vehicule
*/
public function setIdmod(\Vehicules\Entity\Modele $idmod = null)
{
$this->idmod = $idmod;
return $this;
}
/**
* Get idmod
*
* #return \Vehicules\Entity\Modele
*/
public function getIdmod()
{
return $this->idmod;
}
/**
* Add idoptveh
*
* #param \Vehicules\Entity\Optionsvehicule $idoptveh
* #return Vehicule
*/
public function addIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
{
$this->idoptveh[] = $idoptveh;
return $this;
}
/**
* Remove idoptveh
*
* #param \Vehicules\Entity\Optionsvehicule $idoptveh
*/
public function removeIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
{
$this->idoptveh->removeElement($idoptveh);
}
/**
* Get idoptveh
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdoptveh()
{
return $this->idoptveh;
}
/**
* Add idstatut
*
* #param \Vehicules\Entity\Vehiculestatut $idstatut
* #return Vehicule
*/
public function addIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
{
$this->idstatut[] = $idstatut;
return $this;
}
/**
* Remove idstatut
*
* #param \Vehicules\Entity\Vehiculestatut $idstatut
*/
public function removeIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
{
$this->idstatut->removeElement($idstatut);
}
/**
* Get idstatut
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdstatut()
{
return $this->idstatut;
}
public function populate($data) {
$this->setMatricule($data['matricule']) ;
$this->setDatemisecirculation($data['dateMiseCirculation']) ;
$this->setNumchasis($data['numChasis']) ;
$this->setCarburant($data['carburant']) ;
$this->setDernierkm($data['dernierKm']) ;
$this->setPrixachat($data["Prix d'achat"]) ;
$this->setConcessionnaire($data['concessionnaire']) ;
$this->setSouslocation($data['souslocation']) ;
$this->setRemarque($data['remarque']) ;
$this->setPuisfiscal($data['puisfiscal']) ;
$this->setNbreport($data['nbreport']) ;
//$this->addIdoptveh($data['option']) ; /* select................*/
//$this->setIdmod() ; /* select................*/
//$this->addIdstatut() ; /*ghanakhd l option dyal libre */
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'matricule',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 4,
'max' => 14,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'option',
'required' => false,
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
this is my controller VehiculeController:
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/Vehicules for the canonical source repository
* #copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*
*/
namespace Vehicules\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Vehicules\Form\VehiculeForm;
use Vehicules\Entity\Vehicule;
class VehiculesController extends AbstractActionController
{
/**
* #var Doctrine\ORM\EntityManager
*/
protected $_objectManager;
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
public function indexAction()
{
$vehicules = $this->getObjectManager()->getRepository('Vehicules\Entity\Vehicule')->findAll();
return new ViewModel(array('vehicules' => $vehicules));
}
public function addAction()
{ $_objectManager=$this->getObjectManager();
$form = new VehiculeForm($_objectManager);
$request = $this->getRequest();
$post = $this->request->getPost();
if ($this->request->isPost()) {
$Vehicule= new Vehicule();
$form->setData($post);
$form->setInputFilter($Vehicule->getInputFilter());
if ($form->isValid()) {
$f=$form->getData();
$Vehicule->populate($f);
$cat = $this->getObjectManager()->getRepository('Vehicules\Entity\categorie')->findAll();
foreach ($cat as $c){
if($c->getIdcat()==$f['categorie'] ){
$Vehicule->setIdcat($c) ;
exit;
}
}
$mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
foreach ($mod as $m){
if($m->getNom()==$f['modele'] ){
$Vehicule->setIdmod($m->getIdmod()) ;
exit;
}
}
$objectManager = $this->getObjectManager();
$objectManager->persist($Vehicule);
$objectManager->flush();
$id=$Vehicule->getIdveh();
var_dump($id);
$viewModel = new ViewModel(array('form' =>$form,'donne'=>$id));
return $viewModel;
}
}
$viewModel = new ViewModel(array('form' =>$form));
return $viewModel;
}
public function editAction()
{
$id = (int) $this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'add'));
}
$vehicule = $this->getObjectManager()->find('Vehicules\Entity\vehicule', $id);
$objectManager= $this->getObjectManager();
$form = new VehiculeForm($objectManager);
$form->setBindOnValidate(false);
$form->bind($vehicule);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->post());
if ($form->isValid()) {
$form->bindValues();
$this->getEntityManager()->flush();
// Redirect to list of vehicules
return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'index'));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function deleteAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('idVeh');
if (!$id) {
return $this->redirect()->toRoute('vehicules');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->post()->get('del', 'No');
if ($del == 'Yes') {
$id = (int)$request->post()->get('id');
$vehicule = $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id);
if ($vehicule) {
$this->getEntityManager()->remove($vehicule);
$this->getEntityManager()->flush();
}
}
// Redirect to list of albums
return $this->redirect()->toRoute('default', array(
'controller' => 'vehicules',
'action' => 'index',
));
}
return array(
'id' => $id,
'vehicule' => $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id)->getArrayCopy()
);
}
}
to populate forgnein key idMod and idCat i tried with this:
$mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
foreach ($mod as $m){
if($m->getNom()==$f['modele'] ){
$Vehicule->setIdmod($m->getIdmod()) ;
exit;
}
}
but id doesn't work :/
Your issue is the form/entity hydration. You don't need to reinvent the wheel here as Zend\Form already takes care of getting the data in and out of a form.
Currently your form uses the default ArraySerializable hydrator, so when the form is validated and you fetch the data (using $form->getData()) you are given an array. What you want is a already populated Vehicule entity.
The DoctrineModule\Stdlib\Hydrator\DoctrineObject is a hydrator specifically for Doctrine. If you attach it as the hydrator to your form it will return hydrated entity.
To solve this you need to STOP creating the form using new
$form = new VehiculeForm($_objectManager);
Instead create it via the ServiceManager
$form = $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');
Now create the form from a service factory; allowing the injection of the form dependencies, including the hydrator.
MyModule/Factory/Form/VehiculeFormFactory.php
namespace MyModule\Factory\Form;
use MyModule\Entity;
use MyModule\Form;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use DoctrineModule\Stdlib\Hydrator;
class VehiculeFormFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $sl)
{
$objectManager = $sl->get('Doctrine\ORM\EntityManager');
$form = new Form\VehiculeForm($objectManager);
$vehicule = new Entity\Vehicule();
// create the hydrator; this could also be done via the
// hydrator manager but create here for the example
$hydrator = new DoctrineObject($objectManager);
$form->setHydrator($hydrator);
$form->setObject($vehicule);
// We can also take care of the input filter here too!
// meaning less code in the controller and only
// one place to modify should it change
$form->setInputFilter($Vehicule->getInputFilter());
return $form;
}
}
Module.php
public function getFormElementConfig()
{
return array(
'factories' => array(
'MyModule\Form\VehiculeForm' => 'MyModule\Factory\Form\VehiculeForm' // path to our new factory
),
);
}
You can now get rid of your populate() method and allot of the controller code.
FooController.php
//...
protected function getVehiculeForm()
{
return $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');
}
public function addAction()
{
$request = $this->getRequest();
$form = $this->getVehiculeForm();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$vehicule = $form->getData(); // returns the entity!
if ($vehicule instanceof Vehicule) {
/// Fully hydrated entity!
var_dump($vehicule);
}
}
}
//...
}
//...