简体   繁体   中英

Sonata Admin save native collection without Entity

I want to save some data in a serialized array. The following

->add('consumptionData', 'sonata_type_native_collection', array(
            'label' => 'Verbrauchsdaten',
            'entry_type' => ConsumptionDataType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options' => array(
                'label' => false
            )
        ))

works fine with symfony but with sonata admin I get

A new entity was found through the relationship 'AppBundle\\Entity\\Document#meterPoints' that was not configured to cascade persist operations for entity ...

How can I tell sonata that it should be a serialized array and not an Entity?

If you want to save your data as array you can "cast" it to needed type in getter for your field in entity.

If it ruins logic of your code, you can add some to new getter/setter methods for "fake" entity. Form field names are legal when getter and setter are specified for them even if field with this name don't exist in your entity.

So, you can write something like this in your builder:

->add('consumptionDataForArray', 'sonata_type_native_collection', [...])) 

And something like this in your entity:

public function setConsumptionDataForArray($data)
{
    // change your data here as you need

    $this->consumptionData = $neededData;
}

public function getConsumptionDataForArray()
{
    // cast your data back to array

    return $castedBackData;
}

Hope this is the answer to your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM