Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ElementVirtual work with TagField & inline #49

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 33 additions & 14 deletions src/Model/ElementVirtual.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class ElementVirtual extends BaseElement

private static $singular_name = 'virtual block';

private static $inline_editable = false;
private static $inline_editable = true;

/**
* @param BaseElement
Expand Down Expand Up @@ -67,21 +67,13 @@ public function getCMSFields()
$fields->addFieldToTab('Root.Main', LiteralField::create('WarningHeader', '<p class="message error">' . $warning . '</p>'));
}

$autocomplete = AutoCompleteField::create(
'LinkedElementID',
_t(__CLASS__ . '.LinkedElement', 'Linked Element'),
'',
BaseElement::class,
'Title'
);

$autocomplete->setLabelField('VirtualLinkedSummary');
$autocomplete->setDisplayField('VirtualLinkedSummary');
$autocomplete->setSourceFilter(['AvailableGlobally' => 1]);

$availableBlocks = BaseElement::get()->filter('AvailableGlobally', 1)->exclude('ClassName', get_class($this));
$fields->replaceField(
'LinkedElementID',
$autocomplete
TagField::create("LinkedElementRelation", $this->fieldLabel('LinkedElement'), $availableBlocks)
// Bug: TagField (react) setIsMultiple results in empty (https://github.com/silverstripe/silverstripe-tagfield/issues/195)
// ->setIsMultiple(false)
->setCanCreate(false)
);

if($this->LinkedElementID){
Expand All @@ -97,6 +89,33 @@ public function getCMSFields()
return parent::getCMSFields();
}

/**
* Create an intermediary UnsavedRelationList to have TagField save the LinkedElement into
* @return UnsavedRelationList
*/
public function LinkedElementRelation()
{
$this->LinkedElementRelation = UnsavedRelationList::create(
get_class($this),
'LinkedElementRelation',
BaseElement::class
);
$this->LinkedElementRelation->add($this->LinkedElementID);
return $this->LinkedElementRelation;
}

/**
* Transfer LinkedElement from UnsavedRelationList to has_one LinkedElementID
*/
public function onBeforeWrite()
{
if($this->LinkedElementRelation && $this->LinkedElementRelation->first()){
$this->LinkedElementID = $this->LinkedElementRelation->first()->ID;
}

return parent::onBeforeWrite();
}

/**
* @return string
*/
Expand Down