SilverStripe: Trying to implement Contact Form function but getting white screen of death - silverstripe

I'm following this tutorial
I have a page called 'Contact.ss'. The php file looks like this:
class Contact extends Page {
private static $has_one = array (
'Photograph' => 'Image'
);
static $db = array (
'MailTo' => 'Varchar(100)',
'SubmitText' => 'Text'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Main', $Photograph = UploadField::create('Photograph'), 'Content');
$Photograph->getValidator()->setAllowedExtensions(array('png','jpeg','jpg','gif'));
$Photograph->setFolderName('photographs');
$fields->addFieldToTab("Root.Main", new Textfield('Mailto', 'Address to email contact form submission to'));
$fields->addFieldToTab("Root.Main", new TextareaField('SubmiteText', 'Text displayed after contact form submission'));
return $fields;
}
}
class Contact_Controller extends Page_Controller {
static $allowed_actions = array(
'ContactForm'
);
function ContactForm() {
// Create fields
$fields = new FieldSet(
new TextField('Name', 'Name*'),
new EmailField('Email', 'Email*'),
new TextareaField('Comments','Comments*')
);
// Create action
$actions = new FieldSet(
new FormAction('SendContactForm', 'Send')
);
// Create Validators
$validator = new RequiredFields('Name', 'Email', 'Comments');
return new Form($this, 'ContactForm', $fields, $actions, $validator);
}
}
But when I call $ContactForm in the template I get a blank screen when I try to load the page. (500 error)
I've checked to see if it's possible to call the function from the template by replacing all the ContactForm()'s code with:
return "Hello, World!"
It works, so I know the function is being called. But I can't see what's wrong with the code from the tutorial.
Can anyone help me out?

The issue is the tutorial you have used is written for SilverStripe 2.4 while you are using a newer version, SilverStripe 3.1.
For SilverStripe 3.1 I suggest going through the SilverStripe Frontend Forms lesson rather than the SSBits tutorial. The SSBits tutorial is from 2010 and is for SilverStripe 2.4. The SilverStripe Frontend Forms lesson is from 2015 and is for the current version of SilverStripe.
With your current code there are a number of bits of code that need to be updated to work in the latest version of SilverStripe.
FieldSet has been replaced by FieldList. You will need to replace each instance of FieldSet with FieldList in your code.
Your ContactForm should look more like this:
function ContactForm() {
// Create fields
$fields = FieldList::create(
TextField::create('Name', 'Name*'),
EmailField::create('Email', 'Email*'),
TextareaField::create('Comments','Comments*')
);
// Create action
$actions = FieldList::create(
FormAction::create('SendContactForm', 'Send')
);
// Create Validators
$validator = RequiredFields::create('Name', 'Email', 'Comments');
return Form::create($this, 'ContactForm', $fields, $actions, $validator);
}
In SilverStripe 3.1 the in built static variables need to be declared private.
Make sure you declare your $allowed_actions as private:
private static $allowed_actions = array(
'ContactForm'
);
As well as your $db as private:
private static $db = array (
'MailTo' => 'Varchar(100)',
'SubmitText' => 'Text'
);

Related

Support PHP 8's attributes for my routes in custom Symfony framework

I've followed the Symfony Tutorial Series to create my own Symfony framework. Currently I have the following code to define my routes and add them to the UrlMatcher:
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../src/app.php';
$context = new Routing\RequestContext();
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
Here's my app.php file for reference:
<?php
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;
$routes = new Routing\RouteCollection();
$routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [
'year' => null,
'_controller' => 'App\Controller\LeapYearController::index',
]));
return $routes;
What's the simplest way this can be modified to support PHP 8's attributes against the LeapYearController's actions for my routes instead of defining them in the app.php file?
It's been a while since I last looked at Symfony and a lot has changed in the framework aswell as in PHP itself and so far everything I have found is no longer supported.
I've managed to get the following working:
$loader = new AnnotationDirectoryLoader(
new FileLocator(),
new class() extends AnnotationClassLoader {
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot) {
$route->setDefault('_controller', $class->getName() . '::' . $method->getName());
}
}
);
$routes = $loader->load(__DIR__ . '/../src/App/Controller');
Alternatively this works using the Psr4DirectoryLoader introduced in version 6.2:
$loader = new DelegatingLoader(
new LoaderResolver([
new Psr4DirectoryLoader(
new FileLocator()
),
new class() extends AnnotationClassLoader {
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot) {
$route->setDefault('_controller', $class->getName() . '::' . $method->getName());
}
}
])
);
$routes = $loader->load(['path' => __DIR__ . '/../src/App/Controller', 'namespace' => 'App\Controller'], 'attribute');

Create a DataObject to build table rows and columns in SilverStripe

I'm trying to do something very different for a SilverStripe site: on several subpages are tables of data, and these tables each have their own set of column headers, and some tables have more columns than others. I want to avoid building out tables in the Rich Text Editor as that is prone to a lot of mistakes and it's a hassle to maintain over time.
What I would like to do is create a DataObject that allows for a nth number of columns and an nth number of corresponding rows. This way I can call a loop (or possibly two) inside the template where I have the HTML table structure already in place. The content managers have full control over which columns are in the tables for any give subpage, and they don't have to worry about maintaining the HTML table setup.
I've had a couple of ideas that don't produce the results I want without a) making the UI experience too complex for content managers and b) not being able to properly link the columns with the rows.
I have thought of creating a DataObject for Table Headers and one for Table Rows, but then I'm stumped on how to combine them in such a way that would make sense, especially since there could be any number of columns.
Would anyone have any suggestions on to approach this?
UPDATE: Ok, I have something going for the TableRowItem data object that may work, and is close to working. However, the issue is this now: How do I save the field values to the database when I am creating them basically on the fly? As it is now, the only field that saves to the database is the PDF file upload field, everything else is erased upon hitting "create."
<?php
class TruckBodyPdfTableRowItem extends DataObject {
private static $db = array(
);
// One-to-one relationship with gallery page
private static $has_one = array(
'TablePage'=> 'Page',
'TableColumnSet' => 'TableColumnSet',
'PDF' => 'File',
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Main","TablePageID");
$fields->removeFieldFromTab("Root.Main","TableColumnSetID");
$fields->removeFieldFromTab("Root.Main","SortOrder");
$fields->addFieldsToTab("Root.Main", $this->getMyColumnOptions());
return $fields;
}
public function getMyColumnOptions()
{
$columnArray = [];
$Columns = DataObject::get('TableColumnSet');
foreach($Columns as $Column){
$columnArray[] = TextField::create($Column->TableColumnHeader);
}
return $columnArray;
}
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
);
public function canEdit() {
return true;
}
public function canDelete() {
return true;
}
public function canCreate(){
return true;
}
public function canPublish(){
return true;
}
public function canView(){
return true;
}
}
But those are the tricky parts: Figuring out how to map values from one DataObject into labels for another, and then auto-generating an nth number of rows based on how many columns have been created.
<?php
class TablePage extends Page
{
private static $db = array(
'H1' => 'varchar(250)',
);
private static $has_many = array(
'TableRowItems' => 'TableRowItem',
'TableColumnSets' => 'TableColumnSet'
);
private static $has_one = array(
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Main", new TextField("H1"), "Content");
$gridFieldConfig = GridFieldConfig_RecordEditor::create();
$gridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
// field from drawer class => label in UI
'TableColumnHeader' => 'Table Column Header'
));
$gridfield = new GridField(
"TableColumnSets",
"Table Column Sets",
$this->TableColumnSets(),
$gridFieldConfig
);
$fields->addFieldToTab('Root.Specs Table', $gridfield);
$gridFieldConfig2 = GridFieldConfig_RecordEditor::create();
$gridFieldConfig2->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
// field from drawer class => label in UI
'TableRowValue' => 'Table Row Value'
));
$gridfield2 = new GridField(
"TableRowItems",
"Table Row Items",
$this->TableRowItems(),
$gridFieldConfig2
);
$fields->addFieldToTab('Root.Specs Table', $gridfield2);
return $fields;
}
}
class TablePage_Controller extends Page_Controller
{
private static $allowed_actions = array(
);
public function init()
{
parent::init();
// You can include any CSS or JS required by your project here.
// See: http://doc.silverstripe.org/framework/en/reference/requirements
}
}
Here are the classes TableColumnSet and TableRowValue. I figured, there would be one set of column headers associated with an nth number of rows, so I figured there would be a $has_many relationship between the two classes, in that a TableColumnSet could have many TableRowValues, but there would only be one TableColumnSet for all the TableRowValues. I was hoping to associate the TableRowValues to the TableColumnSet values using a dropdown with all the column headers created but that just sounds like a bad idea. Having to manually associate every field in a row to the column headers seems tedious and potentially difficult content managers.
<?php
class TableColumnSet extends DataObject {
private static $db = array(
'SortOrder' => 'Int',
'TableColumnHeader'=>'varchar(250)'
);
// One-to-one relationship with gallery page
private static $has_one = array(
'TablePage'=> 'Page'
);
private static $has_many = array(
'TableRowItems' => 'TableRowItem'
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Main","TablePageID");
$fields->removeFieldFromTab("Root.Main","SortOrder");
return $fields;
}
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
'TableColumnHeader' => 'Table Column Header',
);
public function canEdit() {
return true;
}
public function canDelete() {
return true;
}
public function canCreate(){
return true;
}
public function canPublish(){
return true;
}
public function canView(){
return true;
}
}
I feel like may be on to something here, at least in regards to the relationship between the column headers and rows? I'm not sure, though.
I might be off base here, since I have no experience with SilverStripe. But... my PHP / HTML table solution might apply here:
<?php
// parse your table data into this structure
$tableData = array(
"rowOne" => array(
"columnName" => "columnValue1",
"colName" => "colValue1"
// .....
),
"rowTwo" => array(
"columnName" => "columnValue2",
"colName" => "colValue2"
// .....
)
);
// now loop through the array with a printHeader parameter
$tableHTML = array(
"<table>"
);
$tableHead = array(
"<thead>"
);
$tableBody = array(
"<tbody>"
);
$printHeader = true;
foreach ($tableData as $row) {
foreach ($row as $column => $value) {
$tableRow = "<tr>";
if ($printHeader) {
$tableHead[] = "<th>".$column."</th>";
}
$tableRow .= "<td>".$value."</td>";
}
$tableBody[] = $tableRow."</tr>";
// after the first row, set printHeader to false and close the <thead>
$printHeader = false;
$tableHead[] = "</thead>";
}
// implode table header to string with linebreaks
$tableHead = implode(PHP_EOL, $tableHead);
// close table <tbody> & implode to string with linebreaks
$tableBody[] = "</tbody>";
$tableBody = implode(PHP_EOL, $tableBody);
// add all table elements together
$tableHTML[] = $tableHead;
$tableHTML[] = $tableBody;
$tableHTML[] = "</table>";
// implode table array to string
$tableHTML = implode(PHP_EOL, $tableHTML);
// print or write anywhere
echo($tableHTML);
?>
The array structure for all the steps in the loop are to keep the default server memory cleaner to remove old data. If you concat ($var .= "string";) everything as strings all the references will stay stored in memory and bog down the server when displaying large tables.
I hope this is of some help

How to translate $url_handlers?

I have a situation where I need to translate the following $url_handlers for different countries.
So on an english site the URL looks like this: http://website.com/gyms/boston/group-training
I need to be able to translate the "group-training" part of the URL. I have translated the rest of the site using the _t() method throughout.
My current setup:
class GymLocationPage_Controller extends Page_Controller {
private static $allowed_actions = array(
'currentSpecials',
'sevenDayFreeTrial',
'groupTraining'
);
private static $url_handlers = array(
'current-specials' => 'currentSpecials',
'trial' => 'sevenDayFreeTrial',
'group-training' => 'groupTraining'
);
}
How would one achieve this?
You could update the config inside the controller's init() function, doing something like this:
public function init() {
parent::init();
// Define your translated actions.
$translatedCurrentSpecials = _t('Actions.CURRENT_SPECIALS', 'aktuella-kampanjer');
$translatedSevenDayFreeTrial = _t('Actions.SEVEN_DAY_TRIAL', 'sjudagars-prova-pa-period');
// Define your url handlers.
$urlHandlers = $this->config()->url_handlers;
$translatedUrlHandlers = [
$translatedCurrentSpecials => 'currentSpecials',
$translatedSevenDayFreeTrial => 'sevenDayFreeTrial'
];
// Update the config.
Config::inst()->update(
$this->class,
'url_handlers',
$translatedUrlHandlers + $urlHandlers // Important to prepend and not append.
);
}

SilverStripe gridfield multi class editor has invalid sort() column

I am having trouble setting the SortOrder of a nested has_many relationship where the child items are drag and drop reorder-able though the Orderable Rows module of Gridfield Extensions. I am also using the Multi Class Editor
I have a Page that has many ComplexStrips. These ComplexStrip objects have many 'LinkedObjects'.
The issue:
When I try to add a ComplexStrip via the GridField I get the following error: Uncaught InvalidArgumentException: Invalid sort() column
My Setup:
Page Class:
This class is working fine when I browse to edit it in the CMS.
<?php
class Page extends SiteTree {
private static $has_many = array(
'ComplexStrips' => 'ComplexStrip'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$dataColumns = new GridFieldDataColumns();
$dataColumns->setDisplayFields(
array(
'Title' => 'Title',
'ClassName' => 'Class Name'
)
);
$multiClassConfig = new GridFieldAddNewMultiClass();
$multiClassConfig->setClasses(
array(
'ComplexStrip'
)
);
$stripsGridField = GridField::create('ComplexStrips', 'Complex strips', $this->Strips(),
GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldDetailForm(),
new GridFieldEditButton(),
new GridFieldDeleteAction('unlinkrelation'),
new GridFieldDeleteAction(),
new GridFieldOrderableRows('SortOrder'), // This line causes the issue
new GridFieldTitleHeader(),
$multiClassConfig,
$dataColumns
)
);
$fields->addFieldsToTab(
'Root.Strips',
array(
$stripsGridField
)
);
return $fields;
}
}
TextBlocksStrip Class:
As soon as I try to add one of these via the gridfield on Page I get the error: Uncaught InvalidArgumentException: Invalid sort() column
<?php
class ComplexStrip extends DataObject {
private static $db = array(
'SortOrder' => 'Int'
);
private static $has_many = array(
'TextBlocks' => 'TextBlock'
);
//-------------------------------------------- CMS Fields
public function getCMSFields() {
$fields = parent::getCMSFields();
//---------------------- Main Tab
$textBlocks = GridField::create('TextBlocks', 'Text blocks', $this->TextBlocks(),
GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldAddNewButton('toolbar-header-right'),
new GridFieldDetailForm(),
new GridFieldDataColumns(),
new GridFieldEditButton(),
new GridFieldDeleteAction('unlinkrelation'),
new GridFieldDeleteAction(),
new GridFieldOrderableRows('SortOrder'),
new GridFieldTitleHeader(),
new GridFieldAddExistingAutocompleter('before', array('Title'))
)
);
$fields->addFieldsToTab('Root.Main',
array(
$textBlocks
)
);
return $fields;
}
}
TextBlock Class:
<?php
class TextBlock extends DataObject {
private static $db = array(
'SortOrder' => 'Int'
);
private static $default_sort = 'Sort';
private static $has_one = array(
'TextBlocksStrip' => 'TextBlocksStrip'
);
}
If I remove the line new GridFieldOrderableRows('SortOrder') all works but is obviously not reorder-able.
I am pulling my hair out over this one. Makes no sense to me why this isn't working.
I have made a fairly elegant workaround.
The SortOrder could not be queried as the parent Object ComplexStrip doesn't exist at the time it is attempting to join the sorted table. So wrapping the GridFieldOrderableRows in an if to check if the parent object has been assigned an ID yet.
// Need to wait until parent object is created before trying to set sort order
if($this->ID) {
$textBlocks->addComponents(
new GridFieldOrderableRows('Sort')
);
}
After that everything works the same as before in the CMS. I will open an issue on the module now to see if there is a more permanent solution.
I had the same error as I was using $many_many instead of $has_many. I can see you used $has_many so wouldn't solve your issue but might help others encountering the same error message like I was.

Symfony 2 Sonata admin list views do not display subclasses

Currently I cant get subclasses to appear in a list view using sonta admin bundle for symfony 2
I can get it working for create forms as per the advanced config page (http://sonata-project.org/bundles/admin/2-1/doc/reference/advance.html) but how can you do this with the list view?
If i pass the subclass in the url - list?subclass=MySubClassName
and set the object in my listAction
$object = $this->admin->getNewInstance();
$this->admin->setSubject($object);
I can get the subject and configure the correct fields with configureListFields()
if ($subject instanceof MySubClassName) {
$listMapper->add('MySubClassNameID');
$listMapper->add('MySubClassNameKey');
$listMapper->add('MySubClassNameStatus','text');
}
but the end results table is always blank and the symfony debug toolbar seems to show that the db queries are looking for the parent class. Anyone got this to work?
I'm not sure what you mean with those "subclasses" in the list view, but if you want to add a field form another entity (connected through a foreign key with yours) you can do it lie this:
$listMapper
->addIdentifier('id')
->addIdentifier('title')
->add('name')
->add('entity1.customField1')
->add('entity2.customField2');
Incase anyone else faces this I found out how to do this.
To make it work in a way similar to the edit page you would pass the subclass in the url
...list?subclass=MySubClass
set the subject of your listAction in your custom admin crud controller
public function listAction()
{
if (false === $this->admin->isGranted('LIST')) {
throw new AccessDeniedException();
}
if ($listMode = $this->getRequest()->get('_list_mode')) {
$this->admin->setListMode($listMode);
}
$this->admin->setSubject($this->admin->getNewInstance());
$datagrid = $this->admin->getDatagrid();
$formView = $datagrid->getForm()->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
return $this->render($this->admin->getTemplate('list'), array(
'action' => 'list',
'form' => $formView,
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
));
}
and then over-ride the createQuery method in your Admin class
public function createQuery($context = 'list')
{
$cName = get_class($this->getSubject());
$query = $this->getModelManager()->createQuery($cName);
foreach ($this->extensions as $extension) {
$extension->configureQuery($this, $query, $context);
}
return $query;
}
If you pass anything with url parameters you should also override getPersistentParameters to add your url request to Pager, FilterForm and the form for batchActions (or others that appear on the list view)
<?php
class YourAdmin extends Admin
{
public function getPersistentParameters()
{
if (!$this->getRequest()) {
return array();
}
return array(
'subclass' => $this->getRequest()->get('subclass'),
);
}
}

Resources