1

I have two different data objects (StockExchangeShare and NewsArticle) which are linked with a many_many relation.

In NewsArticle.php:

private static $many_many = [
    'Shares' => StockExchangeShare::class
];

In StockExchangeShare.php:

private static $belongs_many_many = [
    'NewsArticles' => NewsArticle::class
];

When adding a new news article, the user should be able to link some existing stock exchange shares to the new article. This should be done using a GridField with the config 'GridFieldConfig_RelationEditor'.

Currently, this only works after a news article has already been created. I can't add shares via the grid field to a new (not saved) article. This is the error message:

E_RECOVERABLE_ERROR: Argument 1 passed to SilverStripe\ORM\DataList::subtract() must be an instance of SilverStripe\ORM\DataList, instance of SilverStripe\ORM\UnsavedRelationList given, called in /vendor/silverstripe/framework/src/Forms/GridField/GridFieldAddExistingAutocompleter.php on line 247

Here's the code I used to create the grid field:

$gridFieldConfig = GridFieldConfig_RelationEditor::create();
$gridFieldConfig->removeComponentsByType(GridFieldAddNewButton::class);
$gridFieldConfig->getComponentByType(GridFieldAddExistingAutocompleter::class)->setSearchFields(array('name', 'tickerSymbol', 'isin', 'wpknr'));
$gridFieldConfig->getComponentByType(GridFieldAddExistingAutocompleter::class)->setResultsFormat('$name | $isin');

$fields->addFieldsToTab('Root.Main', [
    GridField::create(
        'Shares',
        'Shares',
        $this->Shares(),
        $gridFieldConfig
    ),
]);

Is this a problem with SilverStripe or did I do something wrong?

4

1 回答 1

2

This is the same behaviour in SilverStripe 3 too. Normally what I've done is to check if the record is saved before you display the GridField, otherwise add a message saying it'll be available when you've saved it.

public function updateCMSFields(FieldList $fields)
{
    if (!$this->owner->isInDB()) {
        $fields->addFieldToTab('Root.Main', LiteralField::create('Please note: you can modify relations when this item has been saved.'));
        return;
    }
    // add your GridField now
}
于 2018-02-08T20:27:34.453 回答