3

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
  • 143
  • 2
  • 9

2 Answers2

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,427
  • 1
  • 16
  • 20
  • 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
0

Doctrine docs states this :

You should never rely on the order of your JSON object keys, as some vendors like MySQL sort the keys of its native JSON type using an internal order which is also subject to change.

Roubi
  • 1,989
  • 1
  • 27
  • 36