2

I have this weird problem with the json_array field configuration.

I have configured field meant to store some configuration. Its configured like this:

<field name="config" type="json_array" />

For example, I have an array like this:

[
    'choices' => [
        'Other' => 'other',
        'Male' => 'male',
        'Female' => 'female'
    ]
]

I set the entity property:

$entity->setConfig($config);

And I persist it to the database. The result is this:

"choices": {
    "Male": "male",
    "Other": "other", 
    "Female": "female"
}

When I do json_encode on the same array, the order is not changed, but somehow Doctrine does change the order. Is there a way to prevent this from happening?

Dion Snoeijen
  • 109
  • 1
  • 7

1 Answers1

2

Using one of the enumerated versions will prevent this behaviour:

$v1 = [
    'choices' => [
        'Other',
        'Male',
        'Female'
    ]
];

$v2 = [
    'choices' => [
        ['label' => 'Other', 'value' => 'other'],
        ['label' => 'Male', 'value' => 'male'],
        ['label' => 'Female', 'value' => 'female']
    ]
];

More information you can find here Does JavaScript Guarantee Object Property Order?

vpalade
  • 1,417
  • 1
  • 16
  • 19
  • Thanks! This might do it if the symfony form builder can handle that structure without making an exception for choices. – Dion Snoeijen May 28 '18 at 06:30