ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Adding items to tree through data API

Open ryanmitchell opened this issue 2 years ago • 1 comments

Unless I'm missing something obvious, it feels overly difficult to add items to a structured collection at a given place in the tree, especially when doing it in bulk.

You end up needing to track the collection structure/tree and doing something like:

$collection = Collection::findByHandle('handle');
$collectionStructure = $collection->structure()->in('default');

// make a new entry
$entry = Entry::make()
    ->collection('handle')
    ->locale('default')
    ->slug($termSlug)
    ->published(true)
    ->data([...]);

// parent of entry
$entryParent = Entry::newQuery()->where('x', 'y');

// after save, update tree
$entry->afterSave(function ($entry) use ($entryParent, $collectionStructure) {
    $collectionStructure->syncOriginal(); // this seems to be necessary or you end up with an error about flip() when creating multiple entries in the same request
    if (!$entryParent) {
        $collectionStructure->append($entry);
    } else {
        $collectionStructure->appendTo($entryParent->id(), $entry->id());
    }
    $collectionStructure->save();
});

I would have expected that adding a parent to the data() array on the Entry::make() would be enough to add it to the tree without me needing to handle it or maintain the state of the tree.

Is this something in your roadmap that you plan on changing?

ryanmitchell avatar Jan 18 '22 12:01 ryanmitchell

same here... unfortunately I still can not believe that it didn't make that by itself after saving...

jnbn avatar Jun 02 '22 23:06 jnbn