PM-Riabel PM-Riabel - 2 months ago 10
PHP Question

Symfony3: Why choices submit key text instead of its value

Symfony version 3.1.3

I am generating a choices list from the database like bellow and it works fine.

class ClassType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('class',
EntityType::class,
array('class' => 'PIE10Bundle:Classes',
'expanded' => false,
'multiple' => false,));
// some other form elements
}
}


in the web page it gives HTML Select like below,

<select name="class[class]" id="class_class">
<option value="6">1A</option>
<option value="7">4C</option>
</select>


and in the controller, I am getting the submitted data and debug it as below,

if( $form->isSubmitted() && $form->isValid() )
{
$cName = $form['class']->getData();
echo $cName;
die;
}


My result is
1A
or
4C
(depending on the selection) but not
6
or
7
.
I am expecting to get the values of the choice list but not its key text.

I wonder how this happens and how to fix this to get the value. Further I have another choice list in the same form but it submits the expected value.

Thanks

Answer

try with

$cName->getId() 

I suppose the $cName is an istance of the PIE10Bundle:Classes entity (try dumping a get_class($cName)) and the echo print the name because is implemented as a __toString method.

Hope this help