I have relation between BlogArticle and BlogCategory many_many & belongs_many_many. I would like to add CheckboxSetField or ListBoxField to cmsFields on BlogArticle, which contains BlogCategories.
Following code shows correct checkboxes in cms, but from some reason it doesn't store the values:
class BlogCategory extends DataObject
{
private static $db = [
'Title' => 'Varchar(255)'
];
private static $belongs_many_many = [
'BlogArticles' => BlogArticle::class
];
}
class BlogArticle extends Page
{
private static $many_many = [
"BlogCategories" => BlogCategory::class,
];
public function getCMSFields()
{
$fields = parent::getCMSFields();
$field = CheckboxSetField::create(
'BlogCategories',
'Categories',
BlogCategory::get()
);
$fields->add($field);
return $fields;
}
}
Any ideas what's wrong? Thanks a lot!
On your BlogArticle.php you aren’t referencing the relationship so it can’t save.
So BlogCategory::get() should be $this->BlogCategories() - you will probably have to map() the values aswell.
There’s an example of using the checkbox field with a $many_many here: https://www.silverstripe.org/learn/lessons/v4/working-with-data-relationships-many-many-1
I am looking to make a DataObject class which injects fields into a Page object but I'm having a bit of trouble doing so. The only solutions I've found so far require me to do something within the Page (other than adding in a relationship between the two classes), I'm not all that certain as to what I'm doing wrong...
What I need would be for the DataObject to add a tab and some fields within Page and have the data for that Page to save to the DataObjects table.
In a sense I would like them to be somewhat independent of each other, so that I can link it to Article now and then some other page types at some later date.
This is what I have so far :
Article.php
class Article extends Page {
private static $description = 'An article page for writing and posting content';
private static $has_many = array(
'MyExtraFields' => 'MyExtraFields'
);
}
The DataObject
class MyExtraFields extends DataObject {
private static $db = array(
'ExtraText' => 'Varchar(255)',
'ExtraWYSIWYG' => 'HTMLText'
);
private static $has_many = array(
'Article' => 'Article'
);
private static $summary_fields = array(
'ExtraText' => 'ExtraText',
'ExtraWYSIWYG' => 'ExtraWYSIWYG'
);
public function updateCMSFields(){
$fields = parent::getCMSFields();
$fields->addFieldsToTab('Root.Content.Translation', array(
TextField::create('ExtraText'),
HTMLEditorField::create('ExtraWYSIWYG')
)
);
return $fields;
}
}
If I understand it correctly, you want to be able to add the DataObject MyExtraField to the Pagetype Article. If the MyExtraField is dependent on the Article, then you need to change the Relation of the ExtraField to has_one like jberculo says:
class MyExtraField extends DataObject {
...
private static $has_one = array(
'Article' => 'Article'
);
}
Then you have to add a GridField to the Article's CMS view manage the DataObject:
class Article extends Page {
...
private static $has_many = array(
'MyExtraFields' => 'MyExtraField'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$gridFieldConfig = GridFieldConfig_RecordEditor::create();
$gridfield = new GridField( "MyExtraFields", "MyExtraField", $this->MyExtraField(), $gridFieldConfig );
$fields->addFieldToTab( 'Root.ExtraFields', $gridfield );
return $fields;
}
If you want to reuse the DataObject in different Articles, you need to use a many to many relation and a different GridField-Configuration:
$gridFieldConfig = GridFieldConfig_RelationEditor::create();
You will find the documentation of GridField here:
https://docs.silverstripe.org/en/3.4/developer_guides/forms/field_types/gridfield
If you want to manage has_one relation to be able to add just one optional instance of MyExtraField, you could use:
https://github.com/burnbright/silverstripe-hasonefield
I am trying to translate a DataObject using the _t() method.
I have been using it on Pages without a problem, but it doesn't seem to work on data objects.
class SliderItem extends DataObject {
private static $default_sort = 'Sort';
private static $db = array(
'Sort' => 'Int',
'Title' => 'Varchar(255)',
'Summary' => 'Text'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldsToTab('Root.Main', array(
TextField::create(_t('SliderItem.Title', 'Title')),
TextareaField::create(_t('SliderItem.Summary', 'Summary'))
));
$fields->removeByName(array('HomePageID', 'Sort'));
return $fields;
}
}
mysite/lang/de.yml
de:
SliderItem:
Title: 'I want to change this'
Summary: 'And this..'
Why does this example not work?
Make sure to define the variable name in the FormField constructor as the first parameter and the translatable title as the second parameter.
This:
TextField::create(_t('SliderItem.Title', 'Title'))
Should be this:
TextField::create('Title', _t('SliderItem.Title', 'Title'))
Your getCMSFields function should look something like this:
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldsToTab('Root.Main', array(
TextField::create('Title', _t('SliderItem.Title', 'Title')),
TextareaField::create('Summary', _t('SliderItem.Summary', 'Summary'))
));
$fields->removeByName(array('HomePageID', 'Sort'));
return $fields;
}
In SilverStripe I have a event dataobject
class Event extends DataObject {
private static $db = array(
'Name' => 'Text'
);
private static $has_many = array(
'EventDates' => 'EventDate'
that has many event dates:
class EventDate extends DataObject {
private static $db = array(
'Day' => 'Date',
'StartTime' => 'Varchar',
'EndTime' => 'Varchar'
);
Now if I query all events on a page like
Event::get()
I want them to be sorted by the earliest date.
Which way is the best to achieve this?
You can define a static property on the DataObject class with a default sort rule:
<?php
class EventDate extends DataObject {
…
// This also effects the default sorting of `has_many` related Events.
private static $default_sort = "\"Day\" ASC";
}
?>
Now
<?php
// first we pick a Event object, for instance by a (given) $id
$event = Event::get()->byId($id);
// because the default sort ist Day the attached `EventDate` will now be sorted by `Day` if you don't specify otherwise
$events = $event->EventDates();
// will return the earliest Event (of course you don't filter events here which are in the past).
$firstEvent = $events->First();
// if you then want to sort differently at some place, you can call ->sort() on the list:
$event = Event::get()->byId($id);
$events = $event->EventDates()->sort('LastEdited', 'DESC');
$lastEditedEvent = $events->First();
?>
I'm learning SilverStripe by creating a small website that lets the user manage their fragrances (i.e. perfumes/colognes). The user adds ingredients (that are used in the fragrances they have), then adds their fragrances, at which point they choose which ingredients are in the fragrance they're adding.
I've created the Ingredient and Fragrance classes which both extend DataObject. I've also created the IngredientsPage page which lets the user add/edit/delete ingredients (made up of a name and description) and lists all of the ingredients added so far, and this page is fully functional. I'm now trying to create the FragrancesPage page which will let the user add/edit/delete fragrances (made up of a name, description and ingredients) and list all the ones added so far, but I'm having some trouble.
The only way I know of to create the relationship between a Fragrance and Ingredients (one fragrance has many ingredients, and one ingredient belongs to many fragrances) is using a GridField (if there's a better way, let me know!), as this is what the SilverStripe tutorials get you to do (although in the tutorial it's for the CMS rather than the front-end). However, as soon as I try to add a GridField into the mix, I just get taken to an error page that says "Server Error: Sorry, there was a problem with handling your request.".
My code is as follows.
Ingredient.php:
<?php
class Ingredient extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $belongs_many_many = array(
'Fragrances' => 'Fragrance'
);
}
?>
Fragrance.php:
<?php
class Fragrance extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $many_many = array(
'Ingredients' => 'Ingredient'
);
}
?>
FragrancesPage.php:
<?php
class FragrancesPage extends Page {
private static $icon = 'cms/images/treeicons/reports-file.png';
private static $description = 'Fragrances page';
}
class FragrancesPage_Controller extends Page_Controller {
private static $allowed_actions = array('FragranceAddForm');
function FragranceAddForm() {
$config = GridFieldConfig_RelationEditor::create();
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'Name' => 'Name',
'Ingredient.Name' => 'Ingredient'
));
$fragrances_field = new GridField(
'Ingredients',
'Ingredient',
$this->Ingredients(),
$config
);
$fields = new FieldList(
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$fragrances_field
);
$actions = new FieldList(
new FormAction('doFragranceAdd', 'Add Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
return new Form($this, 'FragranceAddForm', $fields, $actions, $validator);
}
public function doFragranceAdd($data, $form) {
$submission = new Fragrance();
$form->saveInto($submission);
$submission->write();
return $this->redirectBack();
}
public function FragranceList() {
$submissions = Fragrance::get()->sort('Name');
return $submissions;
}
}
?>
If I remove everything from FragrancesPage.php relating to the GridField, the page works fine. I just can't seem to get the GridField working, and don't know of any other way to create the relationship between Fragrances and Ingredients on the front-end. If the code for IngredientsPage.php will be helpful also, let me know and I'll add it.
my guess is that you have error reporting turned off, and that is why you only see such a meaning less error message.
you should turn on display_errors and error_reporting in your php.ini, .htaccess or _ss_environment.php (IMPORTANT: setting it in _config.php will NOT work, as it gets overwritten by the error handler)
the problem I see in your code is that trying to use $this->Ingredients() on FragrancesPage, but as far as I can see only the class Fragrances has a method Ingredients (method is 'magically' created for the many_many relation).
also, I think your setDisplayFields()
so basically you need to use $fragrance->Ingredients() instead of $this->Ingredients().
but that leads us to the next problem: you don't have a fragrance yet.
unfortunately, at this time, GridField only works if you already have an object. this means you have to split it into two forms or use an alternative.
Option 1: use CheckboxSetField to manage the many_many relation.
this will not allow creating Ingredients on the fly, it will only give you check boxes that you can tick to link the items.
public function FragranceAddForm() {
$fragrances_field = new CheckboxSetField('Ingredients', 'Ingredient', Ingredient::get()->map());
$fields = new FieldList(
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$fragrances_field
);
$actions = new FieldList(
new FormAction('doFragranceAdd', 'Add Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
return new Form($this, __FUNCTION__, $fields, $actions, $validator);
}
public function doFragranceAdd($data, $form) {
$submission = new Fragrance();
$form->saveInto($submission);
$submission->write();
return $this->redirectBack();
}
Option 2: use GridField in a second form
this will allow creating Ingredients on the fly, but is a bit more work. and you might run into some troubles with GridField as it is not fully tested in the frontend yet.
(there is a recent question where I wrote a bit about GridField problems in frontends https://stackoverflow.com/a/22059197/1119263)
I guess this place is as good as any to finally write a tutorial/working example for frontend GridFields.
I took the liberty of refactoring your code a bit to include a edit functionality, its much nicer to have the GridField on the edit page than on a separate form.
As mentioned before, the GridField is not working that well in the frontend, there is a module to ease the pain, but it will still be rough around the edges and will require you to do some styling to make it look pretty.
Find the module on Packagist or GitHub
(you will need t
class Ingredient extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $belongs_many_many = array(
'Fragrances' => 'Fragrance'
);
public function getCMSFields() {
// fields used by the GridField, don't let the CMSFields mislead you
return new FieldList(
TextField::create('Name', 'Name'),
TextAreaField::create('Description', 'Description')
);
}
}
class Fragrance extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $many_many = array(
'Ingredients' => 'Ingredient'
);
}
/**
* Form in a separate class, so we can reuse it.
* #param Controller $controller
* #param string $name
* #param Null|Fragrance $fragrance Either null to create a new one, or pass an existing to edit it and add Ingredients
* #return Form
*/
class FragranceForm extends Form {
public function __construct($controller, $name, $fragrance = null) {
if ($fragrance && $fragrance->isInDB()) {
// we can only use a GridField if the object exists and has already been saved
// gridfield needs jQuery
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.min.js');
// ensure we don't have 2 versions of jQuery
Requirements::block(THIRDPARTY_DIR . '/jquery/jquery.js');
$config = FrontEndGridFieldConfig_RelationEditor::create();
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'Name' => 'Name',
'Description' => 'Description',
));
$ingredientField = new FrontEndGridField(
'Ingredients',
'Ingredient',
$fragrance->Ingredients(),
$config
);
} else {
$ingredientField = new LiteralField('Ingredients', '<p>Ingredients can be added after saving</p>');
}
$fields = new FieldList(
new HiddenField('ID', ''),
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$ingredientField
);
$actions = new FieldList(
new FormAction('doFragranceSave', 'Save Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
// populate the fields (ID, Name and Description) with the values from $fragrance. This does not effect the GridField
if ($fragrance && $fragrance->exists()) {
$fields->fieldByName('ID')->setValue($fragrance->ID);
$fields->fieldByName('Name')->setValue($fragrance->Name);
$fields->fieldByName('Description')->setValue($fragrance->Description);
// there is actually a method for that, but we can't use it here,
// because fields are not set yet. we could do it after __construct, but then we would
// overwrite things set by the error handler, so lets just do it by hand
// $this->loadDataFrom($fragrance);
}
parent::__construct($controller, $name, $fields, $actions, $validator);
}
public function doFragranceSave($data, $form) {
if (isset($data['ID']) && $data['ID']) {
$id = (int)$data['ID'];
$fragrance = Fragrance::get()->byID($id);
}
if (!isset($fragrance) || !$fragrance || !$fragrance->exists()) {
// if the ID was invalid or we don't have one, create a new Fragrance
$fragrance = new Fragrance();
}
$form->saveInto($fragrance);
$fragrance->write();
// redirect to the edit page.
$controller = $this->getController();
$editLink = $controller->EditLink($fragrance->ID);
return $controller->redirect($editLink);
}
}
class FragrancesPage extends Page {
}
class FragrancesPage_Controller extends Page_Controller {
private static $allowed_actions = array(
'edit',
'AddForm',
'EditForm',
);
/**
* the default action
* #return ViewableData_Customised
*/
public function index() {
// $this->customise() lets you overwrite variables that you can use in the template later.
return $this->customise(array(
// set the AddForm to $Form instead of $AddForm, this way you can use $Form in template and can reuse the template
'Form' => $this->AddForm(),
));
}
/**
* edit action to edit an existing Fragrance
* links will look like this /FragrancesPage/edit/$ID
*
* #param SS_HTTPRequest $request
* #return SS_HTTPResponse|ViewableData_Customised
*/
public function edit(SS_HTTPRequest $request) {
$id = (int)$request->param('ID');
$fragrance = Fragrance::get()->byID($id);
if (!$fragrance || !$fragrance->exists()) {
// fragrance not found? display a 404 error page
return ErrorPage::response_for(404);
}
// now that we have a $fragrance, overwrite EditForm with a EditForm that contains the $fragrance
$form = $this->EditForm($fragrance);
$return = $this->customise(array(
// also overwrite Title and Content, to display info about what the user can do here
// if you don't overwrite that, it will display the Title and Content of the page
'Title' => 'Edit: ' . $fragrance->Name,
'Content' => '<p>you are editing an existing fragrance</p>',
// set the Form to $Form instead of $EditForm, this way you can use $Form in template and can reuse the template
'Form' => $form,
));
// per default SilverStripe will try to use the following templates: FragrancesPage_edit.ss > FragrancesPage.ss > Page.ss
// if you want to use a custom template here, you can specify that with ->renderWith()
// but you probably won't need that anyway
// $return = $return->renderWith(array('MyCustomTemplateName', 'Page'));
return $return;
}
public function AddForm() {
return new FragranceForm($this, __FUNCTION__);
}
public function EditForm($fragranceOrRequest = null) {
// unfortunately, GridField / FormFields in general are a bit clumsy and do forget what item they where
// suppose to edit, so we have to check what $fragranceOrRequest is and set/get the fragrance to/from session
if ($fragranceOrRequest && is_a($fragranceOrRequest, 'Fragrance')) {
$fragrance = $fragranceOrRequest;
Session::set('FragrancesPage.CurrentFragrance', $fragrance->ID);
} else {
$fragrance = Fragrance::get()->byID(Session::get('FragrancesPage.CurrentFragrance'));
}
if (!$fragrance || !$fragrance->exists()) {
// that's bad, some error has occurred, lets display an ugly 404 page
return $this->httpError(404);
}
return new FragranceForm($this, __FUNCTION__, $fragrance);
}
public function EditLink($ID) {
return $this->Link("edit/$ID");
}
}
I know that's a lot to take in as someone still learning SilverStripe, if you have any questions, feel free to comment or just poke me on IRC