I have a database with a table "teams" and a property "weekday". I generated my doctrine entity and now I'm building a Symfony2 form.
I'd like to save an array with weekdays into my weekdays property in the teams table. The weekdays property is a VARCHAR(255) so it should be able to contain a string array. I use the choice type, but I get an array to string conversion error when submitting the form.
I used the Symfony2 choice formtype (with the multiple option), because a team can select a couple of weekdays when they're available. I first retrieved my team object data. Then I make the form like this:
$builder = $this->createFormBuilder($team);
$form = $builder->add('weekday', 'choice', array(
'choices' => array(
'mon' => 'Monday',
'tue' => 'Tuesday',
'wed' => 'Wednesday',
'thu' => 'Thursday',
'fri' => 'Friday',
'sat' => 'Saturday',
'sun' => 'Sunday',
),
'multiple' => true,
'expanded' => true,
'label' => 'Day of the week',
'label_attr' => array('class' => 'control-label'),
'attr' => array('placeholder' => 'Day of the week', 'size' => '7')
))->getForm();
When the form is submitted, I save the changes to the db with the entity manager:
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
// Save changes to db
$em = $this->getDoctrine()->getManager();
$em->persist($team);
$em->flush();
// Redirect to new canonical url
return $this->redirect($this->generateUrl('team_edit', array('nameCanonical' => $team->getNameCanonical(), 'code' => $team->getCode())));
}
This all seems 100% valid code to me. I've made other forms in symfony2 like this. But when I choose one or multiple weekdays in the form, and then submit, I get this error:
An exception occurred while executing 'UPDATE teams SET weekday = ? WHERE id = ?' with params {"1":["mon","tue","wed"],"2":6}:
Notice: Array to string conversion in /Users/username/Dropbox/www/projectname/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php line 1211
(Full error page here)
I can't think of a way to fix this. Help appreciated! My full code is viewable on this gist.
What you need to do is set the type of your property to array
and Doctrine takes care of the (de)serialization for you.
class Team
{
/**
* @ORM\Column(type="array")
*/
protected $weekdays;
/* Some more code */
}
The list of all possible types can be found in the official documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With