How to pass value to twig in Symfony2 - forms

I'm trying to have inputs with customized labels (based on other entity attribute).
private $kilos_maxlim;
private $precio;
I set the values of $kilos_maxlim in the constructor of the class. So, I have that field filled. I want to show an input of $precio but with the label based on the value of $kilos_maxlim.
I have this input field in the classtype:
->add('precio', null, array(
'attr' => array('autofocus' => true),
'label' => 'label.precio',
))
How can I pass the value without being an input?

It should work as simple as this:
public function buildForm(FormBuilderInterface $builder, array $options) {
// get the actual entity
$entity = $builder->getData();
// set the value as the label
$builder->add('precio', null, array(
'label' => 'label.precio ' . $entity->getKilosMaxlim(),
));
}

Related

Symfony3: pass value to Form EntityType be the default selected value

I have a form that should allow to add an item (device) to a category (brand). Below is a part of the controller that creates the form (the $brand thing doesn't work but I'll figure that out later). Below that is the code that creates my form.
I want my Select box (which is an entitytype of Brand, and shows all possible brands) to also show a default selected value, based on a variable passed down by the controller.
Two questions:
where can I pass this value down?
how can I set a default option for the EntityType select box? I expected it to be 'data' but even hard-coding a number there won't work.
This is the controller bit:
public function createDevice(Request $request, $brand) {
$device = new Device();
$form = $this->createForm(DeviceType::class, $device); // where do I pass the value of the default option?
$form->handleRequest($request);
and the type:
class DeviceType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('brand', EntityType::class, array(
'class' => 'AppBundle:Brand',
'choice_label' => 'name',
'choice_value' => 'id',
'data' => '2' // does not set default value to second item!
Just set Brand into Device.
$em = $this->getDoctrine()->getManager();
$brand = $em->getRepository('AppBundle:Brand')->find(2);
$device = new Device();
$device->setBrand($brand);

Symfony change form collection dropdown with propel model

Is it possible to change the contents of a form dropdown that is part of a form collection that is populated using propel but the data is not mapped. Example of code to get the data below:
AddressType:
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->
->add("addressOne", new addressOneType()),
->add("addressTwo", new addressTwoType(), array(
"required" => false,
)),
}
addressOneType:
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->
->setMethod('POST')
->add('Country', 'model', array(
'mapped' => 'bundle\nameBundle\Model\Countries',
'required' => true,
'multiple' => false,
'expanded' => false,
'property' => 'label',
'query' => CountryQuery::create()->find(),
))
->getForm();
}
This collection is used for a particular part of an application however in this part in need to call a service from the form itself. Would this be possible as I've tried to extend the ContainerInterface and declare this inside of the construct method however this just throws an error.
However, I beleive this to be due to the fact that the form builder is not declared as a service.
Is there an easier way of changing the data of the drop down menu by injecting a new model to override the original. For example:
$form = $this->createForm(new AddressType());
$newData = CountriesQuery::create()
->orderBy("different_field");
$form['collectionName']['fieldname']->setData($newData);
Doing the above doesn't change or override the original model that is changing the data. With or without the ->find() at the end of the $newData field.
Does anyone know of a way to overwrite the data set by the model?
A very simple way for pass specific options to form is in constructor ...
class addressOneType
{
protected $countryQuery;
public function __constructor( $countryQuery = null )
{
$this->countryQuery = $countryQuery;
}
public function buildForm(FormBuilderInterface $builder, array $options){
$query = $this->countryQuery ? $this->countryQuery :
CountryQuery::create();
$builder
->setMethod('POST')
->add('Country', 'model', array(
'mapped' => 'bundle\nameBundle\Model\Countries',
'required' => true,
'multiple' => false,
'expanded' => false,
'property' => 'label',
'query' => $query->find(),
))
->getForm();
}
}
... and you can call to form in this way ...
$cQuery = CountriesQuery::create()->orderBy("different_field");
$form = $this->createForm(new AddressType($cQuery));

bind error to embedded form field in symfony2's controller

Using Symfony2.3.4
As the title quite explains it I need to bind an error message to an embedded form field and preferably in the controller. I'm thinking maybe similar to how I do it with single forms:
use Symfony\Component\Form\FormError;
//....
public function createAction(){
//.....
$postData = current($request->request->all());
if ($postData['field_name'] == '') {
$error = new FormError("Write some stuff in here");
$form->get('field_name')->addError($error);
}
//.....
}
or maybe it's got to be done differently, either way I need help,
thank$
I see, that you are trying to display a message when a form field does not contain any value. You can do this easily in your form class, like this:
buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('field_name', 'text', array(
'label' => 'Field label',
'required' => true,
'constraints' => array(
new NotBlank(array('message' => 'Write some stuff in here.'))
),
));
}
If you need to inject some other kind of constraint to your form which is not part of Symfony2 framework, you can create your own validation constraint.
If you want to add some options to your form in controller, it can be done in the method where you create the form by setting your own options:
class YourController {
public function createForm(YourEntity $yourEntity){
$form = $this->createForm(new YourFormType(), $yourFormType, array(
'action' => $this->generateUrl('your_action_name',
array('your_custom_option_key' => 'Your custom option value')),
'method' => 'POST',
));
return $form;
}
// Rest of code omitted.
}
After that you need to add an option in setDefaultOptions(OptionsResolverInterface $resolver) method, in your form class, like this:
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'your_custom_option_key' => '',
));
}
And then access it in buildForm(FormBuilderInterface $builder, array $options) method, like this:
buildForm(FormBuilderInterface $builder, array $options) {
$options['your_custom_option_key']; // Access content of your option
// The rest of code omitted.
}

Doctrine 2 result caching in Symfony with form type entity

I use APC result caching in docrine, and have filter form with type entity in all website pages and want cache this, but when I add useResultCache() to method I get exception
Entities passed to the choice field must be managed
example
...->getQuery()->useResultCache(true, null, 'someindex')->getResult()
but all action without form with entity type work normally.
Any ideas?
Don't know if You've figured out how to do it, but here's how I've done it (spent half a day figuring this out).
/* in FormType.php */
public function buildForm(FormBuilderInterface $builder, array $options)
{
$items = $options['entity_repository']
->findItems()
->useResultCache(true, 3600, 'my_cache')
->getResult();
$choice_list = new ObjectChoiceList($items, 'name', array(), null, 'id');
$builder->add('item', 'entity', array(
'class' => 'MyBundle:Items',
'multiple' => true,
'expanded' => true,
'choice_list' => $choice_list,
));
}

Symfony 2. How I can set default values to embedded forms from entities?

I need to set default values for my form. There is code, from my controller:
$form = $this->createFormBuilder()->add('user', new Form\UserType($user))
->add('client', new Form\ClientType($client))
->getForm();
And I have two entites: User & Client. So, how I can set default values from entites?
I set the default values for my text fields like this
->add('firstname', 'text', array('attr' => array('value' => 'bla')))
for an Entity you can set empty value to false and fill the prefrred_choices array
->add('language', 'entity', array('empty_value' => false, 'preferred_choices' => array('2'), 'class' => 'CPAppUserBundle:Language', ))
In the form classes of each your user and your client class you can set default values like this:
public function configure() {
$this->setDefault('yourfield', $defaultvalue);
}