804 lines
23 KiB
PHP
Raw Normal View History

2014-05-14 23:24:20 +10:00
<?php namespace Backend\Widgets;
use App;
use Str;
use Lang;
2014-07-09 19:36:49 +10:00
use Model;
2014-05-14 23:24:20 +10:00
use Form as FormHelper;
use Input;
use Event;
use Backend\Classes\FormField;
use Backend\Classes\WidgetBase;
use Backend\Classes\WidgetManager;
use System\Classes\ApplicationException;
use Backend\Classes\FormWidgetBase;
2014-05-14 23:24:20 +10:00
/**
* Form Widget
* Used for building back end forms and renders a form.
*
* @package october\backend
* @author Alexey Bobkov, Samuel Georges
*/
class Form extends WidgetBase
{
2014-05-14 23:24:20 +10:00
/**
* {@inheritDoc}
*/
public $defaultAlias = 'form';
/**
* @var Model Form model object.
*/
public $model;
/**
* @var array Dataset containing field values, if none supplied, model is used.
*/
public $data;
/**
* @var boolean Determines if field definitions have been created.
*/
2014-08-01 18:18:09 +10:00
protected $fieldsDefined = false;
2014-05-14 23:24:20 +10:00
/**
* @var array Collection of all fields used in this form.
*/
2014-08-23 21:46:03 +10:00
protected $fields = [];
2014-05-14 23:24:20 +10:00
2014-08-01 18:20:55 +10:00
/**
2014-05-14 23:24:20 +10:00
* @var array Collection of all form widgets used in this form.
*/
protected $formWidgets = [];
2014-05-14 23:24:20 +10:00
/**
* @var array Collection of fields not contained in a tab.
*/
protected $outsideFields = [];
/**
* @var array Collection of fields inside the primary tabs.
*/
protected $primaryTabs = [];
/**
* @var array Collection of fields inside the secondary tabs.
*/
protected $secondaryTabs = [];
/**
* @var string If the field element names should be contained in an array.
* Eg: <input name="nameArray[fieldName]" />
*/
public $arrayName;
/**
* @var string The context of this form, fields that do not belong
* to this context will not be shown.
*/
protected $activeContext = null;
/**
* @var string Active session key, used for editing forms and deferred bindings.
*/
public $sessionKey;
/**
* @var bool Render this form with uneditable preview data.
*/
public $previewMode = false;
/**
* @var Backend\Classes\WidgetManager
*/
protected $widgetManager;
/**
* Initialize the widget, called by the constructor and free from its parameters.
*/
public function init()
{
$this->widgetManager = WidgetManager::instance();
$this->arrayName = $this->getConfig('arrayName');
$this->activeContext = $this->getConfig('context');
$this->validateModel();
}
/**
* Ensure fields are defined and form widgets are registered so they can
* also be bound to the controller this allows their AJAX features to
* operate.
* @return void
*/
public function bindToController()
{
$this->defineFormFields();
parent::bindToController();
}
/**
* {@inheritDoc}
*/
public function loadAssets()
{
$this->addJs('js/october.form.js', 'core');
2014-05-14 23:24:20 +10:00
}
/**
* Renders the widget.
*
* Options:
* - preview: Render this form as an uneditable preview. Default: false
* - useContainer: Wrap the result in a container, used by AJAX. Default: true
2014-05-14 23:24:20 +10:00
* - section: Which form section to render. Default: null
* - outside: Renders the Outside Fields area.
* - primary: Renders the Primary Tabs area.
* - secondary: Renders the Secondary Tabs area.
* - null: Renders all sections
*/
public function render($options = [])
{
if (isset($options['preview'])) $this->previewMode = $options['preview'];
if (!isset($options['useContainer'])) $options['useContainer'] = true;
if (!isset($options['section'])) $options['section'] = null;
$extraVars = [];
$targetPartial = 'form';
2014-05-14 23:24:20 +10:00
/*
* Determine the partial to use based on the supplied section option
*/
if ($section = $options['section']) {
switch (strtolower($section)) {
default:
case 'outside': $sectionPartial = 'section_outside-fields'; break;
case 'primary': $sectionPartial = 'section_primary-tabs'; break;
case 'secondary': $sectionPartial = 'section_secondary-tabs'; break;
}
$targetPartial = $sectionPartial;
$extraVars['renderSection'] = $section;
}
/*
* Apply a container to the element
*/
if ($useContainer = $options['useContainer']) {
$targetPartial = ($section) ? 'section-container' : 'form-container';
2014-05-14 23:24:20 +10:00
}
$this->prepareVars();
return $this->makePartial($targetPartial, $extraVars);
2014-05-14 23:24:20 +10:00
}
/**
* Renders a single form field
*/
public function renderField($field, $options = [])
2014-05-14 23:24:20 +10:00
{
if (is_string($field)) {
2014-08-23 21:46:03 +10:00
if (!isset($this->fields[$field]))
2014-05-14 23:24:20 +10:00
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
2014-08-23 21:46:03 +10:00
$field = $this->fields[$field];
2014-05-14 23:24:20 +10:00
}
if (!isset($options['useContainer'])) $options['useContainer'] = true;
$targetPartial = $options['useContainer'] ? 'field-container' : 'field';
2014-05-14 23:24:20 +10:00
$this->prepareVars();
return $this->makePartial($targetPartial, ['field' => $field]);
2014-05-14 23:24:20 +10:00
}
/**
* Renders the HTML element for a field
*/
public function renderFieldElement($field)
{
return $this->makePartial('field_'.$field->type, ['field' => $field, 'formModel' => $this->model]);
2014-05-14 23:24:20 +10:00
}
/**
* Validate the supplied form model.
* @return void
*/
protected function validateModel()
{
$this->model = $this->getConfig('model');
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.form.missing_model', ['class'=>get_class($this->controller)]));
$this->data = (object) $this->getConfig('data', $this->model);
2014-05-14 23:24:20 +10:00
return $this->model;
}
/**
* Prepares the list data
*/
2014-08-01 18:18:09 +10:00
protected function prepareVars()
2014-05-14 23:24:20 +10:00
{
$this->defineFormFields();
$this->vars['sessionKey'] = $this->getSessionKey();
$this->vars['outsideFields'] = $this->outsideFields;
$this->vars['primaryTabs'] = $this->primaryTabs;
$this->vars['secondaryTabs'] = $this->secondaryTabs;
}
/**
* Sets or resets form field values.
* @param array $data
* @return array
*/
public function setFormValues($data = null)
{
if ($data == null)
$data = $this->getSaveData();
$this->model->fill($data);
$this->data = (object) array_merge((array) $this->data, (array) $data);
2014-08-23 21:46:03 +10:00
foreach ($this->fields as $field)
$field->value = $this->getFieldValue($field);
return $data;
}
/**
* Event handler for refreshing the form.
*/
public function onRefresh()
{
$result = [];
$saveData = $this->getSaveData();
/*
* Extensibility
*/
$eventResults = $this->fireEvent('form.beforeRefresh', [$saveData]) + Event::fire('backend.form.beforeRefresh', [$this, $saveData]);
foreach ($eventResults as $eventResult)
$saveData = $eventResult + $saveData;
/*
* Set the form variables and prepare the widget
*/
$this->setFormValues($saveData);
$this->prepareVars();
/*
* If an array of fields is supplied, update specified fields individually.
*/
if (($updateFields = post('fields')) && is_array($updateFields)) {
foreach ($updateFields as $field) {
2014-08-23 21:46:03 +10:00
if (!isset($this->fields[$field]))
continue;
2014-08-23 21:46:03 +10:00
$fieldObject = $this->fields[$field];
$result['#' . $fieldObject->getId('group')] = $this->makePartial('field', ['field' => $fieldObject]);
}
}
/*
* Update the whole form
*/
if (empty($result))
$result = ['#'.$this->getId() => $this->makePartial('form')];
/*
* Extensibility
*/
$eventResults = $this->fireEvent('form.refresh', [$result]) + Event::fire('backend.form.refresh', [$this, $result]);
foreach ($eventResults as $eventResult)
$result = $eventResult + $result;
return $result;
}
2014-05-14 23:24:20 +10:00
/**
* Creates a flat array of form fields from the configuration.
* Also slots fields in to their respective tabs.
*/
protected function defineFormFields()
{
if ($this->fieldsDefined)
return;
/*
* Extensibility
*/
Event::fire('backend.form.extendFieldsBefore', [$this]);
$this->fireEvent('form.extendFieldsBefore');
2014-05-14 23:24:20 +10:00
/*
* Outside fields
*/
if (!isset($this->config->fields) || !is_array($this->config->fields))
$this->config->fields = [];
$this->addFields($this->config->fields);
/*
* Primary Tabs + Fields
*/
if (!isset($this->config->tabs['fields']) || !is_array($this->config->tabs['fields']))
$this->config->tabs['fields'] = [];
$this->addFields($this->config->tabs['fields'], 'primary');
/*
* Secondary Tabs + Fields
*/
if (!isset($this->config->secondaryTabs['fields']) || !is_array($this->config->secondaryTabs['fields']))
$this->config->secondaryTabs['fields'] = [];
$this->addFields($this->config->secondaryTabs['fields'], 'secondary');
/*
* Extensibility
*/
Event::fire('backend.form.extendFields', [$this]);
$this->fireEvent('form.extendFields');
2014-05-14 23:24:20 +10:00
/*
* Convert automatic spanned fields
*/
$this->processAutoSpan($this->outsideFields);
foreach ($this->primaryTabs as $fields)
$this->processAutoSpan($fields);
foreach ($this->secondaryTabs as $fields)
$this->processAutoSpan($fields);
/*
* Bind all form widgets to controller
*/
2014-08-23 21:46:03 +10:00
foreach ($this->fields as $field) {
2014-05-14 23:24:20 +10:00
if ($field->type != 'widget')
continue;
$widget = $this->makeFormWidget($field);
$widget->bindToController();
}
$this->fieldsDefined = true;
}
/**
* Converts fields with a span set to 'auto' as either
* 'left' or 'right' depending on the previous field.
*/
protected function processAutoSpan($fields)
{
$prevSpan = null;
foreach ($fields as $field) {
if (strtolower($field->span) == 'auto') {
if ($prevSpan == 'left')
$field->span = 'right';
else
$field->span = 'left';
}
$prevSpan = $field->span;
}
}
/**
* Programatically add fields, used internally and for extensibility.
*/
2014-05-21 21:26:28 +10:00
public function addFields(array $fields, $addToArea = null)
2014-05-14 23:24:20 +10:00
{
foreach ($fields as $name => $config) {
$defaultTab = Lang::get('backend::lang.form.undefined_tab');
if (!is_array($config))
$tab = $defaultTab;
elseif (!isset($config['tab']))
$tab = $config['tab'] = $defaultTab;
else
$tab = $config['tab'];
$fieldObj = $this->makeFormField($name, $config);
/*
* Check that the form field matches the active context
*/
if ($fieldObj->context !== null) {
$context = (is_array($fieldObj->context)) ? $fieldObj->context : [$fieldObj->context];
if (!in_array($this->getContext(), $context))
continue;
}
2014-08-23 21:46:03 +10:00
$this->fields[$name] = $fieldObj;
2014-05-14 23:24:20 +10:00
2014-05-21 21:26:28 +10:00
switch (strtolower($addToArea)) {
2014-05-14 23:24:20 +10:00
case 'primary':
$this->primaryTabs[$tab][$name] = $fieldObj;
break;
case 'secondary':
$this->secondaryTabs[$tab][$name] = $fieldObj;
break;
default:
$this->outsideFields[$name] = $fieldObj;
break;
}
}
}
public function addTabFields(array $fields)
{
return $this->addFields($fields, 'primary');
}
public function addSecondaryTabFields(array $fields)
{
return $this->addFields($fields, 'secondary');
}
/**
* Creates a form field object from name and configuration.
*/
protected function makeFormField($name, $config)
{
$label = (isset($config['label'])) ? $config['label'] : null;
list($fieldName, $fieldContext) = $this->getFieldName($name);
$field = new FormField($fieldName, $label);
if ($fieldContext) $field->context = $fieldContext;
2014-05-14 23:24:20 +10:00
$field->arrayName = $this->arrayName;
$field->idPrefix = $this->getId();
2014-06-08 18:07:56 +10:00
/*
* Simple field type
2014-06-08 18:07:56 +10:00
*/
if (is_string($config)) {
2014-06-08 18:07:56 +10:00
if ($this->isFormWidget($config) !== false)
$field->displayAs('widget', ['widget' => $config]);
else
$field->displayAs($config);
}
2014-06-08 18:08:54 +10:00
/*
* Defined field type
*/
else {
2014-06-08 18:07:56 +10:00
$fieldType = isset($config['type']) ? $config['type'] : null;
if (!is_string($fieldType) && !is_null($fieldType))
throw new ApplicationException(Lang::get('backend::lang.field.invalid_type', ['type'=>gettype($fieldType)]));
/*
* Widget with configuration
*/
if ($this->isFormWidget($fieldType) !== false) {
$config['widget'] = $fieldType;
$fieldType = 'widget';
}
$field->displayAs($fieldType, $config);
}
/*
* Set field value
*/
$field->value = $this->getFieldValue($field);
/*
* Check model if field is required
*/
if (!$field->required && $this->model && method_exists($this->model, 'isAttributeRequired'))
$field->required = $this->model->isAttributeRequired($field->columnName);
2014-05-14 23:24:20 +10:00
/*
* Get field options from model
2014-05-14 23:24:20 +10:00
*/
$optionModelTypes = ['dropdown', 'radio', 'checkboxlist'];
if (in_array($field->type, $optionModelTypes)) {
/*
* Defer the execution of option data collection
*/
$field->options(function() use ($field, $config) {
$fieldOptions = (isset($config['options'])) ? $config['options'] : null;
$fieldOptions = $this->getOptionsFromModel($field, $fieldOptions);
return $fieldOptions;
});
2014-05-14 23:24:20 +10:00
}
return $field;
}
/**
* Check if a field type is a widget or not
* @param string $fieldType
* @return boolean
*/
2014-08-01 18:18:09 +10:00
protected function isFormWidget($fieldType)
2014-05-14 23:24:20 +10:00
{
if ($fieldType === null)
return false;
if (strpos($fieldType, '\\'))
return true;
$widgetClass = $this->widgetManager->resolveFormWidget($fieldType);
if (!class_exists($widgetClass))
return false;
if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase'))
return true;
return false;
}
/**
* Makes a widget object from a form field object.
*/
2014-08-01 18:18:09 +10:00
protected function makeFormWidget($field)
2014-05-14 23:24:20 +10:00
{
if ($field->type != 'widget')
return null;
if (isset($this->formWidgets[$field->columnName]))
return $this->formWidgets[$field->columnName];
$widgetConfig = $this->makeConfig($field->config);
$widgetConfig->alias = $this->alias . studly_case(Str::evalHtmlId($field->columnName));
2014-05-14 23:24:20 +10:00
$widgetConfig->sessionKey = $this->getSessionKey();
$widgetName = $widgetConfig->widget;
$widgetClass = $this->widgetManager->resolveFormWidget($widgetName);
if (!class_exists($widgetClass)) {
throw new ApplicationException(Lang::get('backend::lang.widget.not_registered', [
'name' => $widgetClass
]));
}
$widget = new $widgetClass($this->controller, $this->model, $field, $widgetConfig);
return $this->formWidgets[$field->columnName] = $widget;
}
/**
* Get all the loaded form widgets for the instance.
* @return array
*/
public function getFormWidgets()
{
return $this->formWidgets;
}
/**
* Get a specified form widget
* @param string $columnName
* @return mixed
*/
public function getFormWidget($field)
{
return $this->formWidgets[$field];
}
/**
* Get all the registered fields for the instance.
* @return array
*/
public function getFields()
{
2014-08-23 21:46:03 +10:00
return $this->fields;
}
/**
* Get a specified field object
* @param string $columnName
* @return mixed
*/
public function getField($field)
{
2014-08-23 21:46:03 +10:00
return $this->fields[$field];
}
/**
* Parses a field's name
* @param stirng $field Field name
* @return array [columnName, context]
*/
public function getFieldName($field)
{
if (strpos($field, '@') === false)
return [$field, null];
return explode('@', $field);
}
2014-05-14 23:24:20 +10:00
/**
* Looks up the column
*/
public function getFieldValue($field)
{
if (is_string($field)) {
2014-08-23 21:46:03 +10:00
if (!isset($this->fields[$field]))
2014-05-14 23:24:20 +10:00
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
2014-08-23 21:46:03 +10:00
$field = $this->fields[$field];
2014-05-14 23:24:20 +10:00
}
$columnName = $field->columnName;
2014-07-09 19:36:49 +10:00
$defaultValue = (!$this->model->exists) && strlen($field->defaults) ? $field->defaults : null;
2014-05-14 23:24:20 +10:00
/*
* Array field name, eg: field[key][key2][key3]
*/
$keyParts = Str::evalHtmlArray($columnName);
2014-07-09 19:36:49 +10:00
$lastField = end($keyParts);
$result = $this->data;
2014-05-14 23:24:20 +10:00
/*
2014-07-09 19:36:49 +10:00
* Loop the field key parts and build a value.
* To support relations only the last field should return the
2014-07-09 19:36:49 +10:00
* relation value, all others will look up the relation object as normal.
2014-05-14 23:24:20 +10:00
*/
foreach ($keyParts as $key) {
if ($result instanceof Model && $result->hasRelation($key)) {
if ($key == $lastField)
$result = $result->getRelationValue($key) ?: $defaultValue;
else
$result = $result->{$key};
2014-07-09 19:36:49 +10:00
}
elseif (is_array($result)) {
if (!array_key_exists($key, $result)) return $defaultValue;
$result = $result[$key];
}
else {
if (!isset($result->{$key})) return $defaultValue;
$result = $result->{$key};
}
2014-05-14 23:24:20 +10:00
}
return $result;
}
/**
* Returns a HTML encoded value containing the other fields this
* field depends on
* @param use Backend\Classes\FormField $field
* @return string
*/
public function getFieldDepends($field)
{
if (!$field->depends)
return;
$depends = is_array($field->depends) ? $field->depends : [$field->depends];
$depends = htmlspecialchars(json_encode($depends), ENT_QUOTES, 'UTF-8');
return $depends;
}
2014-05-14 23:24:20 +10:00
/**
* Returns postback data from a submitted form.
*/
public function getSaveData()
{
$data = ($this->arrayName) ? post($this->arrayName) : post();
if (!$data)
$data = [];
/*
* Boolean fields (checkbox, switch) won't be present value FALSE
* Number fields should be converted to integers
2014-05-14 23:24:20 +10:00
*/
2014-08-23 21:46:03 +10:00
foreach ($this->fields as $field) {
if (!in_array($field->type, ['switch', 'checkbox', 'number']))
2014-05-14 23:24:20 +10:00
continue;
/*
* Handle HTML array, eg: item[key][another]
*/
$columnParts = Str::evalHtmlArray($field->columnName);
$columnDotted = implode('.', $columnParts);
$columnValue = array_get($data, $columnDotted, 0);
if ($field->type == 'number') $columnValue = (int) $columnValue;
array_set($data, $columnDotted, $columnValue);
2014-05-14 23:24:20 +10:00
}
/*
* Give widgets an opportunity to process the data.
*/
foreach ($this->formWidgets as $field => $widget) {
$widgetValue = array_key_exists($field, $data)
? $data[$field]
: null;
$data[$field] = $widget->getSaveData($widgetValue);
if ($data[$field] === FormWidgetBase::NO_SAVE_DATA)
unset($data[$field]);
2014-05-14 23:24:20 +10:00
}
return $data;
}
/**
* Looks at the model for defined options.
*/
2014-08-01 18:18:09 +10:00
protected function getOptionsFromModel($field, $fieldOptions)
2014-05-14 23:24:20 +10:00
{
/*
* Advanced usage, supplied options are callable
*/
if (is_array($fieldOptions) && is_callable($fieldOptions)) {
2014-06-01 10:23:59 +10:00
$fieldOptions = call_user_func($fieldOptions, $this, $field);
}
2014-06-01 10:23:59 +10:00
/*
* Refer to the model method or any of its behaviors
*/
2014-06-01 10:23:59 +10:00
if (!is_array($fieldOptions) && !$fieldOptions) {
2014-05-14 23:24:20 +10:00
$methodName = 'get'.studly_case($field->columnName).'Options';
2014-06-16 22:22:31 +10:00
if (!$this->methodExists($this->model, $methodName) && !$this->methodExists($this->model, 'getDropdownOptions'))
2014-05-14 23:24:20 +10:00
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->columnName]));
2014-06-16 22:22:31 +10:00
if ($this->methodExists($this->model, $methodName))
$fieldOptions = $this->model->$methodName($field->value);
2014-06-01 09:14:55 +10:00
else
$fieldOptions = $this->model->getDropdownOptions($field->columnName, $field->value);
2014-05-14 23:24:20 +10:00
}
/*
* Field options are an explicit method reference
*/
elseif (is_string($fieldOptions)) {
2014-06-16 22:22:31 +10:00
if (!$this->methodExists($this->model, $fieldOptions))
2014-05-14 23:24:20 +10:00
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->columnName]));
$fieldOptions = $this->model->$fieldOptions($field->value, $field->columnName);
2014-05-14 23:24:20 +10:00
}
2014-06-01 10:23:59 +10:00
return $fieldOptions;
2014-05-14 23:24:20 +10:00
}
/**
* Returns the active session key.
*/
public function getSessionKey()
{
if ($this->sessionKey)
return $this->sessionKey;
if (post('_session_key'))
return $this->sessionKey = post('_session_key');
return $this->sessionKey = FormHelper::getSessionKey();
}
/**
* Returns the active context for displaying the form.
*/
public function getContext()
{
return $this->activeContext;
}
2014-06-16 22:22:31 +10:00
/**
* Internal helper for method existence checks
* @param object $object
* @param string $method
* @return boolean
*/
2014-08-01 18:18:09 +10:00
protected function methodExists($object, $method)
2014-06-16 22:22:31 +10:00
{
if (method_exists($object, 'methodExists'))
return $object->methodExists($method);
return method_exists($object, $method);
}
2014-05-14 23:24:20 +10:00
}