0

so I'm trying to set a selected option in my form but I can't seem to find out how to do this. I've Googled around and everything seems to be for Symfony2 where default was a thing, this seems to be no longer the case for Symfony4.

I've tried using data and empty_data but both don't select the correct value..

# weirdly, setting to ['guru'] gets undefined index error,
# setting to $options doesn't error
->add('guru', EntityType::class, array(
    'class' => User::class,
    'choice_label' => 'username',
    'data' => $options['guru'] 
 ))

and how I pass $options:

$form = $this->createForm(EditCategoryType::class, array('guru' => $guruName));
treyBake
  • 6,440
  • 6
  • 26
  • 57
  • Possible duplicate of [How to set default value for form field in Symfony2?](https://stackoverflow.com/questions/7913086/how-to-set-default-value-for-form-field-in-symfony2) – Juan I. Morales Pestana May 31 '18 at 11:49
  • Options is the third parameter of the createForm function. Th e second is the object (or smoething else) to update. $form = $this->createForm(EditCategoryType::class, $myCategory, array('guru' => $guruName)); – G1.3 May 31 '18 at 11:58
  • @ThisGuyHasTwoThumbs if you check the docs of version 2,3 and 4 the way you set the data in the form has not change. So you may be doing something wrong with the options array. Forgetting you already solved your question could you post the action and the full form to check it? I just think that you are doing is a bad an unnecesary practice. – Juan I. Morales Pestana May 31 '18 at 12:03
  • What did you use for the data_class parameter value for EditCategoryType? which entity name? – Deniz Aktürk May 31 '18 at 12:46
  • you can get better results if you define the object you will edit here. I will try to explain the answer with an example – Deniz Aktürk May 31 '18 at 12:49

5 Answers5

1

So with the help of @Juan I. Morales Pestana I found an answer, the only reason I've added the below as an answer rather than marking his as correct was because there seems to be a slight difference in how it works now..:

Controller now reads (Thanks to @Juan):

$category = $this->getDoctrine()->getRepository(Category::class)->find($id);
$category->setGuru($category->getGuru());

$form = $this->createForm(EditCategoryType::class, $category);

My EditCategoryType class:

->add('guru', EntityType::class, array(
    'class' => User::class,
    'choice_label' => 'username',
    'mapped' => false,
    'data' => $options['data']->getGuru()
))

updated twig template:

{{ form_widget(form.guru, { 'attr': {'class': 'form-control'} }) }}
treyBake
  • 6,440
  • 6
  • 26
  • 57
0
<a href="{{ path('register_new', { idpackage: p.id }) }}" class="btn_packages">

//sends to form type the package id
$fromPackage = '';
if($request->query->get('idpackage')) {
$fromPackage = $request->query->get('idpackage');
}

$form = $this->createForm(RegisterFormType::class, $register, ['fromPackage' => $fromPackage]);

in formType set the param in options: 
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Register::class,
'fromPackage' => null
]);
}

->add('package',EntityType::class, [
'label' => 'Select one item',
'class' => Package::class,
'choice_label' => function($package) {
    return $package->getTitle() . ' | crédits : ' . $package->getAmount();
},
'attr' => ['class' => 'input-text', ],
'placeholder' => '...',
'required' => false,
'choice_attr' => function($package) use ($idFromPackage) {
    $selected = false;
    if($package->getId() == $idFromPackage) {
        $selected = true;
    }
    return ['selected' => $selected];
},
])
Jerem
  • 47
  • 4
-1

As I said in my comments you are doing something wrong. I will explain all the process:

calling the form in the controller

$person = new Person();
$person->setName('My default name');
$form = $this->createForm('AppBundle\Form\PersonType', $person);
$form->handleRequest($request);

then the createForm function is executed here is the code

Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait

    protected function createForm($type, $data = null, array $options = array())
    {
        return $this->container->get('form.factory')->create($type, $data, $options);
    }

As you can see the data or options are nos setted directly in the form, another function is called and then the form is created

This is the result when I make a dump inside the PersonType

PersonType.php on line 20:
array:35 [▼
  "block_name" => null
  "disabled" => false
  "label" => null
  "label_format" => null
  "translation_domain" => null
  "auto_initialize" => true
  "trim" => true
  "required" => true
  "property_path" => null
  "mapped" => true
  "by_reference" => true
  "inherit_data" => false
  "compound" => true
  "method" => "POST"
  "action" => ""
  "post_max_size_message" => "The uploaded file was too large. Please try to upload a smaller file."
  "error_mapping" => []
  "invalid_message" => "This value is not valid."
  "invalid_message_parameters" => []
  "allow_extra_fields" => false
  "extra_fields_message" => "This form should not contain extra fields."
  "csrf_protection" => true
  "csrf_field_name" => "_token"
  "csrf_message" => "The CSRF token is invalid. Please try to resubmit the form."
  "csrf_token_manager" => CsrfTokenManager {#457 ▶}
  "csrf_token_id" => null
  "attr" => []
  "data_class" => "AppBundle\Entity\Person"
  "empty_data" => Closure {#480 ▶}
  "error_bubbling" => true
  "label_attr" => []
  "upload_max_size_message" => Closure {#478 ▶}
  "validation_groups" => null
  "constraints" => []
  "data" => Person {#407 ▼ // Here is the data!!!
    -id: null
    -name: "My default name"
    -salary: null
    -country: null
  }
]

As you can see the data is indexed at data so that is the reason why you get an undefined index error

So the proper way is to set the entity value from the controller or use your form as a service and call the repository and set the value using the data option which has not changed since version 2. My point is that you are using the form wrong.

Please change your code.

Hope it help

EDITED IN THE SYMFONY 4 WAY(with out namespaces bundles)

Let's see please, I have a Person Entity with a name just for this example

The controller

    $person = new Person(); //or $personsRepository->find('id from request')
    $person->setName('My default name');
    $form = $this->createForm(PersonType::class, $person);
    $form->handleRequest($request);

The form

public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('name',TextType::class,[
            //'data' => 'aaaaa' // <= this works too

        ]);

    }

The options array value which proves that you are accessing wrong

PersonType.php on line 20:
array:35 [▼
  "block_name" => null
  "disabled" => false
  "label" => null
  "label_format" => null
  "translation_domain" => null
  "auto_initialize" => true
  "trim" => true
  "required" => true
  "property_path" => null
  "mapped" => true
  "by_reference" => true
  "inherit_data" => false
  "compound" => true
  "method" => "POST"
  "action" => ""
  "post_max_size_message" => "The uploaded file was too large. Please try to upload a smaller file."
  "error_mapping" => []
  "invalid_message" => "This value is not valid."
  "invalid_message_parameters" => []
  "allow_extra_fields" => false
  "extra_fields_message" => "This form should not contain extra fields."
  "csrf_protection" => true
  "csrf_field_name" => "_token"
  "csrf_message" => "The CSRF token is invalid. Please try to resubmit the form."
  "csrf_token_manager" => CsrfTokenManager {#457 ▶}
  "csrf_token_id" => null
  "attr" => []
  "empty_data" => Closure {#480 ▶}
  "error_bubbling" => true
  "label_attr" => []
  "upload_max_size_message" => Closure {#478 ▶}
  "validation_groups" => null
  "constraints" => []
  "data" => Person {#407 ▼
    -id: null
    -name: "My default name" //Here is the data
    -salary: null
    -country: null
  }
]

AppBundle is just another folder in my folder structure. Be pleased to test your self. The second parameter to the formCreate function is the entity or data not the options you are thinking that the options is the data.

Juan I. Morales Pestana
  • 1,057
  • 1
  • 10
  • 34
-1
$parentCategory = $categoryRepository->repository->find(2);
$category = new Category();
$category->setParentCategory(parentCategory);
$form = $this->createForm(CategoryType::class, $category);

we chose the predefined top category, it works if you use it this way.

Deniz Aktürk
  • 362
  • 1
  • 9
-1

try this : empty_data documentation

rapaelec
  • 1,238
  • 12
  • 10
  • 2
    Please read the full doc before making sugestion... _This option determines what value the field will return when the submitted value is empty (or missing). **It does not set an initial value if none is provided when the form is rendered in a view**._ The question is how to set default selected option... – Juan I. Morales Pestana May 31 '18 at 13:40