SilverStripe - limiting the number of many relations a dataobject can have - silverstripe

If I have a $has_many relationship that I want to manage with a GridField in the cms, how would I go about putting a limit on the number of how many relations one object can have? Is this possible?
Can I do this in the model or would it have to be a check I add into the GridField I'm using to add and remove relations?
I'm looking at implementing GridField_SaveHandler to make a custom GridFieldComponent but not sure how I can use this to abort the save if i detect something is wrong.

the following 2 solutions are not the cleanest way to solve this, but the most pragmatic and easiest to implement.
basically, what I suggest to do, is just count the objects and remove the ability to add new records once the count is above a certain number.
if you want to limit the number of records on a single relation/grid (lets say max 5 players per team):
class Player extends Dataobject {
private static $db = array('Title' => 'Varchar');
private static $has_one = array('TeamPage' => 'TeamPage');
}
class TeamPage extends Page {
private static $has_one = array('Players' => 'Player');
public function getCMSFields() {
$fields = parent::getCMSFields();
$config = GridFieldConfig_RecordEditor::create();
if ($this->Players()->count > 5) {
// remove the buttons if we don't want to allow more records to be added/created
$config->removeComponentsByType('GridFieldAddNewButton');
$config->removeComponentsByType('GridFieldAddExistingAutocompleter');
}
$grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
$fields->addFieldToTab('Root.Main', $grid);
return $fields;
}
}
if you want to limit the total number of records globally (if we limit this way to 5, this means if 1 Team already has 3 Players, then the 2nd team can only have 2):
class Player extends Dataobject {
private static $db = array('Title' => 'Varchar');
private static $has_one = array('TeamPage' => 'TeamPage');
public function canCreate($member = null) {
if (Player::get()->count() > 5) {
return false;
}
return parent::canCreate($member);
}
}
class TeamPage extends Page {
private static $has_one = array('Players' => 'Player');
public function getCMSFields() {
$fields = parent::getCMSFields();
$config = GridFieldConfig_RecordEditor::create();
$grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
$fields->addFieldToTab('Root.Main', $grid);
return $fields;
}
}

I have wrote a quick jQuery plugin to limit the number of items a GridField can have: -
Download the plugin here: - gridfieldlimit.js
https://letscrate.com/f/monkeyben/silverstripe/gridfieldlimit.js
Set up the plugin in the getCMSFields function: -
// Pass GridField configs, each one containing field name and item limit
$vars = array(
"GridFieldLimits" => "[['GRIDFIELD_NAME_1', 3], ['GRIDFIELD_NAME_2', 6]]",
);
// Load the jquery gridfield plugin
Requirements::javascriptTemplate("themes/YOUR_THEME_NAME/javascript/gridfieldlimit.js", $vars);

works for me: make the canCreate method of the DataObject that's managed by your GridField check for existing objects.
of course, this doesn't allow you to implement a customg GridFieldComponent, as you need to modify the DataObject code.

Related

In Silverstripe, how can I automate the CMS field creation for Pages like it works in DataObjects?

In DataObjects, the getCMSFields method creates all the appropriate CMS Fields automatically (it is called scaffolding). However, in classes that extend SiteTree (i.e. Pages) this does not happen.
How can I use this form field scaffolding in Pages?
Besides calling DataObject::getCMSFields() as you already suggested in your own answer, it is also possible to instantiate a scafolder directly:
public function getCMSFields() {
// with tabs
$scaffolder = new FormScaffolder($this);
$scaffolder->restrictFields = ['Title', 'Content'];
$scaffolder->tabbed = true;
$fields = $scaffolder->getFieldList();
$fields->addFieldToTab('Root.Main', [
new MySpecialFieldWithCustomOptions('Links', 'My Links', $foobar),
]);
return $fields;
}
public function getCMSFields() {
// without tabs
$scaffolder = new FormScaffolder($this);
$scaffolder->restrictFields = ['Title', 'Content'];
$fields = $scaffolder->getFieldList();
$fields->push(
new MySpecialFieldWithCustomOptions('Links', 'My Links', $foobar)
);
return $fields;
}
This will work with any DataObject ($this has to be an instace of DataObject). Pages a subclass of DataObjects.
restrictFields is optional, if not provided, it will do all fields it can find.
We go back to DataObject and get the scaffolded fields:
use SilverStripe\ORM\DataObject;
use Page;
class MyPage extends Page
{
private static $db = [
'MyField' => 'Varchar',
];
private static $has_one = [
'MyRelation' => 'MyClass',
];
public function getCMSFields()
{
// fields from Page class
$fields = parent::getCMSFields();
// fields from DataObject class.
$fieldRepository = DataObject::getCMSFields();
$fields->addFieldsToTab(
'Root.MyExtraFields',
[
$fieldRepository->dataFieldByName('MyField'),
$fieldRepository->dataFieldByName('MyRelationID'),
]
);
return $fields;
}
}

Can't add VirtualPage as allowed children

I have created a holder page KochiHolder as below and performed a database rebuild successfully. I have set the $allowed_children of KochiHolder to only accept KochiPage or VirtualPage.
In the CMS I cannot create a VirtualPage under a KochiHolder page.
Why is $allowed_children not working correctly? How do I allow VirtualPage to be created as a sub page of KochiHolder?
KochiHolder
class KochiHolder extends Page {
private static $db = array(
);
private static $has_one = array(
'Photo' => 'Image'
);
private static $can_be_root = false;
private static $allowed_children = array('KochiPage', 'VirtualPage');
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Images", new UploadField('Photo'));
return $fields;
}
}
After a bit of debugging of CMSPageAddController (more specifically, the doAdd action) that Silverstripe uses for the "Add Page" screen in the CMS, I believe I found the root cause of the problem.
So the following error seems to be occurring: Page type "Page" not allowed as child of this parent page (well, that is the error I was getting in my test)
In the SiteTree class, it has a validate function which checks what the allowed children are. One of the checks for this is unrolling VirtualPage to the page it is a virtual of. (There is probably a little more to it than that - I need to do more investigating)
Good news is that you can override this functionality however it isn't great. Basically, because your class extends Page which extends SiteTree, if you specify your own validate function on Page (as VirtualPage extends Page too) you would be able to override the functionality.
In my tests, I used the following:
public function validate()
{
$result = parent::validate();
if ($this instanceof VirtualPage)
{
$newResult = new ValidationResult();
$items = $result->messageList();
foreach ($items as $key => $value)
{
if ($key != 'ALLOWED_CHILDREN')
{
$newResult->error($value, $key);
}
}
return $newResult;
}
return $result;
}
It isn't perfect and it makes some assumptions (eg. error codes are assumed for all items in the messageList but that isn't always the case). I haven't done heaps of testing with it but it does work for my recreation of your particular scenario.

Silverstripe 3 - GridFieldExtensions MultiClass Adding

I'm trying to use https://github.com/silverstripe-australia/silverstripe-gridfieldextensions/ to create a gridfield where I can add different types of dataobjects.
Sadly I can't figure out how to write the correct code for that on my class where I want the gridfield.
Could someone please point me in the right direction?
UPDATE:
Based on your answers, I now have the following structure
class ModularPage extends Page {
private static $has_many = array(
'Sections' => 'MP_Section',
'Galleries' => 'MP_Gallery',
'Paragraphs' => 'MP_Paragraph'
);
public function getCMSFields() {
...
$fields->addFieldToTab('Root.Main', $mutli_grid = GridField::create('Sections', 'Sektionen', $this->Sections(), MultiClassGrid::create(15)));
...
}
}
class MP_Section extends DataObject {
private static $has_one = array(
'Section' => 'MP_Section',
'ModularPage' => 'ModularPage'
);
}
class MP_Gallery extends MP_Section {
private static $has_one = array(
'Section' => 'MP_Section',
'ModularPage' => 'ModularPage'
);
}
So far, so good? Is this right until now?
Cause If I want to add for example a gallery, I receive the following error
[User Error] Couldn't run query: SELECT DISTINCT "MP_Section"."ID", "MP_Section"."SortID" FROM "MP_Section" LEFT JOIN "MP_Gallery" ON "MP_Gallery"."ID" = "MP_Section"."ID" LEFT JOIN "MP_Paragraph" ON "MP_Paragraph"."ID" = "MP_Section"."ID" WHERE ("ModularPageID" = '13') ORDER BY "MP_Section"."SortID" ASC LIMIT 9223372036854775807 Column 'ModularPageID' in where clause is ambiguous
Here is how I usually setup my GridField:
$c = GridFieldConfig_RelationEditor::create();
$c->removeComponentsByType('GridFieldAddNewButton')
->addComponent(new GridFieldAddNewMultiClass())
;
$c->getComponentByType('GridFieldAddNewMultiClass')
->setClasses(array(
'SectionThemesBlock' => SectionThemesBlock::get_section_type(),
'SectionFeaturedCourse' => SectionFeaturedCourse::get_section_type(),
'SectionCallForAction' => SectionCallForAction::get_section_type(),
'SectionContactSheet' => SectionContactSheet::get_section_type()
//....
));
$f = GridField::create('Sections', "Sections", $this->Sections(), $c);
$fields->addFieldToTab("Root.Sections", $f);
Based on the GridFieldConfig_RelationEditor, just remove GridFieldAddNewButton then add GridFieldAddNewMultiClass. Then configure the component to know which classes to have available in the dropdown to create. All those SectionThemesBlock, SectionFeaturedCourse etc extend a common Section dataObject as base. The get_section_type() function is a custom static function on the Section dataobject to get a nice looking name in the dropdown and not have to type it manually all the time....
The basics of the Section dataobject looks like so:
class Section extends DataObject {
public static function get_section_type()
{
return trim(preg_replace('/([A-Z])/', ' $1', str_ireplace('Section', '', get_called_class())));
}
//...
}
And the page where that gridField goes and that has the relation defined on:
class Page extends SiteTree {
//...
private static $has_many = array(
'Slides' => 'Slide'
);
//...
}
Something like this should work
$config = new GridFieldConfig_RecordEditor();
$config->addComponent(new GridFieldAddNewMultiClass());
...
$grid = GridField::create('Grid', 'Grid', $this->GalleryItems(), $config);
You need three DataObjects:
GalleryItem extends DataObject{}
FooGalleryItem extends GalleryItem{}
BarGalleryItem extends GalleryItem{}

Add new Page using GridField - creates the child in root folder

I would like to use GridField to view and create new child pages. Parent is DocumentHolder, child is Document. Both extend SiteTree. When I click to "Add Document" (button generated by grid), fill in the fields and confirm the form, the parent page is ignored and the page is created in root. It works well when I use DataObject. The code looks like this:
class DocumentHolder extends SiteTree
{
private static $allowed_children = array(
'Document'
);
private static $default_child = "Document";
public function getCMSFields()
{
$fields = parent::getCMSFields();
$gridField = new GridField('Documents', 'Documents', SiteTree::get('Document')->filter('ParentID', $this->ID), GridFieldConfig_RecordEditor::create());
$fields->addFieldToTab("Root.Uploads", $gridField);
return $fields;
}
}
class Document extends SiteTree
{
private static $db = array(
);
private static $has_one = array(
);
}
Thanks for help.
Since SiteTree already has a relationship to its Children pages set up, you may as well use it! Since allowed_children will only ever be documents, try this instead:
$gridField = new GridField('Documents', 'Documents', $this->Children(), GridFieldConfig_RecordEditor::create());
I ran into this problem earlier working on my holderpage module. You need to set the ParentID by default. Here's two strategies;
You can use populateDefaults on the child class. E.g.
class Document extends SiteTree
{
private static $default_parent = 'DocumentHolder';
private static $can_be_root = false;
public function populateDefaults(){
parent::populateDefaults();
$this->ParentID = DataObject::get_one(self::$default_parent)->ID;
}
...
Or you can manipulate the record in the gridfield with a custom GridFieldDetailForm implementation or via the updateItemEditForm callback.
<?php
class MyGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
public function ItemEditForm()
{
$form = parent::ItemEditForm();
if (! $this->record->exists() && $this->record->is_a('SiteTree')) {
$parent_page = $this->getController()->currentPage();
if ($parent_page && $parent_page->exists()) {
$this->record->ParentID = $parent_page->ID;
// update URLSegment #TODO perhaps more efficiently?
$field = $this->record->getCMSFields()->dataFieldByName('URLSegment');
$form->Fields()->replaceField('URLSegment', $field);
}
}
return $form;
}
}
This is more complicated although it allowed me to create an effortless module / addon ( https://github.com/briceburg/silverstripe-holderpage )

Customising the CMS

I'm having trouble with how to do something similar to this http://www.silverstripe.org/archive/show/2431. Basically I want the user to be able to create content and have their ID put into the database with the new content. I'm sorry if this is fairly obvious. I am a little stumped though. I am having trouble wrapping my head around how it will actually work. I know I can retrieve the current user using the following code but I'm not sure where to go from there.
$currentUser = Member::currentUser();
In SilverStripe usually the 3rd argument to a FormField is the value, so for example a TextField has the following arguments:
new TextField($name = 'myField', $title = 'Please write something in my Field', $value = "yay");
but this would not work in the CMS (at least in SilverStripe 2 if you are using a Page, not sure on DataObject) because SilverStripe overwrites all values when it tries to populate the Form with the values of the current object
so you have several alternatives, the 2 easiest alternatives are:
class MyContentObject extends DataObject {
public static $db = array(
'Text' => 'HTMLText',
);
public static $has_one = array(
'Member' => 'Member',
)
public function getCMSFields() {
$fields = new FieldSet();
$fields->push(new Textarea('Text', 'Text'));
if (!$this->MemberID)
$this->MemberID = Member::currentUserID();
$fields->push(new HiddenField('MemberID'));
return $fields;
}
}
And 2nd option, which is way better in this case, you don't even need a hidden field, you can just set the MemberID right before the record gets written to database by using onBeforeWrite:
class MyContentObject extends DataObject {
public static $db = array(
'Text' => 'HTMLText',
);
public static $has_one = array(
'Member' => 'Member',
)
public function getCMSFields() {
$fields = new FieldSet();
$fields->push(new Textarea('Text', 'Text'));
return $fields;
}
public function onBeforeWrite() {
// this method will be called every time the object gets saved
parent::onBeforeWrite();
if (!$this->MemberID)
$this->MemberID = Member::currentUserID();
}
}

Resources