API Implement upgrader cleanup, array declaration changes, class injection, rename some models

This commit is contained in:
Robbie Averill 2017-08-11 11:33:06 +12:00
parent eaf374adc5
commit 0008ffaf01
50 changed files with 868 additions and 1588 deletions

View File

@ -2,19 +2,12 @@
namespace SilverStripe\UserForms\Extension; namespace SilverStripe\UserForms\Extension;
use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
use SilverStripe\ORM\DB;
use SilverStripe\Assets\Folder; use SilverStripe\Assets\Folder;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DB;
use SilverStripe\Security\Group; use SilverStripe\Security\Group;
use SilverStripe\Security\Permission; use SilverStripe\Security\Permission;
use SilverStripe\ORM\DataExtension; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
/** /**
* Provides additional file security for uploaded files when the securefiles module is installed * Provides additional file security for uploaded files when the securefiles module is installed

View File

@ -2,45 +2,26 @@
namespace SilverStripe\UserForms\Extension; namespace SilverStripe\UserForms\Extension;
use GridFieldEditableColumns;
use GridFieldOrderableRows;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Tab; use SilverStripe\Forms\Tab;
use SilverStripe\View\Requirements; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\UserForms\Form\GridFieldAddClassesButton;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\Forms\GridField\GridFieldEditButton; use SilverStripe\Forms\GridField\GridFieldEditButton;
use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldDetailForm; use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Versioned\Versioned;
use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataExtension;
use SilverStripe\UserForms\Form\GridFieldAddClassesButton;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\UserForms\Model\EditableFormField\EditableTextField;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\Requirements;
use Symbiote\GridFieldExtensions\GridFieldEditableColumns;
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;
/** /**
* @package userforms * @package userforms
@ -64,7 +45,7 @@ class UserFormFieldEditorExtension extends DataExtension
{ {
$fieldEditor = $this->getFieldEditorGrid(); $fieldEditor = $this->getFieldEditorGrid();
$fields->insertAfter(new Tab('FormFields', _t('UserFormFieldEditorExtension.FORMFIELDS', 'Form Fields')), 'Main'); $fields->insertAfter(new Tab('FormFields', _t(__CLASS__.'.FORMFIELDS', 'Form Fields')), 'Main');
$fields->addFieldToTab('Root.FormFields', $fieldEditor); $fields->addFieldToTab('Root.FormFields', $fieldEditor);
return $fields; return $fields;
@ -103,12 +84,12 @@ class UserFormFieldEditorExtension extends DataExtension
$editableColumns, $editableColumns,
new GridFieldButtonRow(), new GridFieldButtonRow(),
GridFieldAddClassesButton::create(EditableTextField::class) GridFieldAddClassesButton::create(EditableTextField::class)
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD', 'Add Field')) ->setButtonName(_t(__CLASS__.'.ADD_FIELD', 'Add Field'))
->setButtonClass('ss-ui-action-constructive'), ->setButtonClass('ss-ui-action-constructive'),
GridFieldAddClassesButton::create(EditableFormStep::class) GridFieldAddClassesButton::create(EditableFormStep::class)
->setButtonName(_t('UserFormFieldEditorExtension.ADD_PAGE_BREAK', 'Add Page Break')), ->setButtonName(_t(__CLASS__.'.ADD_PAGE_BREAK', 'Add Page Break')),
GridFieldAddClassesButton::create(array(EditableFieldGroup::class, EditableFieldGroupEnd::class)) GridFieldAddClassesButton::create(array(EditableFieldGroup::class, EditableFieldGroupEnd::class))
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD_GROUP', 'Add Field Group')), ->setButtonName(_t(__CLASS__.'.ADD_FIELD_GROUP', 'Add Field Group')),
new GridFieldEditButton(), new GridFieldEditButton(),
new GridFieldDeleteAction(), new GridFieldDeleteAction(),
new GridFieldToolbarHeader(), new GridFieldToolbarHeader(),
@ -118,7 +99,7 @@ class UserFormFieldEditorExtension extends DataExtension
$fieldEditor = GridField::create( $fieldEditor = GridField::create(
'Fields', 'Fields',
_t('UserDefinedForm.FIELDS', 'Fields'), _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.FIELDS', 'Fields'),
$fields, $fields,
$config $config
)->addExtraClass('uf-field-editor'); )->addExtraClass('uf-field-editor');
@ -162,7 +143,7 @@ class UserFormFieldEditorExtension extends DataExtension
// Add step // Add step
$step = EditableFormStep::create(); $step = EditableFormStep::create();
$step->Title = _t('EditableFormStep.TITLE_FIRST', 'First Page'); $step->Title = _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST', 'First Page');
$step->Sort = 1; $step->Sort = 1;
$step->write(); $step->write();
$fields->add($step); $fields->add($step);
@ -190,7 +171,7 @@ class UserFormFieldEditorExtension extends DataExtension
foreach ($this->owner->Fields() as $field) { foreach ($this->owner->Fields() as $field) {
// store any IDs of fields we publish so we don't unpublish them // store any IDs of fields we publish so we don't unpublish them
$seenIDs[] = $field->ID; $seenIDs[] = $field->ID;
$field->doPublish('Stage', 'Live'); $field->publishRecursive();
$field->destroy(); $field->destroy();
} }
@ -296,7 +277,7 @@ class UserFormFieldEditorExtension extends DataExtension
public function onAfterRevertToLive($page) public function onAfterRevertToLive($page)
{ {
foreach ($page->Fields() as $field) { foreach ($page->Fields() as $field) {
$field->publish('Live', 'Stage', false); $field->copyVersionToStage('Live', 'Stage', false);
$field->writeWithoutVersion(); $field->writeWithoutVersion();
} }
} }

View File

@ -2,19 +2,11 @@
namespace SilverStripe\UserForms\Extension; namespace SilverStripe\UserForms\Extension;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\Forms\RequiredFields; use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
class UserFormValidator extends RequiredFields class UserFormValidator extends RequiredFields
{ {
@ -46,7 +38,7 @@ class UserFormValidator extends RequiredFields
$this->validationError( $this->validationError(
'FormFields', 'FormFields',
_t( _t(
"UserFormValidator.UNEXPECTED_BREAK", __CLASS__.".UNEXPECTED_BREAK",
"Unexpected page break '{name}' inside nested field '{group}'", "Unexpected page break '{name}' inside nested field '{group}'",
array( array(
'name' => $field->CMSTitle, 'name' => $field->CMSTitle,
@ -63,7 +55,7 @@ class UserFormValidator extends RequiredFields
$this->validationError( $this->validationError(
'FormFields', 'FormFields',
_t( _t(
"UserFormValidator.NO_PAGE", __CLASS__.".NO_PAGE",
"Field '{name}' found before any pages", "Field '{name}' found before any pages",
array( array(
'name' => $field->CMSTitle 'name' => $field->CMSTitle
@ -89,7 +81,7 @@ class UserFormValidator extends RequiredFields
$this->validationError( $this->validationError(
'FormFields', 'FormFields',
_t( _t(
"UserFormValidator.UNEXPECTED_GROUP_END", __CLASS__.".UNEXPECTED_GROUP_END",
"'{name}' found without a matching group", "'{name}' found without a matching group",
array( array(
'name' => $field->CMSTitle 'name' => $field->CMSTitle
@ -105,7 +97,7 @@ class UserFormValidator extends RequiredFields
$this->validationError( $this->validationError(
'FormFields', 'FormFields',
_t( _t(
"UserFormValidator.WRONG_GROUP_END", __CLASS__.".WRONG_GROUP_END",
"'{name}' found closes the wrong group '{group}'", "'{name}' found closes the wrong group '{group}'",
array( array(
'name' => $field->CMSTitle, 'name' => $field->CMSTitle,
@ -126,7 +118,7 @@ class UserFormValidator extends RequiredFields
$this->validationError( $this->validationError(
'FormFields', 'FormFields',
_t( _t(
"UserFormValidator.CONDITIONAL_REQUIRED", __CLASS__.".CONDITIONAL_REQUIRED",
"Required field '{name}' cannot be placed within a conditional page", "Required field '{name}' cannot be placed within a conditional page",
array( array(
'name' => $field->CMSTitle 'name' => $field->CMSTitle

View File

@ -2,26 +2,17 @@
namespace SilverStripe\UserForms\Form; namespace SilverStripe\UserForms\Form;
use Object;
use SilverStripe\Forms\GridField\GridField_FormAction;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Control\HTTPResponse_Exception; use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Forms\GridField\GridField_HTMLProvider; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridField_ActionProvider; use SilverStripe\Forms\GridField\GridField_ActionProvider;
use SilverStripe\Forms\GridField\GridField_FormAction;
use SilverStripe\Forms\GridField\GridField_HTMLProvider;
/** /**
* A button which allows objects to be created with a specified classname(s) * A button which allows objects to be created with a specified classname(s)
*/ */
class GridFieldAddClassesButton extends Object implements GridField_HTMLProvider, GridField_ActionProvider class GridFieldAddClassesButton implements GridField_HTMLProvider, GridField_ActionProvider
{ {
/** /**
* Name of fragment to insert into * Name of fragment to insert into
* *
@ -186,7 +177,7 @@ class GridFieldAddClassesButton extends Object implements GridField_HTMLProvider
if (!$buttonName) { if (!$buttonName) {
// provide a default button name, can be changed by calling {@link setButtonName()} on this component // provide a default button name, can be changed by calling {@link setButtonName()} on this component
$objectName = $singleton->i18n_singular_name(); $objectName = $singleton->i18n_singular_name();
$buttonName = _t('GridField.Add', 'Add {name}', array('name' => $objectName)); $buttonName = _t('SilverStripe\\Forms\\GridField\\GridField.Add', 'Add {name}', array('name' => $objectName));
} }
$addAction = new GridField_FormAction( $addAction = new GridField_FormAction(

View File

@ -2,32 +2,21 @@
namespace SilverStripe\UserForms\Form; namespace SilverStripe\UserForms\Form;
use ResetFormAction; use ResetFormAction;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FieldList;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\UserForms\FormField\UserFormsStepField; use SilverStripe\Forms\FieldList;
use SilverStripe\UserForms\FormField\UserFormsFieldList; use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction; use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\RequiredFields; use SilverStripe\Forms\RequiredFields;
use SilverStripe\UserForms\FormField\UserFormsStepField;
use SilverStripe\UserForms\FormField\UserFormsFieldList;
/** /**
* @package userforms * @package userforms
*/ */
class UserForm extends Form class UserForm extends Form
{ {
/** /**
* @param Controller $controller * @param Controller $controller
* @param string $name * @param string $name
@ -145,8 +134,8 @@ class UserForm extends Form
*/ */
public function getFormActions() public function getFormActions()
{ {
$submitText = ($this->controller->SubmitButtonText) ? $this->controller->SubmitButtonText : _t('UserDefinedForm.SUBMITBUTTON', 'Submit'); $submitText = ($this->controller->SubmitButtonText) ? $this->controller->SubmitButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SUBMITBUTTON', 'Submit');
$clearText = ($this->controller->ClearButtonText) ? $this->controller->ClearButtonText : _t('UserDefinedForm.CLEARBUTTON', 'Clear'); $clearText = ($this->controller->ClearButtonText) ? $this->controller->ClearButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.CLEARBUTTON', 'Clear');
$actions = new FieldList( $actions = new FieldList(
new FormAction("process", $submitText) new FormAction("process", $submitText)

View File

@ -2,32 +2,18 @@
namespace SilverStripe\UserForms\Form; namespace SilverStripe\UserForms\Form;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\DateField;
use SilverStripe\Forms\GridField\GridField_FormAction;
use SilverStripe\View\ArrayData;
use SilverStripe\ORM\SS_List;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\DateField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridField_FormAction;
use SilverStripe\Forms\GridField\GridFieldFilterHeader; use SilverStripe\Forms\GridField\GridFieldFilterHeader;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\SS_List;
use SilverStripe\View\ArrayData;
/** /**
* Extension to the build in SilverStripe {@link GridField} to allow for * Extension to the build in SilverStripe {@link GridField} to allow for
@ -38,7 +24,6 @@ use SilverStripe\Forms\GridField\GridFieldFilterHeader;
*/ */
class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
{ {
/** /**
* A map of name => value of columns from all submissions * A map of name => value of columns from all submissions
* @var array * @var array
@ -69,7 +54,7 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
public function getHTMLFragments($gridField) public function getHTMLFragments($gridField)
{ {
$fields = new ArrayList(); $fields = ArrayList::create();
$state = $gridField->State->UserFormsGridField; $state = $gridField->State->UserFormsGridField;
$selectedField = $state->filter; $selectedField = $state->filter;
@ -77,13 +62,13 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
// show dropdown of all the fields available from the submitted form fields // show dropdown of all the fields available from the submitted form fields
// that have been saved. Takes the titles from the currently live form. // that have been saved. Takes the titles from the currently live form.
$columnField = new DropdownField('FieldNameFilter', ''); $columnField = DropdownField::create('FieldNameFilter', '');
$columnField->setSource($this->columns); $columnField->setSource($this->columns);
$columnField->setEmptyString(_t('UserFormsGridFieldFilterHeader.FILTERSUBMISSIONS', 'Filter Submissions..')); $columnField->setEmptyString(_t(__CLASS__.'.FILTERSUBMISSIONS', 'Filter Submissions..'));
$columnField->setHasEmptyDefault(true); $columnField->setHasEmptyDefault(true);
$columnField->setValue($selectedField); $columnField->setValue($selectedField);
$valueField = new TextField('FieldValue', '', $selectedValue); $valueField = TextField::create('FieldValue', '', $selectedValue);
$columnField->addExtraClass('ss-gridfield-sort'); $columnField->addExtraClass('ss-gridfield-sort');
$columnField->addExtraClass('no-change-track'); $columnField->addExtraClass('no-change-track');
@ -92,17 +77,17 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
$valueField->addExtraClass('no-change-track'); $valueField->addExtraClass('no-change-track');
$valueField->setAttribute( $valueField->setAttribute(
'placeholder', 'placeholder',
_t('UserFormsGridFieldFilterHeader.WHEREVALUEIS', 'where value is..' _t(__CLASS__.'.WHEREVALUEIS', 'where value is..'
)); ));
$fields->push(new FieldGroup(new CompositeField( $fields->push(FieldGroup::create(CompositeField::create(
$columnField, $columnField,
$valueField $valueField
))); )));
$fields->push(new FieldGroup(new CompositeField( $fields->push(FieldGroup::create(CompositeField::create(
$start = new DateField('StartFilter', _t('UserFormsGridFieldFilterHeader.FROM', 'From')), $start = DateField::create('StartFilter', _t(__CLASS__.'.FROM', 'From')),
$end = new DateField('EndFilter', _t('UserFormsGridFieldFilterHeader.TILL', 'Till')) $end = DateField::create('EndFilter', _t(__CLASS__.'.TILL', 'Till'))
))); )));
foreach (array($start, $end) as $date) { foreach (array($start, $end) as $date) {
@ -116,7 +101,7 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
$start->setValue($state->start); $start->setValue($state->start);
$fields->push($actions = new FieldGroup( $fields->push($actions = FieldGroup::create(
GridField_FormAction::create($gridField, 'filter', false, 'filter', null) GridField_FormAction::create($gridField, 'filter', false, 'filter', null)
->addExtraClass('ss-gridfield-button-filter') ->addExtraClass('ss-gridfield-button-filter')
->setAttribute('title', _t('GridField.Filter', "Filter")) ->setAttribute('title', _t('GridField.Filter', "Filter"))
@ -131,7 +116,7 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
$actions->addExtraClass('filter-buttons'); $actions->addExtraClass('filter-buttons');
$actions->addExtraClass('no-change-track'); $actions->addExtraClass('no-change-track');
$forTemplate = new ArrayData(array( $forTemplate = ArrayData::create(array(
'Fields' => $fields 'Fields' => $fields
)); ));

View File

@ -2,11 +2,8 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
use SilverStripe\Forms\CheckboxSetField; use SilverStripe\Forms\CheckboxSetField;
/** /**
* @package userforms * @package userforms
*/ */

View File

@ -2,14 +2,9 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
use SilverStripe\Forms\CompositeField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\Forms\CompositeField;
/** /**
* Represents a composite field group, which may contain other groups * Represents a composite field group, which may contain other groups

View File

@ -2,11 +2,8 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
/** /**
* Represents a field container which can iteratively process nested fields, converting it into a fieldset * Represents a field container which can iteratively process nested fields, converting it into a fieldset
*/ */

View File

@ -2,19 +2,14 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
/** /**
* A list of formfields which allows for iterative processing of nested composite fields * A list of formfields which allows for iterative processing of nested composite fields
*/ */
class UserFormsFieldList extends FieldList implements UserFormsFieldContainer class UserFormsFieldList extends FieldList implements UserFormsFieldContainer
{ {
public function processNext(EditableFormField $field) public function processNext(EditableFormField $field)
{ {
$formField = $field->getFormField(); $formField = $field->getFormField();

View File

@ -2,19 +2,14 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
/** /**
* Front end composite field for userforms * Front end composite field for userforms
*/ */
class UserFormsGroupField extends UserFormsCompositeField class UserFormsGroupField extends UserFormsCompositeField
{ {
public function __construct($children = null) public function __construct($children = null)
{ {
parent::__construct($children); parent::__construct($children);

View File

@ -2,18 +2,14 @@
namespace SilverStripe\UserForms\FormField; namespace SilverStripe\UserForms\FormField;
/** /**
* Represents a page step in a form, which may contain form fields or other groups * Represents a page step in a form, which may contain form fields or other groups
*/ */
class UserFormsStepField extends UserFormsCompositeField class UserFormsStepField extends UserFormsCompositeField
{ {
private static $casting = [
private static $casting = array(
'StepNumber' => 'Int' 'StepNumber' => 'Int'
); ];
/** /**
* Numeric index (1 based) of this step * Numeric index (1 based) of this step
@ -24,7 +20,7 @@ class UserFormsStepField extends UserFormsCompositeField
*/ */
protected $number = null; protected $number = null;
public function FieldHolder($properties = array()) public function FieldHolder($properties = [])
{ {
return $this->Field($properties); return $this->Field($properties);
} }

View File

@ -1,29 +0,0 @@
<?php
namespace SilverStripe\UserForms\FormField;
use SilverStripe\Security\Group;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\TreeDropdownField;
/**
* {@link TreeDropdownField} subclass for handling loading folders through the
* nested {@link FormField} instances of the {@link FieldEditor}
*
* @deprecated since version 4.0
* @package userforms
*/
class UserformsTreeDropdownField extends TreeDropdownField
{
public function __construct($name, $title = null, $sourceObject = Group::class, $keyField = 'ID', $labelField = 'TreeTitle', $showSearch = true)
{
parent::__construct($name, $title, $sourceObject, $keyField, $labelField, $showSearch);
Deprecation::notice('4.0', __CLASS__ . " is deprecated");
}
}

View File

@ -2,18 +2,13 @@
namespace SilverStripe\UserForms\Model; namespace SilverStripe\UserForms\Model;
use LogicException; use LogicException;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\Control\Controller;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Control\Controller;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use Silverstripe\Versioned\Versioned;
/** /**
* A custom rule for showing / hiding an EditableFormField * A custom rule for showing / hiding an EditableFormField
@ -28,28 +23,27 @@ use SilverStripe\ORM\DataObject;
*/ */
class EditableCustomRule extends DataObject class EditableCustomRule extends DataObject
{ {
private static $condition_options = [
'IsBlank' => 'Is blank',
'IsNotBlank' => 'Is not blank',
'HasValue' => 'Equals',
'ValueNot' => 'Doesn\'t equal',
'ValueLessThan' => 'Less than',
'ValueLessThanEqual' => 'Less than or equal',
'ValueGreaterThan' => 'Greater than',
'ValueGreaterThanEqual' => 'Greater than or equal'
];
private static $condition_options = array( private static $db = [
"IsBlank" => "Is blank",
"IsNotBlank" => "Is not blank",
"HasValue" => "Equals",
"ValueNot" => "Doesn't equal",
"ValueLessThan" => "Less than",
"ValueLessThanEqual" => "Less than or equal",
"ValueGreaterThan" => "Greater than",
"ValueGreaterThanEqual" => "Greater than or equal"
);
private static $db = array(
'Display' => 'Enum("Show,Hide")', 'Display' => 'Enum("Show,Hide")',
'ConditionOption' => 'Enum("IsBlank,IsNotBlank,HasValue,ValueNot,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual")', 'ConditionOption' => 'Enum("IsBlank,IsNotBlank,HasValue,ValueNot,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual")',
'FieldValue' => 'Varchar(255)' 'FieldValue' => 'Varchar(255)'
); ];
private static $has_one = array( private static $has_one = [
'Parent' => EditableFormField::class, 'Parent' => EditableFormField::class,
'ConditionField' => EditableFormField::class 'ConditionField' => EditableFormField::class
); ];
/** /**
* Built in extensions required * Built in extensions required
@ -57,9 +51,11 @@ class EditableCustomRule extends DataObject
* @config * @config
* @var array * @var array
*/ */
private static $extensions = array( private static $extensions = [
"Versioned('Stage', 'Live')" Versioned::class . "('Stage', 'Live')"
); ];
private static $table_name = 'EditableCustomRule';
/** /**
* Publish this custom rule to the live site * Publish this custom rule to the live site
@ -184,12 +180,13 @@ class EditableCustomRule extends DataObject
$target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly()); $target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly());
$fieldValue = Convert::raw2js($this->FieldValue); $fieldValue = Convert::raw2js($this->FieldValue);
$conditionOptions = array( $conditionOptions = [
'ValueLessThan' => '<', 'ValueLessThan' => '<',
'ValueLessThanEqual' => '<=', 'ValueLessThanEqual' => '<=',
'ValueGreaterThan' => '>', 'ValueGreaterThan' => '>',
'ValueGreaterThanEqual' => '>=' 'ValueGreaterThanEqual' => '>='
); ];
// and what should we evaluate // and what should we evaluate
switch ($this->ConditionOption) { switch ($this->ConditionOption) {
case 'IsNotBlank': case 'IsNotBlank':
@ -244,10 +241,10 @@ class EditableCustomRule extends DataObject
break; break;
} }
$result = array( $result = [
'operation' => $expression, 'operation' => $expression,
'event' => $action, 'event' => $action,
); ];
return $result; return $result;
} }

View File

@ -2,77 +2,44 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\SegmentField;
use GridFieldEditableColumns;
use GridFieldAddNewInlineButton;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\TextField;
use SilverStripe\UserForms\Modifier\UnderscoreSegmentFieldModifier;
use SilverStripe\UserForms\Modifier\DisambiguationSegmentFieldModifier;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\LabelField;
use SilverStripe\Core\Config\Config;
use SilverStripe\UserForms\Model\EditableCustomRule;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Control\Controller;
use SilverStripe\CMS\Controllers\CMSPageEditController;
use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Versioned\Versioned; use SilverStripe\CMS\Controllers\CMSPageEditController;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField; use SilverStripe\Control\Controller;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Core\Convert;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\UserForms\Model\Submission\SubmittedFormField;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\Core\ClassInfo; use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\Forms\SegmentField;
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\ValidationException;
use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\UserForms\Model\EditableCustomRule;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep;
use SilverStripe\UserForms\Model\Submission\SubmittedFormField;
use SilverStripe\UserForms\Modifier\DisambiguationSegmentFieldModifier;
use SilverStripe\UserForms\Modifier\UnderscoreSegmentFieldModifier;
use SilverStripe\Versioned\Versioned;
use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton;
use Symbiote\GridFieldExtensions\GridFieldEditableColumns;
/** /**
* Represents the base class of a editable form field * Represents the base class of a editable form field
@ -94,7 +61,6 @@ use SilverStripe\ORM\DataObject;
*/ */
class EditableFormField extends DataObject class EditableFormField extends DataObject
{ {
/** /**
* Set to true to hide from class selector * Set to true to hide from class selector
* *
@ -132,7 +98,7 @@ class EditableFormField extends DataObject
* *
* @var array * @var array
*/ */
public static $allowed_css = array(); public static $allowed_css = [];
/** /**
* Set this to true to enable placeholder field for any given class * Set this to true to enable placeholder field for any given class
@ -145,47 +111,49 @@ class EditableFormField extends DataObject
* @config * @config
* @var array * @var array
*/ */
private static $summary_fields = array( private static $summary_fields = [
'Title' 'Title'
); ];
/** /**
* @config * @config
* @var array * @var array
*/ */
private static $db = array( private static $db = [
"Name" => "Varchar", 'Name' => 'Varchar',
"Title" => "Varchar(255)", 'Title' => 'Varchar(255)',
"Default" => "Varchar(255)", 'Default' => 'Varchar(255)',
"Sort" => "Int", 'Sort' => 'Int',
"Required" => "Boolean", 'Required' => 'Boolean',
"CustomErrorMessage" => "Varchar(255)", 'CustomErrorMessage' => 'Varchar(255)',
"CustomRules" => "Text", // @deprecated from 2.0 'CustomRules' => 'Text', // @deprecated from 2.0
"CustomSettings" => "Text", // @deprecated from 2.0 'CustomSettings' => 'Text', // @deprecated from 2.0
"Migrated" => "Boolean", // set to true when migrated 'Migrated' => 'Boolean', // set to true when migrated
"ExtraClass" => "Text", // from CustomSettings 'ExtraClass' => 'Text', // from CustomSettings
"RightTitle" => "Varchar(255)", // from CustomSettings 'RightTitle' => 'Varchar(255)', // from CustomSettings
"ShowOnLoad" => "Boolean(1)", // from CustomSettings 'ShowOnLoad' => 'Boolean(1)', // from CustomSettings
"ShowInSummary" => "Boolean", 'ShowInSummary' => 'Boolean',
"Placeholder" => "Varchar(255)", 'Placeholder' => 'Varchar(255)',
'DisplayRulesConjunction' => 'Enum("And,Or","Or")', 'DisplayRulesConjunction' => 'Enum("And,Or","Or")',
); ];
private static $table_name = 'EditableFormField';
private static $defaults = array( private static $defaults = [
'ShowOnLoad' => true, 'ShowOnLoad' => true,
); ];
/** /**
* @config * @config
* @var array * @var array
*/ */
private static $has_one = array( private static $has_one = [
"Parent" => UserDefinedForm::class, 'Parent' => UserDefinedForm::class,
); ];
/** /**
* Built in extensions required * Built in extensions required
@ -193,17 +161,17 @@ class EditableFormField extends DataObject
* @config * @config
* @var array * @var array
*/ */
private static $extensions = array( private static $extensions = [
"Versioned('Stage', 'Live')" Versioned::class . "('Stage', 'Live')"
); ];
/** /**
* @config * @config
* @var array * @var array
*/ */
private static $has_many = array( private static $has_many = [
"DisplayRules" => "EditableCustomRule.Parent" // from CustomRules 'DisplayRules' => EditableCustomRule::class . '.Parent'
); ];
/** /**
* @var bool * @var bool
@ -251,44 +219,44 @@ class EditableFormField extends DataObject
*/ */
public function getCMSFields() public function getCMSFields()
{ {
$fields = new FieldList(new TabSet('Root')); $fields = FieldList::create(TabSet::create('Root'));
// Main tab // Main tab
$fields->addFieldsToTab( $fields->addFieldsToTab(
'Root.Main', 'Root.Main',
array( [
ReadonlyField::create( ReadonlyField::create(
'Type', 'Type',
_t('EditableFormField.TYPE', 'Type'), _t(__CLASS__.'.TYPE', 'Type'),
$this->i18n_singular_name() $this->i18n_singular_name()
), ),
CheckboxField::create('ShowInSummary', _t('EditableFormField.SHOWINSUMMARY', 'Show in summary gridfield')), CheckboxField::create('ShowInSummary', _t(__CLASS__.'.SHOWINSUMMARY', 'Show in summary gridfield')),
LiteralField::create( LiteralField::create(
'MergeField', 'MergeField',
_t( _t(
'EditableFormField.MERGEFIELDNAME', __CLASS__.'.MERGEFIELDNAME',
'<div class="field readonly">' . '<div class="field readonly">' .
'<label class="left">' . _t('EditableFormField.MERGEFIELDNAME', 'Merge field') . '</label>' . '<label class="left">' . _t(__CLASS__.'.MERGEFIELDNAME', 'Merge field') . '</label>' .
'<div class="middleColumn">' . '<div class="middleColumn">' .
'<span class="readonly">$' . $this->Name . '</span>' . '<span class="readonly">$' . $this->Name . '</span>' .
'</div>' . '</div>' .
'</div>' '</div>'
) )
), ),
TextField::create('Title', _t('EditableFormField.TITLE', 'Title')), TextField::create('Title', _t(__CLASS__.'.TITLE', 'Title')),
TextField::create('Default', _t('EditableFormField.DEFAULT', 'Default value')), TextField::create('Default', _t(__CLASS__.'.DEFAULT', 'Default value')),
TextField::create('RightTitle', _t('EditableFormField.RIGHTTITLE', 'Right title')), TextField::create('RightTitle', _t(__CLASS__.'.RIGHTTITLE', 'Right title')),
SegmentField::create('Name', _t('EditableFormField.NAME', 'Name'))->setModifiers(array( SegmentField::create('Name', _t(__CLASS__.'.NAME', 'Name'))->setModifiers([
UnderscoreSegmentFieldModifier::create()->setDefault('FieldName'), UnderscoreSegmentFieldModifier::create()->setDefault('FieldName'),
DisambiguationSegmentFieldModifier::create(), DisambiguationSegmentFieldModifier::create(),
))->setPreview($this->Name) ])->setPreview($this->Name)
) ]
); );
$fields->fieldByName('Root.Main')->setTitle(_t('SiteTree.TABMAIN', 'Main')); $fields->fieldByName('Root.Main')->setTitle(_t('SilverStripe\\CMS\\Model\\SiteTree.TABMAIN', 'Main'));
// Custom settings // Custom settings
if (!empty(self::$allowed_css)) { if (!empty(self::$allowed_css)) {
$cssList = array(); $cssList = [];
foreach (self::$allowed_css as $k => $v) { foreach (self::$allowed_css as $k => $v) {
if (!is_array($v)) { if (!is_array($v)) {
$cssList[$k]=$v; $cssList[$k]=$v;
@ -300,10 +268,10 @@ class EditableFormField extends DataObject
$fields->addFieldToTab('Root.Main', $fields->addFieldToTab('Root.Main',
DropdownField::create( DropdownField::create(
'ExtraClass', 'ExtraClass',
_t('EditableFormField.EXTRACLASS_TITLE', 'Extra Styling/Layout'), _t(__CLASS__.'.EXTRACLASS_TITLE', 'Extra Styling/Layout'),
$cssList $cssList
)->setDescription(_t( )->setDescription(_t(
'EditableFormField.EXTRACLASS_SELECT', __CLASS__.'.EXTRACLASS_SELECT',
'Select from the list of allowed styles' 'Select from the list of allowed styles'
)) ))
); );
@ -311,9 +279,9 @@ class EditableFormField extends DataObject
$fields->addFieldToTab('Root.Main', $fields->addFieldToTab('Root.Main',
TextField::create( TextField::create(
'ExtraClass', 'ExtraClass',
_t('EditableFormField.EXTRACLASS_Title', 'Extra CSS classes') _t(__CLASS__.'.EXTRACLASS_Title', 'Extra CSS classes')
)->setDescription(_t( )->setDescription(_t(
'EditableFormField.EXTRACLASS_MULTIPLE', __CLASS__.'.EXTRACLASS_MULTIPLE',
'Separate each CSS class with a single space' 'Separate each CSS class with a single space'
)) ))
); );
@ -323,7 +291,7 @@ class EditableFormField extends DataObject
$validationFields = $this->getFieldValidationOptions(); $validationFields = $this->getFieldValidationOptions();
if ($validationFields && $validationFields->count()) { if ($validationFields && $validationFields->count()) {
$fields->addFieldsToTab('Root.Validation', $validationFields); $fields->addFieldsToTab('Root.Validation', $validationFields);
$fields->fieldByName('Root.Validation')->setTitle(_t('EditableFormField.VALIDATION', 'Validation')); $fields->fieldByName('Root.Validation')->setTitle(_t(__CLASS__.'.VALIDATION', 'Validation'));
} }
// Add display rule fields // Add display rule fields
@ -338,7 +306,7 @@ class EditableFormField extends DataObject
'Root.Main', 'Root.Main',
TextField::create( TextField::create(
'Placeholder', 'Placeholder',
_t('EditableFormField.PLACEHOLDER', 'Placeholder') _t(__CLASS__.'.PLACEHOLDER', 'Placeholder')
) )
); );
} }
@ -360,21 +328,21 @@ class EditableFormField extends DataObject
return new FieldList( return new FieldList(
LabelField::create( LabelField::create(
_t( _t(
'EditableFormField.DISPLAY_RULES_DISABLED', __CLASS__.'.DISPLAY_RULES_DISABLED',
'Display rules are not enabled for required fields. Please uncheck "Is this field Required?" under "Validation" to re-enable.')) 'Display rules are not enabled for required fields. Please uncheck "Is this field Required?" under "Validation" to re-enable.'))
->addExtraClass('message warning')); ->addExtraClass('message warning'));
} }
$self = $this;
$allowedClasses = array_keys($this->getEditableFieldClasses(false)); $allowedClasses = array_keys($this->getEditableFieldClasses(false));
$editableColumns = new GridFieldEditableColumns(); $editableColumns = new GridFieldEditableColumns();
$editableColumns->setDisplayFields(array( $editableColumns->setDisplayFields([
'ConditionFieldID' => function ($record, $column, $grid) use ($allowedClasses, $self) { 'ConditionFieldID' => function ($record, $column, $grid) use ($allowedClasses) {
return DropdownField::create($column, '', EditableFormField::get()->filter(array( return DropdownField::create($column, '', EditableFormField::get()->filter([
'ParentID' => $self->ParentID, 'ParentID' => $this->ParentID,
'ClassName' => $allowedClasses, 'ClassName' => $allowedClasses,
))->exclude(array( ])->exclude([
'ID' => $self->ID, 'ID' => $this->ID,
))->map('ID', 'Title')); ])->map('ID', 'Title'));
}, },
'ConditionOption' => function ($record, $column, $grid) { 'ConditionOption' => function ($record, $column, $grid) {
$options = Config::inst()->get(EditableCustomRule::class, 'condition_options'); $options = Config::inst()->get(EditableCustomRule::class, 'condition_options');
@ -384,7 +352,7 @@ class EditableFormField extends DataObject
'FieldValue' => function ($record, $column, $grid) { 'FieldValue' => function ($record, $column, $grid) {
return TextField::create($column); return TextField::create($column);
} }
)); ]);
// Custom rules // Custom rules
$customRulesConfig = GridFieldConfig::create() $customRulesConfig = GridFieldConfig::create()
@ -398,22 +366,22 @@ class EditableFormField extends DataObject
return new FieldList( return new FieldList(
DropdownField::create('ShowOnLoad', DropdownField::create('ShowOnLoad',
_t('EditableFormField.INITIALVISIBILITY', 'Initial visibility'), _t(__CLASS__.'.INITIALVISIBILITY', 'Initial visibility'),
array( [
1 => 'Show', 1 => 'Show',
0 => 'Hide', 0 => 'Hide',
) ]
), ),
DropdownField::create('DisplayRulesConjunction', DropdownField::create('DisplayRulesConjunction',
_t('EditableFormField.DISPLAYIF', 'Toggle visibility when'), _t(__CLASS__.'.DISPLAYIF', 'Toggle visibility when'),
array( [
'Or' => _t('UserDefinedForm.SENDIFOR', 'Any conditions are true'), 'Or' => _t('UserDefinedForm.SENDIFOR', 'Any conditions are true'),
'And' => _t('UserDefinedForm.SENDIFAND', 'All conditions are true'), 'And' => _t('UserDefinedForm.SENDIFAND', 'All conditions are true'),
) ]
), ),
GridField::create( GridField::create(
'DisplayRules', 'DisplayRules',
_t('EditableFormField.CUSTOMRULES', 'Custom Rules'), _t(__CLASS__.'.CUSTOMRULES', 'Custom Rules'),
$this->DisplayRules(), $this->DisplayRules(),
$customRulesConfig $customRulesConfig
) )
@ -616,7 +584,7 @@ class EditableFormField extends DataObject
*/ */
protected function publishRules($fromStage, $toStage, $createNewVersion) protected function publishRules($fromStage, $toStage, $createNewVersion)
{ {
$seenRuleIDs = array(); $seenRuleIDs = [];
// Don't forget to publish the related custom rules... // Don't forget to publish the related custom rules...
foreach ($this->DisplayRules() as $rule) { foreach ($this->DisplayRules() as $rule) {
@ -812,7 +780,7 @@ class EditableFormField extends DataObject
} }
$prior = 0; // Number of prior group at this level $prior = 0; // Number of prior group at this level
$stack = array(); // Current stack of nested groups, where the top level = the page $stack = []; // Current stack of nested groups, where the top level = the page
foreach ($fields->map('ID', 'ClassName') as $id => $className) { foreach ($fields->map('ID', 'ClassName') as $id => $className) {
if ($className === EditableFormStep::class) { if ($className === EditableFormStep::class) {
$priorPage = empty($stack) ? $prior : $stack[0]; $priorPage = empty($stack) ? $prior : $stack[0];
@ -865,9 +833,9 @@ class EditableFormField extends DataObject
public function getFieldValidationOptions() public function getFieldValidationOptions()
{ {
$fields = new FieldList( $fields = new FieldList(
CheckboxField::create('Required', _t('EditableFormField.REQUIRED', 'Is this field Required?')) CheckboxField::create('Required', _t(__CLASS__.'.REQUIRED', 'Is this field Required?'))
->setDescription(_t('EditableFormField.REQUIRED_DESCRIPTION', 'Please note that conditional fields can\'t be required')), ->setDescription(_t(__CLASS__.'.REQUIRED_DESCRIPTION', 'Please note that conditional fields can\'t be required')),
TextField::create('CustomErrorMessage', _t('EditableFormField.CUSTOMERROR', 'Custom Error Message')) TextField::create('CustomErrorMessage', _t(__CLASS__.'.CUSTOMERROR', 'Custom Error Message'))
); );
$this->extend('updateFieldValidationOptions', $fields); $this->extend('updateFieldValidationOptions', $fields);
@ -951,7 +919,7 @@ class EditableFormField extends DataObject
*/ */
public function getSubmittedFormField() public function getSubmittedFormField()
{ {
return new SubmittedFormField(); return SubmittedFormField::create();
} }
@ -974,7 +942,7 @@ class EditableFormField extends DataObject
public function getErrorMessage() public function getErrorMessage()
{ {
$title = strip_tags("'". ($this->Title ? $this->Title : $this->Name) . "'"); $title = strip_tags("'". ($this->Title ? $this->Title : $this->Name) . "'");
$standard = sprintf(_t('Form.FIELDISREQUIRED', '%s is required').'.', $title); $standard = sprintf(_t('SilverStripe\\Forms\\Form.FIELDISREQUIRED', '%s is required').'.', $title);
// only use CustomErrorMessage if it has a non empty value // only use CustomErrorMessage if it has a non empty value
$errorMessage = (!empty($this->CustomErrorMessage)) ? $this->CustomErrorMessage : $standard; $errorMessage = (!empty($this->CustomErrorMessage)) ? $this->CustomErrorMessage : $standard;
@ -1025,8 +993,8 @@ class EditableFormField extends DataObject
public function getInlineTitleField($column) public function getInlineTitleField($column)
{ {
return TextField::create($column, false) return TextField::create($column, false)
->setAttribute('placeholder', _t('EditableFormField.TITLE', 'Title')) ->setAttribute('placeholder', _t(__CLASS__.'.TITLE', 'Title'))
->setAttribute('data-placeholder', _t('EditableFormField.TITLE', 'Title')); ->setAttribute('data-placeholder', _t(__CLASS__.'.TITLE', 'Title'));
} }
/** /**
@ -1082,7 +1050,7 @@ class EditableFormField extends DataObject
$classes = ClassInfo::getValidSubClasses(EditableFormField::class); $classes = ClassInfo::getValidSubClasses(EditableFormField::class);
// Remove classes we don't want to display in the dropdown. // Remove classes we don't want to display in the dropdown.
$editableFieldClasses = array(); $editableFieldClasses = [];
foreach ($classes as $class) { foreach ($classes as $class) {
// Skip abstract / hidden classes // Skip abstract / hidden classes
if (Config::inst()->get($class, 'abstract', Config::UNINHERITED) || Config::inst()->get($class, 'hidden') if (Config::inst()->get($class, 'abstract', Config::UNINHERITED) || Config::inst()->get($class, 'hidden')
@ -1123,7 +1091,7 @@ class EditableFormField extends DataObject
public function EffectiveDisplayRules() public function EffectiveDisplayRules()
{ {
if ($this->Required) { if ($this->Required) {
return new ArrayList(); return ArrayList::create();
} }
return $this->DisplayRules(); return $this->DisplayRules();
} }
@ -1135,16 +1103,17 @@ class EditableFormField extends DataObject
public function formatDisplayRules() public function formatDisplayRules()
{ {
$holderSelector = $this->getSelectorOnly(); $holderSelector = $this->getSelectorOnly();
$result = array( $result = [
'targetFieldID' => $holderSelector, 'targetFieldID' => $holderSelector,
'conjunction' => $this->DisplayRulesConjunctionNice(), 'conjunction' => $this->DisplayRulesConjunctionNice(),
'selectors' => array(), 'selectors' => [],
'events' => array(), 'events' => [],
'operations' => array(), 'operations' => [],
'initialState' => $this->ShowOnLoadNice(), 'initialState' => $this->ShowOnLoadNice(),
'view' => array(), 'view' => [],
'opposite' => array(), 'opposite' => [],
); ];
// Check for field dependencies / default // Check for field dependencies / default
/** @var EditableCustomRule $rule */ /** @var EditableCustomRule $rule */
foreach ($this->EffectiveDisplayRules() as $rule) { foreach ($this->EffectiveDisplayRules() as $rule) {

View File

@ -2,9 +2,8 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* EditableCheckbox * EditableCheckbox
@ -16,16 +15,17 @@ use SilverStripe\Forms\CheckboxField;
class EditableCheckbox extends EditableFormField class EditableCheckbox extends EditableFormField
{ {
private static $singular_name = 'Checkbox Field'; private static $singular_name = 'Checkbox Field';
private static $plural_name = 'Checkboxes'; private static $plural_name = 'Checkboxes';
protected $jsEventHandler = 'click'; protected $jsEventHandler = 'click';
private static $db = array( private static $db = [
'CheckedDefault' => 'Boolean' // from CustomSettings 'CheckedDefault' => 'Boolean' // from CustomSettings
); ];
private static $table_name = 'EditableCheckbox';
/** /**
* @return FieldList * @return FieldList
@ -36,7 +36,7 @@ class EditableCheckbox extends EditableFormField
$fields->replaceField('Default', CheckboxField::create( $fields->replaceField('Default', CheckboxField::create(
"CheckedDefault", "CheckedDefault",
_t('EditableFormField.CHECKEDBYDEFAULT', 'Checked by Default?') _t('SilverStripe\\UserForms\\Model\\EditableFormField.CHECKEDBYDEFAULT', 'Checked by Default?')
)); ));
return $fields; return $fields;
@ -57,7 +57,9 @@ class EditableCheckbox extends EditableFormField
{ {
$value = (isset($data[$this->Name])) ? $data[$this->Name] : false; $value = (isset($data[$this->Name])) ? $data[$this->Name] : false;
return ($value) ? _t('EditableFormField.YES', 'Yes') : _t('EditableFormField.NO', 'No'); return ($value)
? _t('SilverStripe\\UserForms\\Model\\EditableFormField.YES', 'Yes')
: _t('SilverStripe\\UserForms\\Model\\EditableFormField.NO', 'No');
} }
public function migrateSettings($data) public function migrateSettings($data)

View File

@ -2,12 +2,9 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\FormField\UserFormsCheckboxSetField; use SilverStripe\UserForms\FormField\UserFormsCheckboxSetField;
use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableCustomRule;
/** /**
* EditableCheckboxGroup * EditableCheckboxGroup
* *
@ -18,18 +15,19 @@ use SilverStripe\UserForms\Model\EditableCustomRule;
class EditableCheckboxGroupField extends EditableMultipleOptionField class EditableCheckboxGroupField extends EditableMultipleOptionField
{ {
private static $singular_name = 'Checkbox Group';
private static $singular_name = "Checkbox Group"; private static $plural_name = 'Checkbox Groups';
private static $plural_name = "Checkbox Groups";
protected $jsEventHandler = 'click'; protected $jsEventHandler = 'click';
private static $table_name = 'EditableCheckboxGroupField';
public function getFormField() public function getFormField()
{ {
$field = UserFormsCheckboxSetField::create($this->Name, $this->EscapedTitle, $this->getOptionsMap()) $field = UserFormsCheckboxSetField::create($this->Name, $this->EscapedTitle, $this->getOptionsMap());
->setFieldHolderTemplate('UserFormsMultipleOptionField_holder') $field->setFieldHolderTemplate('UserFormsMultipleOptionField_holder');
->setTemplate('UserFormsCheckboxSetField'); $field->setTemplate('UserFormsCheckboxSetField');
// Set the default checked items // Set the default checked items
$defaultCheckedItems = $this->getDefaultOptions(); $defaultCheckedItems = $this->getDefaultOptions();
@ -48,13 +46,13 @@ class EditableCheckboxGroupField extends EditableMultipleOptionField
if ($entries) { if ($entries) {
if (!is_array($data[$this->Name])) { if (!is_array($data[$this->Name])) {
$entries = array($data[$this->Name]); $entries = [$data[$this->Name]];
} }
foreach ($entries as $selected => $value) { foreach ($entries as $selected => $value) {
if (!$result) { if (!$result) {
$result = $value; $result = $value;
} else { } else {
$result .= ", " . $value; $result .= ', ' . $value;
} }
} }
} }

View File

@ -2,12 +2,9 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use CountryDropdownField; use CountryDropdownField; // @todo
use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableCustomRule;
/** /**
* A dropdown field which allows the user to select a country * A dropdown field which allows the user to select a country
* *
@ -15,11 +12,12 @@ use SilverStripe\UserForms\Model\EditableCustomRule;
*/ */
class EditableCountryDropdownField extends EditableFormField class EditableCountryDropdownField extends EditableFormField
{ {
private static $singular_name = 'Country Dropdown'; private static $singular_name = 'Country Dropdown';
private static $plural_name = 'Country Dropdowns'; private static $plural_name = 'Country Dropdowns';
private static $table_name = 'EditableCountryDropdownField';
/** /**
* @return FieldList * @return FieldList
*/ */

View File

@ -2,15 +2,11 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Forms\DateField; use SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableDateField\FormField;
/** /**
* EditableDateField * EditableDateField
@ -19,19 +15,19 @@ use SilverStripe\Forms\DateField;
* *
* @package userforms * @package userforms
*/ */
class EditableDateField extends EditableFormField class EditableDateField extends EditableFormField
{ {
private static $singular_name = 'Date Field'; private static $singular_name = 'Date Field';
private static $plural_name = 'Date Fields'; private static $plural_name = 'Date Fields';
private static $has_placeholder = true; private static $has_placeholder = true;
private static $db = array( private static $db = [
'DefaultToToday' => 'Boolean' // From customsettings 'DefaultToToday' => 'Boolean' // From customsettings
); ];
private static $table_name = 'EditableDateField';
/** /**
* @return FieldList * @return FieldList
@ -43,7 +39,7 @@ class EditableDateField extends EditableFormField
'Root.Main', 'Root.Main',
CheckboxField::create( CheckboxField::create(
'DefaultToToday', 'DefaultToToday',
_t('EditableFormField.DEFAULTTOTODAY', 'Default to Today?') _t('SilverStripe\\UserForms\\Model\\EditableFormField.DEFAULTTOTODAY', 'Default to Today?')
), ),
'RightTitle' 'RightTitle'
); );
@ -62,7 +58,7 @@ class EditableDateField extends EditableFormField
? DBDatetime::now()->Format('Y-m-d') ? DBDatetime::now()->Format('Y-m-d')
: $this->Default; : $this->Default;
$field = EditableDateField_FormField::create($this->Name, $this->EscapedTitle, $defaultValue) $field = FormField::create($this->Name, $this->EscapedTitle, $defaultValue)
->setConfig('showcalendar', true) ->setConfig('showcalendar', true)
->setFieldHolderTemplate('UserFormsField_holder') ->setFieldHolderTemplate('UserFormsField_holder')
->setTemplate('UserFormsField'); ->setTemplate('UserFormsField');
@ -72,15 +68,3 @@ class EditableDateField extends EditableFormField
return $field; return $field;
} }
} }
/**
* @package userforms
*/
class EditableDateField_FormField extends DateField
{
public function Type()
{
return "date-alt text";
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace SilverStripe\UserForms\Model\EditableFormField\EditableDateField;
use SilverStripe\Forms\DateField;
/**
* @package userforms
*/
class FormField extends DateField
{
public function Type()
{
return "date-alt text";
}
}

View File

@ -2,17 +2,11 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\TextField;
use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableCustomRule;
/** /**
* EditableDropdown * EditableDropdown
* *
@ -25,7 +19,6 @@ use SilverStripe\UserForms\Model\EditableCustomRule;
*/ */
class EditableDropdown extends EditableMultipleOptionField class EditableDropdown extends EditableMultipleOptionField
{ {
private static $singular_name = 'Dropdown Field'; private static $singular_name = 'Dropdown Field';
private static $plural_name = 'Dropdowns'; private static $plural_name = 'Dropdowns';
@ -35,6 +28,8 @@ class EditableDropdown extends EditableMultipleOptionField
'EmptyString' => 'Varchar(255)', 'EmptyString' => 'Varchar(255)',
); );
private static $table_name = 'EditableDropdown';
/** /**
* @return FieldList * @return FieldList
*/ */

View File

@ -2,9 +2,8 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\EmailField; use SilverStripe\Forms\EmailField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* EditableEmailField * EditableEmailField
@ -16,13 +15,14 @@ use SilverStripe\Forms\EmailField;
class EditableEmailField extends EditableFormField class EditableEmailField extends EditableFormField
{ {
private static $singular_name = 'Email Field'; private static $singular_name = 'Email Field';
private static $plural_name = 'Email Fields'; private static $plural_name = 'Email Fields';
private static $has_placeholder = true; private static $has_placeholder = true;
private static $table_name = 'EditableEmailField';
public function getSetsOwnError() public function getSetsOwnError()
{ {
return true; return true;

View File

@ -2,25 +2,19 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Core\Convert;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
use SilverStripe\Forms\LabelField; use SilverStripe\Forms\LabelField;
use SilverStripe\UserForms\FormField\UserFormsGroupField; use SilverStripe\UserForms\FormField\UserFormsGroupField;
use SilverStripe\Core\Convert; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd;
/** /**
* Specifies that this ends a group of fields * Specifies that this ends a group of fields
*/ */
class EditableFieldGroup extends EditableFormField class EditableFieldGroup extends EditableFormField
{ {
private static $has_one = [
private static $has_one = array(
'End' => EditableFieldGroupEnd::class 'End' => EditableFieldGroupEnd::class
); ];
/** /**
* Disable selection of group class * Disable selection of group class
@ -37,10 +31,12 @@ class EditableFieldGroup extends EditableFormField
*/ */
private static $literal = true; private static $literal = true;
private static $table_name = 'EditableFieldGroup';
public function getCMSFields() public function getCMSFields()
{ {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeByName(array('MergeField', 'Default', 'Validation', 'DisplayRules')); $fields->removeByName(['MergeField', 'Default', 'Validation', 'DisplayRules']);
return $fields; return $fields;
} }
@ -51,17 +47,15 @@ class EditableFieldGroup extends EditableFormField
?: 'group'; ?: 'group';
return _t( return _t(
'EditableFieldGroupEnd.FIELD_GROUP_START', 'SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFieldGroupEnd.FIELD_GROUP_START',
'Group {group}', 'Group {group}',
array( ['group' => $title]
'group' => $title
)
); );
} }
public function getInlineClassnameField($column, $fieldClasses) public function getInlineClassnameField($column, $fieldClasses)
{ {
return new LabelField($column, $this->CMSTitle); return LabelField::create($column, $this->CMSTitle);
} }
public function showInReports() public function showInReports()

View File

@ -2,24 +2,20 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
use SilverStripe\Security\Group;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LabelField;
use SilverStripe\Security\Group;
use SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup;
/** /**
* Specifies that this ends a group of fields * Specifies that this ends a group of fields
*/ */
class EditableFieldGroupEnd extends EditableFormField class EditableFieldGroupEnd extends EditableFormField
{ {
private static $belongs_to = [
private static $belongs_to = array(
'Group' => EditableFieldGroup::class 'Group' => EditableFieldGroup::class
); ];
/** /**
* Disable selection of group class * Disable selection of group class
@ -37,28 +33,30 @@ class EditableFieldGroupEnd extends EditableFormField
*/ */
private static $literal = true; private static $literal = true;
private static $table_name = 'EditableFieldGroupEnd';
public function getCMSTitle() public function getCMSTitle()
{ {
$group = $this->Group(); $group = $this->Group();
return _t( return _t(
'EditableFieldGroupEnd.FIELD_GROUP_END', __CLASS__.'.FIELD_GROUP_END',
'{group} end', '{group} end',
array( [
'group' => ($group && $group->exists()) ? $group->CMSTitle : Group::class 'group' => ($group && $group->exists()) ? $group->CMSTitle : Group::class
) ]
); );
} }
public function getCMSFields() public function getCMSFields()
{ {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeByName(array('MergeField', 'Default', 'Validation', 'DisplayRules')); $fields->removeByName(['MergeField', 'Default', 'Validation', 'DisplayRules']);
return $fields; return $fields;
} }
public function getInlineClassnameField($column, $fieldClasses) public function getInlineClassnameField($column, $fieldClasses)
{ {
return new LabelField($column, $this->CMSTitle); return LabelField::create($column, $this->CMSTitle);
} }
public function getInlineTitleField($column) public function getInlineTitleField($column)
@ -85,10 +83,10 @@ class EditableFieldGroupEnd extends EditableFormField
$group = $this->Group(); $group = $this->Group();
if (!($group && $group->exists()) && $this->ParentID) { if (!($group && $group->exists()) && $this->ParentID) {
$group = EditableFieldGroup::get() $group = EditableFieldGroup::get()
->filter(array( ->filter([
'ParentID' => $this->ParentID, 'ParentID' => $this->ParentID,
'Sort:LessThanOrEqual' => $this->Sort 'Sort:LessThanOrEqual' => $this->Sort
)) ])
->where('"EditableFieldGroup"."EndID" IS NULL OR "EditableFieldGroup"."EndID" = 0') ->where('"EditableFieldGroup"."EndID" IS NULL OR "EditableFieldGroup"."EndID" = 0')
->sort('"Sort" DESC') ->sort('"Sort" DESC')
->first(); ->first();

View File

@ -2,24 +2,16 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Folder; use SilverStripe\Assets\Folder;
use SilverStripe\Forms\TreeDropdownField; use SilverStripe\Core\Config\Config;
use SilverStripe\Forms\FileField;
use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\NumericField; use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\FileField; use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\Core\Config\Config; use SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Assets\File;
use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Model\Submission\SubmittedFileField;
/** /**
* Allows a user to add a field that can be used to upload a file. * Allows a user to add a field that can be used to upload a file.
* *
@ -32,22 +24,24 @@ class EditableFileField extends EditableFormField
private static $plural_names = 'File Fields'; private static $plural_names = 'File Fields';
private static $db = array( private static $db = [
'MaxFileSizeMB' => 'Float', 'MaxFileSizeMB' => 'Float',
); ];
private static $has_one = array( private static $has_one = [
'Folder' => Folder::class // From CustomFields 'Folder' => Folder::class // From CustomFields
); ];
private static $table_name = 'EditableFileField';
/** /**
* Further limit uploadable file extensions in addition to the restrictions * Further limit uploadable file extensions in addition to the restrictions
* imposed by the File.allowed_extensions global configuration. * imposed by the File.allowed_extensions global configuration.
* @config * @config
*/ */
private static $allowed_extensions_blacklist = array( private static $allowed_extensions_blacklist = [
'htm', 'html', 'xhtml', 'swf', 'xml' 'htm', 'html', 'xhtml', 'swf', 'xml'
); ];
/** /**
* @return FieldList * @return FieldList
@ -65,14 +59,17 @@ class EditableFileField extends EditableFormField
) )
); );
$fields->addFieldToTab("Root.Main", new LiteralField( $fields->addFieldToTab(
"FileUploadWarning", "Root.Main",
"<p class=\"message notice\">" LiteralField::create(
. _t( 'FileUploadWarning',
"UserDefinedForm.FileUploadWarning", '<p class="message notice">' . _t(
"Files uploaded through this field could be publicly accessible if the exact URL is known" 'SilverStripe\\UserForms\\Model\\UserDefinedForm.FileUploadWarning',
) . "</p>" 'Files uploaded through this field could be publicly accessible if the exact URL is known'
), "Type"); ) . '</p>'
),
'Type'
);
$fields->addFieldToTab( $fields->addFieldToTab(
'Root.Main', 'Root.Main',
@ -114,7 +111,7 @@ class EditableFileField extends EditableFormField
array_diff( array_diff(
// filter out '' since this would be a regex problem on JS end // filter out '' since this would be a regex problem on JS end
array_filter(Config::inst()->get(File::class, 'allowed_extensions')), array_filter(Config::inst()->get(File::class, 'allowed_extensions')),
$this->config()->allowed_extensions_blacklist $this->config()->get('allowed_extensions_blacklist')
) )
); );
@ -150,7 +147,7 @@ class EditableFileField extends EditableFormField
public function getSubmittedFormField() public function getSubmittedFormField()
{ {
return new SubmittedFileField(); return SubmittedFileField::create();
} }

View File

@ -2,40 +2,36 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\HeaderField;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\HeaderField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* Allows an editor to insert a generic heading into a field * Allows an editor to insert a generic heading into a field
* *
* @package userforms * @package userforms
*/ */
class EditableFormHeading extends EditableFormField class EditableFormHeading extends EditableFormField
{ {
private static $singular_name = 'Heading'; private static $singular_name = 'Heading';
private static $plural_name = 'Headings'; private static $plural_name = 'Headings';
private static $literal = true; private static $literal = true;
private static $db = array( private static $db = [
'Level' => 'Int(3)', // From CustomSettings 'Level' => 'Int(3)', // From CustomSettings
'HideFromReports' => 'Boolean(0)' // from CustomSettings 'HideFromReports' => 'Boolean(0)' // from CustomSettings
); ];
private static $defaults = array( private static $defaults = [
'Level' => 3, 'Level' => 3,
'HideFromReports' => false 'HideFromReports' => false
); ];
private static $table_name = 'EditableFormHeading';
/** /**
* @return FieldList * @return FieldList
@ -44,28 +40,28 @@ class EditableFormHeading extends EditableFormField
{ {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeByName(array('Default', 'Validation', 'RightTitle')); $fields->removeByName(['Default', 'Validation', 'RightTitle']);
$levels = array( $levels = [
'1' => '1', '1' => '1',
'2' => '2', '2' => '2',
'3' => '3', '3' => '3',
'4' => '4', '4' => '4',
'5' => '5', '5' => '5',
'6' => '6' '6' => '6'
); ];
$fields->addFieldsToTab('Root.Main', array( $fields->addFieldsToTab('Root.Main', [
DropdownField::create( DropdownField::create(
'Level', 'Level',
_t('EditableFormHeading.LEVEL', 'Select Heading Level'), _t(__CLASS__.'.LEVEL', 'Select Heading Level'),
$levels $levels
), ),
CheckboxField::create( CheckboxField::create(
'HideFromReports', 'HideFromReports',
_t('EditableLiteralField.HIDEFROMREPORT', 'Hide from reports?') _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableLiteralField.HIDEFROMREPORT', 'Hide from reports?')
) )
)); ]);
return $fields; return $fields;
} }

View File

@ -2,11 +2,9 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\FormField\UserFormsStepField;
use SilverStripe\Forms\LabelField; use SilverStripe\Forms\LabelField;
use SilverStripe\UserForms\FormField\UserFormsStepField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* A step in multi-page user form * A step in multi-page user form
@ -15,7 +13,6 @@ use SilverStripe\Forms\LabelField;
*/ */
class EditableFormStep extends EditableFormField class EditableFormStep extends EditableFormField
{ {
private static $singular_name = 'Page Break'; private static $singular_name = 'Page Break';
private static $plural_name = 'Page Breaks'; private static $plural_name = 'Page Breaks';
@ -28,6 +25,8 @@ class EditableFormStep extends EditableFormField
*/ */
private static $hidden = true; private static $hidden = true;
private static $table_name = 'EditableFormStep';
/** /**
* @return FieldList * @return FieldList
*/ */
@ -35,7 +34,7 @@ class EditableFormStep extends EditableFormField
{ {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeByName(array('MergeField', 'Default', 'Validation', 'RightTitle')); $fields->removeByName(['MergeField', 'Default', 'Validation', 'RightTitle']);
return $fields; return $fields;
} }
@ -70,10 +69,7 @@ class EditableFormStep extends EditableFormField
public function getInlineClassnameField($column, $fieldClasses) public function getInlineClassnameField($column, $fieldClasses)
{ {
return new LabelField( return LabelField::create($column, $this->CMSTitle);
$column,
$this->CMSTitle
);
} }
public function getCMSTitle() public function getCMSTitle()
@ -85,9 +81,7 @@ class EditableFormStep extends EditableFormField
return _t( return _t(
'EditableFormStep.STEP_TITLE', 'EditableFormStep.STEP_TITLE',
'Page {page}', 'Page {page}',
array( ['page' => $title]
'page' => $title
)
); );
} }

View File

@ -2,21 +2,14 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig; use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser; use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* Editable Literal Field. A literal field is just a blank slate where * Editable Literal Field. A literal field is just a blank slate where
@ -24,14 +17,14 @@ use SilverStripe\Forms\CompositeField;
* *
* @package userforms * @package userforms
*/ */
class EditableLiteralField extends EditableFormField class EditableLiteralField extends EditableFormField
{ {
private static $singular_name = 'HTML Block'; private static $singular_name = 'HTML Block';
private static $plural_name = 'HTML Blocks'; private static $plural_name = 'HTML Blocks';
private static $table_name = 'EditableLiteralField';
/** /**
* Mark as literal only * Mark as literal only
* *
@ -48,15 +41,15 @@ class EditableLiteralField extends EditableFormField
*/ */
private static $editor_config = null; private static $editor_config = null;
private static $db = array( private static $db = [
'Content' => 'HTMLText', // From CustomSettings 'Content' => 'HTMLText', // From CustomSettings
'HideFromReports' => 'Boolean(0)', // from CustomSettings 'HideFromReports' => 'Boolean(0)', // from CustomSettings
'HideLabel' => 'Boolean(0)' 'HideLabel' => 'Boolean(0)'
); ];
private static $defaults = array( private static $defaults = [
'HideFromReports' => false 'HideFromReports' => false
); ];
/** /**
* Returns the {@see HTMLEditorConfig} instance to use for sanitisation * Returns the {@see HTMLEditorConfig} instance to use for sanitisation
@ -65,7 +58,7 @@ class EditableLiteralField extends EditableFormField
*/ */
protected function getEditorConfig() protected function getEditorConfig()
{ {
$editorConfig = $this->config()->editor_config; $editorConfig = $this->config()->get('editor_config');
if ($editorConfig) { if ($editorConfig) {
return HTMLEditorConfig::get($editorConfig); return HTMLEditorConfig::get($editorConfig);
} }
@ -81,7 +74,7 @@ class EditableLiteralField extends EditableFormField
protected function sanitiseContent($content) protected function sanitiseContent($content)
{ {
// Check if sanitisation is enabled // Check if sanitisation is enabled
if (!HTMLEditorField::config()->sanitise_server_side) { if (!HTMLEditorField::config()->get('sanitise_server_side') {
return $content; return $content;
} }
@ -123,21 +116,21 @@ class EditableLiteralField extends EditableFormField
{ {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeByName(array('Default', 'Validation', 'RightTitle')); $fields->removeByName(['Default', 'Validation', 'RightTitle']);
$fields->addFieldsToTab('Root.Main', array( $fields->addFieldsToTab('Root.Main', [
HTMLEditorField::create('Content', _t('EditableLiteralField.CONTENT', 'HTML')) HTMLEditorField::create('Content', _t(__CLASS__.'.CONTENT', 'HTML'))
->setRows(4) ->setRows(4)
->setColumns(20), ->setColumns(20),
CheckboxField::create( CheckboxField::create(
'HideFromReports', 'HideFromReports',
_t('EditableLiteralField.HIDEFROMREPORT', 'Hide from reports?') _t(__CLASS__.'.HIDEFROMREPORT', 'Hide from reports?')
), ),
CheckboxField::create( CheckboxField::create(
'HideLabel', 'HideLabel',
_t('EditableLiteralField.HIDELABEL', "Hide 'Title' label on frontend?") _t(__CLASS__.'.HIDELABEL', "Hide 'Title' label on frontend?")
) )
)); ]);
return $fields; return $fields;
} }

View File

@ -2,30 +2,27 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Security\Group;
use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\DropdownField;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* Creates an editable field that displays members in a given group * Creates an editable field that displays members in a given group
* *
* @package userforms * @package userforms
*/ */
class EditableMemberListField extends EditableFormField class EditableMemberListField extends EditableFormField
{ {
private static $singular_name = 'Member List Field'; private static $singular_name = 'Member List Field';
private static $plural_name = 'Member List Fields'; private static $plural_name = 'Member List Fields';
private static $has_one = array( private static $has_one = [
'Group' => Group::class 'Group' => Group::class
); ];
private static $table_name = 'EditableMemberListField';
/** /**
* @return FieldList * @return FieldList
@ -40,8 +37,8 @@ class EditableMemberListField extends EditableFormField
$fields->addFieldToTab( $fields->addFieldToTab(
'Root.Main', 'Root.Main',
DropdownField::create( DropdownField::create(
"GroupID", 'GroupID',
_t('EditableFormField.GROUP', Group::class), _t('SilverStripe\\UserForms\\Model\\EditableFormField.GROUP', Group::class),
Group::get()->map() Group::get()->map()
)->setEmptyString(' ') )->setEmptyString(' ')
); );
@ -56,7 +53,7 @@ class EditableMemberListField extends EditableFormField
} }
$members = Member::map_in_groups($this->GroupID); $members = Member::map_in_groups($this->GroupID);
$field = new DropdownField($this->Name, $this->EscapedTitle, $members); $field = DropdownField::create($this->Name, $this->EscapedTitle, $members);
$this->doUpdateFormField($field); $this->doUpdateFormField($field);
return $field; return $field;
} }
@ -66,7 +63,7 @@ class EditableMemberListField extends EditableFormField
if (isset($data[$this->Name])) { if (isset($data[$this->Name])) {
$memberID = $data[$this->Name]; $memberID = $data[$this->Name];
$member = Member::get()->byID($memberID); $member = Member::get()->byID($memberID);
return $member ? $member->getName() : ""; return $member ? $member->getName() : '';
} }
return false; return false;

View File

@ -2,33 +2,22 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use GridFieldEditableColumns;
use GridFieldTitleHeader;
use GridFieldOrderableRows;
use GridFieldAddNewInlineButton;
use SilverStripe\UserForms\Model\EditableFormField\EditableOption;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\TextField;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\Tab; use SilverStripe\Forms\Tab;
use SilverStripe\Versioned\Versioned;
use SilverStripe\ORM\Map; use SilverStripe\ORM\Map;
use SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableOption;
use SilverStripe\Versioned\Versioned;
use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton;
use Symbiote\GridFieldExtensions\GridFieldEditableColumns;
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;
use Symbiote\GridFieldExtensions\GridFieldTitleHeader;
/** /**
* Base class for multiple option fields such as {@link EditableDropdownField} * Base class for multiple option fields such as {@link EditableDropdownField}
@ -45,7 +34,6 @@ use SilverStripe\ORM\Map;
class EditableMultipleOptionField extends EditableFormField class EditableMultipleOptionField extends EditableFormField
{ {
/** /**
* Define this field as abstract (not inherited) * Define this field as abstract (not inherited)
* *
@ -54,9 +42,11 @@ class EditableMultipleOptionField extends EditableFormField
*/ */
private static $abstract = true; private static $abstract = true;
private static $has_many = array( private static $has_many = [
"Options" => EditableOption::class 'Options' => EditableOption::class
); ];
private static $table_name = 'EditableMultipleOptionField';
/** /**
* @return FieldList * @return FieldList
@ -65,26 +55,26 @@ class EditableMultipleOptionField extends EditableFormField
{ {
$this->beforeUpdateCMSFields(function($fields) { $this->beforeUpdateCMSFields(function($fields) {
$editableColumns = new GridFieldEditableColumns(); $editableColumns = new GridFieldEditableColumns();
$editableColumns->setDisplayFields(array( $editableColumns->setDisplayFields([
'Title' => array( 'Title' => [
'title' => _t('EditableMultipleOptionField.TITLE', 'Title'), 'title' => _t(__CLASS__.'.TITLE', 'Title'),
'callback' => function ($record, $column, $grid) { 'callback' => function ($record, $column, $grid) {
return TextField::create($column); return TextField::create($column);
} }
), ],
'Value' => array( 'Value' => [
'title' => _t('EditableMultipleOptionField.VALUE', 'Value'), 'title' => _t(__CLASS__.'.VALUE', 'Value'),
'callback' => function ($record, $column, $grid) { 'callback' => function ($record, $column, $grid) {
return TextField::create($column); return TextField::create($column);
} }
), ],
'Default' => array( 'Default' => [
'title' => _t('EditableMultipleOptionField.DEFAULT', 'Selected by default?'), 'title' => _t(__CLASS__.'.DEFAULT', 'Selected by default?'),
'callback' => function ($record, $column, $grid) { 'callback' => function ($record, $column, $grid) {
return CheckboxField::create($column); return CheckboxField::create($column);
} }
) ]
)); ]);
$optionsConfig = GridFieldConfig::create() $optionsConfig = GridFieldConfig::create()
->addComponents( ->addComponents(
@ -104,7 +94,7 @@ class EditableMultipleOptionField extends EditableFormField
$optionsConfig $optionsConfig
); );
$fields->insertAfter(new Tab('Options', _t('EditableMultipleOptionField.OPTIONSTAB', 'Options')), 'Main'); $fields->insertAfter(Tab::create('Options', _t(__CLASS__.'.OPTIONSTAB', 'Options')), 'Main');
$fields->addFieldToTab('Root.Options', $optionsGrid); $fields->addFieldToTab('Root.Options', $optionsGrid);
}); });
@ -139,7 +129,7 @@ class EditableMultipleOptionField extends EditableFormField
*/ */
protected function publishOptions($fromStage, $toStage, $createNewVersion) protected function publishOptions($fromStage, $toStage, $createNewVersion)
{ {
$seenIDs = array(); $seenIDs = [];
// Publish all options // Publish all options
foreach ($this->Options() as $option) { foreach ($this->Options() as $option) {

View File

@ -2,13 +2,10 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\NumericField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* EditableNumericField * EditableNumericField
@ -27,10 +24,12 @@ class EditableNumericField extends EditableFormField
private static $has_placeholder = true; private static $has_placeholder = true;
private static $db = array( private static $db = [
'MinValue' => 'Int', 'MinValue' => 'Int',
'MaxValue' => 'Int' 'MaxValue' => 'Int'
); ];
private static $table_name = 'EditableNumericField';
public function getSetsOwnError() public function getSetsOwnError()
{ {
@ -56,12 +55,12 @@ class EditableNumericField extends EditableFormField
{ {
$fields = parent::getFieldValidationOptions(); $fields = parent::getFieldValidationOptions();
$fields->push(FieldGroup::create( $fields->push(FieldGroup::create(
_t("EditableNumericField.RANGE", "Allowed numeric range"), _t(__CLASS__.'.RANGE', 'Allowed numeric range'),
array( [
new NumericField('MinValue', false), NumericField::create('MinValue', false),
new LiteralField('RangeValue', _t("EditableNumericField.RANGE_TO", "to")), LiteralField::create('RangeValue', _t(__CLASS__.'.RANGE_TO', 'to')),
new NumericField('MaxValue', false) NumericField::create('MaxValue', false)
) ]
)); ));
return $fields; return $fields;
} }

View File

@ -2,17 +2,12 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableMultipleOptionField;
use SilverStripe\Core\Convert;
use SilverStripe\Control\Controller;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Control\Controller;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\UserForms\Model\EditableFormField\EditableMultipleOptionField;
use SilverStripe\Versioned\Versioned;
/** /**
* Base Class for EditableOption Fields such as the ones used in * Base Class for EditableOption Fields such as the ones used in
@ -23,32 +18,33 @@ use SilverStripe\ORM\DataObject;
*/ */
class EditableOption extends DataObject class EditableOption extends DataObject
{ {
private static $default_sort = 'Sort';
private static $default_sort = "Sort"; private static $db = [
'Name' => 'Varchar(255)',
'Title' => 'Varchar(255)',
'Default' => 'Boolean',
'Sort' => 'Int',
'Value' => 'Varchar(255)',
];
private static $db = array( private static $has_one = [
"Name" => "Varchar(255)", 'Parent' => EditableMultipleOptionField::class,
"Title" => "Varchar(255)", ];
"Default" => "Boolean",
"Sort" => "Int",
"Value" => "Varchar(255)",
);
private static $has_one = array( private static $extensions = [
"Parent" => EditableMultipleOptionField::class, Versioned::class . "('Stage', 'Live')"
); ];
private static $extensions = array( private static $summary_fields = [
"Versioned('Stage', 'Live')"
);
private static $summary_fields = array(
'Title', 'Title',
'Default' 'Default'
); ];
protected static $allow_empty_values = false; protected static $allow_empty_values = false;
private static $table_name = 'EditableOption';
/** /**
* Returns whether to allow empty values or not. * Returns whether to allow empty values or not.
* *

View File

@ -2,12 +2,9 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Forms\OptionsetField; use SilverStripe\Forms\OptionsetField;
use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableCustomRule;
/** /**
* EditableRadioField * EditableRadioField
* *
@ -18,11 +15,12 @@ use SilverStripe\UserForms\Model\EditableCustomRule;
class EditableRadioField extends EditableMultipleOptionField class EditableRadioField extends EditableMultipleOptionField
{ {
private static $singular_name = 'Radio Group'; private static $singular_name = 'Radio Group';
private static $plural_name = 'Radio Groups'; private static $plural_name = 'Radio Groups';
private static $table_name = 'EditableRadioField';
/** /**
* @return FieldList * @return FieldList
*/ */

View File

@ -2,20 +2,14 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\Control\Email\Email; use SilverStripe\Control\Email\Email;
use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\TextareaField; use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\TextField; use SilverStripe\Forms\TextField;
use SilverStripe\UserForms\Model\EditableFormField;
/** /**
* EditableTextField * EditableTextField
@ -27,14 +21,14 @@ use SilverStripe\Forms\TextField;
class EditableTextField extends EditableFormField class EditableTextField extends EditableFormField
{ {
private static $singular_name = 'Text Field'; private static $singular_name = 'Text Field';
private static $plural_name = 'Text Fields'; private static $plural_name = 'Text Fields';
private static $has_placeholder = true; private static $has_placeholder = true;
private static $autocomplete_options = array( /** @skipUpgrade */
private static $autocomplete_options = [
'off' => 'Off', 'off' => 'Off',
'on' => 'On', 'on' => 'On',
'name' => 'Full name', 'name' => 'Full name',
@ -44,7 +38,7 @@ class EditableTextField extends EditableFormField
'family-name' => 'Family name', 'family-name' => 'Family name',
'honorific-suffix' => 'Suffix (e.g Jr.)', 'honorific-suffix' => 'Suffix (e.g Jr.)',
'nickname' => 'Nickname', 'nickname' => 'Nickname',
'email' => Email::class, 'email' => 'Email',
'organization-title' => 'Job title', 'organization-title' => 'Job title',
'organization' => 'Organization', 'organization' => 'Organization',
'street-address' => 'Street address', 'street-address' => 'Street address',
@ -62,50 +56,46 @@ class EditableTextField extends EditableFormField
'sex' => 'Gender identity', 'sex' => 'Gender identity',
'tel' => 'Telephone number', 'tel' => 'Telephone number',
'url' => 'Home page' 'url' => 'Home page'
); ];
protected $jsEventHandler = 'keyup'; protected $jsEventHandler = 'keyup';
private static $db = array( private static $db = [
'MinLength' => 'Int', 'MinLength' => 'Int',
'MaxLength' => 'Int', 'MaxLength' => 'Int',
'Rows' => 'Int(1)', 'Rows' => 'Int(1)',
'Autocomplete' => 'Varchar(255)' 'Autocomplete' => 'Varchar(255)'
); ];
private static $defaults = array( private static $defaults = [
'Rows' => 1 'Rows' => 1
); ];
private static $table_name = 'EditableTextField';
public function getCMSFields() public function getCMSFields()
{ {
// PHP 5.3 compat $this->beforeUpdateCMSFields(function ($fields) {
$self = $this; $fields->addFieldsToTab(
$this->beforeUpdateCMSFields(function ($fields) use ($self) {
$fields->addFieldToTab(
'Root.Main', 'Root.Main',
[
NumericField::create( NumericField::create(
'Rows', 'Rows',
_t('EditableTextField.NUMBERROWS', 'Number of rows') _t(__CLASS__.'.NUMBERROWS', 'Number of rows')
)->setDescription(_t( )->setDescription(_t(
'EditableTextField.NUMBERROWS_DESCRIPTION', __CLASS__.'.NUMBERROWS_DESCRIPTION',
'Fields with more than one row will be generated as a textarea' 'Fields with more than one row will be generated as a textarea'
)) )),
);
$fields->addFieldToTab(
'Root.Main',
DropdownField::create( DropdownField::create(
'Autocomplete', 'Autocomplete',
_t('EditableTextField.AUTOCOMPLETE', 'Autocomplete'), _t(__CLASS__.'.AUTOCOMPLETE', 'Autocomplete'),
$self->config()->get('autocomplete_options') $this->config()->get('autocomplete_options')
)->setDescription(_t( )->setDescription(_t(
'EditableTextField.AUTOCOMPLETE_DESCRIPTION', __CLASS__.'.AUTOCOMPLETE_DESCRIPTION',
'Supported browsers will attempt to populate this field automatically with the users information, use to set the value populated' 'Supported browsers will attempt to populate this field automatically with the users information, use to set the value populated'
)) ))
]
); );
}); });
return parent::getCMSFields(); return parent::getCMSFields();
@ -118,16 +108,16 @@ class EditableTextField extends EditableFormField
{ {
$fields = parent::getFieldValidationOptions(); $fields = parent::getFieldValidationOptions();
$fields->merge(array( $fields->merge([
FieldGroup::create( FieldGroup::create(
_t('EditableTextField.TEXTLENGTH', 'Allowed text length'), _t(__CLASS__.'.TEXTLENGTH', 'Allowed text length'),
array( [
NumericField::create('MinLength', false), NumericField::create('MinLength', false),
LiteralField::create('RangeLength', _t("EditableTextField.RANGE_TO", "to")), LiteralField::create('RangeLength', _t(__CLASS__.".RANGE_TO", "to")),
NumericField::create('MaxLength', false) NumericField::create('MaxLength', false)
]
) )
) ]);
));
return $fields; return $fields;
} }

View File

@ -2,16 +2,11 @@
namespace SilverStripe\UserForms\Model\EditableFormField; namespace SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableCustomRule;
use SilverStripe\Forms\RequiredFields; use SilverStripe\Forms\RequiredFields;
use SilverStripe\UserForms\Model\EditableCustomRule;
class Validator extends RequiredFields
class EditableFormFieldValidator extends RequiredFields
{ {
/** /**
* *
* @var EditableFormField * @var EditableFormField
@ -64,8 +59,8 @@ class EditableFormFieldValidator extends RequiredFields
$this->validationError( $this->validationError(
'Required_Error', 'Required_Error',
_t( _t(
"EditableFormFieldValidator.REQUIRED_ERROR", __CLASS__.'.REQUIRED_ERROR',
"Form fields cannot be required and have conditional display rules." 'Form fields cannot be required and have conditional display rules.'
), ),
'error' 'error'
); );

View File

@ -2,66 +2,38 @@
namespace SilverStripe\UserForms\Model\Recipient; namespace SilverStripe\UserForms\Model\Recipient;
use SilverStripe\Assets\FileFinder;
use SilverStripe\CMS\Controllers\CMSMain;
use GridFieldAddNewInlineButton;
use GridFieldEditableColumns;
use Tabset;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\Recipient\UserDefinedForm_EmailRecipientCondition;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Session;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\TextField;
use SilverStripe\View\Requirements;
use SilverStripe\UserForms\Model\EditableFormField\EditableMultipleOptionField;
use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField;
use SilverStripe\UserForms\Model\EditableFormField\EditableTextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\CMS\Controllers\CMSPageEditController; use SilverStripe\CMS\Controllers\CMSPageEditController;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Session;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\TextareaField; use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Assets\FileFinder; use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableMultipleOptionField;
use SilverStripe\UserForms\Model\EditableFormField\EditableTextField;
use SilverStripe\UserForms\Model\Recipient\EmailRecipientCondition;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\View\Requirements;
use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton;
use Symbiote\GridFieldExtensions\GridFieldEditableColumns;
/** /**
* A Form can have multiply members / emails to email the submission * A Form can have multiply members / emails to email the submission
@ -69,10 +41,9 @@ use SilverStripe\ORM\DataObject;
* *
* @package userforms * @package userforms
*/ */
class UserDefinedForm_EmailRecipient extends DataObject class EmailRecipient extends DataObject
{ {
private static $db = [
private static $db = array(
'EmailAddress' => 'Varchar(200)', 'EmailAddress' => 'Varchar(200)',
'EmailSubject' => 'Varchar(200)', 'EmailSubject' => 'Varchar(200)',
'EmailFrom' => 'Varchar(200)', 'EmailFrom' => 'Varchar(200)',
@ -83,24 +54,26 @@ class UserDefinedForm_EmailRecipient extends DataObject
'SendPlain' => 'Boolean', 'SendPlain' => 'Boolean',
'HideFormData' => 'Boolean', 'HideFormData' => 'Boolean',
'CustomRulesCondition' => 'Enum("And,Or")' 'CustomRulesCondition' => 'Enum("And,Or")'
); ];
private static $has_one = array( private static $has_one = [
'Form' => UserDefinedForm::class, 'Form' => UserDefinedForm::class,
'SendEmailFromField' => EditableFormField::class, 'SendEmailFromField' => EditableFormField::class,
'SendEmailToField' => EditableFormField::class, 'SendEmailToField' => EditableFormField::class,
'SendEmailSubjectField' => EditableFormField::class 'SendEmailSubjectField' => EditableFormField::class
); ];
private static $has_many = array( private static $has_many = [
'CustomRules' => UserDefinedForm_EmailRecipientCondition::class 'CustomRules' => EmailRecipientCondition::class
); ];
private static $summary_fields = array( private static $summary_fields = [
'EmailAddress', 'EmailAddress',
'EmailSubject', 'EmailSubject',
'EmailFrom' 'EmailFrom'
); ];
private static $table_name = 'UserDefinedForm_EmailRecipient';
/** /**
* Setting this to true will allow you to select "risky" fields as * Setting this to true will allow you to select "risky" fields as
@ -117,13 +90,13 @@ class UserDefinedForm_EmailRecipient extends DataObject
{ {
$fields = parent::summaryFields(); $fields = parent::summaryFields();
if (isset($fields['EmailAddress'])) { if (isset($fields['EmailAddress'])) {
$fields['EmailAddress'] = _t('UserDefinedForm.EMAILADDRESS', Email::class); $fields['EmailAddress'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILADDRESS', Email::class);
} }
if (isset($fields['EmailSubject'])) { if (isset($fields['EmailSubject'])) {
$fields['EmailSubject'] = _t('UserDefinedForm.EMAILSUBJECT', 'Subject'); $fields['EmailSubject'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILSUBJECT', 'Subject');
} }
if (isset($fields['EmailFrom'])) { if (isset($fields['EmailFrom'])) {
$fields['EmailFrom'] = _t('UserDefinedForm.EMAILFROM', 'From'); $fields['EmailFrom'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILFROM', 'From');
} }
return $fields; return $fields;
} }
@ -175,7 +148,7 @@ class UserDefinedForm_EmailRecipient extends DataObject
return DropdownField::create($column, false, $formFields->map('ID', 'Title')); return DropdownField::create($column, false, $formFields->map('ID', 'Title'));
}, },
'ConditionOption' => function ($record, $column, $grid) { 'ConditionOption' => function ($record, $column, $grid) {
$options = UserDefinedForm_EmailRecipientCondition::config()->condition_options; $options = EmailRecipientCondition::config()->condition_options;
return DropdownField::create($column, false, $options); return DropdownField::create($column, false, $options);
}, },
'ConditionValue' => function ($record, $column, $grid) { 'ConditionValue' => function ($record, $column, $grid) {
@ -213,7 +186,7 @@ class UserDefinedForm_EmailRecipient extends DataObject
// Check valid email-recipient fields // Check valid email-recipient fields
if ($this->config()->allow_unbound_recipient_fields) { if ($this->config()->get('allow_unbound_recipient_fields')) {
// To address can only be email fields or multi option fields // To address can only be email fields or multi option fields
$validEmailToFields = ArrayList::create($validEmailFromFields->toArray()); $validEmailToFields = ArrayList::create($validEmailFromFields->toArray());
$validEmailToFields->merge($multiOptionFields); $validEmailToFields->merge($multiOptionFields);
@ -226,40 +199,55 @@ class UserDefinedForm_EmailRecipient extends DataObject
$fields = FieldList::create(Tabset::create('Root')->addExtraClass('EmailRecipientForm')); $fields = FieldList::create(Tabset::create('Root')->addExtraClass('EmailRecipientForm'));
// Configuration fields // Configuration fields
$fields->addFieldsToTab('Root.EmailDetails', array( $fields->addFieldsToTab('Root.EmailDetails', [
// Subject // Subject
FieldGroup::create( FieldGroup::create(
TextField::create('EmailSubject', _t('UserDefinedForm.TYPESUBJECT', 'Type subject')) TextField::create(
'EmailSubject',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPESUBJECT', 'Type subject')
)
->setAttribute('style', 'min-width: 400px;'), ->setAttribute('style', 'min-width: 400px;'),
DropdownField::create( DropdownField::create(
'SendEmailSubjectFieldID', 'SendEmailSubjectFieldID',
_t('UserDefinedForm.SELECTAFIELDTOSETSUBJECT', '.. or select a field to use as the subject'), _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.SELECTAFIELDTOSETSUBJECT',
'.. or select a field to use as the subject'
),
$validSubjectFields->map('ID', 'Title') $validSubjectFields->map('ID', 'Title')
)->setEmptyString('') )->setEmptyString('')
) )
->setTitle(_t('UserDefinedForm.EMAILSUBJECT', 'Email subject')), ->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILSUBJECT', 'Email subject')),
// To // To
FieldGroup::create( FieldGroup::create(
TextField::create('EmailAddress', _t('UserDefinedForm.TYPETO', 'Type to address')) TextField::create(
'EmailAddress',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPETO', 'Type to address')
)
->setAttribute('style', 'min-width: 400px;'), ->setAttribute('style', 'min-width: 400px;'),
DropdownField::create( DropdownField::create(
'SendEmailToFieldID', 'SendEmailToFieldID',
_t('UserDefinedForm.ORSELECTAFIELDTOUSEASTO', '.. or select a field to use as the to address'), _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.ORSELECTAFIELDTOUSEASTO',
'.. or select a field to use as the to address'
),
$validEmailToFields->map('ID', 'Title') $validEmailToFields->map('ID', 'Title')
)->setEmptyString(' ') )->setEmptyString(' ')
) )
->setTitle(_t('UserDefinedForm.SENDEMAILTO', 'Send email to')) ->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDEMAILTO', 'Send email to'))
->setDescription(_t( ->setDescription(_t(
'UserDefinedForm.SENDEMAILTO_DESCRIPTION', 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDEMAILTO_DESCRIPTION',
'You may enter multiple email addresses as a comma separated list.' 'You may enter multiple email addresses as a comma separated list.'
)), )),
// From // From
TextField::create('EmailFrom', _t('UserDefinedForm.FROMADDRESS', 'Send email from')) TextField::create(
'EmailFrom',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.FROMADDRESS', 'Send email from')
)
->setDescription(_t( ->setDescription(_t(
'UserDefinedForm.EmailFromContent', 'SilverStripe\\UserForms\\Model\\UserDefinedForm.EmailFromContent',
"The from address allows you to set who the email comes from. On most servers this ". "The from address allows you to set who the email comes from. On most servers this ".
"will need to be set to an email address on the same domain name as your site. ". "will need to be set to an email address on the same domain name as your site. ".
"For example on yoursite.com the from address may need to be something@yoursite.com. ". "For example on yoursite.com the from address may need to be something@yoursite.com. ".
@ -269,22 +257,31 @@ class UserDefinedForm_EmailRecipient extends DataObject
// Reply-To // Reply-To
FieldGroup::create( FieldGroup::create(
TextField::create('EmailReplyTo', _t('UserDefinedForm.TYPEREPLY', 'Type reply address')) TextField::create('EmailReplyTo', _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPEREPLY',
'Type reply address'
))
->setAttribute('style', 'min-width: 400px;'), ->setAttribute('style', 'min-width: 400px;'),
DropdownField::create( DropdownField::create(
'SendEmailFromFieldID', 'SendEmailFromFieldID',
_t('UserDefinedForm.ORSELECTAFIELDTOUSEASFROM', '.. or select a field to use as reply to address'), _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.ORSELECTAFIELDTOUSEASFROM',
'.. or select a field to use as reply to address'
),
$validEmailFromFields->map('ID', 'Title') $validEmailFromFields->map('ID', 'Title')
)->setEmptyString(' ') )->setEmptyString(' ')
) )
->setTitle(_t('UserDefinedForm.REPLYADDRESS', 'Email for reply to')) ->setTitle(_t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.REPLYADDRESS',
'Email for reply to'
))
->setDescription(_t( ->setDescription(_t(
'UserDefinedForm.REPLYADDRESS_DESCRIPTION', 'SilverStripe\\UserForms\\Model\\UserDefinedForm.REPLYADDRESS_DESCRIPTION',
'The email address which the recipient is able to \'reply\' to.' 'The email address which the recipient is able to \'reply\' to.'
)) ))
)); ]);
$fields->fieldByName('Root.EmailDetails')->setTitle(_t('UserDefinedForm_EmailRecipient.EMAILDETAILSTAB', 'Email Details')); $fields->fieldByName('Root.EmailDetails')->setTitle(_t(__CLASS.'.EMAILDETAILSTAB', 'Email Details'));
// Only show the preview link if the recipient has been saved. // Only show the preview link if the recipient has been saved.
if (!empty($this->EmailTemplate)) { if (!empty($this->EmailTemplate)) {
@ -294,64 +291,79 @@ class UserDefinedForm_EmailRecipient extends DataObject
singleton(CMSPageEditController::class)->getEditForm()->FormAction(), singleton(CMSPageEditController::class)->getEditForm()->FormAction(),
"field/EmailRecipients/item/{$this->ID}/preview" "field/EmailRecipients/item/{$this->ID}/preview"
), ),
_t('UserDefinedForm.PREVIEW_EMAIL', 'Preview email'), _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL', 'Preview email'),
_t('UserDefinedForm.PREVIEW_EMAIL_DESCRIPTION', 'Note: Unsaved changes will not appear in the preview.') _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL_DESCRIPTION',
'Note: Unsaved changes will not appear in the preview.'
)
); );
} else { } else {
$preview = sprintf( $preview = sprintf(
'<em>%s</em>', '<em>%s</em>',
_t( _t(
'UserDefinedForm.PREVIEW_EMAIL_UNAVAILABLE', 'SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL_UNAVAILABLE',
'You can preview this email once you have saved the Recipient.' 'You can preview this email once you have saved the Recipient.'
) )
); );
} }
// Email templates // Email templates
$fields->addFieldsToTab('Root.EmailContent', array( $fields->addFieldsToTab('Root.EmailContent', [
CheckboxField::create('HideFormData', _t('UserDefinedForm.HIDEFORMDATA', 'Hide form data from email?')), CheckboxField::create(
'HideFormData',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.HIDEFORMDATA', 'Hide form data from email?')
),
CheckboxField::create( CheckboxField::create(
'SendPlain', 'SendPlain',
_t('UserDefinedForm.SENDPLAIN', 'Send email as plain text? (HTML will be stripped)') _t(
'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDPLAIN',
'Send email as plain text? (HTML will be stripped)'
)
), ),
DropdownField::create( DropdownField::create(
'EmailTemplate', 'EmailTemplate',
_t('UserDefinedForm.EMAILTEMPLATE', 'Email template'), _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILTEMPLATE', 'Email template'),
$this->getEmailTemplateDropdownValues() $this->getEmailTemplateDropdownValues()
)->addExtraClass('toggle-html-only'), )->addExtraClass('toggle-html-only'),
HTMLEditorField::create('EmailBodyHtml', _t('UserDefinedForm.EMAILBODYHTML', 'Body')) HTMLEditorField::create(
'EmailBodyHtml',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILBODYHTML', 'Body')
)
->addExtraClass('toggle-html-only'), ->addExtraClass('toggle-html-only'),
TextareaField::create('EmailBody', _t('UserDefinedForm.EMAILBODY', 'Body')) TextareaField::create(
'EmailBody',
_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILBODY', 'Body')
)
->addExtraClass('toggle-plain-only'), ->addExtraClass('toggle-plain-only'),
LiteralField::create('EmailPreview', $preview) LiteralField::create('EmailPreview', $preview)
)); ));
$fields->fieldByName('Root.EmailContent')->setTitle(_t('UserDefinedForm_EmailRecipient.EMAILCONTENTTAB', 'Email Content')); $fields->fieldByName('Root.EmailContent')->setTitle(_t(__CLASS.'.EMAILCONTENTTAB', 'Email Content'));
// Custom rules for sending this field // Custom rules for sending this field
$grid = new GridField( $grid = GridField::create(
"CustomRules", 'CustomRules',
_t('EditableFormField.CUSTOMRULES', 'Custom Rules'), _t('SilverStripe\\UserForms\\Model\\EditableFormField.CUSTOMRULES', 'Custom Rules'),
$this->CustomRules(), $this->CustomRules(),
$this->getRulesConfig() $this->getRulesConfig()
); );
$grid->setDescription(_t( $grid->setDescription(_t(
'UserDefinedForm.RulesDescription', 'SilverStripe\\UserForms\\Model\\UserDefinedForm.RulesDescription',
'Emails will only be sent to the recipient if the custom rules are met. If no rules are defined, this receipient will receive notifications for every submission.' 'Emails will only be sent to the recipient if the custom rules are met. If no rules are defined, this receipient will receive notifications for every submission.'
)); ));
$fields->addFieldsToTab('Root.CustomRules', array( $fields->addFieldsToTab('Root.CustomRules', [
new DropdownField( DropdownField::create(
'CustomRulesCondition', 'CustomRulesCondition',
_t('UserDefinedForm.SENDIF', 'Send condition'), _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIF', 'Send condition'),
array( [
'Or' => _t('UserDefinedForm.SENDIFOR', 'Any conditions are true'), 'Or' => _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFOR', 'Any conditions are true'),
'And' => _t('UserDefinedForm.SENDIFAND', 'All conditions are true') 'And' => _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFAND', 'All conditions are true')
) ]
), ),
$grid $grid
)); ]);
$fields->fieldByName('Root.CustomRules')->setTitle(_t('UserDefinedForm_EmailRecipient.CUSTOMRULESTAB', 'Custom Rules')); $fields->fieldByName('Root.CustomRules')->setTitle(_t(__CLASS.'.CUSTOMRULESTAB', 'Custom Rules'));
$this->extend('updateCMSFields', $fields); $this->extend('updateCMSFields', $fields);
return $fields; return $fields;
@ -445,7 +457,7 @@ class UserDefinedForm_EmailRecipient extends DataObject
// Check all rules // Check all rules
$isAnd = $this->CustomRulesCondition === 'And'; $isAnd = $this->CustomRulesCondition === 'And';
foreach ($customRules as $customRule) { foreach ($customRules as $customRule) {
/** @var UserDefinedForm_EmailRecipientCondition $customRule */ /** @var EmailRecipientCondition $customRule */
$matches = $customRule->matches($data); $matches = $customRule->matches($data);
if ($isAnd && !$matches) { if ($isAnd && !$matches) {
return false; return false;
@ -493,12 +505,12 @@ class UserDefinedForm_EmailRecipient extends DataObject
*/ */
public function getEmailTemplateDropdownValues() public function getEmailTemplateDropdownValues()
{ {
$templates = array(); $templates = [];
$finder = new FileFinder(); $finder = new FileFinder();
$finder->setOption('name_regex', '/^.*\.ss$/'); $finder->setOption('name_regex', '/^.*\.ss$/');
$found = $finder->find(BASE_PATH . '/' . UserDefinedForm::config()->email_template_directory); $found = $finder->find(BASE_PATH . '/' . UserDefinedForm::config()->get('email_template_directory'));
foreach ($found as $key => $value) { foreach ($found as $key => $value) {
$template = pathinfo($value); $template = pathinfo($value);
@ -516,11 +528,11 @@ class UserDefinedForm_EmailRecipient extends DataObject
*/ */
public function validate() { public function validate() {
$result = parent::validate(); $result = parent::validate();
$checkEmail = array( $checkEmail = [
'EmailAddress' => 'EMAILADDRESSINVALID', 'EmailAddress' => 'EMAILADDRESSINVALID',
'EmailFrom' => 'EMAILFROMINVALID', 'EmailFrom' => 'EMAILFROMINVALID',
'EmailReplyTo' => 'EMAILREPLYTOINVALID', 'EmailReplyTo' => 'EMAILREPLYTOINVALID',
); ];
foreach ($checkEmail as $check => $translation) { foreach ($checkEmail as $check => $translation) {
if ($this->$check) { if ($this->$check) {
//may be a comma separated list of emails //may be a comma separated list of emails
@ -528,7 +540,7 @@ class UserDefinedForm_EmailRecipient extends DataObject
foreach ($addresses as $address) { foreach ($addresses as $address) {
$trimAddress = trim($address); $trimAddress = trim($address);
if ($trimAddress && !Email::is_valid_address($trimAddress)) { if ($trimAddress && !Email::is_valid_address($trimAddress)) {
$error = _t("UserDefinedForm_EmailRecipient.$translation", $error = _t(__CLASS.".$translation",
"Invalid email address $trimAddress"); "Invalid email address $trimAddress");
$result->error($error . " ($trimAddress)"); $result->error($error . " ($trimAddress)");
} }

View File

@ -2,58 +2,53 @@
namespace SilverStripe\UserForms\Model\Recipient; namespace SilverStripe\UserForms\Model\Recipient;
use LogicException; use LogicException;
use SilverStripe\UserForms\Model\Recipient\UserDefinedForm_EmailRecipient;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\Control\Controller;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Control\Controller;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\UserForms\Model\Recipient\EmailRecipient;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
/** /**
* Declares a condition that determines whether an email can be sent to a given recipient * Declares a condition that determines whether an email can be sent to a given recipient
* *
* @method UserDefinedForm_EmailRecipient Parent() * @method EmailRecipient Parent()
* *
* @property Enum ConditionOption * @property Enum ConditionOption
* @property Varchar ConditionValue * @property Varchar ConditionValue
* *
* @method EditableFormField ConditionField * @method EditableFormField ConditionField
*/ */
class UserDefinedForm_EmailRecipientCondition extends DataObject class EmailRecipientCondition extends DataObject
{ {
/** /**
* List of options * List of options
* *
* @config * @config
* @var array * @var array
*/ */
private static $condition_options = array( private static $condition_options = [
"IsBlank" => "Is blank", 'IsBlank' => 'Is blank',
"IsNotBlank" => "Is not blank", 'IsNotBlank' => 'Is not blank',
"Equals" => "Equals", 'Equals' => 'Equals',
"NotEquals" => "Doesn't equal", 'NotEquals' => "Doesn't equal",
"ValueLessThan" => "Less than", 'ValueLessThan' => 'Less than',
"ValueLessThanEqual" => "Less than or equal", 'ValueLessThanEqual' => 'Less than or equal',
"ValueGreaterThan" => "Greater than", 'ValueGreaterThan' => 'Greater than',
"ValueGreaterThanEqual" => "Greater than or equal" 'ValueGreaterThanEqual' => 'Greater than or equal'
); ];
private static $db = array( private static $db = [
'ConditionOption' => 'Enum("IsBlank,IsNotBlank,Equals,NotEquals,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual")', 'ConditionOption' => 'Enum("IsBlank,IsNotBlank,Equals,NotEquals,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual")',
'ConditionValue' => 'Varchar' 'ConditionValue' => 'Varchar'
); ];
private static $has_one = array( private static $has_one = [
'Parent' => UserDefinedForm_EmailRecipient::class, 'Parent' => EmailRecipient::class,
'ConditionField' => EditableFormField::class 'ConditionField' => EditableFormField::class
); ];
private static $table_name = 'UserDefinedForm_EmailRecipientCondition';
/** /**
* *

View File

@ -2,12 +2,8 @@
namespace SilverStripe\UserForms\Model\Recipient; namespace SilverStripe\UserForms\Model\Recipient;
use SilverStripe\Control\Email\Email; use SilverStripe\Control\Email\Email;
/** /**
* Email that gets sent to the people listed in the Email Recipients when a * Email that gets sent to the people listed in the Email Recipients when a
* submission is made. * submission is made.
@ -17,8 +13,7 @@ use SilverStripe\Control\Email\Email;
class UserFormRecipientEmail extends Email class UserFormRecipientEmail extends Email
{ {
protected $ss_template = 'SubmittedFormEmail';
protected $ss_template = "SubmittedFormEmail";
protected $data; protected $data;

View File

@ -2,21 +2,14 @@
namespace SilverStripe\UserForms\Model\Recipient; namespace SilverStripe\UserForms\Model\Recipient;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\View\SSViewer; use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
use SilverStripe\View\ArrayData;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField; use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormHeading; use SilverStripe\UserForms\Model\EditableFormField\EditableFormHeading;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\View\ArrayData;
use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest; use SilverStripe\View\SSViewer;
/** /**
* Controller that handles requests to EmailRecipient's * Controller that handles requests to EmailRecipient's
@ -25,13 +18,12 @@ use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
*/ */
class UserFormRecipientItemRequest extends GridFieldDetailForm_ItemRequest class UserFormRecipientItemRequest extends GridFieldDetailForm_ItemRequest
{ {
private static $allowed_actions = [
private static $allowed_actions = array(
'edit', 'edit',
'view', 'view',
'ItemEditForm', 'ItemEditForm',
'preview' 'preview'
); ];
/** /**
* Renders a preview of the recipient email. * Renders a preview of the recipient email.
@ -40,13 +32,13 @@ class UserFormRecipientItemRequest extends GridFieldDetailForm_ItemRequest
{ {
// Enable theme for preview (may be needed for Shortcodes) // Enable theme for preview (may be needed for Shortcodes)
Config::nest(); Config::nest();
Config::inst()->update(SSViewer::class, 'theme_enabled', true); Config::modify()->set(SSViewer::class, 'theme_enabled', true);
$content = $this->customise(new ArrayData(array( $content = $this->customise(ArrayData::create([
'Body' => $this->record->getEmailBodyContent(), 'Body' => $this->record->getEmailBodyContent(),
'HideFormData' => $this->record->HideFormData, 'HideFormData' => $this->record->HideFormData,
'Fields' => $this->getPreviewFieldData() 'Fields' => $this->getPreviewFieldData()
)))->renderWith($this->record->EmailTemplate); ]))->renderWith($this->record->EmailTemplate);
Config::unnest(); Config::unnest();
@ -55,24 +47,25 @@ class UserFormRecipientItemRequest extends GridFieldDetailForm_ItemRequest
/** /**
* Get some placeholder field values to display in the preview * Get some placeholder field values to display in the preview
*
* @return ArrayList * @return ArrayList
*/ */
private function getPreviewFieldData() protected function getPreviewFieldData()
{ {
$data = new ArrayList(); $data = ArrayList::create();
$fields = $this->record->Form()->Fields()->filter(array( $fields = $this->record->Form()->Fields()->filter([
'ClassName:not' => EditableLiteralField::class, 'ClassName:not' => EditableLiteralField::class,
'ClassName:not' => EditableFormHeading::class 'ClassName:not' => EditableFormHeading::class
)); ]);
foreach ($fields as $field) { foreach ($fields as $field) {
$data->push(new ArrayData(array( $data->push(ArrayData::create([
'Name' => $field->dbObject('Name'), 'Name' => $field->dbObject('Name'),
'Title' => $field->dbObject('Title'), 'Title' => $field->dbObject('Title'),
'Value' => DBField::create_field('Varchar', '$' . $field->Name), 'Value' => DBField::create_field('Varchar', '$' . $field->Name),
'FormattedValue' => DBField::create_field('Varchar', '$' . $field->Name) 'FormattedValue' => DBField::create_field('Varchar', '$' . $field->Name)
))); ]));
} }
return $data; return $data;

View File

@ -2,12 +2,9 @@
namespace SilverStripe\UserForms\Model\Submission; namespace SilverStripe\UserForms\Model\Submission;
use SilverStripe\Assets\File; use SilverStripe\Assets\File;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
/** /**
* A file uploaded on a {@link UserDefinedForm} and attached to a single * A file uploaded on a {@link UserDefinedForm} and attached to a single
* {@link SubmittedForm}. * {@link SubmittedForm}.
@ -17,10 +14,11 @@ use SilverStripe\ORM\FieldType\DBField;
class SubmittedFileField extends SubmittedFormField class SubmittedFileField extends SubmittedFormField
{ {
private static $has_one = [
'UploadedFile' => File::class
];
private static $has_one = array( private static $table_name = 'SubmittedFileField';
"UploadedFile" => File::class
);
/** /**
* Return the value of this field for inclusion into things such as * Return the value of this field for inclusion into things such as
@ -32,7 +30,7 @@ class SubmittedFileField extends SubmittedFormField
{ {
$name = $this->getFileName(); $name = $this->getFileName();
$link = $this->getLink(); $link = $this->getLink();
$title = _t('SubmittedFileField.DOWNLOADFILE', 'Download File'); $title = _t(__CLASS__.'.DOWNLOADFILE', 'Download File');
if ($link) { if ($link) {
return DBField::create_field('HTMLText', sprintf( return DBField::create_field('HTMLText', sprintf(
@ -51,7 +49,7 @@ class SubmittedFileField extends SubmittedFormField
*/ */
public function getExportValue() public function getExportValue()
{ {
return ($link = $this->getLink()) ? $link : ""; return ($link = $this->getLink()) ? $link : '';
} }
/** /**

View File

@ -2,47 +2,39 @@
namespace SilverStripe\UserForms\Model\Submission; namespace SilverStripe\UserForms\Model\Submission;
use SilverStripe\Security\Member;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\UserForms\Model\Submission\SubmittedFormField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldExportButton; use SilverStripe\Forms\GridField\GridFieldExportButton;
use SilverStripe\Forms\GridField\GridFieldPrintButton; use SilverStripe\Forms\GridField\GridFieldPrintButton;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\Security\Member;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\UserForms\Model\Submission\SubmittedFormField;
/** /**
* Contents of an UserDefinedForm submission * Contents of an UserDefinedForm submission
* *
* @package userforms * @package userforms
*/ */
class SubmittedForm extends DataObject class SubmittedForm extends DataObject
{ {
private static $has_one = [
'SubmittedBy' => Member::class,
'Parent' => UserDefinedForm::class,
];
private static $has_one = array( private static $has_many = [
"SubmittedBy" => Member::class, 'Values' => SubmittedFormField::class
"Parent" => UserDefinedForm::class, ];
);
private static $has_many = array( private static $summary_fields = [
"Values" => SubmittedFormField::class
);
private static $summary_fields = array(
'ID', 'ID',
'Created' 'Created'
); ];
private static $table_name = 'SubmittedForm';
/** /**
* Returns the value of a relation or, in the case of this form, the value * Returns the value of a relation or, in the case of this form, the value
@ -75,14 +67,12 @@ class SubmittedForm extends DataObject
*/ */
public function getCMSFields() public function getCMSFields()
{ {
$self = $this; $this->beforeUpdateCMSFields(function ($fields) {
$this->beforeUpdateCMSFields(function ($fields) use ($self) {
$fields->removeByName('Values'); $fields->removeByName('Values');
//check to ensure there is a Member to extract an Email from else null value //check to ensure there is a Member to extract an Email from else null value
if($self->SubmittedBy() && $self->SubmittedBy()->exists()){ if($this->SubmittedBy() && $this->SubmittedBy()->exists()){
$submitter = $self->SubmittedBy()->Email; $submitter = $this->SubmittedBy()->Email;
} else { } else {
$submitter = null; $submitter = null;
} }
@ -100,7 +90,7 @@ class SubmittedForm extends DataObject
$values = GridField::create( $values = GridField::create(
'Values', 'Values',
SubmittedFormField::class, SubmittedFormField::class,
$self->Values()->sort('Created', 'ASC') $this->Values()->sort('Created', 'ASC')
); );
$exportColumns = array( $exportColumns = array(

View File

@ -2,37 +2,35 @@
namespace SilverStripe\UserForms\Model\Submission; namespace SilverStripe\UserForms\Model\Submission;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
/** /**
* Data received from a UserDefinedForm submission * Data received from a UserDefinedForm submission
* *
* @package userforms * @package userforms
*/ */
class SubmittedFormField extends DataObject class SubmittedFormField extends DataObject
{ {
private static $db = [
'Name' => 'Varchar',
'Value' => 'Text',
'Title' => 'Varchar(255)'
];
private static $db = array( private static $has_one = [
"Name" => "Varchar", 'Parent' => SubmittedForm::class
"Value" => "Text", ];
"Title" => "Varchar(255)"
);
private static $has_one = array( private static $summary_fields = [
"Parent" => SubmittedForm::class
);
private static $summary_fields = array(
'Title' => 'Title', 'Title' => 'Title',
'FormattedValue' => 'Value' 'FormattedValue' => 'Value'
); ];
private static $table_name = 'SubmittedFormField';
/** /**
* @param Member * @param Member $member
* *
* @return boolean * @return boolean
*/ */
@ -42,7 +40,7 @@ class SubmittedFormField extends DataObject
} }
/** /**
* @param Member * @param Member $member
* *
* @return boolean * @return boolean
*/ */
@ -52,7 +50,7 @@ class SubmittedFormField extends DataObject
} }
/** /**
* @param Member * @param Member $member
* *
* @return boolean * @return boolean
*/ */
@ -62,7 +60,7 @@ class SubmittedFormField extends DataObject
} }
/** /**
* @param Member * @param Member $member
* *
* @return boolean * @return boolean
*/ */
@ -106,8 +104,8 @@ class SubmittedFormField extends DataObject
*/ */
public function getEditableField() public function getEditableField()
{ {
return $this->Parent()->Parent()->Fields()->filter(array( return $this->Parent()->Parent()->Fields()->filter([
'Name' => $this->Name 'Name' => $this->Name
))->First(); ])->First();
} }
} }

View File

@ -3,78 +3,48 @@
namespace SilverStripe\UserForms\Model; namespace SilverStripe\UserForms\Model;
use Page; use Page;
use Colymba\BulkManager\BulkManager;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\CheckboxField;
use HtmlEditorField;
use GridFieldBulkManager;
use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
use SilverStripe\UserForms\Model\Recipient\UserDefinedForm_EmailRecipient;
use SilverStripe\View\Requirements;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldDetailForm; use SilverStripe\Forms\GridField\GridFieldAddNewButton;
use SilverStripe\UserForms\Model\Recipient\UserFormRecipientItemRequest; use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\ORM\DB;
use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\UserForms\Form\UserFormsGridFieldFilterHeader;
use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldEditButton;
use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Forms\GridField\GridFieldEditButton;
use SilverStripe\Forms\GridField\GridFieldExportButton;
use SilverStripe\Forms\GridField\GridFieldPageCount; use SilverStripe\Forms\GridField\GridFieldPageCount;
use SilverStripe\Forms\GridField\GridFieldPaginator; use SilverStripe\Forms\GridField\GridFieldPaginator;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldExportButton;
use SilverStripe\Forms\GridField\GridFieldPrintButton; use SilverStripe\Forms\GridField\GridFieldPrintButton;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField; use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\Forms\TextField; use SilverStripe\Forms\TextField;
use SilverStripe\Forms\FieldList; use SilverStripe\ORM\ArrayList;
use SilverStripe\Core\Injector\Injector; use SilverStripe\ORM\DB;
use SilverStripe\UserForms\Task\UserFormsUpgradeService; use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension;
use SilverStripe\UserForms\Extension\UserFormValidator; use SilverStripe\UserForms\Extension\UserFormValidator;
use SilverStripe\UserForms\Form\UserFormsGridFieldFilterHeader;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\UserForms\Model\Recipient\EmailRecipient;
use SilverStripe\UserForms\Model\Recipient\UserFormRecipientItemRequest;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
use SilverStripe\UserForms\Task\UserFormsUpgradeService;
use SilverStripe\View\Requirements;
/** /**
* @package userforms * @package userforms
*/ */
class UserDefinedForm extends Page class UserDefinedForm extends Page
{ {
/** /**
* @var string * @var string
*/ */
@ -117,54 +87,56 @@ class UserDefinedForm extends Page
*/ */
private static $block_default_userforms_js = false; private static $block_default_userforms_js = false;
private static $table_name = 'UserDefinedForm';
/** /**
* Built in extensions required by this page * Built in extensions required by this page
* @config * @config
* @var array * @var array
*/ */
private static $extensions = array( private static $extensions = [
UserFormFieldEditorExtension::class UserFormFieldEditorExtension::class
); ];
/** /**
* @var array Fields on the user defined form page. * @var array Fields on the user defined form page.
*/ */
private static $db = array( private static $db = [
"SubmitButtonText" => "Varchar", 'SubmitButtonText' => 'Varchar',
"ClearButtonText" => "Varchar", 'ClearButtonText' => 'Varchar',
"OnCompleteMessage" => "HTMLText", 'OnCompleteMessage' => 'HTMLText',
"ShowClearButton" => "Boolean", 'ShowClearButton' => 'Boolean',
'DisableSaveSubmissions' => 'Boolean', 'DisableSaveSubmissions' => 'Boolean',
'EnableLiveValidation' => 'Boolean', 'EnableLiveValidation' => 'Boolean',
'DisplayErrorMessagesAtTop' => 'Boolean', 'DisplayErrorMessagesAtTop' => 'Boolean',
'DisableAuthenicatedFinishAction' => 'Boolean', 'DisableAuthenicatedFinishAction' => 'Boolean',
'DisableCsrfSecurityToken' => 'Boolean' 'DisableCsrfSecurityToken' => 'Boolean'
); ];
/** /**
* @var array Default values of variables when this page is created * @var array Default values of variables when this page is created
*/ */
private static $defaults = array( private static $defaults = [
'Content' => '$UserDefinedForm', 'Content' => '$UserDefinedForm',
'DisableSaveSubmissions' => 0, 'DisableSaveSubmissions' => 0,
'OnCompleteMessage' => '<p>Thanks, we\'ve received your submission.</p>' 'OnCompleteMessage' => '<p>Thanks, we\'ve received your submission.</p>'
); ];
/** /**
* @var array * @var array
*/ */
private static $has_many = array( private static $has_many = [
"Submissions" => SubmittedForm::class, 'Submissions' => SubmittedForm::class,
"EmailRecipients" => UserDefinedForm_EmailRecipient::class 'EmailRecipients' => EmailRecipient::class
); ];
/** /**
* @var array * @var array
* @config * @config
*/ */
private static $casting = array( private static $casting = [
'ErrorContainerID' => 'Text' 'ErrorContainerID' => 'Text'
); ];
/** /**
* Error container selector which matches the element for grouped messages * Error container selector which matches the element for grouped messages
@ -194,7 +166,7 @@ class UserDefinedForm extends Page
* Example layout: array('EditableCheckbox3' => 'EditableCheckbox14') * Example layout: array('EditableCheckbox3' => 'EditableCheckbox14')
* @var array * @var array
*/ */
protected $fieldsFromTo = array(); protected $fieldsFromTo = [];
/** /**
* @return FieldList * @return FieldList
@ -203,18 +175,16 @@ class UserDefinedForm extends Page
{ {
Requirements::css(USERFORMS_DIR . '/css/UserForm_cms.css'); Requirements::css(USERFORMS_DIR . '/css/UserForm_cms.css');
$self = $this; $this->beforeUpdateCMSFields(function ($fields) {
$this->beforeUpdateCMSFields(function ($fields) use ($self) {
// define tabs // define tabs
$fields->findOrMakeTab('Root.FormOptions', _t('UserDefinedForm.CONFIGURATION', 'Configuration')); $fields->findOrMakeTab('Root.FormOptions', _t(__CLASS__.'.CONFIGURATION', 'Configuration'));
$fields->findOrMakeTab('Root.Recipients', _t('UserDefinedForm.RECIPIENTS', 'Recipients')); $fields->findOrMakeTab('Root.Recipients', _t(__CLASS__.'.RECIPIENTS', 'Recipients'));
$fields->findOrMakeTab('Root.Submissions', _t('UserDefinedForm.SUBMISSIONS', 'Submissions')); $fields->findOrMakeTab('Root.Submissions', _t(__CLASS__.'.SUBMISSIONS', 'Submissions'));
// text to show on complete // text to show on complete
$onCompleteFieldSet = new CompositeField( $onCompleteFieldSet = CompositeField::create(
$label = new LabelField('OnCompleteMessageLabel', _t('UserDefinedForm.ONCOMPLETELABEL', 'Show on completion')), $label = LabelField::create('OnCompleteMessageLabel', _t(__CLASS__.'.ONCOMPLETELABEL', 'Show on completion')),
$editor = new HtmlEditorField('OnCompleteMessage', '', _t('UserDefinedForm.ONCOMPLETEMESSAGE', $self->OnCompleteMessage)) $editor = HTMLEditorField::create('OnCompleteMessage', '', _t(__CLASS__.'.ONCOMPLETEMESSAGE', $self->OnCompleteMessage))
); );
$onCompleteFieldSet->addExtraClass('field'); $onCompleteFieldSet->addExtraClass('field');
@ -226,13 +196,13 @@ class UserDefinedForm extends Page
$emailRecipientsConfig = GridFieldConfig_RecordEditor::create(10); $emailRecipientsConfig = GridFieldConfig_RecordEditor::create(10);
$emailRecipientsConfig->getComponentByType(GridFieldAddNewButton::class) $emailRecipientsConfig->getComponentByType(GridFieldAddNewButton::class)
->setButtonName( ->setButtonName(
_t('UserDefinedForm.ADDEMAILRECIPIENT', 'Add Email Recipient') _t(__CLASS__.'.ADDEMAILRECIPIENT', 'Add Email Recipient')
); );
// who do we email on submission // who do we email on submission
$emailRecipients = new GridField( $emailRecipients = GridField::create(
'EmailRecipients', 'EmailRecipients',
_t('UserDefinedForm.EMAILRECIPIENTS', 'Email Recipients'), _t(__CLASS__.'.EMAILRECIPIENTS', 'Email Recipients'),
$self->EmailRecipients(), $self->EmailRecipients(),
$emailRecipientsConfig $emailRecipientsConfig
); );
@ -265,7 +235,7 @@ SQL;
$columns[$name] = trim(strtr($title, '.', ' ')); $columns[$name] = trim(strtr($title, '.', ' '));
} }
$config = new GridFieldConfig(); $config = GridFieldConfig::create();
$config->addComponent(new GridFieldToolbarHeader()); $config->addComponent(new GridFieldToolbarHeader());
$config->addComponent($sort = new GridFieldSortableHeader()); $config->addComponent($sort = new GridFieldSortableHeader());
$config->addComponent($filter = new UserFormsGridFieldFilterHeader()); $config->addComponent($filter = new UserFormsGridFieldFilterHeader());
@ -285,7 +255,7 @@ SQL;
'Created' => 'Created', 'Created' => 'Created',
'LastEdited' => 'Last Edited' 'LastEdited' => 'Last Edited'
); );
foreach(EditableFormField::get()->filter(array("ParentID" => $parentID)) as $eff) { foreach(EditableFormField::get()->filter(array('ParentID' => $parentID)) as $eff) {
if($eff->ShowInSummary) { if($eff->ShowInSummary) {
$summaryarray[$eff->Name] = $eff->Title ?: $eff->Name; $summaryarray[$eff->Name] = $eff->Title ?: $eff->Name;
} }
@ -296,8 +266,8 @@ SQL;
/** /**
* Support for {@link https://github.com/colymba/GridFieldBulkEditingTools} * Support for {@link https://github.com/colymba/GridFieldBulkEditingTools}
*/ */
if (class_exists('GridFieldBulkManager')) { if (class_exists(BulkManager::class)) {
$config->addComponent(new GridFieldBulkManager()); $config->addComponent(new BulkManager);
} }
$sort->setThrowExceptionOnBadDataType(false); $sort->setThrowExceptionOnBadDataType(false);
@ -320,7 +290,7 @@ SQL;
$submissions = GridField::create( $submissions = GridField::create(
'Submissions', 'Submissions',
_t('UserDefinedForm.SUBMISSIONS', 'Submissions'), _t(__CLASS__.'.SUBMISSIONS', 'Submissions'),
$self->Submissions()->sort('Created', 'DESC'), $self->Submissions()->sort('Created', 'DESC'),
$config $config
); );
@ -329,7 +299,7 @@ SQL;
'Root.FormOptions', 'Root.FormOptions',
CheckboxField::create( CheckboxField::create(
'DisableSaveSubmissions', 'DisableSaveSubmissions',
_t('UserDefinedForm.SAVESUBMISSIONS', 'Disable Saving Submissions to Server') _t(__CLASS__.'.SAVESUBMISSIONS', 'Disable Saving Submissions to Server')
) )
); );
}); });
@ -337,10 +307,10 @@ SQL;
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
if ($this->EmailRecipients()->Count() == 0 && static::config()->recipients_warning_enabled) { if ($this->EmailRecipients()->Count() == 0 && static::config()->recipients_warning_enabled) {
$fields->addFieldToTab("Root.Main", new LiteralField("EmailRecipientsWarning", $fields->addFieldToTab('Root.Main', LiteralField::create('EmailRecipientsWarning',
"<p class=\"message warning\">" . _t("UserDefinedForm.NORECIPIENTS", '<p class="message warning">' . _t(__CLASS__.'.NORECIPIENTS',
"Warning: You have not configured any recipients. Form submissions may be missed.") 'Warning: You have not configured any recipients. Form submissions may be missed.')
. "</p>"), "Title"); . '</p>'), 'Title');
} }
return $fields; return $fields;
@ -356,11 +326,11 @@ SQL;
*/ */
public function FilteredEmailRecipients($data = null, $form = null) public function FilteredEmailRecipients($data = null, $form = null)
{ {
$recipients = new ArrayList($this->EmailRecipients()->toArray()); $recipients = ArrayList::create($this->EmailRecipients()->toArray());
// Filter by rules // Filter by rules
$recipients = $recipients->filterByCallback(function ($recipient) use ($data, $form) { $recipients = $recipients->filterByCallback(function ($recipient) use ($data, $form) {
/** @var UserDefinedForm_EmailRecipient $recipient */ /** @var EmailRecipient $recipient */
return $recipient->canSend($data, $form); return $recipient->canSend($data, $form);
}); });
@ -377,17 +347,17 @@ SQL;
*/ */
public function getFormOptions() public function getFormOptions()
{ {
$submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t('UserDefinedForm.SUBMITBUTTON', 'Submit'); $submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t(__CLASS__.'.SUBMITBUTTON', 'Submit');
$clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t('UserDefinedForm.CLEARBUTTON', 'Clear'); $clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t(__CLASS__.'.CLEARBUTTON', 'Clear');
$options = new FieldList( $options = FieldList::create(
new TextField("SubmitButtonText", _t('UserDefinedForm.TEXTONSUBMIT', 'Text on submit button:'), $submit), TextField::create('SubmitButtonText', _t(__CLASS__.'.TEXTONSUBMIT', 'Text on submit button:'), $submit),
new TextField("ClearButtonText", _t('UserDefinedForm.TEXTONCLEAR', 'Text on clear button:'), $clear), TextField::create('ClearButtonText', _t(__CLASS__.'.TEXTONCLEAR', 'Text on clear button:'), $clear),
new CheckboxField("ShowClearButton", _t('UserDefinedForm.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton), CheckboxField::create('ShowClearButton', _t(__CLASS__.'.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton),
new CheckboxField("EnableLiveValidation", _t('UserDefinedForm.ENABLELIVEVALIDATION', 'Enable live validation')), CheckboxField::create('EnableLiveValidation', _t(__CLASS__.'.ENABLELIVEVALIDATION', 'Enable live validation')),
new CheckboxField("DisplayErrorMessagesAtTop", _t('UserDefinedForm.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')), CheckboxField::create('DisplayErrorMessagesAtTop', _t(__CLASS__.'.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')),
new CheckboxField('DisableCsrfSecurityToken', _t('UserDefinedForm.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')), CheckboxField::create('DisableCsrfSecurityToken', _t(__CLASS__.'.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')),
new CheckboxField('DisableAuthenicatedFinishAction', _t('UserDefinedForm.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action')) CheckboxField::create('DisableAuthenicatedFinishAction', _t(__CLASS__.'.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action'))
); );
$this->extend('updateFormOptions', $options); $this->extend('updateFormOptions', $options);
@ -402,14 +372,14 @@ SQL;
*/ */
public function getErrorContainerID() public function getErrorContainerID()
{ {
return $this->config()->error_container_id; return $this->config()->get('error_container_id');
} }
public function requireDefaultRecords() public function requireDefaultRecords()
{ {
parent::requireDefaultRecords(); parent::requireDefaultRecords();
if (!$this->config()->upgrade_on_build) { if (!$this->config()->get('upgrade_on_build')) {
return; return;
} }
@ -428,6 +398,6 @@ SQL;
*/ */
public function getCMSValidator() public function getCMSValidator()
{ {
return new UserFormValidator(); return UserFormValidator::create();
} }
} }

View File

@ -3,75 +3,53 @@
namespace SilverStripe\UserForms\Model; namespace SilverStripe\UserForms\Model;
use PageController; use PageController;
use Object;
use SilverStripe\View\Requirements;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\UserForms\Form\UserForm;
use SilverStripe\Forms\Form;
use SilverStripe\Control\Controller;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
use SilverStripe\Security\Member;
use SilverStripe\ORM\ArrayList;
use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
use SilverStripe\Assets\Upload;
use SilverStripe\Assets\File; use SilverStripe\Assets\File;
use SilverStripe\ORM\ValidationException; use SilverStripe\Assets\Upload;
use SilverStripe\UserForms\Model\Recipient\UserFormRecipientEmail; use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTP; use SilverStripe\Control\HTTP;
use SilverStripe\View\SSViewer; use SilverStripe\Forms\Form;
use SilverStripe\Control\Session; use SilverStripe\i18n\i18n;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Member;
use SilverStripe\UserForms\Form\UserForm;
use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
use SilverStripe\UserForms\Model\Recipient\UserFormRecipientEmail;
use SilverStripe\UserForms\Model\Submission\SubmittedForm;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements;
use SilverStripe\View\SSViewer;
/** /**
* Controller for the {@link UserDefinedForm} page type. * Controller for the {@link UserDefinedForm} page type.
* *
* @package userforms * @package userforms
*/ */
class UserDefinedFormController extends PageController class UserDefinedFormController extends PageController
{ {
private static $finished_anchor = '#uff'; private static $finished_anchor = '#uff';
private static $allowed_actions = array( private static $allowed_actions = [
'index', 'index',
'ping', 'ping',
'Form', 'Form',
'finished' 'finished'
); ];
public function init() protected function init()
{ {
parent::init(); parent::init();
$page = $this->data(); $page = $this->data();
// load the css // load the css
if (!$page->config()->block_default_userforms_css) { if (!$page->config()->get('block_default_userforms_css')) {
Requirements::css(USERFORMS_DIR . '/css/UserForm.css'); Requirements::css(USERFORMS_DIR . '/css/UserForm.css');
} }
// load the jquery // load the jquery
if (!$page->config()->block_default_userforms_js) { if (!$page->config()->get('block_default_userforms_js')) {
$lang = i18n::get_lang_from_locale(i18n::get_locale()); $lang = i18n::get_lang_from_locale(i18n::get_locale());
Requirements::javascript(FRAMEWORK_DIR .'/thirdparty/jquery/jquery.js'); Requirements::javascript(FRAMEWORK_DIR .'/thirdparty/jquery/jquery.js');
Requirements::javascript(USERFORMS_DIR . '/thirdparty/jquery-validate/jquery.validate.min.js'); Requirements::javascript(USERFORMS_DIR . '/thirdparty/jquery-validate/jquery.validate.min.js');
@ -86,7 +64,7 @@ class UserDefinedFormController extends PageController
); );
// Bind a confirmation message when navigating away from a partially completed form. // Bind a confirmation message when navigating away from a partially completed form.
if ($page::config()->enable_are_you_sure) { if ($page::config()->get('enable_are_you_sure')) {
Requirements::javascript(USERFORMS_DIR . '/thirdparty/jquery.are-you-sure/jquery.are-you-sure.js'); Requirements::javascript(USERFORMS_DIR . '/thirdparty/jquery.are-you-sure/jquery.are-you-sure.js');
} }
} }
@ -105,17 +83,17 @@ class UserDefinedFormController extends PageController
$hasLocation = stristr($this->Content, '$UserDefinedForm'); $hasLocation = stristr($this->Content, '$UserDefinedForm');
if ($hasLocation) { if ($hasLocation) {
$content = preg_replace('/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i', $form->forTemplate(), $this->Content); $content = preg_replace('/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i', $form->forTemplate(), $this->Content);
return array( return [
'Content' => DBField::create_field('HTMLText', $content), 'Content' => DBField::create_field('HTMLText', $content),
'Form' => "" 'Form' => ''
); ];
} }
} }
return array( return [
'Content' => DBField::create_field('HTMLText', $this->Content), 'Content' => DBField::create_field('HTMLText', $this->Content),
'Form' => $this->Form() 'Form' => $this->Form()
); ];
} }
/** /**
@ -149,10 +127,10 @@ class UserDefinedFormController extends PageController
*/ */
public function generateConditionalJavascript() public function generateConditionalJavascript()
{ {
$default = ""; $default = '';
$rules = ""; $rules = '';
$watch = array(); $watch = [];
if ($this->Fields()) { if ($this->Fields()) {
/** @var EditableFormField $field */ /** @var EditableFormField $field */
@ -191,7 +169,7 @@ JS
*/ */
public function process($data, $form) public function process($data, $form)
{ {
$submittedForm = Object::create(SubmittedForm::class); $submittedForm = SubmittedForm::create();
$submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0;
$submittedForm->ParentID = $this->ID; $submittedForm->ParentID = $this->ID;
@ -201,7 +179,7 @@ JS
} }
$attachments = array(); $attachments = array();
$submittedFields = new ArrayList(); $submittedFields = ArrayList::create();
foreach ($this->Fields() as $field) { foreach ($this->Fields() as $field) {
if (!$field->showInReports()) { if (!$field->showInReports()) {
@ -228,8 +206,8 @@ JS
$foldername = $field->getFormField()->getFolderName(); $foldername = $field->getFormField()->getFolderName();
// create the file from post data // create the file from post data
$upload = new Upload(); $upload = Upload::create();
$file = new File(); $file = File::create();
$file->ShowInSearch = 0; $file->ShowInSearch = 0;
try { try {
$upload->loadIntoFile($_FILES[$field->Name], $file, $foldername); $upload->loadIntoFile($_FILES[$field->Name], $file, $foldername);
@ -260,22 +238,25 @@ JS
$submittedFields->push($submittedField); $submittedFields->push($submittedField);
} }
$emailData = array( $emailData = [
"Sender" => Member::currentUser(), 'Sender' => Member::currentUser(),
"Fields" => $submittedFields 'Fields' => $submittedFields
); ];
$this->extend('updateEmailData', $emailData, $attachments); $this->extend('updateEmailData', $emailData, $attachments);
// email users on submit. // email users on submit.
if ($recipients = $this->FilteredEmailRecipients($data, $form)) { if ($recipients = $this->FilteredEmailRecipients($data, $form)) {
foreach ($recipients as $recipient) { foreach ($recipients as $recipient) {
$email = new UserFormRecipientEmail($submittedFields); $email = UserFormRecipientEmail::create($submittedFields);
$mergeFields = $this->getMergeFieldsMap($emailData['Fields']); $mergeFields = $this->getMergeFieldsMap($emailData['Fields']);
if ($attachments) { if ($attachments) {
foreach ($attachments as $file) { foreach ($attachments as $file) {
if ($file->ID != 0) { if (!$file->ID != 0) {
continue;
}
$email->attachFile( $email->attachFile(
$file->Filename, $file->Filename,
$file->Filename, $file->Filename,
@ -283,7 +264,6 @@ JS
); );
} }
} }
}
$parsedBody = SSViewer::execute_string($recipient->getEmailBodyContent(), $mergeFields); $parsedBody = SSViewer::execute_string($recipient->getEmailBodyContent(), $mergeFields);
@ -348,8 +328,9 @@ JS
$submittedForm->extend('updateAfterProcess'); $submittedForm->extend('updateAfterProcess');
Session::clear("FormInfo.{$form->FormName()}.errors"); $session = $this->getRequest()->getSession();
Session::clear("FormInfo.{$form->FormName()}.data"); $session->clear("FormInfo.{$form->FormName()}.errors");
$session->clear("FormInfo.{$form->FormName()}.data");
$referrer = (isset($data['Referrer'])) ? '?referrer=' . urlencode($data['Referrer']) : ""; $referrer = (isset($data['Referrer'])) ? '?referrer=' . urlencode($data['Referrer']) : "";
@ -357,24 +338,24 @@ JS
// the finished method directly. // the finished method directly.
if (!$this->DisableAuthenicatedFinishAction) { if (!$this->DisableAuthenicatedFinishAction) {
if (isset($data['SecurityID'])) { if (isset($data['SecurityID'])) {
Session::set('FormProcessed', $data['SecurityID']); $session->set('FormProcessed', $data['SecurityID']);
} else { } else {
// if the form has had tokens disabled we still need to set FormProcessed // if the form has had tokens disabled we still need to set FormProcessed
// to allow us to get through the finshed method // to allow us to get through the finshed method
if (!$this->Form()->getSecurityToken()->isEnabled()) { if (!$this->Form()->getSecurityToken()->isEnabled()) {
$randNum = rand(1, 1000); $randNum = rand(1, 1000);
$randHash = md5($randNum); $randHash = md5($randNum);
Session::set('FormProcessed', $randHash); $session->set('FormProcessed', $randHash);
Session::set('FormProcessedNum', $randNum); $session->set('FormProcessedNum', $randNum);
} }
} }
} }
if (!$this->DisableSaveSubmissions) { if (!$this->DisableSaveSubmissions) {
Session::set('userformssubmission'. $this->ID, $submittedForm->ID); $session->set('userformssubmission'. $this->ID, $submittedForm->ID);
} }
return $this->redirect($this->Link('finished') . $referrer . $this->config()->finished_anchor); return $this->redirect($this->Link('finished') . $referrer . $this->config()->get('finished_anchor'));
} }
/** /**
@ -385,7 +366,7 @@ JS
*/ */
protected function getMergeFieldsMap($fields = array()) protected function getMergeFieldsMap($fields = array())
{ {
$data = new ArrayData(array()); $data = ArrayData::create([]);
foreach ($fields as $field) { foreach ($fields as $field) {
$data->setField($field->Name, DBField::create_field('Text', $field->Value)); $data->setField($field->Name, DBField::create_field('Text', $field->Value));
@ -402,7 +383,7 @@ JS
*/ */
public function finished() public function finished()
{ {
$submission = Session::get('userformssubmission'. $this->ID); $submission = $this->getRequest()->getSession()->get('userformssubmission'. $this->ID);
if ($submission) { if ($submission) {
$submission = SubmittedForm::get()->byId($submission); $submission = SubmittedForm::get()->byId($submission);
@ -411,36 +392,36 @@ JS
$referrer = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : null; $referrer = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : null;
if (!$this->DisableAuthenicatedFinishAction) { if (!$this->DisableAuthenicatedFinishAction) {
$formProcessed = Session::get('FormProcessed'); $formProcessed = $this->getRequest()->getSession()->get('FormProcessed');
if (!isset($formProcessed)) { if (!isset($formProcessed)) {
return $this->redirect($this->Link() . $referrer); return $this->redirect($this->Link() . $referrer);
} else { } else {
$securityID = Session::get('SecurityID'); $securityID = $this->getRequest()->getSession()->get('SecurityID');
// make sure the session matches the SecurityID and is not left over from another form // make sure the session matches the SecurityID and is not left over from another form
if ($formProcessed != $securityID) { if ($formProcessed != $securityID) {
// they may have disabled tokens on the form // they may have disabled tokens on the form
$securityID = md5(Session::get('FormProcessedNum')); $securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum'));
if ($formProcessed != $securityID) { if ($formProcessed != $securityID) {
return $this->redirect($this->Link() . $referrer); return $this->redirect($this->Link() . $referrer);
} }
} }
} }
Session::clear('FormProcessed'); $this->getRequest()->getSession()->clear('FormProcessed');
} }
$data = array( $data = [
'Submission' => $submission, 'Submission' => $submission,
'Link' => $referrer 'Link' => $referrer
); ];
$this->extend('updateReceivedFormSubmissionData', $data); $this->extend('updateReceivedFormSubmissionData', $data);
return $this->customise(array( return $this->customise([
'Content' => $this->customise($data)->renderWith('ReceivedFormSubmission'), 'Content' => $this->customise($data)->renderWith('ReceivedFormSubmission'),
'Form' => '', 'Form' => '',
)); ]);
} }
/** /**

View File

@ -2,23 +2,12 @@
namespace SilverStripe\UserForms\Modifier; namespace SilverStripe\UserForms\Modifier;
use SilverStripe\Forms\SegmentFieldModifier\AbstractSegmentFieldModifier;
use EditableformField;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use SilverStripe\Forms\SegmentFieldModifier\AbstractSegmentFieldModifier;
use SilverStripe\UserForms\Model\EditableFormField;
class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier
{ {
/**
* @inheritdoc
*
* @param string $value
*
* @return string
*/
public function getPreview($value) public function getPreview($value)
{ {
if ($this->form instanceof Form && $record = $this->form->getRecord()) { if ($this->form instanceof Form && $record = $this->form->getRecord()) {
@ -26,7 +15,7 @@ class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier
$try = $value; $try = $value;
$sibling = EditableformField::get() $sibling = EditableFormField::get()
->filter('ParentID', $parent->ID) ->filter('ParentID', $parent->ID)
->filter('Name', $try) ->filter('Name', $try)
->where('"ID" != ' . $record->ID) ->where('"ID" != ' . $record->ID)
@ -37,7 +26,7 @@ class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier
while ($sibling !== null) { while ($sibling !== null) {
$try = $value . '_' . $counter++; $try = $value . '_' . $counter++;
$sibling = EditableformField::get() $sibling = EditableFormField::get()
->filter('ParentID', $parent->ID) ->filter('ParentID', $parent->ID)
->filter('Name', $try) ->filter('Name', $try)
->first(); ->first();
@ -51,13 +40,6 @@ class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier
return $value; return $value;
} }
/**
* @inheritdoc
*
* @param string $value
*
* @return string
*/
public function getSuggestion($value) public function getSuggestion($value)
{ {
return $this->getPreview($value); return $this->getPreview($value);

View File

@ -2,32 +2,15 @@
namespace SilverStripe\UserForms\Modifier; namespace SilverStripe\UserForms\Modifier;
use SilverStripe\Forms\SegmentFieldModifier\SlugSegmentFieldModifier; use SilverStripe\Forms\SegmentFieldModifier\SlugSegmentFieldModifier;
class UnderscoreSegmentFieldModifier extends SlugSegmentFieldModifier class UnderscoreSegmentFieldModifier extends SlugSegmentFieldModifier
{ {
/**
* @inheritdoc
*
* @param string $value
*
* @return string
*/
public function getPreview($value) public function getPreview($value)
{ {
return str_replace('-', '_', parent::getPreview($value)); return str_replace('-', '_', parent::getPreview($value));
} }
/**
* @inheritdoc
*
* @param string $value
*
* @return string
*/
public function getSuggestion($value) public function getSuggestion($value)
{ {
return str_replace('-', '_', parent::getSuggestion($value)); return str_replace('-', '_', parent::getSuggestion($value));

View File

@ -2,13 +2,10 @@
namespace SilverStripe\UserForms\Task; namespace SilverStripe\UserForms\Task;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\ORM\DB;
use SilverStripe\Dev\MigrationTask; use SilverStripe\Dev\MigrationTask;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
/** /**
* UserForms Column Clean Task * UserForms Column Clean Task
@ -20,24 +17,24 @@ use SilverStripe\Dev\MigrationTask;
class UserFormsColumnCleanTask extends MigrationTask class UserFormsColumnCleanTask extends MigrationTask
{ {
protected $title = 'UserForms EditableFormField Column Clean task';
protected $title = "UserForms EditableFormField Column Clean task"; protected $description = 'Removes unused columns from EditableFormField for MySQL databases;';
protected $description = "Removes unused columns from EditableFormField for MySQL databases;"; protected $tables = [EditableFormField::class];
protected $tables = array(EditableFormField::class); protected $keepColumns = ['ID'];
protected $keepColumns = array('ID');
/** /**
* Publish the existing forms. * Publish the existing forms.
*
*/ */
public function run($request) public function run($request)
{ {
/** @var \SilverStripe\ORM\DataObjectSchema $schema */
$schema = DataObject::getSchema();
foreach ($this->tables as $db) { foreach ($this->tables as $db) {
$obj = new $db(); $columns = $schema->databaseFields($db);
$columns = $obj->database_fields($db);
$query = "SHOW COLUMNS FROM $db"; $query = "SHOW COLUMNS FROM $db";
$liveColumns = DB::query($query)->column(); $liveColumns = DB::query($query)->column();
$backedUp = 0; $backedUp = 0;

View File

@ -1,306 +0,0 @@
<?php
namespace SilverStripe\UserForms\Task;
use SilverStripe\UserForms\Model\EditableFormField\EditableFormField;
use SilverStripe\Versioned\Versioned;
use SilverStripe\UserForms\Model\EditableCustomRule;
use SilverStripe\Control\Director;
use SilverStripe\ORM\DB;
/**
* Service to support upgrade of userforms module
*/
class UserFormsUpgradeService
{
/**
* @var bool
*/
protected $quiet;
public function run()
{
$this->log("Upgrading formfield rules and custom settings");
// List of rules that have been created in all stages
$fields = Versioned::get_including_deleted(EditableFormField::class);
foreach ($fields as $field) {
$this->upgradeField($field);
}
}
/**
* Migrate a versioned field in all stages
*
* @param EditableFormField $field
*/
protected function upgradeField(EditableFormField $field)
{
$this->log("Upgrading formfield ID = ".$field->ID);
// Check versions this field exists on
$filter = sprintf('"EditableFormField"."ID" = \'%d\' AND "Migrated" = 0', $field->ID);
$stageField = Versioned::get_one_by_stage(EditableFormField::class, 'Stage', $filter);
$liveField = Versioned::get_one_by_stage(EditableFormField::class, 'Live', $filter);
if ($stageField) {
$this->upgradeFieldInStage($stageField, 'Stage');
}
if ($liveField) {
$this->upgradeFieldInStage($liveField, 'Live');
}
}
/**
* Migrate a versioned field in a single stage
*
* @param EditableFormField $field
* @param stage $stage
*/
protected function upgradeFieldInStage(EditableFormField $field, $stage)
{
Versioned::reading_stage($stage);
// Migrate field rules
$this->migrateRules($field, $stage);
// Migrate custom settings
$this->migrateCustomSettings($field, $stage);
// Flag as migrated
$field->Migrated = true;
$field->write();
}
/**
* Migrate custom rules for the given field
*
* @param EditableFormField $field
* @param string $stage
*/
protected function migrateRules(EditableFormField $field, $stage)
{
$rulesData = $field->CustomRules
? unserialize($field->CustomRules)
: array();
// Skip blank rules or fields with custom rules already
if (empty($rulesData) || $field->DisplayRules()->count()) {
return;
}
// Check value of this condition
foreach ($rulesData as $ruleDataItem) {
if (empty($ruleDataItem['ConditionOption']) || empty($ruleDataItem['Display'])) {
continue;
}
// Get data for this rule
$conditionOption = $ruleDataItem['ConditionOption'];
$display = $ruleDataItem['Display'];
$conditionFieldName = empty($ruleDataItem['ConditionField']) ? null : $ruleDataItem['ConditionField'];
$value = isset($ruleDataItem['Value'])
? $ruleDataItem['Value']
: null;
// Create rule
$rule = $this->findOrCreateRule($field, $stage, $conditionOption, $display, $conditionFieldName, $value);
$this->log("Upgrading rule ID = " . $rule->ID);
}
}
/**
* Migrate custom settings for the given field
*
* @param EditableFormField $field
* @param string $stage
*/
protected function migrateCustomSettings(EditableFormField $field, $stage)
{
// Custom settings include:
// - ExtraClass
// - RightTitle
// - ShowOnLoad (show or '' are treated as true)
//
// - CheckedDefault (new field on EditableCheckbox - should be read from old "default" value)
// - Default (EditableCheckbox)
// - DefaultToToday (EditableDateField)
// - Folder (EditableFileField)
// - Level (EditableFormHeading)
// - HideFromReports (EditableFormHeading / EditableLiteralField)
// - Content (EditableLiteralField)
// - GroupID (EditableMemberListField)
// - MinValue (EditableNumericField)
// - MaxValue (EditableNumericField)
// - MinLength (EditableTextField)
// - MaxLength (EditableTextField)
// - Rows (EditableTextField)
// - Placeholder (EditableTextField / EditableEmailField / EditableNumericField)
$customSettings = $field->CustomSettings
? unserialize($field->CustomSettings)
: array();
// Skip blank rules or fields with custom rules already
if (empty($customSettings)) {
return;
}
$field->migrateSettings($customSettings);
if ($field->config()->has_placeholder) {
$this->migratePlaceholder($field, $field->ClassName);
}
$field->write();
}
/**
* Create or find an existing field with the matched specification
*
* @param EditableFormField $field
* @param string $stage
* @param string $conditionOption
* @param string $display
* @param string $conditionFieldName
* @param string $value
* @return EditableCustomRule
*/
protected function findOrCreateRule(EditableFormField $field, $stage, $conditionOption, $display, $conditionFieldName, $value)
{
// Get id of field
$conditionField = $conditionFieldName
? EditableFormField::get()->filter('Name', $conditionFieldName)->first()
: null;
// If live, search stage record for matching one
if ($stage === 'Live') {
$list = Versioned::get_by_stage(EditableCustomRule::class, 'Stage')
->filter(array(
'ParentID' => $field->ID,
'ConditionFieldID' => $conditionField ? $conditionField->ID : 0,
'Display' => $display,
'ConditionOption' => $conditionOption
));
if ($value) {
$list = $list->filter('FieldValue', $value);
} else {
$list = $list->where('"FieldValue" IS NULL OR "FieldValue" = \'\'');
}
$rule = $list->first();
if ($rule) {
$rule->write();
$rule->publish("Stage", "Live");
return $rule;
}
}
// If none found, or in stage, create new record
$rule = new EditableCustomRule();
$rule->ParentID = $field->ID;
$rule->ConditionFieldID = $conditionField ? $conditionField->ID : 0;
$rule->Display = $display;
$rule->ConditionOption = $conditionOption;
$rule->FieldValue = $value;
$rule->write();
return $rule;
}
public function log($message)
{
if ($this->getQuiet()) {
return;
}
if (Director::is_cli()) {
echo "{$message}\n";
} else {
echo "{$message}<br />";
}
}
/**
* Set if this service should be quiet
*
* @param bool $quiet
* @return $ths
*/
public function setQuiet($quiet)
{
$this->quiet = $quiet;
return $this;
}
public function getQuiet()
{
return $this->quiet;
}
/**
* Migrate Placeholder data from field specific table to the EditableFormField table
*
* @param EditableFormField $field
* @param string $tableName
*/
private function migratePlaceholder($field, $tableName)
{
// Migrate Placeholder setting from $tableName table to EditableFormField table
if ($field->Placeholder) {
return;
}
// Check if draft table exists
if (!DB::get_schema()->hasTable($tableName)) {
// Check if _obsolete_ draft table exists
$tableName = '_obsolete_' . $tableName;
if (!DB::get_schema()->hasTable($tableName)) {
return;
}
}
// Check if old Placeholder column exists
if (!DB::get_schema()->hasField($tableName, 'Placeholder')) {
return;
}
// Fetch existing draft Placeholder value
$query = "SELECT \"Placeholder\" FROM \"$tableName\" WHERE \"ID\" = '$field->ID'";
$draftPlaceholder = DB::query($query)->value();
if (!$draftPlaceholder) {
return;
}
// Update draft Placeholder value
DB::prepared_query(
"UPDATE \"EditableFormField\" SET \"Placeholder\" = ? WHERE \"ID\" = ?",
array($draftPlaceholder, $field->ID)
);
$livePlaceholder = $draftPlaceholder;
// Check if live table exists
$tableName = $tableName . '_Live';
if (DB::get_schema()->hasTable($tableName)) {
// Fetch existing live Placeholder value
$query = "SELECT \"Placeholder\" FROM \"$tableName\" WHERE \"ID\" = '" . $field->ID . "'";
$livePlaceholder = DB::query($query)->value();
if (!$livePlaceholder) {
$livePlaceholder = $draftPlaceholder;
}
}
// Update live Placeholder value
DB::prepared_query(
"UPDATE \"EditableFormField_Live\" SET \"Placeholder\" = ? WHERE \"ID\" = ?",
array($draftPlaceholder, $field->ID)
);
}
}

View File

@ -1,33 +0,0 @@
<?php
namespace SilverStripe\UserForms\Task;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\UserForms\Task\UserFormsUpgradeService;
use SilverStripe\Dev\BuildTask;
/**
* Assists with upgrade of userforms to 3.0
*
* @author dmooyman
*/
class UserFormsUpgradeTask extends BuildTask
{
protected $title = "UserForms 3.0 Migration Tool";
protected $description = "Upgrade tool for sites upgrading to userforms 3.0";
public function run($request)
{
$service = Injector::inst()->create(UserFormsUpgradeService::class);
$service->log("Upgrading userforms module");
$service->setQuiet(false)
->run();
$service->log("Done");
}
}

View File

@ -1,48 +0,0 @@
<?php
namespace SilverStripe\UserForms\Task;
use SilverStripe\UserForms\Model\UserDefinedForm;
use SilverStripe\Versioned\Versioned;
use SilverStripe\Dev\MigrationTask;
/**
* UserForms Versioned Task
*
* Initial migration script for forms that do not exist on the live site.
* In previous versions of UserForms it did not provide staging / live functionality
* When upgrading to the new version we need to publish the existing pages.
*
* @package userforms
*/
class UserFormsVersionedTask extends MigrationTask
{
protected $title = "UserForms Versioned Initial Migration";
protected $description = "Publishes the existing forms";
/**
* Publish the existing forms.
*
*/
public function run($request)
{
$forms = Versioned::get_by_stage(UserDefinedForm::class, 'Live');
if ($forms) {
foreach ($forms as $form) {
echo "Publishing $form->Title <br />";
$form->doPublish();
}
echo "Complete";
} else {
echo "No Forms Found";
}
}
}