How to Set Default Value for Form Field in Symfony2

How to set default value for form field in Symfony2?

Can be use during the creation easily with :

->add('myfield', 'text', array(
'label' => 'Field',
'empty_data' => 'Default value'
))

How do I specify default values in a Symfony form

http://symfony.com/doc/current/components/form.html#setting-default-values

If you need your form to load with some default values (or you're building an "edit" form), simply pass in the default data when creating your form builder.

$quoteItem = new QuoteItem();
$quoteItem->getQuoteFlight()->setSpecMajorSetupCharge(QuoteFlight::SPEC_MAJOR_SETUP_CHARGE).

$form = $this->createForm(QuoteItemType::class, $quoteItem);
// ...

Using data option is no good, because:

http://symfony.com/doc/current/reference/forms/types/form.html#data

The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose it's persisted value when the form is submitted.

So the recomendation is to set explicitly the data in the underlined object on initialization, either in __constructor() or before bind the object to the form.

How to set as a default value in a Symfony 2 form field the authentified username from the FOSUserBundle

You can passe variable from your controller to your form :

in your controller :

$username=$this->container->get('security.context')->getToken()->getUser()->getUsername()
$form = $this->createForm(new MyFormType($username), $entity);

in your form :

protected $username;

public function __construct (array $username = null)
{
$this->username = $username ;
}

public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('myfield', 'text', array(
'label' => 'Field',
'data' => $this->username))
}

How to set a default value in a Symfony 2 form field?

What you're trying to do here is creating a security hole: anyone would be able to inject any ID in the user_product_id field and dupe you application. Not mentioning that it's useless to render a field and to not show it.

You can set a default value to user_product_id in your entity:

/**
* @ORM\Annotations...
*/
private $user_product_id = 9000;

Symfony2: How to set default value for a field DateTime

You should replace :

public function  __construct()
{
$this->fechaAlta = new \DateTime();
}

by

public function  __construct()
{
$this->fechaAlta = new \DateTime('now');
}

Symfony 3 forms: how to set default value for a textarea widget

Assuming you are using Symfony 3.4, there's quite a good documentation for that.

Long story short, you should use data:

$builder->add('token', TextareaType::class, array(
'data' => 'abcdef',
));

As the docs say:

The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted.

how to set default value to a symfony form field (User field) following the connected user, following the ManyToMany relation between entities

I found the solution,

As explained here, only the owning side is responsible for the connection management.

The problem was not with the method $parc->addUser($currentUser);, it's just that that entity Parcs was not the owner to manage this relation when would like to persist datas.

So I have inversed the entity owner properties. In Parcs.php the relation have to be like that:

/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Users", inversedBy="parcs")
* @ORM\JoinTable(name="parcs_users",
* joinColumns={
* @ORM\JoinColumn(name="parc_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* }
* )
*/
private $users;

I have to remove the relation in Users.php in order to write this:

/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Parcs", mappedBy="users")
*/
private $parcs;

And this my controller for the addAction():

public function addParcsAction() {

if (!$this->get('security.context')->isGranted('ROLE_EDIT')) {
throw new HttpException("403");
}

$em=$this->getDoctrine()->getManager();
$parc = new Parcs;
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$parc->addUser($currentUser);

$form = $this->createForm(new ParcsType(), $parc);
$request = $this->getRequest();

if ($request->isMethod('POST') | ($form->isValid())) {

$form->bind($request);

$parc = $form->getData();
$em->persist($parc);
$em->flush();

return $this->redirect($this->generateUrl('indexParc'));
}

else {
return $this->render('MySpaceMyBundle:Parcs:addParcs.html.twig', array('form' => $form->createView() ));
}
}

Thank you a lot by answering, noticed here that it was not the $parc->addUser($currentUser); who was making troubles, but the owner side of the relation.

How to set a default value in Symfony2 so that automatic CRUD generated forms don't require those fields?

Your boolean value need to have nullable set as true:

/**
* @var string $sale
*
* @ORM\Column(name="sale", type="boolean", nullable=true)
*/
private $sale = false;


Related Topics



Leave a reply



Submit