Symfony 2 Entity Field - symfony

I am getting error when I am using following entity type field,
It is showing me select field fine but when I am trying to save it it is giving me following error
Code 1:
->add('agentFirstname', 'entity', array(
'class' => 'AcmeClientBundle:Client',
'property' => 'firstName',
))
Error 1: Catchable Fatal Error: Object of class
Acme\ClientBundle\Entity\Client could not be converted to string
When I am using second code then everything is working fine
Code 2:
->add('agentFirstname', 'text', array(
)
)
Error 2: No Error
Please find my entity bellow
/**
* #var string
*
* #ORM\Column(name="agent_firstname", type="string", length=255)
*/
private $agentFirstname;
I want to make select field here for client first name entity which is here
/**
* #var string
*/
private $firstName;

Symfony cannot access the $firstName property as its visibility is private.
You need to add a getFirstName() method to your Acme\ClientBundle\Entity\Client class.
public function getFirstName()
{
return $this->firstName;
}
Now change your form code to:
->add('agentFirstname', 'entity', array(
'class' => 'AcmeClientBundle:Client', 'property' => 'getFirstName'
))

Related

Neither the property "dispositif" nor one of the methods

In a controller, I create a form:
$em = $this->getDoctrine()->getManager();
$formProjetSearch = $this->createForm(EgwProjetSearchType::class, $em, [
'em' => $this->getDoctrine()->getManager(),
]);
In my EgwProjetSearchType, I have:
$builder->add('dispositif', 'entity', array(
'class' => 'LeaPrestaBundle:EgwDispositif',
'property' => 'nomDispositif',
'label' => 'nomDispositif',
'required' => true,
'empty_value' => '',
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('d')
->where('d.isActive = :isActive')
->setParameter('isActive', 1)
->orderBy('d.nomDispositif','ASC');
},
));
And I've got this error:
Neither the property "dispositif" nor one of the methods "getDispositif()", "dispositif()", "isDispositif()", "hasDispositif()", "__get()" exist and have public access in class "Doctrine\ORM\EntityManager".
Nonetheless, the entity exists:
<?php
namespace Lea\PrestaBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Lea\PrestaBundle\Entity\EgwDispositif
*
* #ORM\Table(name="egw_dispositif")
* #ORM\Entity
*/
class EgwDispositif
{
/**
* #var integer $idDispositif
*
* #ORM\Column(name="id_dispositif", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idDispositif;
/**
* #ORM\ManyToOne(targetEntity="EgwTypePrestation", inversedBy="dispositifs")
* #ORM\JoinColumn(name="id_type_prestation", referencedColumnName="id")
*/
private $idTypePrestation;
ETC ...
Thanks for your help !
Thakns for your messages, but, I just want to display in a form a entity in a listbox : i use the type EgwProjetSearchType, i add a field which is "dispositif" coming from entity EgwDispositif (which exists) and the return message is :
Neither the property "dispositif" nor one of the methods
"getDispositif()", "dispositif()", "isDispositif()", "hasDispositif()",
"__get()" exis``t and have public access in class
"Doctrine\ORM\EntityManager"
So it's not a problem of argument EM passed in the form EgwProjetSearchType : Symfony says "the entity doesnt exists"....
I dont have to pass EwgDispositif ?? It was not the cas in Symfony 2 : i had :
$formProjetSearch = $this->createForm(new EgwProjetSearchType($this-
getDoctrine()->getManager()));
And this doesnt work anymore in 3.4.
So i changed the code :
$formProjetSearch = $this->createForm(EgwProjetSearchType::class, $em, [
'em' => $this->getDoctrine()->getManager(),
]);
In your entity you need to define your getters and setters. Your entity class is private so you must define public getters and setters to access the private objects.
https://symfony.com/doc/current/doctrine.html

Symfony form submission with handleRequest issue

I'm experiencing an odd error with my form validation in Symfony 4. It is a simple contact form represented by this entity:
class ContactRequest
{
/** #var int */
private $id;
/** #var string */
private $fullName;
//...
/**
* #return string
*/
public function getFullName() : string
{
return $this->fullName;
}
In my controller I'm handling the submission as per Symfony website but there is something I'm missing for I'm getting the following error:
Type error: Return value of App\Entity\ContactRequest::getFullName() must be of the type string, null returned
Now, I know what is the meaning of that: it expects a string to be returned by the method getFullName whereas null is actually returned but I don't understand why.
This is my controller
public function contactSubmit(Request $request, ValidatorInterface $validator)
{
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
if($form->isValid()){
//...
}
$errors = $validator->validate($form);
Shouldn't the handleRequest() method set the values in the entity for me?
To my surprise, when I have initialised the entity before, it worked well notwithstanding the entity is already set in the configureOptions() method in the form:
$contact = new ContactRequest;
$contact
->setFullName($request->request->get('contact')['fullName'])
//...
$form = $this->createForm(
ContactType::class
$contact
);
$form->setData($contact);
$form->handleRequest($request);
However, shouldn't the scope of using the handleRequest() be to avoid setting the entity's values manually? Shouldn't the handleRequest() method take care of setting those values?
I know I could validate the submitted data against the entity too (thing that I've successfully tried), without using the handleRequest() at all but it would piss me off a little. Why would I need to set a form in such a case?
This is the ContactType form:
//...
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fullName', TextType::class, [
'required' => true,
'empty_data' => 'a',
'attr' => [
'placeholder' => 'Full Name',
'class' => 'form-control'
]
])
//...
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => ContactRequest::class
]);
}
In order to find out where your getFullName gets called you could (atleast in dev environment) print the backtrace on the call:
/**
* #return string
*/
public function getFullName() : string
{
if ($this->fullName === null)
{
echo "<pre>getFullName on uninitialized entity:\n";
debug_print_backtrace();
die();
}
return $this->fullName;
}
But as said in the comments: Initializing the entity with a null value in that field and not allowing the getter to return a null value seems kinda odd to me, so : ?string to allow for nullable return values (as of PHP 7.1) seems to be the next best option.

Cannot found entity after add form in Symfony

I have three entity (Activite, CabinetEquipe and ActiviteEquipe). When I add Activite, I want to add many CabinetEquipe in ActiviteEquipe.
CabinetEquipe entity
/**
* #var string
*
* #ORM\Column(name="libelle", type="string", nullable=false, length=125)
*/
private $libelle;
Activite entity
/**
* #ORM\OneToMany(targetEntity="LogicielBundle\Entity\ActiviteEquipe", mappedBy="activite", cascade={"persist", "remove"})
*/
private $equipes;
public function addEquipe(\LogicielBundle\Entity\ActiviteEquipe $equipe)
{
$this->equipes[] = $equipe;
$equipe->setActivite($this);
return $this;
}
public function removeEquipe(\LogicielBundle\Entity\ActiviteEquipe $equipe)
{
$this->equipes->removeElement($equipe);
}
public function getEquipes()
{
return $this->equipes;
}
ActiviteEquipe entity
/**
* #ORM\ManyToOne(targetEntity="UtilisateurBundle\Entity\CabinetEquipe")
* #ORM\JoinColumn(nullable=false)
*/
private $equipe;
public function setEquipe(\UtilisateurBundle\Entity\CabinetEquipe $equipe)
{
$this->equipe = $equipe;
return $this;
}
public function getEquipe()
{
return $this->equipe;
}
But, after my form for add Activite, I have this error : Found entity of type UtilisateurBundle\Entity\CabinetEquipe on association LogicielBundle\Entity\Activite#equipes, but expecting LogicielBundle\Entity\ActiviteEquipe
My Form :
$builder->add('equipes', 'entity', array(
'label' => 'Équipe(s)',
'class' => 'UtilisateurBundle\Entity\CabinetEquipe',
'expanded' => true,
'multiple' => true,
'choices' => $equipes,
'property' => function($equipe) {
return $equipe->getLibelle();
}
));
Can you help me pleases ? I'm newbie in Symfony
You expect \LogicielBundle\Entity\ActiviteEquipe in your entity.
public function addEquipe(\LogicielBundle\Entity\ActiviteEquipe $equipe)
{
But in form you work on \UtilisateurBundle\Entity\CabinetEquipe.
$builder->add('equipes', 'entity', array(
'label' => 'Équipe(s)',
'class' => 'UtilisateurBundle\Entity\CabinetEquipe',
In form you need to choose entity which is expected in addEquipe and removeEquipe.
Looks like you expect some kind of proxy (ActiviteEquipe) which is imo not needed here.

Neither the property xxx exist and have public access in class blabla... but they do

i hope its a silly problem but i can't see it. I'm working on a Symfony 2 project (version 2.7) and i have this Exception :
Neither the property "contracts" nor one of the methods "addContract()"/"removeContract()", "setContracts()", "contracts()", "__set()" or "__call()" exist and have public access in class "AppBundle\Entity\User\User"
I understand the exception but addContract() exists and is public, so do the property contracts in my User class. I got this exception when i submit a form. (In this form, i include the contracts form. The problem might be here)
My UserClass with contracts property
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $contracts;
/**
* Add contracts
*
* #param \AppBundle\Entity\Work\Contract $contracts
* #return User
*/
public function addContract(Contract $contracts)
{
$this->contracts[] = $contracts;
return $this;
}
/**
* Remove contracts
*
* #param \AppBundle\Entity\Work\Contract $contracts
*/
public function removeContract(Contract $contracts)
{
$this->contracts->removeElement($contracts);
}
/**
* Get contracts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContracts()
{
return $this->contracts;
}
My UserType form
class UserType extends BaseType {
/**
* Constructor
*/
public function __construct()
{
parent::__construct('AppBundle\Entity\User\User');
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('number', 'text', array(
'label' => 'form.number',
))
->add('seniority', 'date', array(
'label' => 'form.seniority',
'widget' => 'single_text',
'input' => 'datetime',
'format' => 'dd/MM/yyyy',
))
->add('comment', 'textarea', array(
'label' => 'form.comment',
'required' => false,
))
->add('contracts', new ContractType());
}
As you can see, i add my Contract Form to my builder, and its render great. I got the exception when i submit it.
Ah, and i use Yaml mapping. The relation between User and Contract is a OneToMany - ManyToOne. One user can have many contracts.
Thanks !
May be you should build your form like this (as of contracts is an ArrayCollection type):
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
....
->add('contracts', 'collection', array(
'type' => new ContractType(),
'by_reference' => false,
...
));
}

Symfony2 Sonata admin datatransformer

I'm trying to set a form type "sonata_type_immutable_array" as follows:
->add('metadatos', 'sonata_type_immutable_array', array(
'keys' => array(
array('Test', 'text', array('required' => false)),
array('URL', 'url', array('required' => false)),
)
))
And saving like this:
public function setMetadatos(\Portal\EntradasBundle\Entity\EntradaMeta $metadatos = null)
{
$this->metadatos = $metadatos;
return $this;
}
But always get the error:
Catchable Fatal Error: Argument 1 passed to Portal\EntradasBundle\Entity\Entrada::setMetadatos() must be an instance of Portal\EntradasBundle\Entity\EntradaMeta, array given
I dont know how to set a datatransformer (ArrayToModelTransformer) to reach this.
Anyone can help me plz. Thanks in advance!
A data transformer is quite simple,
Look at this:
http://symfony.com/doc/current/cookbook/form/data_transformers.html
A data transformer is used like this:
/**
* #var ObjectManager
*/
private $om;
/**
* #param ObjectManager $om
*/
public function __construct($om)
{
$this->om = $om;
}
[..]
$yourTransformer = new YourDataTransformer($this->om);
And then ->addModelTransformer($yourTransformer))
It's used to get the id of an object , and/or get the object from an id.

Resources