Symfony2: setting the default option of a select - symfony

I have a form with a dropdown (select) and I would like to choose the option selected by default:
This is the code that generates the select:
$builder->add('language', 'choice', array(
'label' => 'pages.age.gateway.language.label',
'choices' => array(1 => 'first option', 2 => 'second option'),
));
I've tried the following (suggested here, Symfony2 Setting a default choice field selection):
$builder->add('language', 'choice', array(
'label' => 'pages.age.gateway.language.label',
'choices' => array(1 => 'first option', 2 => 'second option'),
'data' => '2'
));
this didn't work with my code (my understanding of symfony2, I might not be in the right direction).
Another alternative would be using 'preferred_choices' but I'd like to avoid this, as I wouldn't like to modify the order in which the options are displayed.

If your form depends of an entity:
/* Action */
public function myAction()
{
$user = new User();
$user->setLanguage(2); // Set the default option
$form = $this->createForm(new UserType(), $user); // Give the user to the form
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$user = $form->getData();
// Do something like save / redirect
}
}
return array(
'form' => $form->createView(),
);
}
Also you can set a preferred choice (but not a true default value) thanks to preferred_choices key (it move up the value to the top of the select):
$builder->add('language', 'choice', array(
'label' => 'pages.age.gateway.language.label',
'choices' => array(1 => 'first option', 2 => 'second option'),
'preferred_choices' => 2
));

You want to add option without the value. You can do this with option empty_value.
$builder
->add('gender', 'choice', array(
'label' => 'Gender',
'choices' => array('male', 'female'),
'empty_value' => 'Please select option'
));

Related

Symfony 2, choices from database

I'm trying to display a form with a "select" where is the "options" from a query.
$results = $conn->query(" select gsm, name from Contact");
$row = $results->fetchAll();
and after that: I trying to use this
foreach($row as $lign)
$centretechnique[$lign['gsm']] = $lign['name'];
and in formbuilder
$form->add('centretechnique', 'choice', array('required' => false, 'error_bubbling' => true, "empty_value" => "Choisir ", 'choices' => $centretechnique));
I want to display a list of select option with value=gsm and the displayed value is the name
this method llow me to display , but the problem that if I have duplicate option, only on option will be displayed.
for example, the result of the request is
array (size=2)
0 =>
array (size=2)
'gsm' => string '628436515' (length=9)
'name' => string 'name1' (length=7)
1 =>
array (size=2)
'gsm' => string '628436515' (length=9)
'name' => string 'name 2' (length=4)
just one option will be displayed.
any help please
If you want to populate choices form type from the database, then you should be using the form entity type.
Something like this:
$form->add(
'centretechnique',
'entity',
array(
'class' => 'MyBundle:Contact',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.name', 'ASC');
},
'choice_label' => 'name',
'choice_value' => 'gsm',
'multiple' => false,
'expanded' => false,
'required' => false,
)
)
By building your choices you do :
$centretechnique[$lign['gsm']] = $lign['name'];
So your code does overwrite the first choice with the second, since you use the same key twice ...

How to change the size of a "select box" form

A client doesn't want to scroll in a select form so I need to increase the size of my select form.
I tried this but still doesn't work, I only see 4 inputs :
{{ form_widget(filterForm.accomodationFilter1, { attr: { class: 'fancyselect filter type' }, {'size': '10'} }) }}
Any idea how I can do that and where is the documentation ?
Thanks
Try doing it directly in the formBuilder:
->add('example', 'choice', array(
'attr' => array('class' => 'fancyselect filter type',
'style' => 'max-width:100px'),
'choices' => 'choices',
)
Or just use:
->add('example', 'choice', array(
'attr' => array('class' => 'fancyselect filter type'),
'choices' => 'choices',
'max_length' => 100,
)

Creating array from an object in symfony2

I'm trying to access a list of categories I have in a database and put them into a form in Symfony2.
public function productAddAction()
{
$product = new Product();
$categories = $this->getDoctrine()
->getRepository('AudsurShopBundle:Category')
->findAll();
$form = $this->createFormBuilder($product)
->add('category', 'choice', array(
'choices' => $categories, /* this is wrong */
'multiple' => false,
))
->add('name', 'text')
->add('save', 'submit', array('label' => 'Create Task'))
->getForm();
return $this->render('AudsurAdminBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
How do I go from $categories to an object that I can put into the following part, and it complying with what the function expects?
->add('category', 'choice', array(
'choices' => $categories, /* this is wrong */
'multiple' => false,
))
I know this is basic, but I can't seem to find the right keywords to find the answer (what should I have looked for?)
First off, "this is wrong" is not a specific error message for us to help you very much. It's like saying "my code doesn't work" and not telling us why. Moving on to your actual problem..
You're not using the right Form type to handle the entity type and display it properly. As #Talus mentioned, the Field Type you need is entity. There's a few things you're missing, such as the class parameter and the property parameter (assuming you haven't written a __toString() function in the Entity class.)
$categories = $this->getDoctrine()
->getRepository('AudsurShopBundle:Category')
->findAll();
$form = $this->createFormBuilder($product)
->add('category', 'entity', array(
'class' => 'AudsurShopBundle:Category',
'choices' => $categories,
'multiple' => false,
'property' => 'name', // This needs to be an actual property, I just assumed name
))
->add('name', 'text')
->add('save', 'submit', array('label' => 'Create Task'))
->getForm();
Since you're using all Category entities that exist, the findAll() query is actually not necessary. You can instead go for the basic usage:
$form = $this->createFormBuilder($product)
->add('category', 'entity', array(
'class' => 'AudsurShopBundle:Category',
'multiple' => false,
'property' => 'name', // This needs to be an actual property, I just assumed name
))
->add('name', 'text')
->add('save', 'submit', array('label' => 'Create Task'))
->getForm();
If you're looking for a specific subset of the Categories, you can use the choices property like before or pass a query_builder.
IRC, I think there is a type for that : http://symfony.com/fr/doc/current/reference/forms/types/entity.html
This should help to whatever you want to do, if I understood what you meant. :)
Well you can parse an Array from database:
Create a method in repository findAllArray():
public function findAllArray() {
return $this->getEntityManager()
->createQuery(
'SELECT Category '.
'FROM AudsurShopBundle:Category AS Category'
)
->getArrayResult();
}
Then call it in your controller and get all categories:
$categories = $this->getDoctrine()
->getRepository('AudsurShopBundle:Category')
->findAllArray();
When you have got array, make it suitable for choice (create new array $choices):
$choices = array();
foreach ($categories as $category) {
$choices[$value['id']] = $value['title'];
}
Then put this new array into form:
->add('category', 'entity', array(
'choices' => $choices,
Hope it helped. Have a nice day.

symfony form builder update option field

is it possible to update an option field after adding it ?
$builder
->add('examens', 'entity', array(
'class' => 'TelegrammeExamenBundle:ExamExamen',
'property' => 'libelle',
'required' => true,
'empty_value' => 'Sélectionnez un examen',
//'data' => $this->em->getReference("TelegrammeExamenBundle:ExamExamen", 510),
'data' => null,
'query_builder' => function(ExamenRepository $r) {
return $r->getSelectList();
},
'attr' => array('class' => 'bg_white_filet_gris')
))
;
how modify field option ??? (setOption don't exist)
if (...) $builder->get('examens')->setOption('property', 'test');
You can simply ->add() it again. As the API documentation suggests for the add method:
Adds or replaces a child to the form
http://api.symfony.com/2.8/Symfony/Component/Form/FormInterface.html#method_add
This can be used to modify form elements for example in a FormEvent.
Alternatively the FormBuilder provides a setAttribute() method which can be used as follows:
$builder->get('examens')->setAttribute('property', 'test');

Correct way to use Drupal 7 Entities and Field API

I'm trying to use Drupal 7's entities and field API to correctly build a new module. What I have been unable to understand from the documentation is the correct way to use the new API to create a 'content type' (not a node type) with a number of set fields, such as Body.
I'm trying to set up the entity using hook_entity_info, then I believe I need to add the body field using field_create_instance, but I can't seem to get it to work.
In mycontenttype.module:
/**
* Implements hook_entity_info().
*/
function mycontenttype_entity_info() {
$return = array(
'mycontenttype' => array(
'label' => t('My Content Type'),
'controller class' => 'MyContentTypeEntityController',
'base table' => 'content_type',
'uri callback' => 'content_type_uri',
'entity keys' => array(
'id' => 'cid',
'label' => 'title',
),
'bundles' => array(
'mycontenttype' => array(
'label' => 'My Content Type',
'admin' => array(
'path' => 'admin/contenttype',
'access arguments' => array('administer contenttype'),
),
),
),
'fieldable' => true,
),
);
return $return;
}
/**
* Implements hook_field_extra_fields().
*/
function mycontenttype_field_extra_fields() {
$return['mycontenttype']['mycontenttype'] = array(
'form' => array(
'body' => array(
'label' => 'Body',
'description' => t('Body content'),
'weight' => 0,
),
),
);
return $return;
}
Then does this go in the .install file?
function mycontenttype_install() {
$field = array(
'field_name' => 'body',
'type' => 'text_with_summary',
'entity_types' => array('survey'),
'translatable' => TRUE,
);
field_create_field($field);
$instance = array(
'entity_type' => 'mycontenttype',
'field_name' => 'body',
'bundle' => 'mycontenttype',
'label' => 'Body',
'widget_type' => 'text_textarea_with_summary',
'settings' => array('display_summary' => TRUE),
'display' => array(
'default' => array(
'label' => 'hidden',
'type' => 'text_default',
),
'teaser' => array(
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
),
),
);
field_create_instance($instance);
}
I think your problem is that if node module is installed, there is already a field named 'body'. You should either re-name your field to something like 'mycontenttype_body' (comment.module uses comment_body), or re-use the 'body' field and skip the adding the field part and skip to adding the instance of it. The former is recommended over the latter.
Every field has an array property, entity_types, which limits the entities to which the field can be attached.
The best Drupal solution I can find, hook_field_create_field, can alter fields as they are created, but that's no good for the body field which is created on installation.
So my solution is just to edit the database directly in my hook_install
$data_col = db_query("SELECT data from field_config where field_name = 'body'")->fetchAssoc();
$data = unserialize($data_col['data']);
$data['entity_types'][] = 'MY_ENTITY_TYPE';
db_update('field_config')
->fields(array('data' => array('data' => serialize($data))))
->condition('field_name', 'body')
->execute();
just started down the same path here is a video from fago
Here's a nice repo to start: Lawmakers entity

Resources