Updating modules/backend/widgets

This commit is contained in:
Stefan Talen 2014-10-11 00:39:34 +02:00
parent aa68d163a0
commit b64a744498
7 changed files with 433 additions and 236 deletions

View File

@ -102,8 +102,9 @@ class Filter extends WidgetBase
{
$this->defineFilterScopes();
if (!$scope = post('scopeName'))
if (!$scope = post('scopeName')) {
return;
}
$scope = $this->getScope($scope);
@ -124,8 +125,9 @@ class Filter extends WidgetBase
*/
$params = func_get_args();
$result = $this->fireEvent('filter.update', [$params]);
if ($result && is_array($result))
if ($result && is_array($result)) {
return Util::arrayMerge($result);
}
}
/**
@ -137,8 +139,9 @@ class Filter extends WidgetBase
$this->defineFilterScopes();
$searchQuery = post('search');
if (!$scopeName = post('scopeName'))
if (!$scopeName = post('scopeName')) {
return;
}
$scope = $this->getScope($scopeName);
$activeKeys = $scope->value ? array_keys($scope->value) : [];
@ -188,8 +191,9 @@ class Filter extends WidgetBase
{
$active = [];
foreach ($availableOptions as $id => $option) {
if (!in_array($id, $activeKeys))
if (!in_array($id, $activeKeys)) {
continue;
}
$active[$id] = $option;
unset($availableOptions[$id]);
@ -204,8 +208,9 @@ class Filter extends WidgetBase
protected function getOptionsFromModel($scope, $searchQuery = null)
{
$model = $this->scopeModels[$scope->scopeName];
if (!$searchQuery)
if (!$searchQuery) {
return $model->all();
}
$searchFields = [$model->getKeyName(), $this->getScopeNameColumn($scope)];
return $model->searchWhere($searchQuery, $searchFields)->get();
@ -216,8 +221,9 @@ class Filter extends WidgetBase
*/
protected function defineFilterScopes()
{
if ($this->scopesDefined)
if ($this->scopesDefined) {
return;
}
/*
* Extensibility
@ -228,8 +234,9 @@ class Filter extends WidgetBase
/*
* All scopes
*/
if (!isset($this->config->scopes) || !is_array($this->config->scopes))
if (!isset($this->config->scopes) || !is_array($this->config->scopes)) {
$this->config->scopes = [];
}
$this->addScopes($this->config->scopes);
@ -256,8 +263,9 @@ class Filter extends WidgetBase
*/
if ($scopeObj->context !== null) {
$context = (is_array($scopeObj->context)) ? $scopeObj->context : [$scopeObj->context];
if (!in_array($this->getContext(), $context))
if (!in_array($this->getContext(), $context)) {
continue;
}
}
/*
@ -318,11 +326,13 @@ class Filter extends WidgetBase
*/
public function applyScopeToQuery($scope, $query)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
if (!$scope->value)
if (!$scope->value) {
return;
}
$value = is_array($scope->value) ? array_keys($scope->value) : $scope->value;
@ -331,11 +341,10 @@ class Filter extends WidgetBase
*/
if ($scopeConditions = $scope->conditions) {
if (is_array($value)) {
$filtered = implode(',', array_build($value, function($key, $_value){
$filtered = implode(',', array_build($value, function ($key, $_value) {
return [$key, Db::getPdo()->quote($_value)];
}));
}
else {
} else {
$filtered = Db::getPdo()->quote($value);
}
@ -361,8 +370,9 @@ class Filter extends WidgetBase
*/
public function getScopeValue($scope, $default = null)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
$cacheKey = 'scope-'.$scope->scopeName;
return $this->getSession($cacheKey, $default);
@ -373,8 +383,9 @@ class Filter extends WidgetBase
*/
public function setScopeValue($scope, $value)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
$cacheKey = 'scope-'.$scope->scopeName;
$this->putSession($cacheKey, $value);
@ -398,8 +409,9 @@ class Filter extends WidgetBase
*/
public function getScope($scope)
{
if (!isset($this->allScopes[$scope]))
if (!isset($this->allScopes[$scope])) {
throw new ApplicationException('No definition for scope ' . $scope);
}
return $this->allScopes[$scope];
}
@ -411,8 +423,9 @@ class Filter extends WidgetBase
*/
public function getScopeNameColumn($scope)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
return $scope->nameFrom;
}
@ -451,14 +464,16 @@ class Filter extends WidgetBase
protected function optionsFromAjax($options)
{
$processed = [];
if (!is_array($options))
if (!is_array($options)) {
return $processed;
}
foreach ($options as $option) {
if (!$id = array_get($option, 'id')) continue;
if (!$id = array_get($option, 'id')) {
continue;
}
$processed[$id] = array_get($option, 'name');
}
return $processed;
}
}
}

View File

@ -140,9 +140,15 @@ class Form extends WidgetBase
*/
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;
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';
@ -153,10 +159,17 @@ class Form extends WidgetBase
if ($section = $options['section']) {
switch (strtolower($section)) {
case 'outside':
$sectionPartial = 'section_outside-fields';
break;
case 'primary':
$sectionPartial = 'section_primary-tabs';
break;
case 'secondary':
$sectionPartial = 'section_secondary-tabs';
break;
default:
case 'outside': $sectionPartial = 'section_outside-fields'; break;
case 'primary': $sectionPartial = 'section_primary-tabs'; break;
case 'secondary': $sectionPartial = 'section_secondary-tabs'; break;
break;
}
$targetPartial = $sectionPartial;
@ -180,13 +193,19 @@ class Form extends WidgetBase
public function renderField($field, $options = [])
{
if (is_string($field)) {
if (!isset($this->fields[$field]))
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
if (!isset($this->fields[$field])) {
throw new ApplicationException(Lang::get(
'backend::lang.form.missing_definition',
compact('field')
));
}
$field = $this->fields[$field];
}
if (!isset($options['useContainer'])) $options['useContainer'] = true;
if (!isset($options['useContainer'])) {
$options['useContainer'] = true;
}
$targetPartial = $options['useContainer'] ? 'field-container' : 'field';
$this->prepareVars();
@ -209,8 +228,12 @@ class Form extends WidgetBase
{
$this->model = $this->getConfig('model');
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.form.missing_model', ['class'=>get_class($this->controller)]));
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);
@ -236,8 +259,9 @@ class Form extends WidgetBase
*/
public function setFormValues($data = null)
{
if ($data == null)
if ($data == null) {
$data = $this->getSaveData();
}
$this->model->fill($data);
$this->data = (object) array_merge((array) $this->data, (array) $data);
@ -260,9 +284,12 @@ class Form extends WidgetBase
/*
* Extensibility
*/
$eventResults = $this->fireEvent('form.beforeRefresh', [$saveData]) + Event::fire('backend.form.beforeRefresh', [$this, $saveData]);
foreach ($eventResults as $eventResult)
$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
@ -276,8 +303,9 @@ class Form extends WidgetBase
if (($updateFields = post('fields')) && is_array($updateFields)) {
foreach ($updateFields as $field) {
if (!isset($this->fields[$field]))
if (!isset($this->fields[$field])) {
continue;
}
$fieldObject = $this->fields[$field];
$result['#' . $fieldObject->getId('group')] = $this->makePartial('field', ['field' => $fieldObject]);
@ -287,15 +315,19 @@ class Form extends WidgetBase
/*
* Update the whole form
*/
if (empty($result))
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)
$eventResults = $this->fireEvent('form.refresh', [$result]) +
Event::fire('backend.form.refresh', [$this, $result]);
foreach ($eventResults as $eventResult) {
$result = $eventResult + $result;
}
return $result;
}
@ -306,8 +338,9 @@ class Form extends WidgetBase
*/
protected function defineFormFields()
{
if ($this->fieldsDefined)
if ($this->fieldsDefined) {
return;
}
/*
* Extensibility
@ -318,24 +351,27 @@ class Form extends WidgetBase
/*
* Outside fields
*/
if (!isset($this->config->fields) || !is_array($this->config->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']))
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']))
if (!isset($this->config->secondaryTabs['fields']) || !is_array($this->config->secondaryTabs['fields'])) {
$this->config->secondaryTabs['fields'] = [];
}
$this->addFields($this->config->secondaryTabs['fields'], 'secondary');
@ -350,18 +386,21 @@ class Form extends WidgetBase
*/
$this->processAutoSpan($this->outsideFields);
foreach ($this->primaryTabs as $fields)
foreach ($this->primaryTabs as $fields) {
$this->processAutoSpan($fields);
}
foreach ($this->secondaryTabs as $fields)
foreach ($this->secondaryTabs as $fields) {
$this->processAutoSpan($fields);
}
/*
* Bind all form widgets to controller
*/
foreach ($this->fields as $field) {
if ($field->type != 'widget')
if ($field->type != 'widget') {
continue;
}
$widget = $this->makeFormWidget($field);
$widget->bindToController();
@ -379,10 +418,11 @@ class Form extends WidgetBase
$prevSpan = null;
foreach ($fields as $field) {
if (strtolower($field->span) == 'auto') {
if ($prevSpan == 'left')
if ($prevSpan == 'left') {
$field->span = 'right';
else
} else {
$field->span = 'left';
}
}
$prevSpan = $field->span;
@ -397,12 +437,13 @@ class Form extends WidgetBase
foreach ($fields as $name => $config) {
$defaultTab = Lang::get('backend::lang.form.undefined_tab');
if (!is_array($config))
if (!is_array($config)) {
$tab = $defaultTab;
elseif (!isset($config['tab']))
} elseif (!isset($config['tab'])) {
$tab = $config['tab'] = $defaultTab;
else
} else {
$tab = $config['tab'];
}
$fieldObj = $this->makeFormField($name, $config);
@ -411,8 +452,9 @@ class Form extends WidgetBase
*/
if ($fieldObj->context !== null) {
$context = (is_array($fieldObj->context)) ? $fieldObj->context : [$fieldObj->context];
if (!in_array($this->getContext(), $context))
if (!in_array($this->getContext(), $context)) {
continue;
}
}
$this->fields[$name] = $fieldObj;
@ -428,7 +470,6 @@ class Form extends WidgetBase
$this->outsideFields[$name] = $fieldObj;
break;
}
}
}
@ -451,7 +492,9 @@ class Form extends WidgetBase
list($fieldName, $fieldContext) = $this->getFieldName($name);
$field = new FormField($fieldName, $label);
if ($fieldContext) $field->context = $fieldContext;
if ($fieldContext) {
$field->context = $fieldContext;
}
$field->arrayName = $this->arrayName;
$field->idPrefix = $this->getId();
@ -459,20 +502,22 @@ class Form extends WidgetBase
* Simple field type
*/
if (is_string($config)) {
if ($this->isFormWidget($config) !== false)
if ($this->isFormWidget($config) !== false) {
$field->displayAs('widget', ['widget' => $config]);
else
} else {
$field->displayAs($config);
}
}
/*
* Defined field type
*/
else {
} else {
$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)]));
if (!is_string($fieldType) && !is_null($fieldType)) {
throw new ApplicationException(Lang::get(
'backend::lang.field.invalid_type',
['type'=>gettype($fieldType)]
));
}
/*
* Widget with configuration
@ -493,8 +538,9 @@ class Form extends WidgetBase
/*
* Check model if field is required
*/
if (!$field->required && $this->model && method_exists($this->model, 'isAttributeRequired'))
if (!$field->required && $this->model && method_exists($this->model, 'isAttributeRequired')) {
$field->required = $this->model->isAttributeRequired($field->fieldName);
}
/*
* Get field options from model
@ -505,7 +551,7 @@ class Form extends WidgetBase
/*
* Defer the execution of option data collection
*/
$field->options(function() use ($field, $config) {
$field->options(function () use ($field, $config) {
$fieldOptions = (isset($config['options'])) ? $config['options'] : null;
$fieldOptions = $this->getOptionsFromModel($field, $fieldOptions);
return $fieldOptions;
@ -522,19 +568,23 @@ class Form extends WidgetBase
*/
protected function isFormWidget($fieldType)
{
if ($fieldType === null)
if ($fieldType === null) {
return false;
}
if (strpos($fieldType, '\\'))
if (strpos($fieldType, '\\')) {
return true;
}
$widgetClass = $this->widgetManager->resolveFormWidget($fieldType);
if (!class_exists($widgetClass))
if (!class_exists($widgetClass)) {
return false;
}
if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase'))
if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase')) {
return true;
}
return false;
}
@ -544,11 +594,13 @@ class Form extends WidgetBase
*/
protected function makeFormWidget($field)
{
if ($field->type != 'widget')
if ($field->type != 'widget') {
return null;
}
if (isset($this->formWidgets[$field->fieldName]))
if (isset($this->formWidgets[$field->fieldName])) {
return $this->formWidgets[$field->fieldName];
}
$widgetConfig = $this->makeConfig($field->config);
$widgetConfig->alias = $this->alias . studly_case(Str::evalHtmlId($field->fieldName));
@ -557,9 +609,10 @@ class Form extends WidgetBase
$widgetName = $widgetConfig->widget;
$widgetClass = $this->widgetManager->resolveFormWidget($widgetName);
if (!class_exists($widgetClass)) {
throw new ApplicationException(Lang::get('backend::lang.widget.not_registered', [
'name' => $widgetClass
]));
throw new ApplicationException(Lang::get(
'backend::lang.widget.not_registered',
['name' => $widgetClass]
));
}
$widget = new $widgetClass($this->controller, $this->model, $field, $widgetConfig);
@ -611,8 +664,9 @@ class Form extends WidgetBase
*/
public function getFieldName($field)
{
if (strpos($field, '@') === false)
if (strpos($field, '@') === false) {
return [$field, null];
}
return explode('@', $field);
}
@ -623,8 +677,12 @@ class Form extends WidgetBase
public function getFieldValue($field)
{
if (is_string($field)) {
if (!isset($this->fields[$field]))
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
if (!isset($this->fields[$field])) {
throw new ApplicationException(Lang::get(
'backend::lang.form.missing_definition',
compact('field')
));
}
$field = $this->fields[$field];
}
@ -647,17 +705,20 @@ class Form extends WidgetBase
foreach ($keyParts as $key) {
if ($result instanceof Model && $result->hasRelation($key)) {
if ($key == $lastField)
if ($key == $lastField) {
$result = $result->getRelationValue($key) ?: $defaultValue;
else
} else {
$result = $result->{$key};
}
elseif (is_array($result)) {
if (!array_key_exists($key, $result)) return $defaultValue;
}
} elseif (is_array($result)) {
if (!array_key_exists($key, $result)) {
return $defaultValue;
}
$result = $result[$key];
}
else {
if (!isset($result->{$key})) return $defaultValue;
} else {
if (!isset($result->{$key})) {
return $defaultValue;
}
$result = $result->{$key};
}
@ -674,8 +735,9 @@ class Form extends WidgetBase
*/
public function getFieldDepends($field)
{
if (!$field->depends)
if (!$field->depends) {
return;
}
$depends = is_array($field->depends) ? $field->depends : [$field->depends];
$depends = htmlspecialchars(json_encode($depends), ENT_QUOTES, 'UTF-8');
@ -689,17 +751,18 @@ class Form extends WidgetBase
{
$data = ($this->arrayName) ? post($this->arrayName) : post();
if (!$data)
if (!$data) {
$data = [];
}
/*
* Boolean fields (checkbox, switch) won't be present value FALSE
* Number fields should be converted to integers
*/
foreach ($this->fields as $field) {
if (!in_array($field->type, ['switch', 'checkbox', 'number']))
if (!in_array($field->type, ['switch', 'checkbox', 'number'])) {
continue;
}
/*
* Handle HTML array, eg: item[key][another]
@ -722,8 +785,9 @@ class Form extends WidgetBase
: null;
$data[$field] = $widget->getSaveData($widgetValue);
if ($data[$field] === FormWidgetBase::NO_SAVE_DATA)
if ($data[$field] === FormWidgetBase::NO_SAVE_DATA) {
unset($data[$field]);
}
}
/*
@ -731,8 +795,9 @@ class Form extends WidgetBase
*/
$remappedFields = [];
foreach ($this->fields as $field) {
if ($field->fieldName == $field->valueFrom)
if ($field->fieldName == $field->valueFrom) {
continue;
}
/*
* Get the value, remove it from the data collection
@ -776,21 +841,31 @@ class Form extends WidgetBase
*/
if (!is_array($fieldOptions) && !$fieldOptions) {
$methodName = 'get'.studly_case($field->fieldName).'Options';
if (!$this->methodExists($this->model, $methodName) && !$this->methodExists($this->model, 'getDropdownOptions'))
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->fieldName]));
if (
!$this->methodExists($this->model, $methodName) &&
!$this->methodExists($this->model, 'getDropdownOptions')
) {
throw new ApplicationException(Lang::get(
'backend::lang.field.options_method_not_exists',
['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->fieldName]
));
}
if ($this->methodExists($this->model, $methodName))
if ($this->methodExists($this->model, $methodName)) {
$fieldOptions = $this->model->$methodName($field->value);
else
} else {
$fieldOptions = $this->model->getDropdownOptions($field->fieldName, $field->value);
}
}
/*
* Field options are an explicit method reference
*/
elseif (is_string($fieldOptions)) {
if (!$this->methodExists($this->model, $fieldOptions))
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->fieldName]));
} elseif (is_string($fieldOptions)) {
if (!$this->methodExists($this->model, $fieldOptions)) {
throw new ApplicationException(Lang::get(
'backend::lang.field.options_method_not_exists',
['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->fieldName]
));
}
$fieldOptions = $this->model->$fieldOptions($field->value, $field->fieldName);
}
@ -803,11 +878,13 @@ class Form extends WidgetBase
*/
public function getSessionKey()
{
if ($this->sessionKey)
if ($this->sessionKey) {
return $this->sessionKey;
}
if (post('_session_key'))
if (post('_session_key')) {
return $this->sessionKey = post('_session_key');
}
return $this->sessionKey = FormHelper::getSessionKey();
}
@ -828,10 +905,10 @@ class Form extends WidgetBase
*/
protected function methodExists($object, $method)
{
if (method_exists($object, 'methodExists'))
if (method_exists($object, 'methodExists')) {
return $object->methodExists($method);
}
return method_exists($object, $method);
}
}

View File

@ -117,8 +117,9 @@ class Grid extends WidgetBase
protected function makeToolbarWidget()
{
if ($this->disableToolbar)
if ($this->disableToolbar) {
return;
}
$defaultConfig = [
'buttons' => $this->getViewPath('_toolbar.htm'),
@ -148,8 +149,9 @@ class Grid extends WidgetBase
public function onDataChanged()
{
if (!$this->monitorChanges)
if (!$this->monitorChanges) {
return;
}
/*
* Changes array, each array item will contain:
@ -168,16 +170,19 @@ class Grid extends WidgetBase
public function onDataSource()
{
if (!$this->useDataSource)
if (!$this->useDataSource) {
return;
}
$result = [];
if ($_result = $this->fireEvent('grid.dataSource', [], true))
if ($_result = $this->fireEvent('grid.dataSource', [], true)) {
$result = $_result;
}
if (!is_array($result))
if (!is_array($result)) {
$result = [];
}
return ['result' => $result];
}
@ -188,8 +193,9 @@ class Grid extends WidgetBase
protected function getColumnHeaders()
{
if (!$this->showHeader)
if (!$this->showHeader) {
return false;
}
$headers = [];
foreach ($this->columns as $key => $column) {
@ -214,8 +220,9 @@ class Grid extends WidgetBase
$item = [];
$item['data'] = $key;
if (isset($column['readOnly']))
if (isset($column['readOnly'])) {
$item['readOnly'] = $column['readOnly'];
}
$item = $this->evalColumnType($column, $item);
$definitions[] = $item;
@ -225,8 +232,9 @@ class Grid extends WidgetBase
protected function evalColumnType($column, $item)
{
if (!isset($column['type']))
if (!isset($column['type'])) {
return $item;
}
switch ($column['type']) {
case 'number':
@ -244,8 +252,12 @@ class Grid extends WidgetBase
case 'autocomplete':
$item['type'] = 'autocomplete';
if (isset($column['options'])) $item['source'] = $column['options'];
if (isset($column['strict'])) $item['strict'] = $column['strict'];
if (isset($column['options'])) {
$item['source'] = $column['options'];
}
if (isset($column['strict'])) {
$item['strict'] = $column['strict'];
}
break;
}
@ -266,5 +278,4 @@ class Grid extends WidgetBase
$this->addJs('vendor/handsontable/jquery.handsontable.js', 'core');
$this->addJs('js/datagrid.js', 'core');
}
}

View File

@ -152,7 +152,10 @@ class Lists extends WidgetBase
*/
$this->recordUrl = $this->getConfig('recordUrl', $this->recordUrl);
$this->recordOnClick = $this->getConfig('recordOnClick', $this->recordOnClick);
$this->recordsPerPage = $this->getSession('per_page', $this->getConfig('recordsPerPage', $this->recordsPerPage));
$this->recordsPerPage = $this->getSession(
'per_page',
$this->getConfig('recordsPerPage', $this->recordsPerPage)
);
$this->noRecordsMessage = $this->getConfig('noRecordsMessage', $this->noRecordsMessage);
$this->defaultSort = $this->getConfig('defaultSort', $this->defaultSort);
$this->showSorting = $this->getConfig('showSorting', $this->showSorting);
@ -206,8 +209,7 @@ class Lists extends WidgetBase
$this->vars['pageLast'] = $this->records->getLastPage();
$this->vars['pageFrom'] = $this->records->getFrom();
$this->vars['pageTo'] = $this->records->getTo();
}
else {
} else {
$this->vars['recordTotal'] = $this->records->count();
$this->vars['pageCurrent'] = 1;
}
@ -239,11 +241,19 @@ class Lists extends WidgetBase
{
$this->model = $this->getConfig('model');
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.list.missing_model', ['class'=>get_class($this->controller)]));
if (!$this->model) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_model',
['class'=>get_class($this->controller)]
));
}
if (!$this->model instanceof Model)
throw new ApplicationException(Lang::get('backend::lang.model.invalid_class', ['model'=>get_class($this->model), 'class'=>get_class($this->controller)]));
if (!$this->model instanceof Model) {
throw new ApplicationException(Lang::get(
'backend::lang.model.invalid_class',
['model'=>get_class($this->model), 'class'=>get_class($this->controller)]
));
}
return $this->model;
}
@ -295,11 +305,10 @@ class Lists extends WidgetBase
: $table . '.' . $column->valueFrom;
$relationSearchable[$column->relation][] = $columnName;
}
/*
* Primary
*/
else {
} else {
$columnName = isset($column->sqlSelect)
? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
: $primaryTable . '.' . $column->columnName;
@ -314,11 +323,13 @@ class Lists extends WidgetBase
*/
foreach ($this->getVisibleListColumns() as $column) {
if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom)))
if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
continue;
}
if (isset($column->valueFrom))
if (isset($column->valueFrom)) {
$withs[] = $column->relation;
}
$joins[] = $column->relation;
}
@ -335,7 +346,7 @@ class Lists extends WidgetBase
$columnsToSearch = array_get($relationSearchable, $join, []);
if (count($columnsToSearch) > 0) {
$query->whereHas($join, function($_query) use ($columnsToSearch) {
$query->whereHas($join, function ($_query) use ($columnsToSearch) {
$_query->searchWhere($this->searchTerm, $columnsToSearch);
});
}
@ -353,8 +364,9 @@ class Lists extends WidgetBase
* Custom select queries
*/
foreach ($this->getVisibleListColumns() as $column) {
if (!isset($column->sqlSelect))
if (!isset($column->sqlSelect)) {
continue;
}
$alias = Db::getQueryGrammar()->wrap($column->columnName);
@ -379,11 +391,10 @@ class Lists extends WidgetBase
$joinSql = $countQuery->select($joinSql)->toSql();
$selects[] = Db::raw("(".$joinSql.") as ".$alias);
}
/*
* Primary column
*/
else {
} else {
$sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
$selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
}
@ -393,7 +404,7 @@ class Lists extends WidgetBase
* Apply a supplied search term for primary columns
*/
if (count($primarySearchable) > 0) {
$query->orWhere(function($innerQuery) use ($primarySearchable) {
$query->orWhere(function ($innerQuery) use ($primarySearchable) {
$innerQuery->searchWhere($this->searchTerm, $primarySearchable);
});
}
@ -402,8 +413,9 @@ class Lists extends WidgetBase
* Apply sorting
*/
if ($sortColumn = $this->getSortColumn()) {
if (($column = array_get($this->columns, $sortColumn)) && $column->sqlSelect)
if (($column = array_get($this->columns, $sortColumn)) && $column->sqlSelect) {
$sortColumn = $column->sqlSelect;
}
$query->orderBy($sortColumn, $this->sortDirection);
}
@ -437,12 +449,12 @@ class Lists extends WidgetBase
{
if ($this->showTree) {
$records = $this->model->getAllRoot();
}
else {
} else {
$model = $this->prepareModel();
$records = ($this->showPagination)
? $model->paginate($this->recordsPerPage)
: $model->get();
}
return $this->records = $records;
@ -455,11 +467,13 @@ class Lists extends WidgetBase
*/
public function getRecordUrl($record)
{
if (isset($this->recordOnClick))
if (isset($this->recordOnClick)) {
return 'javascript:;';
}
if (!isset($this->recordUrl))
if (!isset($this->recordUrl)) {
return null;
}
$columns = array_keys($record->getAttributes());
$url = RouterHelper::parseValues($record, $columns, $this->recordUrl);
@ -473,8 +487,9 @@ class Lists extends WidgetBase
*/
public function getRecordOnClick($record)
{
if (!isset($this->recordOnClick))
if (!isset($this->recordOnClick)) {
return null;
}
$columns = array_keys($record->getAttributes());
$recordOnClick = RouterHelper::parseValues($record, $columns, $this->recordOnClick);
@ -511,27 +526,32 @@ class Lists extends WidgetBase
/*
* Supplied column list
*/
if ($this->columnOverride === null)
if ($this->columnOverride === null) {
$this->columnOverride = $this->getSession('visible', null);
}
if ($this->columnOverride && is_array($this->columnOverride)) {
$invalidColumns = array_diff($this->columnOverride, array_keys($definitions));
if (!count($definitions))
throw new ApplicationException(Lang::get('backend::lang.list.missing_column', ['columns'=>implode(',', $invalidColumns)]));
if (!count($definitions)) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_column',
['columns'=>implode(',', $invalidColumns)]
));
}
foreach ($this->columnOverride as $columnName) {
$definitions[$columnName]->invisible = false;
$columns[$columnName] = $definitions[$columnName];
}
}
/*
* Use default column list
*/
else {
} else {
foreach ($definitions as $columnName => $column) {
if ($column->invisible)
if ($column->invisible) {
continue;
}
$columns[$columnName] = $definitions[$columnName];
}
@ -545,8 +565,12 @@ class Lists extends WidgetBase
*/
protected function defineListColumns()
{
if (!isset($this->config->columns) || !is_array($this->config->columns) || !count($this->config->columns))
throw new ApplicationException(Lang::get('backend::lang.list.missing_columns', ['class'=>get_class($this->controller)]));
if (!isset($this->config->columns) || !is_array($this->config->columns) || !count($this->config->columns)) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_columns',
['class'=>get_class($this->controller)]
));
}
$this->addColumns($this->config->columns);
@ -589,12 +613,13 @@ class Lists extends WidgetBase
*/
protected function makeListColumn($name, $config)
{
if (is_string($config))
if (is_string($config)) {
$label = $config;
elseif (isset($config['label']))
} elseif (isset($config['label'])) {
$label = $config['label'];
else
} else {
$label = studly_case($name);
}
$columnType = isset($config['type']) ? $config['type'] : null;
@ -612,8 +637,12 @@ class Lists extends WidgetBase
{
$columns = $this->visibleColumns ?: $this->getVisibleListColumns();
$total = count($columns);
if ($this->showCheckboxes) $total++;
if ($this->showSetup) $total++;
if ($this->showCheckboxes) {
$total++;
}
if ($this->showSetup) {
$total++;
}
return $total;
}
@ -627,11 +656,13 @@ class Lists extends WidgetBase
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.overrideHeaderValue', [$this, $column, $value], true))
if ($response = Event::fire('backend.list.overrideHeaderValue', [$this, $column, $value], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.overrideHeaderValue', [$column, $value], true))
if ($response = $this->fireEvent('list.overrideHeaderValue', [$column, $value], true)) {
$value = $response;
}
return $value;
}
@ -648,38 +679,42 @@ class Lists extends WidgetBase
* Handle taking name from model attribute.
*/
if ($column->valueFrom) {
if (!array_key_exists($columnName, $record->getRelations()))
if (!array_key_exists($columnName, $record->getRelations())) {
$value = null;
elseif ($this->isColumnRelated($column, true))
} elseif ($this->isColumnRelated($column, true)) {
$value = implode(', ', $record->{$columnName}->lists($column->valueFrom));
elseif ($this->isColumnRelated($column))
} elseif ($this->isColumnRelated($column)) {
$value = $record->{$columnName}->{$column->valueFrom};
else
} else {
$value = $record->{$column->valueFrom};
}
}
/*
* Otherwise, if the column is a relation, it will be a custom select,
* so prevent the Model from attempting to load the relation
* if the value is NULL.
*/
else {
if ($record->hasRelation($columnName) && array_key_exists($columnName, $record->attributes))
} else {
if ($record->hasRelation($columnName) && array_key_exists($columnName, $record->attributes)) {
$value = $record->attributes[$columnName];
else
} else {
$value = $record->{$columnName};
}
}
if (method_exists($this, 'eval'. studly_case($column->type) .'TypeValue'))
if (method_exists($this, 'eval'. studly_case($column->type) .'TypeValue')) {
$value = $this->{'eval'. studly_case($column->type) .'TypeValue'}($record, $column, $value);
}
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.overrideColumnValue', [$this, $record, $column, $value], true))
if ($response = Event::fire('backend.list.overrideColumnValue', [$this, $record, $column, $value], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.overrideColumnValue', [$record, $column, $value], true))
if ($response = $this->fireEvent('list.overrideColumnValue', [$record, $column, $value], true)) {
$value = $response;
}
return $value;
}
@ -696,11 +731,13 @@ class Lists extends WidgetBase
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.injectRowClass', [$this, $record], true))
if ($response = Event::fire('backend.list.injectRowClass', [$this, $record], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.injectRowClass', [$record], true))
if ($response = $this->fireEvent('list.injectRowClass', [$record], true)) {
$value = $response;
}
return $value;
}
@ -738,13 +775,15 @@ class Lists extends WidgetBase
*/
protected function evalDatetimeTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format !== null)
if ($column->format !== null) {
return $value->format($column->format);
}
return $value->toDayDateTimeString();
}
@ -754,13 +793,15 @@ class Lists extends WidgetBase
*/
protected function evalTimeTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format === null)
if ($column->format === null) {
$column->format = 'g:i A';
}
return $value->format($column->format);
}
@ -770,13 +811,15 @@ class Lists extends WidgetBase
*/
protected function evalDateTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format !== null)
if ($column->format !== null) {
return $value->format($column->format);
}
return $value->toFormattedDateString();
}
@ -786,8 +829,9 @@ class Lists extends WidgetBase
*/
protected function evalTimesinceTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
@ -799,11 +843,16 @@ class Lists extends WidgetBase
*/
protected function validateDateTimeValue($value, $column)
{
if ($value instanceof DateTime)
if ($value instanceof DateTime) {
$value = Carbon::instance($value);
}
if (!$value instanceof Carbon)
throw new ApplicationException(Lang::get('backend::lang.list.invalid_column_datetime', ['column' => $column->columnName]));
if (!$value instanceof Carbon) {
throw new ApplicationException(Lang::get(
'backend::lang.list.invalid_column_datetime',
['column' => $column->columnName]
));
}
return $value;
}
@ -830,8 +879,7 @@ class Lists extends WidgetBase
{
if (empty($term)) {
$this->showTree = $this->getConfig('showTree', $this->showTree);
}
else {
} else {
$this->showTree = false;
}
@ -848,8 +896,9 @@ class Lists extends WidgetBase
$searchable = [];
foreach ($columns as $column) {
if (!$column->searchable)
if (!$column->searchable) {
continue;
}
$searchable[] = $column;
}
@ -873,10 +922,11 @@ class Lists extends WidgetBase
*/
$sortOptions = ['column' => $this->getSortColumn(), 'direction' => $this->sortDirection];
if ($column != $sortOptions['column'] || $sortOptions['direction'] == 'asc')
if ($column != $sortOptions['column'] || $sortOptions['direction'] == 'asc') {
$this->sortDirection = $sortOptions['direction'] = 'desc';
else
} else {
$this->sortDirection = $sortOptions['direction'] = 'asc';
}
$this->sortColumn = $sortOptions['column'] = $column;
@ -896,11 +946,13 @@ class Lists extends WidgetBase
*/
protected function getSortColumn()
{
if (!$this->isSortable())
if (!$this->isSortable()) {
return false;
}
if ($this->sortColumn !== null)
if ($this->sortColumn !== null) {
return $this->sortColumn;
}
/*
* User preference
@ -908,18 +960,19 @@ class Lists extends WidgetBase
if ($this->showSorting && ($sortOptions = $this->getSession('sort'))) {
$this->sortColumn = $sortOptions['column'];
$this->sortDirection = $sortOptions['direction'];
}
/*
* Supplied default
*/
else {
} else {
if (is_string($this->defaultSort)) {
$this->sortColumn = $this->defaultSort;
$this->sortDirection = 'desc';
}
elseif (is_array($this->defaultSort) && isset($this->defaultSort['column'])) {
} elseif (is_array($this->defaultSort) && isset($this->defaultSort['column'])) {
$this->sortColumn = $this->defaultSort['column'];
$this->sortDirection = (isset($this->defaultSort['direction'])) ? $this->defaultSort['direction'] : 'desc';
$this->sortDirection = (isset($this->defaultSort['direction'])) ?
$this->defaultSort['direction'] :
'desc';
}
}
@ -940,10 +993,11 @@ class Lists extends WidgetBase
*/
protected function isSortable($column = null)
{
if ($column === null)
if ($column === null) {
return (count($this->getSortableColumns()) > 0);
else
} else {
return array_key_exists($column, $this->getSortableColumns());
}
}
/**
@ -951,15 +1005,17 @@ class Lists extends WidgetBase
*/
protected function getSortableColumns()
{
if ($this->sortableColumns !== null)
if ($this->sortableColumns !== null) {
return $this->sortableColumns;
}
$columns = $this->getColumns();
$sortable = [];
foreach ($columns as $column) {
if (!$column->sortable)
if (!$column->sortable) {
continue;
}
$sortable[$column->columnName] = $column;
}
@ -1003,8 +1059,9 @@ class Lists extends WidgetBase
protected function getSetupPerPageOptions()
{
$perPageOptions = [20, 40, 80, 100, 120];
if (!in_array($this->recordsPerPage, $perPageOptions))
if (!in_array($this->recordsPerPage, $perPageOptions)) {
$perPageOptions[] = $this->recordsPerPage;
}
sort($perPageOptions);
return $perPageOptions;
@ -1036,15 +1093,23 @@ class Lists extends WidgetBase
*/
public function validateTree()
{
if (!$this->showTree) return;
if (!$this->showTree) {
return;
}
$this->showSorting = $this->showPagination = false;
if (!$this->model->methodExists('getChildren'))
throw new ApplicationException('To display list as a tree, the specified model must have a method "getChildren"');
if (!$this->model->methodExists('getChildren')) {
throw new ApplicationException(
'To display list as a tree, the specified model must have a method "getChildren"'
);
}
if (!$this->model->methodExists('getChildCount'))
throw new ApplicationException('To display list as a tree, the specified model must have a method "getChildCount"');
if (!$this->model->methodExists('getChildCount')) {
throw new ApplicationException(
'To display list as a tree, the specified model must have a method "getChildCount"'
);
}
}
/**
@ -1080,14 +1145,20 @@ class Lists extends WidgetBase
*/
protected function isColumnRelated($column, $multi = false)
{
if (!isset($column->relation))
if (!isset($column->relation)) {
return false;
}
if (!$this->model->hasRelation($column->relation))
throw new ApplicationException(Lang::get('backend::lang.model.missing_relation', ['class'=>get_class($this->model), 'relation'=>$column->relation]));
if (!$this->model->hasRelation($column->relation)) {
throw new ApplicationException(Lang::get(
'backend::lang.model.missing_relation',
['class'=>get_class($this->model), 'relation'=>$column->relation]
));
}
if (!$multi)
if (!$multi) {
return true;
}
$relationType = $this->model->getRelationType($column->relation);
@ -1101,5 +1172,4 @@ class Lists extends WidgetBase
'hasManyThrough'
]);
}
}
}

View File

@ -62,9 +62,10 @@ class ReportContainer extends WidgetBase
if (File::isFile($path)) {
$config = $this->makeConfig($configFile);
foreach ($config as $field=>$value) {
if (property_exists($this, $field))
foreach ($config as $field => $value) {
if (property_exists($this, $field)) {
$this->$field = $value;
}
}
}
}
@ -116,8 +117,9 @@ class ReportContainer extends WidgetBase
public function onLoadAddPopup()
{
$sizes = [];
for ($i = 1; $i <= 10; $i++)
for ($i = 1; $i <= 10; $i++) {
$sizes[$i] = $i < 10 ? $i : $i.' (' . Lang::get('backend::lang.dashboard.full_width') . ')';
}
$this->vars['sizes'] = $sizes;
$this->vars['widgets'] = WidgetManager::instance()->listReportWidgets();
@ -130,15 +132,18 @@ class ReportContainer extends WidgetBase
$className = trim(Request::input('className'));
$size = trim(Request::input('size'));
if (!$className)
if (!$className) {
throw new ApplicationException('Please select a widget to add.');
}
if (!class_exists($className))
if (!class_exists($className)) {
throw new ApplicationException('The selected class doesn\'t exist.');
}
$widget = new $className($this->controller);
if (!($widget instanceof \Backend\Classes\ReportWidgetBase))
if (!($widget instanceof \Backend\Classes\ReportWidgetBase)) {
throw new ApplicationException('The selected class is not a report widget.');
}
$widgetInfo = $this->addWidget($widget, $size);
@ -162,8 +167,9 @@ class ReportContainer extends WidgetBase
} while (array_key_exists($alias, $widgets));
$sortOrder = 0;
foreach ($widgets as $widgetInfo)
foreach ($widgets as $widgetInfo) {
$sortOrder = max($sortOrder, $widgetInfo['sortOrder']);
}
$sortOrder++;
@ -184,22 +190,26 @@ class ReportContainer extends WidgetBase
$aliases = trim(Request::input('aliases'));
$orders = trim(Request::input('orders'));
if (!$aliases)
if (!$aliases) {
throw new ApplicationException('Invalid aliases string.');
}
if (!$orders)
if (!$orders) {
throw new ApplicationException('Invalid orders string.');
}
$aliases = explode(',', $aliases);
$orders = explode(',', $orders);
if (count($aliases) != count($orders))
if (count($aliases) != count($orders)) {
throw new ApplicationException('Invalid data posted.');
}
$widgets = $this->getWidgetsFromUserPreferences();
foreach ($aliases as $index=>$alias) {
if (isset($widgets[$alias]))
foreach ($aliases as $index => $alias) {
if (isset($widgets[$alias])) {
$widgets[$alias]['sortOrder'] = $orders[$index];
}
}
$this->setWidgetsToUserPreferences($widgets);
@ -219,8 +229,9 @@ class ReportContainer extends WidgetBase
$configuration['alias'] = $alias;
$className = $widgetInfo['class'];
if (!class_exists($className))
if (!class_exists($className)) {
continue;
}
$widget = new $className($this->controller, $configuration);
$widget->bindToController();
@ -228,7 +239,7 @@ class ReportContainer extends WidgetBase
$result[$alias] = ['widget' => $widget, 'sortOrder' => $widgetInfo['sortOrder']];
}
uasort($result, function($a, $b){
uasort($result, function ($a, $b) {
return $a['sortOrder'] - $b['sortOrder'];
});
@ -238,7 +249,9 @@ class ReportContainer extends WidgetBase
protected function getWidgetsFromUserPreferences()
{
$widgets = UserPreferences::forUser()->get($this->getUserPreferencesKey(), $this->defaultWidgets);
if (!is_array($widgets)) return [];
if (!is_array($widgets)) {
return [];
}
return $widgets;
}
@ -262,8 +275,9 @@ class ReportContainer extends WidgetBase
{
$widgets = $this->getWidgetsFromUserPreferences();
if (isset($widgets[$alias]))
if (isset($widgets[$alias])) {
unset($widgets[$alias]);
}
$this->setWidgetsToUserPreferences($widgets);
}
@ -271,8 +285,9 @@ class ReportContainer extends WidgetBase
protected function findWidgetByAlias($alias)
{
$widgets = $this->loadWidgets();
if (!isset($widgets[$alias]))
if (!isset($widgets[$alias])) {
throw new ApplicationException('The specified widget is not found.');
}
return $widgets[$alias]['widget'];
}
@ -320,8 +335,9 @@ class ReportContainer extends WidgetBase
];
foreach ($params as $name => $value) {
if (isset($property[$name]))
if (isset($property[$name])) {
continue;
}
$property[$name] = !is_array($value) ? Lang::get($value) : $value;
}
@ -351,4 +367,4 @@ class ReportContainer extends WidgetBase
{
return 'backend::reportwidgets.'.$this->context;
}
}
}

View File

@ -53,22 +53,26 @@ class Search extends WidgetBase
/*
* Process configuration
*/
if (isset($this->config->prompt))
if (isset($this->config->prompt)) {
$this->placeholder = trans($this->config->prompt);
}
if (isset($this->config->partial))
if (isset($this->config->partial)) {
$this->customPartial = $this->config->partial;
}
if (isset($this->config->growable))
if (isset($this->config->growable)) {
$this->growable = $this->config->growable;
}
/*
* Add CSS class styles
*/
$this->cssClasses[] = 'icon search';
if ($this->growable)
if ($this->growable) {
$this->cssClasses[] = 'growable';
}
}
/**
@ -78,10 +82,11 @@ class Search extends WidgetBase
{
$this->prepareVars();
if ($this->customPartial)
if ($this->customPartial) {
return $this->controller->makePartial($this->customPartial);
else
} else {
return $this->makePartial('search');
}
}
/**
@ -109,8 +114,9 @@ class Search extends WidgetBase
*/
$params = func_get_args();
$result = $this->fireEvent('search.submit', [$params]);
if ($result && is_array($result))
if ($result && is_array($result)) {
return Util::arrayMerge($result);
}
}
/**
@ -126,10 +132,11 @@ class Search extends WidgetBase
*/
public function setActiveTerm($term)
{
if (strlen($term))
if (strlen($term)) {
$this->putSession('term', $term);
else
} else {
$this->resetSession();
}
$this->activeTerm = $term;
}
@ -142,4 +149,4 @@ class Search extends WidgetBase
{
return $this->alias . '[term]';
}
}
}

View File

@ -43,10 +43,10 @@ class Toolbar extends WidgetBase
*/
if (isset($this->config->search)) {
if (is_string($this->config->search))
$searchConfig = $this->makeConfig($this->config->search);
if (is_string($this->config->search)) {
$searchConfig = $this->makeConfig(['partial' => $this->config->search]);
else
$searchConfig = $this->makeConfig($this->config->search);
}
$searchConfig->alias = $this->alias . 'Search';
$this->searchWidget = $this->makeWidget('Backend\Widgets\Search', $searchConfig);
@ -80,9 +80,10 @@ class Toolbar extends WidgetBase
public function makeControlPanel()
{
if (!isset($this->config->buttons))
if (!isset($this->config->buttons)) {
return false;
}
return $this->controller->makePartial($this->config->buttons, $this->vars);
}
}
}