repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/Badge.php | src/Grid/Displayers/Badge.php | <?php
namespace Encore\Admin\Grid\Displayers;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;
class Badge extends AbstractDisplayer
{
public function display($style = 'red')
{
if ($this->value instanceof Arrayable) {
$this->value = $this->value->toArray();
}
return collect((array) $this->value)->map(function ($name) use ($style) {
if (is_array($style)) {
$style = Arr::get($style, $this->getColumn()->getOriginal(), 'red');
}
return "<span class='badge bg-{$style}'>$name</span>";
})->implode(' ');
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/Prefix.php | src/Grid/Displayers/Prefix.php | <?php
namespace Encore\Admin\Grid\Displayers;
class Prefix extends AbstractDisplayer
{
public function display($prefix = null, $delimiter = ' ')
{
if ($prefix instanceof \Closure) {
$prefix = $prefix->call($this->row, $this->getValue(), $this->getColumn()->getOriginal());
}
return <<<HTML
{$prefix}{$delimiter}{$this->getValue()}
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/Select.php | src/Grid/Displayers/Select.php | <?php
namespace Encore\Admin\Grid\Displayers;
use Encore\Admin\Admin;
use Illuminate\Support\Arr;
class Select extends AbstractDisplayer
{
public function display($options = [])
{
return Admin::component('admin::grid.inline-edit.select', [
'key' => $this->getKey(),
'value' => $this->getValue(),
'display' => Arr::get($options, $this->getValue(), ''),
'name' => $this->getPayloadName(),
'resource' => $this->getResource(),
'trigger' => "ie-trigger-{$this->getClassName()}",
'target' => "ie-template-{$this->getClassName()}",
'options' => $options,
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/DropdownActions.php | src/Grid/Displayers/DropdownActions.php | <?php
namespace Encore\Admin\Grid\Displayers;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Admin;
use Encore\Admin\Grid\Actions\Delete;
use Encore\Admin\Grid\Actions\Edit;
use Encore\Admin\Grid\Actions\Show;
class DropdownActions extends Actions
{
protected $view = 'admin::grid.actions.dropdown';
/**
* @var array
*/
protected $custom = [];
/**
* @var array
*/
protected $default = [];
/**
* @var array
*/
protected $defaultClass = [Edit::class, Show::class, Delete::class];
/**
* @param RowAction $action
*
* @return $this
*/
public function add(RowAction $action)
{
$this->prepareAction($action);
array_push($this->custom, $action);
return $this;
}
/**
* Prepend default `edit` `view` `delete` actions.
*/
protected function prependDefaultActions()
{
foreach ($this->defaultClass as $class) {
/** @var RowAction $action */
$action = new $class();
$this->prepareAction($action);
array_push($this->default, $action);
}
}
/**
* @param RowAction $action
*/
protected function prepareAction(RowAction $action)
{
$action->setGrid($this->grid)
->setColumn($this->column)
->setRow($this->row);
}
/**
* Disable view action.
*
* @param bool $disable
*
* @return $this
*/
public function disableView(bool $disable = true)
{
if ($disable) {
array_delete($this->defaultClass, Show::class);
} elseif (!in_array(Show::class, $this->defaultClass)) {
array_push($this->defaultClass, Show::class);
}
return $this;
}
/**
* Disable delete.
*
* @param bool $disable
*
* @return $this.
*/
public function disableDelete(bool $disable = true)
{
if ($disable) {
array_delete($this->defaultClass, Delete::class);
} elseif (!in_array(Delete::class, $this->defaultClass)) {
array_push($this->defaultClass, Delete::class);
}
return $this;
}
/**
* Disable edit.
*
* @param bool $disable
*
* @return $this
*/
public function disableEdit(bool $disable = true)
{
if ($disable) {
array_delete($this->defaultClass, Edit::class);
} elseif (!in_array(Edit::class, $this->defaultClass)) {
array_push($this->defaultClass, Edit::class);
}
return $this;
}
/**
* @param null|\Closure $callback
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
*/
public function display($callback = null)
{
if ($callback instanceof \Closure) {
$callback->call($this, $this);
}
if ($this->disableAll) {
return '';
}
$this->prependDefaultActions();
$variables = [
'default' => $this->default,
'custom' => $this->custom,
];
if (empty($variables['default']) && empty($variables['custom'])) {
return;
}
return Admin::component($this->view, $variables);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/Suffix.php | src/Grid/Displayers/Suffix.php | <?php
namespace Encore\Admin\Grid\Displayers;
class Suffix extends AbstractDisplayer
{
public function display($suffix = null, $delimiter = ' ')
{
if ($suffix instanceof \Closure) {
$suffix = $suffix->call($this->row, $this->getValue());
}
return <<<HTML
{$this->getValue()}{$delimiter}{$suffix}
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Displayers/Limit.php | src/Grid/Displayers/Limit.php | <?php
namespace Encore\Admin\Grid\Displayers;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Str;
class Limit extends AbstractDisplayer
{
protected function addScript()
{
$script = <<<'JS'
$('.limit-more').click(function () {
$(this).parent('.limit-text').toggleClass('hide').siblings().toggleClass('hide');
});
JS;
Admin::script($script);
}
public function display($limit = 100, $end = '...')
{
$this->addScript();
$value = Str::limit($this->value, $limit, $end);
$original = $this->getColumn()->getOriginal();
if ($value == $original) {
return $value;
}
return <<<HTML
<div class="limit-text">
<span class="text">{$value}</span>
<a href="javascript:void(0);" class="limit-more"> <i class="fa fa-angle-double-down"></i></a>
</div>
<div class="limit-text hide">
<span class="text">{$original}</span>
<a href="javascript:void(0);" class="limit-more"> <i class="fa fa-angle-double-up"></i></a>
</div>
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/CreateButton.php | src/Grid/Tools/CreateButton.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
class CreateButton extends AbstractTool
{
/**
* @var Grid
*/
protected $grid;
/**
* Create a new CreateButton instance.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
}
/**
* Render CreateButton.
*
* @return string
*/
public function render()
{
if (!$this->grid->showCreateBtn()) {
return '';
}
$new = trans('admin.new');
return <<<EOT
<div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
<a href="{$this->grid->getCreateUrl()}" class="btn btn-sm btn-success" title="{$new}">
<i class="fa fa-plus"></i><span class="hidden-xs"> {$new}</span>
</a>
</div>
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/ExportButton.php | src/Grid/Tools/ExportButton.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
use Encore\Admin\Grid;
class ExportButton extends AbstractTool
{
/**
* @var Grid
*/
protected $grid;
/**
* Create a new Export button instance.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
}
/**
* Set up script for export button.
*/
protected function setUpScripts()
{
$script = <<<SCRIPT
$('.{$this->grid->getExportSelectedName()}').click(function (e) {
e.preventDefault();
var rows = $.admin.grid.selected().join();
if (!rows) {
return false;
}
var href = $(this).attr('href').replace('__rows__', rows);
location.href = href;
});
SCRIPT;
Admin::script($script);
}
/**
* Render Export button.
*
* @return string
*/
public function render()
{
if (!$this->grid->showExportBtn()) {
return '';
}
$this->setUpScripts();
$trans = [
'export' => trans('admin.export'),
'all' => trans('admin.all'),
'current_page' => trans('admin.current_page'),
'selected_rows' => trans('admin.selected_rows'),
];
$page = request('page', 1);
return <<<EOT
<div class="btn-group pull-right" style="margin-right: 10px">
<a href="{$this->grid->getExportUrl('all')}" target="_blank" class="btn btn-sm btn-twitter" title="{$trans['export']}"><i class="fa fa-download"></i><span class="hidden-xs"> {$trans['export']}</span></a>
<button type="button" class="btn btn-sm btn-twitter dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="{$this->grid->getExportUrl('all')}" target="_blank">{$trans['all']}</a></li>
<li><a href="{$this->grid->getExportUrl('page', $page)}" target="_blank">{$trans['current_page']}</a></li>
<li><a href="{$this->grid->getExportUrl('selected', '__rows__')}" target="_blank" class='{$this->grid->getExportSelectedName()}'>{$trans['selected_rows']}</a></li>
</ul>
</div>
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/Selector.php | src/Grid/Tools/Selector.php | <?php
namespace Encore\Admin\Grid\Tools;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class Selector implements Renderable
{
/**
* @var array|Collection
*/
protected $selectors = [];
/**
* @var array
*/
protected static $selected;
/**
* Selector constructor.
*/
public function __construct()
{
$this->selectors = new Collection();
}
/**
* @param string $column
* @param string|array $label
* @param array|\Closure $options
* @param null|\Closure $query
*
* @return $this
*/
public function select($column, $label, $options = [], $query = null)
{
return $this->addSelector($column, $label, $options, $query);
}
/**
* @param string $column
* @param string $label
* @param array $options
* @param null|\Closure $query
*
* @return $this
*/
public function selectOne($column, $label, $options = [], $query = null)
{
return $this->addSelector($column, $label, $options, $query, 'one');
}
/**
* @param string $column
* @param string $label
* @param array $options
* @param null $query
* @param string $type
*
* @return $this
*/
protected function addSelector($column, $label, $options = [], $query = null, $type = 'many')
{
if (is_array($label)) {
if ($options instanceof \Closure) {
$query = $options;
}
$options = $label;
$label = __(Str::title($column));
}
$this->selectors[$column] = compact('label', 'options', 'type', 'query');
return $this;
}
/**
* Get all selectors.
*
* @return array|Collection
*/
public function getSelectors()
{
return $this->selectors;
}
/**
* @return array
*/
public static function parseSelected()
{
if (!is_null(static::$selected)) {
return static::$selected;
}
$selected = request('_selector', []);
if (!is_array($selected)) {
return [];
}
$selected = array_filter($selected, function ($value) {
return !is_null($value);
});
foreach ($selected as &$value) {
$value = explode(',', $value);
}
return static::$selected = $selected;
}
/**
* @param string $column
* @param mixed $value
* @param bool $add
*
* @return string
*/
public static function url($column, $value = null, $add = false)
{
$query = request()->query();
$selected = static::parseSelected();
$options = Arr::get($selected, $column, []);
if (is_null($value)) {
Arr::forget($query, "_selector.{$column}");
return request()->fullUrlWithQuery($query);
}
if (in_array($value, $options)) {
array_delete($options, $value);
} else {
if ($add) {
$options = [];
}
array_push($options, $value);
}
if (!empty($options)) {
Arr::set($query, "_selector.{$column}", implode(',', $options));
} else {
Arr::forget($query, "_selector.{$column}");
}
return request()->fullUrlWithQuery($query);
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
return view('admin::grid.selector', [
'selectors' => $this->selectors,
'selected' => static::parseSelected(),
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/BatchDelete.php | src/Grid/Tools/BatchDelete.php | <?php
namespace Encore\Admin\Grid\Tools;
class BatchDelete extends BatchAction
{
public function __construct($title)
{
$this->title = $title;
}
/**
* Script of batch delete action.
*/
public function script()
{
$trans = [
'delete_confirm' => trans('admin.delete_confirm'),
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
];
return <<<EOT
$('{$this->getElementClass()}').on('click', function() {
swal({
title: "{$trans['delete_confirm']}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$trans['confirm']}",
showLoaderOnConfirm: true,
cancelButtonText: "{$trans['cancel']}",
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
method: 'post',
url: '{$this->resource}/' + $.admin.grid.selected().join(),
data: {
_method:'delete',
_token:'{$this->getToken()}'
},
success: function (data) {
$.pjax.reload('#pjax-container');
resolve(data);
}
});
});
}
}).then(function(result) {
var data = result.value;
if (typeof data === 'object') {
if (data.status) {
swal(data.message, '', 'success');
} else {
swal(data.message, '', 'error');
}
}
});
});
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/Footer.php | src/Grid/Tools/Footer.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Database\Query\Builder;
class Footer extends AbstractTool
{
/**
* @var Builder
*/
protected $queryBuilder;
/**
* Footer constructor.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
}
/**
* Get model query builder.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function queryBuilder()
{
if (!$this->queryBuilder) {
$this->queryBuilder = $this->grid->model()->getQueryBuilder();
}
return $this->queryBuilder;
}
/**
* {@inheritdoc}
*/
public function render()
{
$content = call_user_func($this->grid->footer(), $this->queryBuilder());
if (empty($content)) {
return '';
}
if ($content instanceof Renderable) {
$content = $content->render();
}
if ($content instanceof Htmlable) {
$content = $content->toHtml();
}
return <<<HTML
<div class="box-footer clearfix">
{$content}
</div>
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/PerPageSelector.php | src/Grid/Tools/PerPageSelector.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
use Encore\Admin\Grid;
class PerPageSelector extends AbstractTool
{
/**
* @var string
*/
protected $perPage;
/**
* @var string
*/
protected $perPageName = '';
/**
* Create a new PerPageSelector instance.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
$this->initialize();
}
/**
* Do initialize work.
*
* @return void
*/
protected function initialize()
{
$this->perPageName = $this->grid->model()->getPerPageName();
$this->perPage = (int) \request()->input(
$this->perPageName,
$this->grid->perPage
);
}
/**
* Get options for selector.
*
* @return static
*/
public function getOptions()
{
return collect($this->grid->perPages)
->push($this->grid->perPage)
->push($this->perPage)
->unique()
->sort();
}
/**
* Render PerPageSelector。
*
* @return string
*/
public function render()
{
Admin::script($this->script());
$options = $this->getOptions()->map(function ($option) {
$selected = ($option == $this->perPage) ? 'selected' : '';
$url = \request()->fullUrlWithQuery([$this->perPageName => $option]);
return "<option value=\"$url\" $selected>$option</option>";
})->implode("\r\n");
$trans = [
'show' => trans('admin.show'),
'entries' => trans('admin.entries'),
];
return <<<EOT
<label class="control-label pull-right" style="margin-right: 10px; font-weight: 100;">
<small>{$trans['show']}</small>
<select class="input-sm {$this->grid->getPerPageName()}" name="per-page">
$options
</select>
<small>{$trans['entries']}</small>
</label>
EOT;
}
/**
* Script of PerPageSelector.
*
* @return string
*/
protected function script()
{
return <<<EOT
$('.{$this->grid->getPerPageName()}').on("change", function(e) {
$.pjax({url: this.value, container: '#pjax-container'});
});
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/FixColumns.php | src/Grid/Tools/FixColumns.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Support\Collection;
class FixColumns
{
/**
* @var Grid
*/
protected $grid;
/**
* @var int
*/
protected $head;
/**
* @var int
*/
protected $tail;
/**
* @var Collection
*/
protected $left;
/**
* @var Collection
*/
protected $right;
/**
* @var string
*/
protected $view = 'admin::grid.fixed-table';
/**
* FixColumns constructor.
*
* @param Grid $grid
* @param int $head
* @param int $tail
*/
public function __construct(Grid $grid, $head, $tail = -1)
{
$this->grid = $grid;
$this->head = $head;
$this->tail = $tail;
$this->left = Collection::make();
$this->right = Collection::make();
}
/**
* @return Collection
*/
public function leftColumns()
{
return $this->left;
}
/**
* @return Collection
*/
public function rightColumns()
{
return $this->right;
}
/**
* @return \Closure
*/
public function apply()
{
$this->grid->setView($this->view, [
'allName' => $this->grid->getSelectAllName(),
'rowName' => $this->grid->getGridRowName(),
]);
return function (Grid $grid) {
if ($this->head > 0) {
$this->left = $grid->visibleColumns()->slice(0, $this->head);
}
if ($this->tail < 0) {
$this->right = $grid->visibleColumns()->slice($this->tail);
}
};
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/QuickSearch.php | src/Grid/Tools/QuickSearch.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid\Concerns\HasQuickSearch;
use Illuminate\Support\Arr;
class QuickSearch extends AbstractTool
{
/**
* @var string
*/
protected $view = 'admin::grid.quick-search';
/**
* @var string
*/
protected $placeholder;
/**
* Set placeholder.
*
* @param string $text
*
* @return $this
*/
public function placeholder($text = '')
{
$this->placeholder = $text;
return $this;
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$query = request()->query();
Arr::forget($query, HasQuickSearch::$searchKey);
$vars = [
'action' => request()->url().'?'.http_build_query($query),
'key' => HasQuickSearch::$searchKey,
'value' => request(HasQuickSearch::$searchKey),
'placeholder' => $this->placeholder,
];
return view($this->view, $vars);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/ColumnSelector.php | src/Grid/Tools/ColumnSelector.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
use Encore\Admin\Grid;
use Illuminate\Support\Collection;
class ColumnSelector extends AbstractTool
{
const SELECT_COLUMN_NAME = '_columns_';
/**
* @var array
*/
protected static $ignored = [
Grid\Column::SELECT_COLUMN_NAME,
Grid\Column::ACTION_COLUMN_NAME,
];
/**
* Create a new Export button instance.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
}
/**
* @return Collection
*/
protected function getGridColumns()
{
return $this->grid->columns()->reject(function ($column) {
return in_array($column->getName(), static::$ignored);
})->map(function ($column) {
return [$column->getName() => $column->getLabel()];
})->collapse();
}
/**
* Ignore a column to display in column selector.
*
* @param string|array $name
*/
public static function ignore($name)
{
static::$ignored = array_merge(static::$ignored, (array) $name);
}
/**
* {@inheritdoc}
*
* @return string
*/
public function render()
{
if (!$this->grid->showColumnSelector()) {
return '';
}
return Admin::component('admin::components.grid-column-selector', [
'columns' => $this->getGridColumns(),
'visible' => $this->grid->visibleColumnNames(),
'defaults' => $this->grid->getDefaultVisibleColumnNames(),
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/TotalRow.php | src/Grid/Tools/TotalRow.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid\Column;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
class TotalRow extends AbstractTool
{
/**
* @var Builder
*/
protected $query;
/**
* @var array
*/
protected $columns;
/**
* @var Collection
*/
protected $visibleColumns;
/**
* TotalRow constructor.
*
* @param Builder $query
* @param array $columns
*/
public function __construct($query, array $columns)
{
$this->query = $query;
$this->columns = $columns;
}
/**
* Get total value of current column.
*
* @param string $column
* @param mixed $display
*
* @return mixed
*/
protected function total($column, $display = null)
{
if (!is_callable($display) && !is_null($display)) {
return $display;
}
$sum = $this->query->sum($column);
if (is_callable($display)) {
return call_user_func($display, $sum);
}
return $sum;
}
/**
* @param Collection $columns
*/
public function setVisibleColumns($columns)
{
$this->visibleColumns = $columns;
}
/**
* @return Collection|static
*/
public function getVisibleColumns()
{
if ($this->visibleColumns) {
return $this->visibleColumns;
}
return $this->getGrid()->visibleColumns();
}
/**
* Render total-row.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$columns = $this->getVisibleColumns()->map(function (Column $column) {
$name = $column->getName();
$total = '';
if (Arr::has($this->columns, $name)) {
$total = $this->total($name, Arr::get($this->columns, $name));
}
return [
'class' => $column->getClassName(),
'value' => $total,
];
});
return view('admin::grid.total-row', compact('columns'));
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/BatchActions.php | src/Grid/Tools/BatchActions.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
use Illuminate\Support\Collection;
class BatchActions extends AbstractTool
{
/**
* @var Collection
*/
protected $actions;
/**
* @var bool
*/
protected $enableDelete = true;
/**
* @var bool
*/
private $holdAll = false;
/**
* BatchActions constructor.
*/
public function __construct()
{
$this->actions = new Collection();
$this->appendDefaultAction();
}
/**
* Append default action(batch delete action).
*
* return void
*/
protected function appendDefaultAction()
{
$this->add(new BatchDelete(trans('admin.batch_delete')));
}
/**
* Disable delete.
*
* @return $this
*/
public function disableDelete(bool $disable = true)
{
$this->enableDelete = !$disable;
return $this;
}
/**
* Disable delete And Hode SelectAll Checkbox.
*
* @return $this
*/
public function disableDeleteAndHodeSelectAll()
{
$this->enableDelete = false;
$this->holdAll = true;
return $this;
}
/**
* Add a batch action.
*
* @param $title
* @param BatchAction|null $action
*
* @return $this
*/
public function add($title, BatchAction $action = null)
{
$id = $this->actions->count();
if (func_num_args() == 1) {
$action = $title;
} elseif (func_num_args() == 2) {
$action->setTitle($title);
}
if (method_exists($action, 'setId')) {
$action->setId($id);
}
$this->actions->push($action);
return $this;
}
/**
* Setup scripts of batch actions.
*
* @return void
*/
protected function addActionScripts()
{
$this->actions->each(function ($action) {
$action->setGrid($this->grid);
if (method_exists($action, 'script')) {
Admin::script($action->script());
}
});
}
/**
* Render BatchActions button groups.
*
* @return string
*/
public function render()
{
if (!$this->enableDelete) {
$this->actions->shift();
}
$this->addActionScripts();
return Admin::component('admin::grid.batch-actions', [
'all' => $this->grid->getSelectAllName(),
'row' => $this->grid->getGridRowName(),
'actions' => $this->actions,
'holdAll' => $this->holdAll,
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/Paginator.php | src/Grid/Tools/Paginator.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Pagination\LengthAwarePaginator;
class Paginator extends AbstractTool
{
/**
* @var \Illuminate\Pagination\LengthAwarePaginator
*/
protected $paginator = null;
/**
* @var bool
*/
protected $perPageSelector = true;
/**
* Create a new Paginator instance.
*
* @param Grid $grid
*/
public function __construct(Grid $grid, $perPageSelector = true)
{
$this->grid = $grid;
$this->perPageSelector = $perPageSelector;
$this->initPaginator();
}
/**
* Initialize work for Paginator.
*
* @return void
*/
protected function initPaginator()
{
$this->paginator = $this->grid->model()->eloquent();
if ($this->paginator instanceof LengthAwarePaginator) {
$this->paginator->appends(request()->all());
}
}
/**
* Get Pagination links.
*
* @return string
*/
protected function paginationLinks()
{
return $this->paginator->render('admin::pagination');
}
/**
* Get per-page selector.
*
* @return PerPageSelector
*/
protected function perPageSelector()
{
if (!$this->perPageSelector) {
return;
}
return new PerPageSelector($this->grid);
}
/**
* Get range infomation of paginator.
*
* @return string|\Symfony\Component\Translation\TranslatorInterface
*/
protected function paginationRanger()
{
$parameters = [
'first' => $this->paginator->firstItem(),
'last' => $this->paginator->lastItem(),
'total' => $this->paginator->total(),
];
$parameters = collect($parameters)->flatMap(function ($parameter, $key) {
return [$key => "<b>$parameter</b>"];
});
return trans('admin.pagination.range', $parameters->all());
}
/**
* Render Paginator.
*
* @return string
*/
public function render()
{
if (!$this->grid->showPagination()) {
return '';
}
return $this->paginationRanger().
$this->paginationLinks().
$this->perPageSelector();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/FilterButton.php | src/Grid/Tools/FilterButton.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
class FilterButton extends AbstractTool
{
/**
* {@inheritdoc}
*/
public function render()
{
$label = '';
$filter = $this->grid->getFilter();
if ($scope = $filter->getCurrentScope()) {
$label = " {$scope->getLabel()} ";
}
return Admin::component('admin::filter.button', [
'scopes' => $filter->getScopes(),
'label' => $label,
'cancel' => $filter->urlWithoutScopes(),
'btn_class' => uniqid().'-filter-btn',
'expand' => $filter->expand,
'filter_id' => $filter->getFilterID(),
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/BatchAction.php | src/Grid/Tools/BatchAction.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Contracts\Support\Renderable;
abstract class BatchAction implements Renderable
{
/**
* @var int
*/
protected $id;
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $resource;
/**
* @var Grid
*/
protected $grid;
/**
* @param $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Set title for this action.
*
* @param string $title
*
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param Grid $grid
*/
public function setGrid(Grid $grid)
{
$this->grid = $grid;
$this->resource = $grid->resource();
}
/**
* @return string
*/
public function getToken()
{
return csrf_token();
}
/**
* @param bool $dotPrefix
*
* @return string
*/
public function getElementClass($dotPrefix = true)
{
return sprintf(
'%s%s-%s',
$dotPrefix ? '.' : '',
$this->grid->getGridBatchName(),
$this->id
);
}
/**
* @return string
*/
public function render()
{
return $this->title;
}
/**
* @return mixed
*/
abstract public function script();
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/QuickCreate.php | src/Grid/Tools/QuickCreate.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
use Encore\Admin\Form\Field\MultipleSelect;
use Encore\Admin\Form\Field\Select;
use Encore\Admin\Form\Field\Text;
use Encore\Admin\Grid;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Collection;
class QuickCreate implements Renderable
{
/**
* @var Grid
*/
protected $parent;
/**
* @var Collection
*/
protected $fields;
/**
* QuickCreate constructor.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->parent = $grid;
$this->fields = Collection::make();
}
protected function formatPlaceholder($placeholder)
{
return array_filter((array) $placeholder);
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function text($column, $placeholder = '')
{
$field = new Text($column, $this->formatPlaceholder($placeholder));
$this->addField($field->width('200px'));
return $field;
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function email($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->inputmask(['alias' => 'email']);
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function ip($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->inputmask(['alias' => 'ip'])
->width('120px');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function url($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->inputmask(['alias' => 'url']);
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function password($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->attribute('type', 'password')
->width('100px');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function mobile($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->inputmask(['mask' => '99999999999'])
->width('100px');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Text
*/
public function integer($column, $placeholder = '')
{
return $this->text($column, $placeholder)
->inputmask(['alias' => 'integer'])
->width('120px');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Select
*/
public function select($column, $placeholder = '')
{
$field = new Select($column, $this->formatPlaceholder($placeholder));
$this->addField($field);
return $field;
}
/**
* @param string $column
* @param string $placeholder
*
* @return MultipleSelect
*/
public function multipleSelect($column, $placeholder = '')
{
$field = new MultipleSelect($column, $this->formatPlaceholder($placeholder));
$this->addField($field);
return $field;
}
/**
* @param string $column
* @param string $placeholder
*
* @return Field\Date
*/
public function datetime($column, $placeholder = '')
{
return $this->date($column, $placeholder)->format('YYYY-MM-DD HH:mm:ss');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Field\Date
*/
public function time($column, $placeholder = '')
{
return $this->date($column, $placeholder)->format('HH:mm:ss');
}
/**
* @param string $column
* @param string $placeholder
*
* @return Field\Date
*/
public function date($column, $placeholder = '')
{
$field = new Field\Date($column, $this->formatPlaceholder($placeholder));
$this->addField($field);
return $field;
}
/**
* @param Field $field
*
* @return Field
*/
protected function addField(Field $field)
{
$elementClass = array_merge(['quick-create'], $field->getElementClass());
$field->addElementClass($elementClass);
$field->setView($this->resolveView(get_class($field)));
$this->fields->push($field);
return $field;
}
/**
* @param string $class
*
* @return string
*/
protected function resolveView($class)
{
$path = explode('\\', $class);
$name = strtolower(array_pop($path));
return "admin::grid.quick-create.{$name}";
}
protected function script()
{
$url = $this->parent->resource();
$script = <<<SCRIPT
;(function () {
$('.quick-create .create').click(function () {
$('.quick-create .create-form').show();
$(this).hide();
});
$('.quick-create .cancel').click(function () {
$('.quick-create .create-form').hide();
$('.quick-create .create').show();
});
$('.quick-create .create-form').submit(function (e) {
$(':submit', e.target).button('loading');
e.preventDefault();
$.ajax({
url: '{$url}',
type: 'POST',
data: $(this).serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
if (data.status == true) {
$.admin.toastr.success(data.message, '', {positionClass:"toast-top-center"});
$.admin.reload();
return;
}
if (typeof data.validation !== 'undefined') {
$.admin.toastr.warning(data.message, '', {positionClass:"toast-top-center"})
}
},
error: function(XMLHttpRequest, textStatus){
$(':submit', e.target).button('reset');
if (typeof XMLHttpRequest.responseJSON === 'object') {
$.admin.toastr.error(XMLHttpRequest.responseJSON.message, '', {positionClass:"toast-top-center", timeOut: 10000});
}
}
});
return false;
});
})();
SCRIPT;
Admin::script($script);
}
/**
* @param int $columnCount
*
* @return array|string
*/
public function render($columnCount = 0)
{
if ($this->fields->isEmpty()) {
return '';
}
$this->script();
$vars = [
'columnCount' => $columnCount,
'fields' => $this->fields,
];
return view('admin::grid.quick-create.form', $vars)->render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/Header.php | src/Grid/Tools/Header.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Database\Query\Builder;
class Header extends AbstractTool
{
/**
* @var Builder
*/
protected $queryBuilder;
/**
* Header constructor.
*
* @param Grid $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
}
/**
* Get model query builder.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function queryBuilder()
{
if (!$this->queryBuilder) {
$this->queryBuilder = $this->grid->model()->getQueryBuilder();
}
return $this->queryBuilder;
}
/**
* {@inheritdoc}
*/
public function render()
{
$content = call_user_func($this->grid->header(), $this->queryBuilder());
if (empty($content)) {
return '';
}
if ($content instanceof Renderable) {
$content = $content->render();
}
if ($content instanceof Htmlable) {
$content = $content->toHtml();
}
return <<<HTML
<div class="box-header with-border clearfix">
{$content}
</div>
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Grid/Tools/AbstractTool.php | src/Grid/Tools/AbstractTool.php | <?php
namespace Encore\Admin\Grid\Tools;
use Encore\Admin\Grid;
use Illuminate\Contracts\Support\Renderable;
abstract class AbstractTool implements Renderable
{
/**
* @var Grid
*/
protected $grid;
/**
* @var bool
*/
protected $disabled = false;
/**
* Toggle this button.
*
* @param bool $disable
*
* @return $this
*/
public function disable(bool $disable = true)
{
$this->disabled = $disable;
return $this;
}
/**
* If the tool is allowed.
*/
public function allowed()
{
return !$this->disabled;
}
/**
* Set parent grid.
*
* @param Grid $grid
*
* @return $this
*/
public function setGrid(Grid $grid)
{
$this->grid = $grid;
return $this;
}
/**
* @return Grid
*/
public function getGrid()
{
return $this->grid;
}
/**
* {@inheritdoc}
*/
abstract public function render();
/**
* @return string
*/
public function __toString()
{
return $this->render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Builder.php | src/Form/Builder.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Admin;
use Encore\Admin\Form;
use Encore\Admin\Form\Field\Hidden;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
/**
* Class Builder.
*/
class Builder
{
/**
* Previous url key.
*/
const PREVIOUS_URL_KEY = '_previous_';
/**
* @var mixed
*/
protected $id;
/**
* @var Form
*/
protected $form;
/**
* @var
*/
protected $action;
/**
* @var Collection
*/
protected $fields;
/**
* @var array
*/
protected $options = [];
/**
* Modes constants.
*/
const MODE_EDIT = 'edit';
const MODE_CREATE = 'create';
/**
* Form action mode, could be create|view|edit.
*
* @var string
*/
protected $mode = 'create';
/**
* @var array
*/
protected $hiddenFields = [];
/**
* @var Tools
*/
protected $tools;
/**
* @var Footer
*/
protected $footer;
/**
* Width for label and field.
*
* @var array
*/
protected $width = [
'label' => 2,
'field' => 8,
];
/**
* View for this form.
*
* @var string
*/
protected $view = 'admin::form';
/**
* Form title.
*
* @var string
*/
protected $title;
/**
* @var string
*/
protected $formClass;
/**
* Builder constructor.
*
* @param Form $form
*
* @return void
*/
public function __construct(Form $form)
{
$this->form = $form;
$this->fields = new Collection();
$this->init();
}
/**
* Do initialize.
*
* @return void
*/
public function init()
{
$this->tools = new Tools($this);
$this->footer = new Footer($this);
$this->formClass = 'model-form-'.uniqid();
}
/**
* Get form tools instance.
*
* @return Tools
*/
public function getTools()
{
return $this->tools;
}
/**
* Get form footer instance.
*
* @return Footer
*/
public function getFooter()
{
return $this->footer;
}
/**
* Set the builder mode.
*
* @param string $mode
*
* @return void
*/
public function setMode($mode = 'create')
{
$this->mode = $mode;
}
/**
* @return string
*/
public function getMode(): string
{
return $this->mode;
}
/**
* Returns builder is $mode.
*
* @param string $mode
*
* @return bool
*/
public function isMode($mode): bool
{
return $this->mode === $mode;
}
/**
* Check if is creating resource.
*
* @return bool
*/
public function isCreating(): bool
{
return $this->isMode(static::MODE_CREATE);
}
/**
* Check if is editing resource.
*
* @return bool
*/
public function isEditing(): bool
{
return $this->isMode(static::MODE_EDIT);
}
/**
* Set resource Id.
*
* @param mixed $id
*
* @return void
*/
public function setResourceId($id)
{
$this->id = $id;
}
/**
* Get Resource id.
*
* @return mixed
*/
public function getResourceId()
{
return $this->id;
}
/**
* @param int|null $slice
*
* @return string
*/
public function getResource(int $slice = null): string
{
if ($this->mode === self::MODE_CREATE) {
return $this->form->resource(-1);
}
if ($slice !== null) {
return $this->form->resource($slice);
}
return $this->form->resource();
}
/**
* @param int $field
* @param int $label
*
* @return $this
*/
public function setWidth($field = 8, $label = 2): self
{
$this->width = [
'label' => $label,
'field' => $field,
];
return $this;
}
/**
* Get label and field width.
*
* @return array
*/
public function getWidth(): array
{
return $this->width;
}
/**
* Set form action.
*
* @param string $action
*
* @return void
*/
public function setAction($action)
{
$this->action = $action;
}
/**
* Get Form action.
*
* @return string
*/
public function getAction(): string
{
if ($this->action) {
return $this->action;
}
if ($this->isMode(static::MODE_EDIT)) {
return $this->form->resource().'/'.$this->id;
}
if ($this->isMode(static::MODE_CREATE)) {
return $this->form->resource(-1);
}
return '';
}
/**
* Set view for this form.
*
* @param string $view
*
* @return $this
*/
public function setView($view): self
{
$this->view = $view;
return $this;
}
/**
* Set title for form.
*
* @param string $title
*
* @return $this
*/
public function setTitle($title): self
{
$this->title = $title;
return $this;
}
/**
* Get fields of this builder.
*
* @return Collection
*/
public function fields(): Collection
{
return $this->fields;
}
/**
* Get specify field.
*
* @param string $name
*
* @return mixed
*/
public function field($name)
{
return $this->fields()->first(function (Field $field) use ($name) {
return $field->column() === $name;
});
}
/**
* If the parant form has rows.
*
* @return bool
*/
public function hasRows(): bool
{
return !empty($this->form->rows);
}
/**
* Get field rows of form.
*
* @return array
*/
public function getRows(): array
{
return $this->form->rows;
}
/**
* @return array
*/
public function getHiddenFields(): array
{
return $this->hiddenFields;
}
/**
* @param Field $field
*
* @return void
*/
public function addHiddenField(Field $field)
{
$this->hiddenFields[] = $field;
}
/**
* Add or get options.
*
* @param array $options
*
* @return array|null
*/
public function options($options = [])
{
if (empty($options)) {
return $this->options;
}
$this->options = array_merge($this->options, $options);
}
/**
* Get or set option.
*
* @param string $option
* @param mixed $value
*
* @return $this
*/
public function option($option, $value = null)
{
if (func_num_args() === 1) {
return Arr::get($this->options, $option);
}
$this->options[$option] = $value;
return $this;
}
/**
* @return string
*/
public function title(): string
{
if ($this->title) {
return $this->title;
}
if ($this->mode === static::MODE_CREATE) {
return trans('admin.create');
}
if ($this->mode === static::MODE_EDIT) {
return trans('admin.edit');
}
return '';
}
/**
* Determine if form fields has files.
*
* @return bool
*/
public function hasFile(): bool
{
foreach ($this->fields() as $field) {
if ($field instanceof Field\File || $field instanceof Field\MultipleFile) {
return true;
}
}
return false;
}
/**
* Add field for store redirect url after update or store.
*
* @return void
*/
protected function addRedirectUrlField()
{
$previous = URL::previous();
if (!$previous || $previous === URL::current()) {
return;
}
if (Str::contains($previous, url($this->getResource()))) {
$this->addHiddenField((new Hidden(static::PREVIOUS_URL_KEY))->value($previous));
}
}
/**
* Open up a new HTML form.
*
* @param array $options
*
* @return string
*/
public function open($options = []): string
{
$attributes = [];
if ($this->isMode(self::MODE_EDIT)) {
$this->addHiddenField((new Hidden('_method'))->value('PUT'));
}
$this->addRedirectUrlField();
$attributes['action'] = $this->getAction();
$attributes['method'] = Arr::get($options, 'method', 'post');
$attributes['class'] = implode(' ', ['form-horizontal', $this->formClass]);
$attributes['accept-charset'] = 'UTF-8';
if ($this->hasFile()) {
$attributes['enctype'] = 'multipart/form-data';
}
$html = [];
foreach ($attributes as $name => $value) {
$html[] = "$name=\"$value\"";
}
return '<form '.implode(' ', $html).' pjax-container>';
}
/**
* Close the current form.
*
* @return string
*/
public function close(): string
{
$this->form = null;
$this->fields = null;
return '</form>';
}
/**
* @param string $message
*
* @return void
*/
public function confirm(string $message)
{
$trans = [
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
];
$script = <<<SCRIPT
$('form.{$this->formClass} button[type=submit]').click(function (e) {
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "$message",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$trans['confirm']}",
cancelButtonText: "{$trans['cancel']}",
}).then(function (result) {
if (result.value) {
form.submit();
}
});
});
SCRIPT;
Admin::script($script);
}
/**
* Remove reserved fields like `id` `created_at` `updated_at` in form fields.
*
* @return void
*/
protected function removeReservedFields()
{
if (!$this->isCreating()) {
return;
}
$reservedColumns = [
$this->form->model()->getCreatedAtColumn(),
$this->form->model()->getUpdatedAtColumn(),
];
if ($this->form->model()->incrementing) {
$reservedColumns[] = $this->form->model()->getKeyName();
}
$this->form->getLayout()->removeReservedFields($reservedColumns);
$this->fields = $this->fields()->reject(function (Field $field) use ($reservedColumns) {
return in_array($field->column(), $reservedColumns, true);
});
}
/**
* Render form header tools.
*
* @return string
*/
public function renderTools(): string
{
return $this->tools->render();
}
/**
* Render form footer.
*
* @return string
*/
public function renderFooter(): string
{
return $this->footer->render();
}
/**
* Add script for tab form.
*
* @return void
*/
protected function addTabformScript()
{
$script = <<<'SCRIPT'
var hash = document.location.hash;
if (hash) {
$('.nav-tabs a[href="' + hash + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
history.pushState(null,null, e.target.hash);
});
if ($('.has-error').length) {
$('.has-error').each(function () {
var tabId = '#'+$(this).closest('.tab-pane').attr('id');
$('li a[href="'+tabId+'"] i').removeClass('hide');
});
var first = $('.has-error:first').closest('.tab-pane').attr('id');
$('li a[href="#'+first+'"]').tab('show');
}
SCRIPT;
Admin::script($script);
}
/**
* Add script for cascade.
*
* @return void
*/
protected function addCascadeScript()
{
$script = <<<SCRIPT
;(function () {
$('form.{$this->formClass}').submit(function (e) {
e.preventDefault();
$(this).find('div.cascade-group.hide :input').attr('disabled', true);
});
})();
SCRIPT;
Admin::script($script);
}
/**
* Render form.
*
* @return string
*/
public function render(): string
{
$this->removeReservedFields();
$tabObj = $this->form->setTab();
if (!$tabObj->isEmpty()) {
$this->addTabformScript();
}
$this->addCascadeScript();
$data = [
'form' => $this,
'tabObj' => $tabObj,
'width' => $this->width,
'layout' => $this->form->getLayout(),
];
return view($this->view, $data)->render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Row.php | src/Form/Row.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Form;
use Illuminate\Contracts\Support\Renderable;
class Row implements Renderable
{
/**
* Callback for add field to current row.s.
*
* @var \Closure
*/
protected $callback;
/**
* Parent form.
*
* @var Form
*/
protected $form;
/**
* Fields in this row.
*
* @var array
*/
protected $fields = [];
/**
* Default field width for appended field.
*
* @var int
*/
protected $defaultFieldWidth = 12;
/**
* Row constructor.
*
* @param \Closure $callback
* @param Form $form
*/
public function __construct(\Closure $callback, Form $form)
{
$this->callback = $callback;
$this->form = $form;
call_user_func($this->callback, $this);
}
/**
* Get fields of this row.
*
* @return array
*/
public function getFields()
{
return $this->fields;
}
/**
* Set width for a incomming field.
*
* @param int $width
*
* @return $this
*/
public function width($width = 12)
{
$this->defaultFieldWidth = $width;
return $this;
}
/**
* Render the row.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
return view('admin::form.row', ['fields' => $this->fields]);
}
/**
* Add field.
*
* @param string $method
* @param array $arguments
*
* @return Field|void
*/
public function __call($method, $arguments)
{
$field = $this->form->__call($method, $arguments);
$field->disableHorizontal();
$this->fields[] = [
'width' => $this->defaultFieldWidth,
'element' => $field,
];
return $field;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Footer.php | src/Form/Footer.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Admin;
use Illuminate\Contracts\Support\Renderable;
class Footer implements Renderable
{
/**
* Footer view.
*
* @var string
*/
protected $view = 'admin::form.footer';
/**
* Form builder instance.
*
* @var Builder
*/
protected $builder;
/**
* Available buttons.
*
* @var array
*/
protected $buttons = ['reset', 'submit'];
/**
* Available checkboxes.
*
* @var array
*/
protected $checkboxes = ['view', 'continue_editing', 'continue_creating'];
/**
* @var string
*/
protected $defaultCheck;
/**
* Footer constructor.
*
* @param Builder $builder
*/
public function __construct(Builder $builder)
{
$this->builder = $builder;
}
/**
* Disable reset button.
*
* @return $this
*/
public function disableReset(bool $disable = true)
{
if ($disable) {
array_delete($this->buttons, 'reset');
} elseif (!in_array('reset', $this->buttons)) {
array_push($this->buttons, 'reset');
}
return $this;
}
/**
* Disable submit button.
*
* @return $this
*/
public function disableSubmit(bool $disable = true)
{
if ($disable) {
array_delete($this->buttons, 'submit');
} elseif (!in_array('submit', $this->buttons)) {
array_push($this->buttons, 'submit');
}
return $this;
}
/**
* Disable View Checkbox.
*
* @return $this
*/
public function disableViewCheck(bool $disable = true)
{
if ($disable) {
array_delete($this->checkboxes, 'view');
} elseif (!in_array('view', $this->checkboxes)) {
array_push($this->checkboxes, 'view');
}
return $this;
}
/**
* Disable Editing Checkbox.
*
* @return $this
*/
public function disableEditingCheck(bool $disable = true)
{
if ($disable) {
array_delete($this->checkboxes, 'continue_editing');
} elseif (!in_array('continue_editing', $this->checkboxes)) {
array_push($this->checkboxes, 'continue_editing');
}
return $this;
}
/**
* Disable Creating Checkbox.
*
* @return $this
*/
public function disableCreatingCheck(bool $disable = true)
{
if ($disable) {
array_delete($this->checkboxes, 'continue_creating');
} elseif (!in_array('continue_creating', $this->checkboxes)) {
array_push($this->checkboxes, 'continue_creating');
}
return $this;
}
/**
* Set `view` as default check.
*
* @return $this
*/
public function checkView()
{
$this->defaultCheck = 'view';
return $this;
}
/**
* Set `continue_creating` as default check.
*
* @return $this
*/
public function checkCreating()
{
$this->defaultCheck = 'continue_creating';
return $this;
}
/**
* Set `continue_editing` as default check.
*
* @return $this
*/
public function checkEditing()
{
$this->defaultCheck = 'continue_editing';
return $this;
}
/**
* Setup scripts.
*/
protected function setupScript()
{
$script = <<<'EOT'
$('.after-submit').iCheck({checkboxClass:'icheckbox_minimal-blue'}).on('ifChecked', function () {
$('.after-submit').not(this).iCheck('uncheck');
});
EOT;
Admin::script($script);
}
/**
* Render footer.
*
* @return string
*/
public function render()
{
$this->setupScript();
$submitRedirects = [
1 => 'continue_editing',
2 => 'continue_creating',
3 => 'view',
];
$data = [
'width' => $this->builder->getWidth(),
'buttons' => $this->buttons,
'checkboxes' => $this->checkboxes,
'submit_redirects' => $submitRedirects,
'default_check' => $this->defaultCheck,
];
return view($this->view, $data)->render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/EmbeddedForm.php | src/Form/EmbeddedForm.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Form as WidgetForm;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
/**
* Class EmbeddedForm.
*
* @method Field\Text text($column, $label = '')
* @method Field\Checkbox checkbox($column, $label = '')
* @method Field\Radio radio($column, $label = '')
* @method Field\Select select($column, $label = '')
* @method Field\MultipleSelect multipleSelect($column, $label = '')
* @method Field\Textarea textarea($column, $label = '')
* @method Field\Hidden hidden($column, $label = '')
* @method Field\Id id($column, $label = '')
* @method Field\Ip ip($column, $label = '')
* @method Field\Url url($column, $label = '')
* @method Field\Color color($column, $label = '')
* @method Field\Email email($column, $label = '')
* @method Field\Mobile mobile($column, $label = '')
* @method Field\Slider slider($column, $label = '')
* @method Field\Map map($latitude, $longitude, $label = '')
* @method Field\Editor editor($column, $label = '')
* @method Field\File file($column, $label = '')
* @method Field\Image image($column, $label = '')
* @method Field\Date date($column, $label = '')
* @method Field\Datetime datetime($column, $label = '')
* @method Field\Time time($column, $label = '')
* @method Field\Year year($column, $label = '')
* @method Field\Month month($column, $label = '')
* @method Field\DateRange dateRange($start, $end, $label = '')
* @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
* @method Field\TimeRange timeRange($start, $end, $label = '')
* @method Field\Number number($column, $label = '')
* @method Field\Currency currency($column, $label = '')
* @method Field\HasMany hasMany($relationName, $callback)
* @method Field\SwitchField switch($column, $label = '')
* @method Field\Display display($column, $label = '')
* @method Field\Rate rate($column, $label = '')
* @method Field\Divide divider()
* @method Field\Password password($column, $label = '')
* @method Field\Decimal decimal($column, $label = '')
* @method Field\Html html($html, $label = '')
* @method Field\Tags tags($column, $label = '')
* @method Field\Icon icon($column, $label = '')
* @method Field\Embeds embeds($column, $label = '')
*/
class EmbeddedForm
{
/**
* @var Form|WidgetForm
*/
protected $parent = null;
/**
* Fields in form.
*
* @var Collection
*/
protected $fields;
/**
* Original data for this field.
*
* @var array
*/
protected $original = [];
/**
* Column name for this form.
*
* @var string
*/
protected $column;
/**
* EmbeddedForm constructor.
*
* @param string $column
*/
public function __construct($column)
{
$this->column = $column;
$this->fields = new Collection();
}
/**
* Get all fields in current form.
*
* @return Collection
*/
public function fields()
{
return $this->fields;
}
/**
* Set parent form for this form.
*
* @param Form $parent
*
* @return $this
*/
public function setParent(Form $parent)
{
$this->parent = $parent;
return $this;
}
/**
* Set parent form for this form.
*
* @param WidgetForm $parent
*
* @return $this
*/
public function setParentWidgetForm(WidgetForm $parent)
{
$this->parent = $parent;
return $this;
}
/**
* Set original values for fields.
*
* @param array $data
*
* @return $this
*/
public function setOriginal($data)
{
if (empty($data)) {
return $this;
}
if (is_string($data)) {
$data = json_decode($data, true);
}
$this->original = $data;
return $this;
}
/**
* Prepare for insert or update.
*
* @param array $input
*
* @return mixed
*/
public function prepare($input)
{
foreach ($input as $key => $record) {
$this->setFieldOriginalValue($key);
$input[$key] = $this->prepareValue($key, $record);
}
return $input;
}
/**
* Do prepare work for each field.
*
* @param string $key
* @param string $record
*
* @return mixed
*/
protected function prepareValue($key, $record)
{
$field = $this->fields->first(function (Field $field) use ($key) {
return in_array($key, (array) $field->column());
});
if ($field && method_exists($field, 'prepare')) {
return $field->prepare($record);
}
return $record;
}
/**
* Set original data for each field.
*
* @param string $key
*
* @return void
*/
protected function setFieldOriginalValue($key)
{
if (array_key_exists($key, $this->original)) {
$values = $this->original[$key];
$this->fields->each(function (Field $field) use ($values) {
$field->setOriginal($values);
});
}
}
/**
* Fill data to all fields in form.
*
* @param array $data
*
* @return $this
*/
public function fill(array $data)
{
$this->fields->each(function (Field $field) use ($data) {
$field->fill($data);
});
return $this;
}
/**
* Format form, set `element name` `error key` and `element class`.
*
* @param Field $field
*
* @return Field
*/
protected function formatField(Field $field)
{
$jsonKey = $field->column();
$elementName = $elementClass = $errorKey = [];
if (is_array($jsonKey)) {
foreach ($jsonKey as $index => $name) {
$elementName[$index] = "{$this->column}[$name]";
$errorKey[$index] = "{$this->column}.$name";
$elementClass[$index] = "{$this->column}_$name";
}
} else {
$elementName = "{$this->column}[$jsonKey]";
$errorKey = "{$this->column}.$jsonKey";
$elementClass = "{$this->column}_$jsonKey";
}
$field->setElementName($elementName)
->setErrorKey($errorKey)
->setElementClass($elementClass);
return $field;
}
/**
* Add a field to form.
*
* @param Field $field
*
* @return $this
*/
public function pushField(Field $field)
{
$field = $this->formatField($field);
$this->fields->push($field);
return $this;
}
/**
* Add nested-form fields dynamically.
*
* @param string $method
* @param array $arguments
*
* @return Field|$this
*/
public function __call($method, $arguments)
{
if ($className = Form::findFieldClass($method)) {
$column = Arr::get($arguments, 0, '');
/** @var Field $field */
$field = new $className($column, array_slice($arguments, 1));
if ($this->parent instanceof WidgetForm) {
$field->setWidgetForm($this->parent);
} else {
$field->setForm($this->parent);
}
$this->pushField($field);
return $field;
}
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field.php | src/Form/Field.php | <?php
namespace Encore\Admin\Form;
use Closure;
use Encore\Admin\Admin;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Form as WidgetForm;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
/**
* Class Field.
*/
class Field implements Renderable
{
use Macroable;
const FILE_DELETE_FLAG = '_file_del_';
const FILE_SORT_FLAG = '_file_sort_';
/**
* Element id.
*
* @var array|string
*/
protected $id;
/**
* Element value.
*
* @var mixed
*/
protected $value;
/**
* Data of all original columns of value.
*
* @var mixed
*/
protected $data;
/**
* Field original value.
*
* @var mixed
*/
protected $original;
/**
* Field default value.
*
* @var mixed
*/
protected $default;
/**
* Element label.
*
* @var string
*/
protected $label = '';
/**
* Column name.
*
* @var string|array
*/
protected $column = '';
/**
* Form element name.
*
* @var string
*/
protected $elementName = [];
/**
* Form element classes.
*
* @var array
*/
protected $elementClass = [];
/**
* Variables of elements.
*
* @var array
*/
protected $variables = [];
/**
* Options for specify elements.
*
* @var array
*/
protected $options = [];
/**
* Checked for specify elements.
*
* @var array
*/
protected $checked = [];
/**
* Validation rules.
*
* @var array|\Closure
*/
protected $rules = [];
/**
* The validation rules for creation.
*
* @var array|\Closure
*/
public $creationRules = [];
/**
* The validation rules for updates.
*
* @var array|\Closure
*/
public $updateRules = [];
/**
* @var \Closure
*/
protected $validator;
/**
* Validation messages.
*
* @var array
*/
protected $validationMessages = [];
/**
* Css required by this field.
*
* @var array
*/
protected static $css = [];
/**
* Js required by this field.
*
* @var array
*/
protected static $js = [];
/**
* Script for field.
*
* @var string
*/
protected $script = '';
/**
* Element attributes.
*
* @var array
*/
protected $attributes = [];
/**
* Parent form.
*
* @var Form|WidgetForm
*/
protected $form = null;
/**
* View for field to render.
*
* @var string
*/
protected $view = '';
/**
* Help block.
*
* @var array
*/
protected $help = [];
/**
* Key for errors.
*
* @var mixed
*/
protected $errorKey;
/**
* Placeholder for this field.
*
* @var string|array
*/
protected $placeholder;
/**
* Width for label and field.
*
* @var array
*/
protected $width = [
'label' => 2,
'field' => 8,
];
/**
* If the form horizontal layout.
*
* @var bool
*/
protected $horizontal = true;
/**
* column data format.
*
* @var \Closure
*/
protected $customFormat = null;
/**
* @var bool
*/
protected $display = true;
/**
* @var array
*/
protected $labelClass = [];
/**
* @var array
*/
protected $groupClass = [];
/**
* @var \Closure
*/
protected $callback;
/**
* column is snake-casing attributes.
*
* @var bool
*/
protected $snakeAttributes = false;
/**
* @var bool
*/
public $isJsonType = false;
/**
* Field constructor.
*
* @param $column
* @param array $arguments
*/
public function __construct($column = '', $arguments = [])
{
$this->column = $this->formatColumn($column);
$this->label = $this->formatLabel($arguments);
$this->id = $this->formatId($column);
}
/**
* Get assets required by this field.
*
* @return array
*/
public static function getAssets()
{
return [
'css' => static::$css,
'js' => static::$js,
];
}
/**
* Format the field column name.
*
* @param string $column
*
* @return mixed|string
*/
protected function formatColumn($column = '')
{
if (Str::contains($column, '->')) {
$this->isJsonType = true;
$column = str_replace('->', '.', $column);
}
return $column;
}
/**
* Format the field element id.
*
* @param string|array $column
*
* @return string|array
*/
protected function formatId($column)
{
return str_replace('.', '_', $column);
}
/**
* Format the label value.
*
* @param array $arguments
*
* @return string
*/
protected function formatLabel($arguments = []): string
{
$column = is_array($this->column) ? current($this->column) : $this->column;
$label = $arguments[0] ?? ucfirst($column);
return str_replace(['.', '_', '->'], ' ', $label);
}
/**
* Format the name of the field.
*
* @param string $column
*
* @return array|mixed|string
*/
protected function formatName($column)
{
if (is_string($column)) {
if (Str::contains($column, '->')) {
$name = explode('->', $column);
} else {
$name = explode('.', $column);
}
if (count($name) === 1) {
return $name[0];
}
$html = array_shift($name);
foreach ($name as $piece) {
$html .= "[$piece]";
}
return $html;
}
if (is_array($this->column)) {
$names = [];
foreach ($this->column as $key => $name) {
$names[$key] = $this->formatName($name);
}
return $names;
}
return '';
}
/**
* Set form element name.
*
* @param string $name
*
* @return $this
*
* @author Edwin Hui
*/
public function setElementName($name): self
{
$this->elementName = $name;
return $this;
}
/**
* Set snake attributes to the field.
*
* @param bool $snakeAttributes
*
* @return $this
*/
public function setSnakeAttributes($snakeAttributes)
{
$this->snakeAttributes = $snakeAttributes;
return $this;
}
/**
* Get snake attributes of the field.
*
* @return bool
*/
public function getSnakeAttributes()
{
return $this->snakeAttributes;
}
/**
* Determine if a column needs to be snaked.
*
* @param string|array $column
*
* @return string|array
*/
protected function columnShouldSnaked($column)
{
return $this->getSnakeAttributes() ? Str::snake($column) : $column;
}
/**
* Fill data to the field.
*
* @param array $data
*
* @return void
*/
public function fill($data)
{
$this->data = $data;
if (is_array($this->column)) {
foreach ($this->column as $key => $column) {
$this->value[$key] = Arr::get($data, $this->columnShouldSnaked($column));
}
return;
}
$this->value = Arr::get($data, $this->columnShouldSnaked($this->column));
$this->formatValue();
}
/**
* Format value by passing custom formater.
*/
protected function formatValue()
{
if (isset($this->customFormat) && $this->customFormat instanceof \Closure) {
$this->value = call_user_func($this->customFormat, $this->value);
}
}
/**
* custom format form column data when edit.
*
* @param \Closure $call
*
* @return $this
*/
public function customFormat(\Closure $call): self
{
$this->customFormat = $call;
return $this;
}
/**
* Set original value to the field.
*
* @param array $data
*
* @return void
*/
public function setOriginal($data)
{
if (is_array($this->column)) {
foreach ($this->column as $key => $column) {
$this->original[$key] = Arr::get($data, $column);
}
return;
}
$this->original = Arr::get($data, $this->column);
}
/**
* @param Form $form
*
* @return $this
*/
public function setForm(Form $form = null)
{
$this->form = $form;
return $this;
}
/**
* Set Widget/Form as field parent.
*
* @param WidgetForm $form
*
* @return $this
*/
public function setWidgetForm(WidgetForm $form)
{
$this->form = $form;
return $this;
}
/**
* Set width for field and label.
*
* @param int $field
* @param int $label
*
* @return $this
*/
public function setWidth($field = 8, $label = 2): self
{
$this->width = [
'label' => $label,
'field' => $field,
];
return $this;
}
/**
* Set the field options.
*
* @param array $options
*
* @return $this
*/
public function options($options = [])
{
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
$this->options = array_merge($this->options, $options);
return $this;
}
/**
* Set the field option checked.
*
* @param array $checked
*
* @return $this
*/
public function checked($checked = [])
{
if ($checked instanceof Arrayable) {
$checked = $checked->toArray();
}
$this->checked = array_merge($this->checked, $checked);
return $this;
}
/**
* Add `required` attribute to current field if has required rule,
* except file and image fields.
*
* @param array $rules
*/
protected function addRequiredAttribute($rules)
{
if (!is_array($rules)) {
return;
}
if (!in_array('required', $rules, true)) {
return;
}
$this->setLabelClass(['asterisk']);
// Only text field has `required` attribute.
if (!$this instanceof Form\Field\Text) {
return;
}
//do not use required attribute with tabs
if ($this->form && $this->form->getTab()) {
return;
}
$this->required();
}
/**
* If has `required` rule, add required attribute to this field.
*/
protected function addRequiredAttributeFromRules()
{
if ($this->data === null) {
// Create page
$rules = $this->creationRules ?: $this->rules;
} else {
// Update page
$rules = $this->updateRules ?: $this->rules;
}
$this->addRequiredAttribute($rules);
}
/**
* Format validation rules.
*
* @param array|string $rules
*
* @return array
*/
protected function formatRules($rules): array
{
if (is_string($rules)) {
$rules = array_filter(explode('|', $rules));
}
return array_filter((array) $rules);
}
/**
* @param string|array|Closure $input
* @param string|array $original
*
* @return array|Closure
*/
protected function mergeRules($input, $original)
{
if ($input instanceof Closure) {
$rules = $input;
} else {
if (!empty($original)) {
$original = $this->formatRules($original);
}
$rules = array_merge($original, $this->formatRules($input));
}
return $rules;
}
/**
* Set the validation rules for the field.
*
* @param array|callable|string $rules
* @param array $messages
*
* @return $this
*/
public function rules($rules = null, $messages = []): self
{
$this->rules = $this->mergeRules($rules, $this->rules);
$this->setValidationMessages('default', $messages);
return $this;
}
/**
* Set the update validation rules for the field.
*
* @param array|callable|string $rules
* @param array $messages
*
* @return $this
*/
public function updateRules($rules = null, $messages = []): self
{
$this->updateRules = $this->mergeRules($rules, $this->updateRules);
$this->setValidationMessages('update', $messages);
return $this;
}
/**
* Set the creation validation rules for the field.
*
* @param array|callable|string $rules
* @param array $messages
*
* @return $this
*/
public function creationRules($rules = null, $messages = []): self
{
$this->creationRules = $this->mergeRules($rules, $this->creationRules);
$this->setValidationMessages('creation', $messages);
return $this;
}
/**
* Set validation messages for column.
*
* @param string $key
* @param array $messages
*
* @return $this
*/
public function setValidationMessages($key, array $messages): self
{
$this->validationMessages[$key] = $messages;
return $this;
}
/**
* Get validation messages for the field.
*
* @return array|mixed
*/
public function getValidationMessages()
{
// Default validation message.
$messages = $this->validationMessages['default'] ?? [];
if (request()->isMethod('POST')) {
$messages = $this->validationMessages['creation'] ?? $messages;
} elseif (request()->isMethod('PUT')) {
$messages = $this->validationMessages['update'] ?? $messages;
}
return $messages;
}
/**
* Get field validation rules.
*
* @return string
*/
protected function getRules()
{
if (request()->isMethod('POST')) {
$rules = $this->creationRules ?: $this->rules;
} elseif (request()->isMethod('PUT')) {
$rules = $this->updateRules ?: $this->rules;
} else {
$rules = $this->rules;
}
if ($rules instanceof \Closure) {
$rules = $rules->call($this, $this->form);
}
if (is_string($rules)) {
$rules = array_filter(explode('|', $rules));
}
if (!$this->form || !$this->form instanceof Form) {
return $rules;
}
if (!$id = $this->form->model()->getKey()) {
return $rules;
}
if (is_array($rules)) {
foreach ($rules as &$rule) {
if (is_string($rule)) {
$rule = str_replace('{{id}}', $id, $rule);
}
}
}
return $rules;
}
/**
* Remove a specific rule by keyword.
*
* @param string $rule
*
* @return void
*/
protected function removeRule($rule)
{
if (is_array($this->rules)) {
array_delete($this->rules, $rule);
return;
}
if (!is_string($this->rules)) {
return;
}
$pattern = "/{$rule}[^\|]?(\||$)/";
$this->rules = preg_replace($pattern, '', $this->rules, -1);
}
/**
* Set field validator.
*
* @param callable $validator
*
* @return $this
*/
public function validator(callable $validator): self
{
$this->validator = $validator;
return $this;
}
/**
* Get key for error message.
*
* @return string|array
*/
public function getErrorKey()
{
return $this->errorKey ?: $this->column;
}
/**
* Set key for error message.
*
* @param string $key
*
* @return $this
*/
public function setErrorKey($key): self
{
$this->errorKey = $key;
return $this;
}
/**
* Set or get value of the field.
*
* @param null $value
*
* @return mixed
*/
public function value($value = null)
{
if ($value === null) {
return $this->value ?? $this->getDefault();
}
$this->value = $value;
return $this;
}
/**
* Set or get data.
*
* @param array $data
*
* @return mixed
*/
public function data(array $data = null)
{
if ($data === null) {
return $this->data;
}
$this->data = $data;
return $this;
}
/**
* Set default value for field.
*
* @param $default
*
* @return $this
*/
public function default($default): self
{
$this->default = $default;
return $this;
}
/**
* Get default value.
*
* @return mixed
*/
public function getDefault()
{
if ($this->default instanceof \Closure) {
return call_user_func($this->default, $this->form);
}
return $this->default;
}
/**
* Set help block for current field.
*
* @param string $text
* @param string $icon
*
* @return $this
*/
public function help($text = '', $icon = 'fa-info-circle'): self
{
$this->help = compact('text', 'icon');
return $this;
}
/**
* Get column of the field.
*
* @return string|array
*/
public function column()
{
return $this->column;
}
/**
* Get label of the field.
*
* @return string
*/
public function label(): string
{
return $this->label;
}
/**
* Get original value of the field.
*
* @return mixed
*/
public function original()
{
return $this->original;
}
/**
* Get validator for this field.
*
* @param array $input
*
* @return bool|\Illuminate\Contracts\Validation\Validator|mixed
*/
public function getValidator(array $input)
{
if ($this->validator) {
return $this->validator->call($this, $input);
}
$rules = $attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
if (is_string($this->column)) {
if (!Arr::has($input, $this->column)) {
return false;
}
$input = $this->sanitizeInput($input, $this->column);
$rules[$this->column] = $fieldRules;
$attributes[$this->column] = $this->label;
}
if (is_array($this->column)) {
foreach ($this->column as $key => $column) {
if (!array_key_exists($column, $input)) {
continue;
}
$input[$column.$key] = Arr::get($input, $column);
$rules[$column.$key] = $fieldRules;
$attributes[$column.$key] = $this->label."[$column]";
}
}
return \validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* Sanitize input data.
*
* @param array $input
* @param string $column
*
* @return array
*/
protected function sanitizeInput($input, $column)
{
if ($this instanceof Field\MultipleSelect) {
$value = Arr::get($input, $column);
Arr::set($input, $column, array_filter($value));
}
return $input;
}
/**
* Add html attributes to elements.
*
* @param array|string $attribute
* @param mixed $value
*
* @return $this
*/
public function attribute($attribute, $value = null): self
{
if (is_array($attribute)) {
$this->attributes = array_merge($this->attributes, $attribute);
} else {
$this->attributes[$attribute] = (string) $value;
}
return $this;
}
/**
* Remove html attributes from elements.
*
* @param array|string $attribute
*
* @return $this
*/
public function removeAttribute($attribute): self
{
Arr::forget($this->attributes, $attribute);
return $this;
}
/**
* Set Field style.
*
* @param string $attr
* @param string $value
*
* @return $this
*/
public function style($attr, $value): self
{
return $this->attribute('style', "{$attr}: {$value}");
}
/**
* Set Field width.
*
* @param string $width
*
* @return $this
*/
public function width($width): self
{
return $this->style('width', $width);
}
/**
* Specifies a regular expression against which to validate the value of the input.
*
* @param string $regexp
*
* @return $this
*/
public function pattern($regexp): self
{
return $this->attribute('pattern', $regexp);
}
/**
* set the input filed required.
*
* @param bool $isLabelAsterisked
*
* @return $this
*/
public function required($isLabelAsterisked = true): self
{
if ($isLabelAsterisked) {
$this->setLabelClass(['asterisk']);
}
return $this->attribute('required', true);
}
/**
* Set the field automatically get focus.
*
* @return $this
*/
public function autofocus(): self
{
return $this->attribute('autofocus', true);
}
/**
* Set the field as readonly mode.
*
* @return $this
*/
public function readonly()
{
return $this->attribute('readonly', true);
}
/**
* Set field as disabled.
*
* @return $this
*/
public function disable(): self
{
return $this->attribute('disabled', true);
}
/**
* Set field placeholder.
*
* @param string $placeholder
*
* @return $this
*/
public function placeholder($placeholder = ''): self
{
$this->placeholder = $placeholder;
return $this;
}
/**
* Get placeholder.
*
* @return mixed
*/
public function getPlaceholder()
{
return $this->placeholder ?: trans('admin.input').' '.$this->label;
}
/**
* Add a divider after this field.
*
* @return $this
*/
public function divider()
{
$this->form->divider();
return $this;
}
/**
* Prepare for a field value before update or insert.
*
* @param $value
*
* @return mixed
*/
public function prepare($value)
{
return $value;
}
/**
* Format the field attributes.
*
* @return string
*/
protected function formatAttributes(): string
{
$html = [];
foreach ($this->attributes as $name => $value) {
$html[] = $name.'="'.e($value).'"';
}
return implode(' ', $html);
}
/**
* @return $this
*/
public function disableHorizontal(): self
{
$this->horizontal = false;
return $this;
}
/**
* @return array
*/
public function getViewElementClasses(): array
{
if ($this->horizontal) {
return [
'label' => "col-sm-{$this->width['label']} {$this->getLabelClass()}",
'field' => "col-sm-{$this->width['field']}",
'form-group' => $this->getGroupClass(true),
];
}
return ['label' => $this->getLabelClass(), 'field' => '', 'form-group' => ''];
}
/**
* Set form element class.
*
* @param string|array $class
*
* @return $this
*/
public function setElementClass($class): self
{
$this->elementClass = array_merge($this->elementClass, (array) $class);
return $this;
}
/**
* Get element class.
*
* @return array
*/
public function getElementClass(): array
{
if (!$this->elementClass) {
$name = $this->elementName ?: $this->formatName($this->column);
$this->elementClass = (array) str_replace(['[', ']'], '_', $name);
}
return $this->elementClass;
}
/**
* Get element class string.
*
* @return mixed
*/
public function getElementClassString()
{
$elementClass = $this->getElementClass();
if (Arr::isAssoc($elementClass)) {
$classes = [];
foreach ($elementClass as $index => $class) {
$classes[$index] = is_array($class) ? implode(' ', $class) : $class;
}
return $classes;
}
return implode(' ', $elementClass);
}
/**
* Get element class selector.
*
* @return string|array
*/
public function getElementClassSelector()
{
$elementClass = $this->getElementClass();
if (Arr::isAssoc($elementClass)) {
$classes = [];
foreach ($elementClass as $index => $class) {
$classes[$index] = '.'.(is_array($class) ? implode('.', $class) : $class);
}
return $classes;
}
return '.'.implode('.', $elementClass);
}
/**
* Add the element class.
*
* @param $class
*
* @return $this
*/
public function addElementClass($class): self
{
if (is_array($class) || is_string($class)) {
$this->elementClass = array_unique(array_merge($this->elementClass, (array) $class));
}
return $this;
}
/**
* Remove element class.
*
* @param $class
*
* @return $this
*/
public function removeElementClass($class): self
{
$delClass = [];
if (is_string($class) || is_array($class)) {
$delClass = (array) $class;
}
foreach ($delClass as $del) {
if (($key = array_search($del, $this->elementClass, true)) !== false) {
unset($this->elementClass[$key]);
}
}
return $this;
}
/**
* Set form group class.
*
* @param string|array $class
*
* @return $this
*/
public function setGroupClass($class): self
{
if (is_array($class)) {
$this->groupClass = array_merge($this->groupClass, $class);
} else {
$this->groupClass[] = $class;
}
return $this;
}
/**
* Get element class.
*
* @param bool $default
*
* @return string
*/
protected function getGroupClass($default = false): string
{
return ($default ? 'form-group ' : '').implode(' ', array_filter($this->groupClass));
}
/**
* reset field className.
*
* @param string $className
* @param string $resetClassName
*
* @return $this
*/
public function resetElementClassName(string $className, string $resetClassName): self
{
if (($key = array_search($className, $this->getElementClass())) !== false) {
$this->elementClass[$key] = $resetClassName;
}
return $this;
}
/**
* Add variables to field view.
*
* @param array $variables
*
* @return $this
*/
public function addVariables(array $variables = []): self
{
$this->variables = array_merge($this->variables, $variables);
return $this;
}
/**
* @return string
*/
public function getLabelClass(): string
{
return implode(' ', $this->labelClass);
}
/**
* @param array $labelClass
* @param bool $replace
*
* @return self
*/
public function setLabelClass(array $labelClass, $replace = false): self
{
$this->labelClass = $replace ? $labelClass : array_merge($this->labelClass, $labelClass);
return $this;
}
/**
* Get the view variables of this field.
*
* @return array
*/
public function variables(): array
{
return array_merge($this->variables, [
'id' => $this->id,
'name' => $this->elementName ?: $this->formatName($this->column),
'help' => $this->help,
'class' => $this->getElementClassString(),
'value' => $this->value(),
'label' => $this->label,
'viewClass' => $this->getViewElementClasses(),
'column' => $this->column,
'errorKey' => $this->getErrorKey(),
'attributes' => $this->formatAttributes(),
'placeholder' => $this->getPlaceholder(),
]);
}
/**
* Get view of this field.
*
* @return string
*/
public function getView(): string
{
if (!empty($this->view)) {
return $this->view;
}
$class = explode('\\', static::class);
return 'admin::form.'.strtolower(end($class));
}
/**
* Set view of current field.
*
* @param string $view
*
* @return string
*/
public function setView($view): self
{
$this->view = $view;
return $this;
}
/**
* Get script of current field.
*
* @return string
*/
public function getScript(): string
{
return $this->script;
}
/**
* Set script of current field.
*
* @param string $script
*
* @return $this
*/
public function setScript($script): self
{
$this->script = $script;
return $this;
}
/**
* To set this field should render or not.
*
* @param bool $display
*
* @return $this
*/
public function setDisplay(bool $display): self
{
$this->display = $display;
return $this;
}
/**
* If this field should render.
*
* @return bool
*/
protected function shouldRender(): bool
{
if (!$this->display) {
return false;
}
return true;
}
/**
* @param \Closure $callback
*
* @return \Encore\Admin\Form\Field
*/
public function with(Closure $callback): self
{
$this->callback = $callback;
return $this;
}
/**
* Render this filed.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
*/
public function render()
{
if (!$this->shouldRender()) {
return '';
}
$this->addRequiredAttributeFromRules();
if ($this->callback instanceof Closure) {
$this->value = $this->callback->call($this->form->model(), $this->value, $this);
}
Admin::script($this->script);
return Admin::component($this->getView(), $this->variables());
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
*/
protected function fieldRender(array $variables = [])
{
if (!empty($variables)) {
$this->addVariables($variables);
}
return self::render();
}
/**
* @return string
*/
public function __toString()
{
return $this->render()->render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Tab.php | src/Form/Tab.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Form;
use Illuminate\Support\Collection;
class Tab
{
/**
* @var Form
*/
protected $form;
/**
* @var Collection
*/
protected $tabs;
/**
* @var int
*/
protected $offset = 0;
/**
* Tab constructor.
*
* @param Form $form
*/
public function __construct(Form $form)
{
$this->form = $form;
$this->tabs = new Collection();
}
/**
* Append a tab section.
*
* @param string $title
* @param \Closure $content
* @param bool $active
*
* @return $this
*/
public function append($title, \Closure $content, $active = false)
{
$fields = $this->collectFields($content);
$id = 'form-'.($this->tabs->count() + 1);
$this->tabs->push(compact('id', 'title', 'fields', 'active'));
return $this;
}
/**
* Collect fields under current tab.
*
* @param \Closure $content
*
* @return Collection
*/
protected function collectFields(\Closure $content)
{
call_user_func($content, $this->form);
$fields = clone $this->form->fields();
$all = $fields->toArray();
foreach ($this->form->rows as $row) {
$rowFields = array_map(function ($field) {
return $field['element'];
}, $row->getFields());
$match = false;
foreach ($rowFields as $field) {
if (($index = array_search($field, $all)) !== false) {
if (!$match) {
$fields->put($index, $row);
} else {
$fields->pull($index);
}
$match = true;
}
}
}
$fields = $fields->slice($this->offset);
$this->offset += $fields->count();
return $fields;
}
/**
* Get all tabs.
*
* @return Collection
*/
public function getTabs()
{
// If there is no active tab, then active the first.
if ($this->tabs->filter(function ($tab) {
return $tab['active'];
})->isEmpty()) {
$first = $this->tabs->first();
$first['active'] = true;
$this->tabs->offsetSet(0, $first);
}
return $this->tabs;
}
/**
* @return bool
*/
public function isEmpty()
{
return $this->tabs->isEmpty();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Tools.php | src/Form/Tools.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Facades\Admin;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Collection;
class Tools implements Renderable
{
/**
* @var Builder
*/
protected $form;
/**
* Collection of tools.
*
* @var array
*/
protected $tools = ['delete', 'view', 'list'];
/**
* Tools should be appends to default tools.
*
* @var Collection
*/
protected $appends;
/**
* Tools should be prepends to default tools.
*
* @var Collection
*/
protected $prepends;
/**
* Create a new Tools instance.
*
* @param Builder $builder
*/
public function __construct(Builder $builder)
{
$this->form = $builder;
$this->appends = new Collection();
$this->prepends = new Collection();
}
/**
* Append a tools.
*
* @param mixed $tool
*
* @return $this
*/
public function append($tool)
{
$this->appends->push($tool);
return $this;
}
/**
* Prepend a tool.
*
* @param mixed $tool
*
* @return $this
*/
public function prepend($tool)
{
$this->prepends->push($tool);
return $this;
}
/**
* Disable `list` tool.
*
* @return $this
*/
public function disableList(bool $disable = true)
{
if ($disable) {
array_delete($this->tools, 'list');
} elseif (!in_array('list', $this->tools)) {
array_push($this->tools, 'list');
}
return $this;
}
/**
* Disable `delete` tool.
*
* @return $this
*/
public function disableDelete(bool $disable = true)
{
if ($disable) {
array_delete($this->tools, 'delete');
} elseif (!in_array('delete', $this->tools)) {
array_push($this->tools, 'delete');
}
return $this;
}
/**
* Disable `edit` tool.
*
* @return $this
*/
public function disableView(bool $disable = true)
{
if ($disable) {
array_delete($this->tools, 'view');
} elseif (!in_array('view', $this->tools)) {
array_push($this->tools, 'view');
}
return $this;
}
/**
* Get request path for resource list.
*
* @return string
*/
protected function getListPath()
{
return $this->form->getResource();
}
/**
* Get request path for edit.
*
* @return string
*/
protected function getDeletePath()
{
return $this->getViewPath();
}
/**
* Get request path for delete.
*
* @return string
*/
protected function getViewPath()
{
$key = $this->form->getResourceId();
if ($key) {
return $this->getListPath().'/'.$key;
} else {
return $this->getListPath();
}
}
/**
* Get parent form of tool.
*
* @return Builder
*/
public function form()
{
return $this->form;
}
/**
* Render list button.
*
* @return string
*/
protected function renderList()
{
$text = trans('admin.list');
return <<<EOT
<div class="btn-group pull-right" style="margin-right: 5px">
<a href="{$this->getListPath()}" class="btn btn-sm btn-default" title="$text"><i class="fa fa-list"></i><span class="hidden-xs"> $text</span></a>
</div>
EOT;
}
/**
* Render list button.
*
* @return string
*/
protected function renderView()
{
$view = trans('admin.view');
return <<<HTML
<div class="btn-group pull-right" style="margin-right: 5px">
<a href="{$this->getViewPath()}" class="btn btn-sm btn-primary" title="{$view}">
<i class="fa fa-eye"></i><span class="hidden-xs"> {$view}</span>
</a>
</div>
HTML;
}
/**
* Render `delete` tool.
*
* @return string
*/
protected function renderDelete()
{
$trans = [
'delete_confirm' => trans('admin.delete_confirm'),
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
'delete' => trans('admin.delete'),
];
$class = uniqid();
$script = <<<SCRIPT
$('.{$class}-delete').unbind('click').click(function() {
swal({
title: "{$trans['delete_confirm']}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$trans['confirm']}",
showLoaderOnConfirm: true,
cancelButtonText: "{$trans['cancel']}",
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
method: 'post',
url: '{$this->getDeletePath()}',
data: {
_method:'delete',
_token:LA.token,
},
success: function (data) {
$.pjax({container:'#pjax-container', url: '{$this->getListPath()}' });
resolve(data);
}
});
});
}
}).then(function(result) {
var data = result.value;
if (typeof data === 'object') {
if (data.status) {
swal(data.message, '', 'success');
} else {
swal(data.message, '', 'error');
}
}
});
});
SCRIPT;
Admin::script($script);
return <<<HTML
<div class="btn-group pull-right" style="margin-right: 5px">
<a href="javascript:void(0);" class="btn btn-sm btn-danger {$class}-delete" title="{$trans['delete']}">
<i class="fa fa-trash"></i><span class="hidden-xs"> {$trans['delete']}</span>
</a>
</div>
HTML;
}
/**
* Add a tool.
*
* @param string $tool
*
* @return $this
*
* @deprecated use append instead.
*/
public function add($tool)
{
return $this->append($tool);
}
/**
* Disable back button.
*
* @return $this
*
* @deprecated
*/
public function disableBackButton()
{
}
/**
* Disable list button.
*
* @return $this
*
* @deprecated Use disableList instead.
*/
public function disableListButton()
{
return $this->disableList();
}
/**
* Render custom tools.
*
* @param Collection $tools
*
* @return mixed
*/
protected function renderCustomTools($tools)
{
if ($this->form->isCreating()) {
$this->disableView();
$this->disableDelete();
}
if (empty($tools)) {
return '';
}
return $tools->map(function ($tool) {
if ($tool instanceof Renderable) {
return $tool->render();
}
if ($tool instanceof Htmlable) {
return $tool->toHtml();
}
return (string) $tool;
})->implode(' ');
}
/**
* Render tools.
*
* @return string
*/
public function render()
{
$output = $this->renderCustomTools($this->prepends);
foreach ($this->tools as $tool) {
$renderMethod = 'render'.ucfirst($tool);
$output .= $this->$renderMethod();
}
return $output.$this->renderCustomTools($this->appends);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/NestedForm.php | src/Form/NestedForm.php | <?php
namespace Encore\Admin\Form;
use Encore\Admin\Admin;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Form as WidgetForm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
/**
* Class NestedForm.
*
* @method Field\Text text($column, $label = '')
* @method Field\Checkbox checkbox($column, $label = '')
* @method Field\Radio radio($column, $label = '')
* @method Field\Select select($column, $label = '')
* @method Field\MultipleSelect multipleSelect($column, $label = '')
* @method Field\Textarea textarea($column, $label = '')
* @method Field\Hidden hidden($column, $label = '')
* @method Field\Id id($column, $label = '')
* @method Field\Ip ip($column, $label = '')
* @method Field\Url url($column, $label = '')
* @method Field\Color color($column, $label = '')
* @method Field\Email email($column, $label = '')
* @method Field\Mobile mobile($column, $label = '')
* @method Field\Slider slider($column, $label = '')
* @method Field\Map map($latitude, $longitude, $label = '')
* @method Field\Editor editor($column, $label = '')
* @method Field\File file($column, $label = '')
* @method Field\Image image($column, $label = '')
* @method Field\Date date($column, $label = '')
* @method Field\Datetime datetime($column, $label = '')
* @method Field\Time time($column, $label = '')
* @method Field\Year year($column, $label = '')
* @method Field\Month month($column, $label = '')
* @method Field\DateRange dateRange($start, $end, $label = '')
* @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
* @method Field\TimeRange timeRange($start, $end, $label = '')
* @method Field\Number number($column, $label = '')
* @method Field\Currency currency($column, $label = '')
* @method Field\HasMany hasMany($relationName, $callback)
* @method Field\SwitchField switch($column, $label = '')
* @method Field\Display display($column, $label = '')
* @method Field\Rate rate($column, $label = '')
* @method Field\Divide divider()
* @method Field\Password password($column, $label = '')
* @method Field\Decimal decimal($column, $label = '')
* @method Field\Html html($html, $label = '')
* @method Field\Tags tags($column, $label = '')
* @method Field\Icon icon($column, $label = '')
* @method Field\Embeds embeds($column, $label = '')
*/
class NestedForm
{
const DEFAULT_KEY_NAME = '__LA_KEY__';
const REMOVE_FLAG_NAME = '_remove_';
const REMOVE_FLAG_CLASS = 'fom-removed';
/**
* @var mixed
*/
protected $key;
/**
* @var string
*/
protected $relationName;
/**
* NestedForm key.
*
* @var Model
*/
protected $model;
/**
* Fields in form.
*
* @var Collection
*/
protected $fields;
/**
* Original data for this field.
*
* @var array
*/
protected $original = [];
/**
* @var \Encore\Admin\Form|\Encore\Admin\Widgets\Form
*/
protected $form;
/**
* Create a new NestedForm instance.
*
* NestedForm constructor.
*
* @param string $relation
* @param Model $model
*/
public function __construct($relation, $model = null)
{
$this->relationName = $relation;
$this->model = $model;
$this->fields = new Collection();
}
/**
* Get current model.
*
* @return Model|null
*/
public function model()
{
return $this->model;
}
/**
* Get the value of the model's primary key.
*
* @return mixed|null
*/
public function getKey()
{
if ($this->model) {
$key = $this->model->getKey();
}
if (!is_null($this->key)) {
$key = $this->key;
}
if (isset($key)) {
return $key;
}
return 'new_'.static::DEFAULT_KEY_NAME;
}
/**
* Set key for current form.
*
* @param mixed $key
*
* @return $this
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Set Form.
*
* @param Form $form
*
* @return $this
*/
public function setForm(Form $form = null)
{
$this->form = $form;
return $this;
}
/**
* Set Widget/Form.
*
* @param WidgetForm $form
*
* @return $this
*/
public function setWidgetForm(WidgetForm $form = null)
{
$this->form = $form;
return $this;
}
/**
* Get form.
*
* @return Form
*/
public function getForm()
{
return $this->form;
}
/**
* Set original values for fields.
*
* @param array $data
* @param string $relatedKeyName
*
* @return $this
*/
public function setOriginal($data, $relatedKeyName = null)
{
if (empty($data)) {
return $this;
}
foreach ($data as $key => $value) {
/*
* like $this->original[30] = [ id = 30, .....]
*/
if ($relatedKeyName) {
$key = $value[$relatedKeyName];
}
$this->original[$key] = $value;
}
return $this;
}
/**
* Prepare for insert or update.
*
* @param array $input
*
* @return mixed
*/
public function prepare($input)
{
foreach ($input as $key => $record) {
$this->setFieldOriginalValue($key);
$input[$key] = $this->prepareRecord($record);
}
return $input;
}
/**
* Set original data for each field.
*
* @param string $key
*
* @return void
*/
protected function setFieldOriginalValue($key)
{
$values = [];
if (array_key_exists($key, $this->original)) {
$values = $this->original[$key];
}
$this->fields->each(function (Field $field) use ($values) {
$field->setOriginal($values);
});
}
/**
* Do prepare work before store and update.
*
* @param array $record
*
* @return array
*/
protected function prepareRecord($record)
{
if ($record[static::REMOVE_FLAG_NAME] == 1) {
return $record;
}
$prepared = [];
/* @var Field $field */
foreach ($this->fields as $field) {
$columns = $field->column();
$value = $this->fetchColumnValue($record, $columns);
if (is_null($value)) {
continue;
}
if (method_exists($field, 'prepare')) {
$value = $field->prepare($value);
}
if (($field instanceof \Encore\Admin\Form\Field\Hidden) || $value != $field->original()) {
if (is_array($columns)) {
foreach ($columns as $name => $column) {
Arr::set($prepared, $column, $value[$name]);
}
} elseif (is_string($columns)) {
Arr::set($prepared, $columns, $value);
}
}
}
$prepared[static::REMOVE_FLAG_NAME] = $record[static::REMOVE_FLAG_NAME];
return $prepared;
}
/**
* Fetch value in input data by column name.
*
* @param array $data
* @param string|array $columns
*
* @return array|mixed
*/
protected function fetchColumnValue($data, $columns)
{
if (is_string($columns)) {
return Arr::get($data, $columns);
}
if (is_array($columns)) {
$value = [];
foreach ($columns as $name => $column) {
if (!Arr::has($data, $column)) {
continue;
}
$value[$name] = Arr::get($data, $column);
}
return $value;
}
}
/**
* @param Field $field
*
* @return $this
*/
public function pushField(Field $field)
{
$this->fields->push($field);
return $this;
}
/**
* Get fields of this form.
*
* @return Collection
*/
public function fields()
{
return $this->fields;
}
/**
* Fill data to all fields in form.
*
* @param array $data
*
* @return $this
*/
public function fill(array $data)
{
/* @var Field $field */
foreach ($this->fields() as $field) {
$field->fill($data);
}
return $this;
}
/**
* Get the html and script of template.
*
* @return array
*/
public function getTemplateHtmlAndScript()
{
$html = '';
$scripts = [];
/* @var Field $field */
foreach ($this->fields() as $field) {
//when field render, will push $script to Admin
$html .= $field->render();
/*
* Get and remove the last script of Admin::$script stack.
*/
if ($field->getScript()) {
$scripts[] = array_pop(Admin::$script);
}
}
return [$html, implode("\r\n", $scripts)];
}
/**
* Set `errorKey` `elementName` `elementClass` for fields inside hasmany fields.
*
* @param Field $field
*
* @return Field
*/
protected function formatField(Field $field)
{
$column = $field->column();
$elementName = $elementClass = $errorKey = [];
$key = $this->getKey();
if (is_array($column)) {
foreach ($column as $k => $name) {
$errorKey[$k] = sprintf('%s.%s.%s', $this->relationName, $key, $name);
$elementName[$k] = sprintf('%s[%s][%s]', $this->relationName, $key, $name);
$elementClass[$k] = [$this->relationName, $name];
}
} else {
$errorKey = sprintf('%s.%s.%s', $this->relationName, $key, $column);
$elementName = sprintf('%s[%s][%s]', $this->relationName, $key, $column);
$elementClass = [$this->relationName, $column];
}
return $field->setErrorKey($errorKey)
->setElementName($elementName)
->setElementClass($elementClass);
}
/**
* Add nested-form fields dynamically.
*
* @param string $method
* @param array $arguments
*
* @return mixed
*/
public function __call($method, $arguments)
{
if ($className = Form::findFieldClass($method)) {
$column = Arr::get($arguments, 0, '');
/* @var Field $field */
$field = new $className($column, array_slice($arguments, 1));
if ($this->form instanceof WidgetForm) {
$field->setWidgetForm($this->form);
} else {
$field->setForm($this->form);
}
$field = $this->formatField($field);
$this->pushField($field);
return $field;
}
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Layout/Layout.php | src/Form/Layout/Layout.php | <?php
/**
* Copyright (c) 2019. Mallto.Co.Ltd.<mall-to.com> All rights reserved.
*/
namespace Encore\Admin\Form\Layout;
use Encore\Admin\Form;
use Illuminate\Support\Collection;
class Layout
{
/**
* @var Collection
*/
protected $columns;
/**
* @var Column
*/
protected $current;
/**
* @var Form
*/
protected $parent;
/**
* Layout constructor.
*
* @param Form $form
*/
public function __construct(Form $form)
{
$this->parent = $form;
$this->current = new Column();
$this->columns = new Collection();
}
/**
* Add a filter to layout column.
*
* @param Form\Field $field
*/
public function addField(Form\Field $field)
{
$this->current->add($field);
}
/**
* Add a new column in layout.
*
* @param int $width
* @param \Closure $closure
*/
public function column($width, \Closure $closure)
{
if ($this->columns->isEmpty()) {
$column = $this->current;
$column->setWidth($width);
} else {
$column = new Column($width);
$this->current = $column;
}
$this->columns->push($column);
$closure($this->parent);
}
/**
* Get all columns in filter layout.
*
* @return Collection
*/
public function columns()
{
if ($this->columns->isEmpty()) {
$this->columns->push($this->current);
}
return $this->columns;
}
/**
* Remove reserved fields from form layout.
*
* @param array $fields
*/
public function removeReservedFields(array $fields)
{
if (empty($fields)) {
return;
}
foreach ($this->columns() as &$column) {
$column->removeFields($fields);
}
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Layout/Column.php | src/Form/Layout/Column.php | <?php
/**
* Copyright (c) 2019. Mallto.Co.Ltd.<mall-to.com> All rights reserved.
*/
namespace Encore\Admin\Form\Layout;
use Encore\Admin\Form\Field;
use Illuminate\Support\Collection;
class Column
{
/**
* @var Collection
*/
protected $fields;
/**
* @var int
*/
protected $width;
/**
* Column constructor.
*
* @param int $width
*/
public function __construct($width = 12)
{
$this->width = $width;
$this->fields = new Collection();
}
/**
* Add a filter to this column.
*
* @param Field $field
*/
public function add(Field $field)
{
$this->fields->push($field);
}
/**
* Remove fields from column.
*
* @param $fields
*/
public function removeFields($fields)
{
$this->fields = $this->fields->reject(function (Field $field) use ($fields) {
return in_array($field->column(), $fields);
});
}
/**
* Get all filters in this column.
*
* @return Collection
*/
public function fields()
{
return $this->fields;
}
/**
* Set column width.
*
* @param int $width
*/
public function setWidth($width)
{
$this->width = $width;
}
/**
* Get column width.
*
* @return int
*/
public function width()
{
return $this->width;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Concerns/HasHooks.php | src/Form/Concerns/HasHooks.php | <?php
namespace Encore\Admin\Form\Concerns;
use Closure;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\Response;
trait HasHooks
{
/**
* Supported hooks: submitted, editing, saving, saved, deleting, deleted.
*
* @var array
*/
protected $hooks = [];
/**
* Initialization closure array.
*
* @var []Closure
*/
protected static $initCallbacks;
/**
* Initialize with user pre-defined default disables, etc.
*
* @param Closure $callback
*/
public static function init(Closure $callback = null)
{
static::$initCallbacks[] = $callback;
}
/**
* Call the initialization closure array in sequence.
*/
protected function callInitCallbacks()
{
if (empty(static::$initCallbacks)) {
return;
}
foreach (static::$initCallbacks as $callback) {
$callback($this);
}
}
/**
* Register a hook.
*
* @param string $name
* @param Closure $callback
*
* @return $this
*/
protected function registerHook($name, Closure $callback)
{
$this->hooks[$name][] = $callback;
return $this;
}
/**
* Call hooks by giving name.
*
* @param string $name
* @param array $parameters
*
* @return Response
*/
protected function callHooks($name, $parameters = [])
{
$hooks = Arr::get($this->hooks, $name, []);
foreach ($hooks as $func) {
if (!$func instanceof Closure) {
continue;
}
$response = call_user_func($func, $this, $parameters);
if ($response instanceof Response) {
return $response;
}
}
}
/**
* Set after getting editing model callback.
*
* @param Closure $callback
*
* @return $this
*/
public function editing(Closure $callback)
{
return $this->registerHook('editing', $callback);
}
/**
* Set submitted callback.
*
* @param Closure $callback
*
* @return $this
*/
public function submitted(Closure $callback)
{
return $this->registerHook('submitted', $callback);
}
/**
* Set saving callback.
*
* @param Closure $callback
*
* @return $this
*/
public function saving(Closure $callback)
{
return $this->registerHook('saving', $callback);
}
/**
* Set saved callback.
*
* @param Closure $callback
*
* @return $this
*/
public function saved(Closure $callback)
{
return $this->registerHook('saved', $callback);
}
/**
* @param Closure $callback
*
* @return $this
*/
public function deleting(Closure $callback)
{
return $this->registerHook('deleting', $callback);
}
/**
* @param Closure $callback
*
* @return $this
*/
public function deleted(Closure $callback)
{
return $this->registerHook('deleted', $callback);
}
/**
* Call editing callbacks.
*
* @return mixed
*/
protected function callEditing()
{
return $this->callHooks('editing');
}
/**
* Call submitted callback.
*
* @return mixed
*/
protected function callSubmitted()
{
return $this->callHooks('submitted');
}
/**
* Call saving callback.
*
* @return mixed
*/
protected function callSaving()
{
return $this->callHooks('saving');
}
/**
* Callback after saving a Model.
*
* @return mixed|null
*/
protected function callSaved()
{
return $this->callHooks('saved');
}
/**
* Call hooks when deleting.
*
* @param mixed $id
*
* @return mixed
*/
protected function callDeleting($id)
{
return $this->callHooks('deleting', $id);
}
/**
* @return mixed
*/
protected function callDeleted()
{
return $this->callHooks('deleted');
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Concerns/HandleCascadeFields.php | src/Form/Concerns/HandleCascadeFields.php | <?php
namespace Encore\Admin\Form\Concerns;
use Encore\Admin\Form\Field;
trait HandleCascadeFields
{
/**
* @param array $dependency
* @param \Closure $closure
*/
public function cascadeGroup(\Closure $closure, array $dependency)
{
$this->pushField($group = new Field\CascadeGroup($dependency));
call_user_func($closure, $this);
$group->end();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Concerns/HasFields.php | src/Form/Concerns/HasFields.php | <?php
namespace Encore\Admin\Form\Concerns;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
/**
* @method Field\Text text($column, $label = '')
* @method Field\Checkbox checkbox($column, $label = '')
* @method Field\CheckboxButton checkboxButton($column, $label = '')
* @method Field\CheckboxCard checkboxCard($column, $label = '')
* @method Field\Radio radio($column, $label = '')
* @method Field\RadioButton radioButton($column, $label = '')
* @method Field\RadioCard radioCard($column, $label = '')
* @method Field\Select select($column, $label = '')
* @method Field\MultipleSelect multipleSelect($column, $label = '')
* @method Field\Textarea textarea($column, $label = '')
* @method Field\Hidden hidden($column, $label = '')
* @method Field\Id id($column, $label = '')
* @method Field\Ip ip($column, $label = '')
* @method Field\Url url($column, $label = '')
* @method Field\Color color($column, $label = '')
* @method Field\Email email($column, $label = '')
* @method Field\Mobile mobile($column, $label = '')
* @method Field\Slider slider($column, $label = '')
* @method Field\File file($column, $label = '')
* @method Field\Image image($column, $label = '')
* @method Field\Date date($column, $label = '')
* @method Field\Datetime datetime($column, $label = '')
* @method Field\Time time($column, $label = '')
* @method Field\Year year($column, $label = '')
* @method Field\Month month($column, $label = '')
* @method Field\DateRange dateRange($start, $end, $label = '')
* @method Field\DateMultiple DateMultiple($column, $label = '')
* @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
* @method Field\TimeRange timeRange($start, $end, $label = '')
* @method Field\Number number($column, $label = '')
* @method Field\Currency currency($column, $label = '')
* @method Field\SwitchField switch($column, $label = '')
* @method Field\Display display($column, $label = '')
* @method Field\Rate rate($column, $label = '')
* @method Field\Divider divider($title = '')
* @method Field\Password password($column, $label = '')
* @method Field\Decimal decimal($column, $label = '')
* @method Field\Html html($html, $label = '')
* @method Field\Tags tags($column, $label = '')
* @method Field\Icon icon($column, $label = '')
* @method Field\Embeds embeds($column, $label = '', $callback)
* @method Field\MultipleImage multipleImage($column, $label = '')
* @method Field\MultipleFile multipleFile($column, $label = '')
* @method Field\Captcha captcha($column, $label = '')
* @method Field\Listbox listbox($column, $label = '')
* @method Field\Table table($column, $label, $builder)
* @method Field\Timezone timezone($column, $label = '')
* @method Field\KeyValue keyValue($column, $label = '')
* @method Field\ListField list($column, $label = '')
* @method Field\HasMany hasMany($relationName, $label = '', $callback)
* @method Field\HasMany morphMany($relationName, $label = '', $callback)
* @method Field\BelongsTo belongsTo($column, $selectable, $label = '')
* @method Field\BelongsToMany belongsToMany($column, $selectable, $label = '')
*/
trait HasFields
{
/**
* Available fields.
*
* @var array
*/
public static $availableFields = [
'button' => Field\Button::class,
'checkbox' => Field\Checkbox::class,
'checkboxButton' => Field\CheckboxButton::class,
'checkboxCard' => Field\CheckboxCard::class,
'color' => Field\Color::class,
'currency' => Field\Currency::class,
'date' => Field\Date::class,
'dateRange' => Field\DateRange::class,
'DateMultiple' => Field\DateMultiple::class,
'datetime' => Field\Datetime::class,
'dateTimeRange' => Field\DatetimeRange::class,
'datetimeRange' => Field\DatetimeRange::class,
'decimal' => Field\Decimal::class,
'display' => Field\Display::class,
'divider' => Field\Divider::class,
'embeds' => Field\Embeds::class,
'email' => Field\Email::class,
'file' => Field\File::class,
'hidden' => Field\Hidden::class,
'id' => Field\Id::class,
'image' => Field\Image::class,
'ip' => Field\Ip::class,
'mobile' => Field\Mobile::class,
'month' => Field\Month::class,
'multipleSelect' => Field\MultipleSelect::class,
'number' => Field\Number::class,
'password' => Field\Password::class,
'radio' => Field\Radio::class,
'radioButton' => Field\RadioButton::class,
'radioCard' => Field\RadioCard::class,
'rate' => Field\Rate::class,
'select' => Field\Select::class,
'slider' => Field\Slider::class,
'switch' => Field\SwitchField::class,
'text' => Field\Text::class,
'textarea' => Field\Textarea::class,
'time' => Field\Time::class,
'timeRange' => Field\TimeRange::class,
'url' => Field\Url::class,
'year' => Field\Year::class,
'html' => Field\Html::class,
'tags' => Field\Tags::class,
'icon' => Field\Icon::class,
'multipleFile' => Field\MultipleFile::class,
'multipleImage' => Field\MultipleImage::class,
'captcha' => Field\Captcha::class,
'listbox' => Field\Listbox::class,
'table' => Field\Table::class,
'timezone' => Field\Timezone::class,
'keyValue' => Field\KeyValue::class,
'list' => Field\ListField::class,
'hasMany' => Field\HasMany::class,
'morphMany' => Field\HasMany::class,
'belongsTo' => Field\BelongsTo::class,
'belongsToMany' => Field\BelongsToMany::class,
];
/**
* Form field alias.
*
* @var array
*/
public static $fieldAlias = [];
/**
* Register custom field.
*
* @param string $abstract
* @param string $class
*
* @return void
*/
public static function extend($abstract, $class)
{
static::$availableFields[$abstract] = $class;
}
/**
* Set form field alias.
*
* @param string $field
* @param string $alias
*
* @return void
*/
public static function alias($field, $alias)
{
static::$fieldAlias[$alias] = $field;
}
/**
* Remove registered field.
*
* @param array|string $abstract
*/
public static function forget($abstract)
{
Arr::forget(static::$availableFields, $abstract);
}
/**
* Find field class.
*
* @param string $method
*
* @return bool|mixed
*/
public static function findFieldClass($method)
{
// If alias exists.
if (isset(static::$fieldAlias[$method])) {
$method = static::$fieldAlias[$method];
}
$class = Arr::get(static::$availableFields, $method);
if (class_exists($class)) {
return $class;
}
return false;
}
/**
* Collect assets required by registered field.
*
* @return array
*/
public static function collectFieldAssets(): array
{
if (!empty(static::$collectedAssets)) {
return static::$collectedAssets;
}
$css = collect();
$js = collect();
foreach (static::$availableFields as $field) {
if (!method_exists($field, 'getAssets')) {
continue;
}
$assets = call_user_func([$field, 'getAssets']);
$css->push(Arr::get($assets, 'css'));
$js->push(Arr::get($assets, 'js'));
}
return static::$collectedAssets = [
'css' => $css->flatten()->unique()->filter()->toArray(),
'js' => $js->flatten()->unique()->filter()->toArray(),
];
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Number.php | src/Form/Field/Number.php | <?php
namespace Encore\Admin\Form\Field;
class Number extends Text
{
protected static $js = [
'/vendor/laravel-admin/number-input/bootstrap-number-input.js',
];
public function render()
{
$this->default($this->default);
$this->script = <<<EOT
$('{$this->getElementClassSelector()}:not(.initialized)')
.addClass('initialized')
.bootstrapNumber({
upClass: 'success',
downClass: 'primary',
center: true
});
EOT;
$this->prepend('')->defaultAttribute('style', 'width: 100px');
return parent::render();
}
/**
* Set min value of number field.
*
* @param int $value
*
* @return $this
*/
public function min($value)
{
$this->attribute('min', $value);
return $this;
}
/**
* Set max value of number field.
*
* @param int $value
*
* @return $this
*/
public function max($value)
{
$this->attribute('max', $value);
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/MultipleSelect.php | src/Form/Field/MultipleSelect.php | <?php
namespace Encore\Admin\Form\Field;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany as HasManyRelation;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class MultipleSelect extends Select
{
/**
* Other key for many-to-many relation.
*
* @var string
*/
protected $otherKey;
/**
* Get other key for this many-to-many relation.
*
* @throws \Exception
*
* @return string
*/
protected function getOtherKey()
{
if ($this->otherKey) {
return $this->otherKey;
}
if (is_callable([$this->form->model(), $this->column])) {
$relation = $this->form->model()->{$this->column}();
if ($relation instanceof BelongsToMany) {
/* @var BelongsToMany $relation */
$fullKey = $relation->getQualifiedRelatedPivotKeyName();
$fullKeyArray = explode('.', $fullKey);
return $this->otherKey = 'pivot.'.end($fullKeyArray);
} elseif ($relation instanceof HasManyRelation) {
/* @var HasManyRelation $relation */
return $this->otherKey = $relation->getRelated()->getKeyName();
}
}
throw new \Exception('Column of this field must be a `BelongsToMany` or `HasMany` relation.');
}
/**
* {@inheritdoc}
*/
public function fill($data)
{
if ($this->form && $this->form->shouldSnakeAttributes()) {
$key = Str::snake($this->column);
} else {
$key = $this->column;
}
$relations = Arr::get($data, $key);
if (is_string($relations)) {
$this->value = explode(',', $relations);
}
if (!is_array($relations)) {
$this->applyCascadeConditions();
return;
}
$first = current($relations);
if (is_null($first)) {
$this->value = null;
// MultipleSelect value store as an ont-to-many relationship.
} elseif (is_array($first)) {
foreach ($relations as $relation) {
$this->value[] = Arr::get($relation, $this->getOtherKey());
}
// MultipleSelect value store as a column.
} else {
$this->value = $relations;
}
$this->applyCascadeConditions();
}
/**
* {@inheritdoc}
*/
public function setOriginal($data)
{
$relations = Arr::get($data, $this->column);
if (is_string($relations)) {
$this->original = explode(',', $relations);
}
if (!is_array($relations)) {
return;
}
$first = current($relations);
if (is_null($first)) {
$this->original = null;
// MultipleSelect value store as an ont-to-many relationship.
} elseif (is_array($first)) {
foreach ($relations as $relation) {
$this->original[] = Arr::get($relation, $this->getOtherKey());
}
// MultipleSelect value store as a column.
} else {
$this->original = $relations;
}
}
public function prepare($value)
{
$value = (array) $value;
return array_filter($value, 'strlen');
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Display.php | src/Form/Field/Display.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Display extends Field
{
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Decimal.php | src/Form/Field/Decimal.php | <?php
namespace Encore\Admin\Form\Field;
class Decimal extends Text
{
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/input-mask/jquery.inputmask.bundle.min.js',
];
/**
* @see https://github.com/RobinHerbots/Inputmask#options
*
* @var array
*/
protected $options = [
'alias' => 'decimal',
'rightAlign' => true,
];
public function render()
{
$this->inputmask($this->options);
$this->prepend('<i class="fa '.$this->icon.' fa-fw"></i>')
->defaultAttribute('style', 'width: 130px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/SwitchField.php | src/Form/Field/SwitchField.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
class SwitchField extends Field
{
protected static $css = [
'/vendor/laravel-admin/bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.min.css',
];
protected static $js = [
'/vendor/laravel-admin/bootstrap-switch/dist/js/bootstrap-switch.min.js',
];
protected $states = [
'on' => ['value' => 1, 'text' => 'ON', 'color' => 'primary'],
'off' => ['value' => 0, 'text' => 'OFF', 'color' => 'default'],
];
protected $size = 'small';
public function setSize($size)
{
$this->size = $size;
return $this;
}
public function states($states = [])
{
foreach (Arr::dot($states) as $key => $state) {
Arr::set($this->states, $key, $state);
}
return $this;
}
public function prepare($value)
{
if (isset($this->states[$value])) {
return $this->states[$value]['value'];
}
return $value;
}
public function render()
{
if (!$this->shouldRender()) {
return '';
}
foreach ($this->states as $state => $option) {
if ($this->value() == $option['value']) {
$this->value = $state;
break;
}
}
$this->script = <<<EOT
$('{$this->getElementClassSelector()}.la_checkbox').bootstrapSwitch({
size:'{$this->size}',
onText: '{$this->states['on']['text']}',
offText: '{$this->states['off']['text']}',
onColor: '{$this->states['on']['color']}',
offColor: '{$this->states['off']['color']}',
onSwitchChange: function(event, state) {
$(event.target).closest('.bootstrap-switch').next().val(state ? 'on' : 'off').change();
}
});
EOT;
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Icon.php | src/Form/Field/Icon.php | <?php
namespace Encore\Admin\Form\Field;
class Icon extends Text
{
protected $default = 'fa-pencil';
protected static $css = [
'/vendor/laravel-admin/fontawesome-iconpicker/dist/css/fontawesome-iconpicker.min.css',
];
protected static $js = [
'/vendor/laravel-admin/fontawesome-iconpicker/dist/js/fontawesome-iconpicker.min.js',
];
public function render()
{
$this->script = <<<EOT
$('{$this->getElementClassSelector()}').iconpicker({placement:'bottomLeft'});
EOT;
$this->prepend('<i class="fa fa-pencil fa-fw"></i>')
->defaultAttribute('style', 'width: 140px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Radio.php | src/Form/Field/Radio.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
use Illuminate\Contracts\Support\Arrayable;
class Radio extends Field
{
use CanCascadeFields;
protected $inline = true;
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/iCheck/all.css',
];
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/iCheck/icheck.min.js',
];
/**
* @var string
*/
protected $cascadeEvent = 'ifChecked';
/**
* Set options.
*
* @param array|callable|string $options
*
* @return $this
*/
public function options($options = [])
{
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
$this->options = (array) $options;
return $this;
}
/**
* Set checked.
*
* @param array|callable|string $checked
*
* @return $this
*/
public function checked($checked = [])
{
if ($checked instanceof Arrayable) {
$checked = $checked->toArray();
}
// input radio checked should be unique
$this->checked = is_array($checked) ? (array) end($checked) : (array) $checked;
return $this;
}
/**
* Draw inline radios.
*
* @return $this
*/
public function inline()
{
$this->inline = true;
return $this;
}
/**
* Draw stacked radios.
*
* @return $this
*/
public function stacked()
{
$this->inline = false;
return $this;
}
/**
* Set options.
*
* @param array|callable|string $values
*
* @return $this
*/
public function values($values)
{
return $this->options($values);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->script = "$('{$this->getElementClassSelector()}').iCheck({radioClass:'iradio_minimal-blue'});";
$this->addCascadeScript();
$this->addVariables(['options' => $this->options, 'checked' => $this->checked, 'inline' => $this->inline]);
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Month.php | src/Form/Field/Month.php | <?php
namespace Encore\Admin\Form\Field;
class Month extends Date
{
protected $format = 'MM';
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Tags.php | src/Form/Field/Tags.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
class Tags extends Field
{
/**
* @var array
*/
protected $value = [];
/**
* @var bool
*/
protected $keyAsValue = false;
/**
* @var string
*/
protected $visibleColumn = null;
/**
* @var string
*/
protected $key = null;
/**
* @var \Closure
*/
protected $saveAction = null;
/**
* @var array
*/
protected $separators = [',', ';', ',', ';', ' '];
/**
* @var array
*/
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/select2/select2.min.css',
];
/**
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/select2/select2.full.min.js',
];
/**
* {@inheritdoc}
*/
public function fill($data)
{
$this->value = Arr::get($data, $this->column);
if (is_array($this->value) && $this->keyAsValue) {
$this->value = array_column($this->value, $this->visibleColumn, $this->key);
}
if (is_string($this->value)) {
$this->value = explode(',', $this->value);
}
$this->value = array_filter((array) $this->value, 'strlen');
}
/**
* Set visible column and key of data.
*
* @param $visibleColumn
* @param $key
*
* @return $this
*/
public function pluck($visibleColumn, $key)
{
if (!empty($visibleColumn) && !empty($key)) {
$this->keyAsValue = true;
}
$this->visibleColumn = $visibleColumn;
$this->key = $key;
return $this;
}
/**
* Set the field options.
*
* @param array|Collection|Arrayable $options
*
* @return $this|Field
*/
public function options($options = [])
{
if (!$this->keyAsValue) {
return parent::options($options);
}
if ($options instanceof Collection) {
$options = $options->pluck($this->visibleColumn, $this->key)->toArray();
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
$this->options = $options + $this->options;
return $this;
}
/**
* Set Tag Separators.
*
* @param array $separators
*
* @return $this
*/
public function separators($separators = [])
{
if ($separators instanceof Collection or $separators instanceof Arrayable) {
$separators = $separators->toArray();
}
if (!empty($separators)) {
$this->separators = $separators;
}
return $this;
}
/**
* Set save Action.
*
* @param \Closure $saveAction
*
* @return $this
*/
public function saving(\Closure $saveAction)
{
$this->saveAction = $saveAction;
return $this;
}
/**
* {@inheritdoc}
*/
public function prepare($value)
{
$value = array_filter($value, 'strlen');
if ($this->keyAsValue) {
return is_null($this->saveAction) ? $value : ($this->saveAction)($value);
}
if (is_array($value) && !Arr::isAssoc($value)) {
$value = implode(',', $value);
}
return $value;
}
/**
* Get or set value for this field.
*
* @param mixed $value
*
* @return $this|array|mixed
*/
public function value($value = null)
{
if (is_null($value)) {
return empty($this->value) ? ($this->getDefault() ?? []) : $this->value;
}
$this->value = (array) $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function render()
{
if (!$this->shouldRender()) {
return '';
}
$this->setupScript();
if ($this->keyAsValue) {
$options = $this->value + $this->options;
} else {
$options = array_unique(array_merge($this->value, $this->options));
}
return parent::fieldRender([
'options' => $options,
'keyAsValue' => $this->keyAsValue,
]);
}
protected function setupScript()
{
$separators = json_encode($this->separators);
$separatorsStr = implode('', $this->separators);
$this->script = <<<JS
$("{$this->getElementClassSelector()}").select2({
tags: true,
tokenSeparators: $separators,
createTag: function(params) {
if (/[$separatorsStr]/.test(params.term)) {
var str = params.term.trim().replace(/[$separatorsStr]*$/, '');
return { id: str, text: str }
} else {
return null;
}
}
});
JS;
Admin::script(
<<<'JS'
$(document).off('keyup', '.select2-selection--multiple .select2-search__field').on('keyup', '.select2-selection--multiple .select2-search__field', function (event) {
try {
if (event.keyCode == 13) {
var $this = $(this), optionText = $this.val();
if (optionText != "" && $this.find("option[value='" + optionText + "']").length === 0) {
var $select = $this.parents('.select2-container').prev("select");
var newOption = new Option(optionText, optionText, true, true);
$select.append(newOption).trigger('change');
$this.val('');
$select.select2('close');
}
}
} catch (e) {
console.error(e);
}
});
JS
);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Checkbox.php | src/Form/Field/Checkbox.php | <?php
namespace Encore\Admin\Form\Field;
use Illuminate\Contracts\Support\Arrayable;
class Checkbox extends MultipleSelect
{
protected $inline = true;
protected $canCheckAll = false;
protected $groups = null;
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/iCheck/all.css',
];
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/iCheck/icheck.min.js',
];
/**
* @var string
*/
protected $cascadeEvent = 'ifChanged';
/**
* Set options.
*
* @param array|callable|string $options
*
* @return $this|mixed
*/
public function options($options = [])
{
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
if (is_callable($options)) {
$this->options = $options;
} else {
$this->options = (array) $options;
}
return $this;
}
/**
* Add a checkbox above this component, so you can select all checkboxes by click on it.
*
* @return $this
*/
public function canCheckAll()
{
$this->canCheckAll = true;
return $this;
}
/**
* Set chekbox groups.
*
* @param array
*
* @return $this
*/
public function groups(array $groups = [])
{
$this->groups = $groups;
return $this;
}
/**
* Set checked.
*
* @param array|callable|string $checked
*
* @return $this
*/
public function checked($checked = [])
{
if ($checked instanceof Arrayable) {
$checked = $checked->toArray();
}
$this->checked = (array) $checked;
return $this;
}
/**
* Draw inline checkboxes.
*
* @return $this
*/
public function inline()
{
$this->inline = true;
return $this;
}
/**
* Draw stacked checkboxes.
*
* @return $this
*/
public function stacked()
{
$this->inline = false;
return $this;
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->script = "$('{$this->getElementClassSelector()}').iCheck({checkboxClass:'icheckbox_minimal-blue'});";
$this->addVariables([
'checked' => $this->checked,
'inline' => $this->inline,
'canCheckAll' => $this->canCheckAll,
'groups' => $this->groups,
]);
if ($this->canCheckAll) {
$checkAllClass = uniqid('check-all-');
$this->script .= <<<SCRIPT
$('.{$checkAllClass}').iCheck({checkboxClass:'icheckbox_minimal-blue'}).on('ifChanged', function () {
if (this.checked) {
$('{$this->getElementClassSelector()}').iCheck('check');
} else {
$('{$this->getElementClassSelector()}').iCheck('uncheck');
}
});
SCRIPT;
$this->addVariables(['checkAllClass' => $checkAllClass]);
}
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Mobile.php | src/Form/Field/Mobile.php | <?php
namespace Encore\Admin\Form\Field;
class Mobile extends Text
{
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/input-mask/jquery.inputmask.bundle.min.js',
];
/**
* @see https://github.com/RobinHerbots/Inputmask#options
*
* @var array
*/
protected $options = [
'mask' => '99999999999',
];
public function render()
{
$this->inputmask($this->options);
$this->prepend('<i class="fa fa-phone fa-fw"></i>')
->defaultAttribute('style', 'width: 150px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Table.php | src/Form/Field/Table.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Widgets\Form as WidgetForm;
class Table extends HasMany
{
/**
* @var string
*/
protected $viewMode = 'table';
/**
* Table constructor.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->column = $column;
if (count($arguments) == 1) {
$this->label = $this->formatLabel();
$this->builder = $arguments[0];
}
if (count($arguments) == 2) {
list($this->label, $this->builder) = $arguments;
}
}
/**
* @return array
*/
protected function buildRelatedForms()
{
// if (is_null($this->form)) {
// return [];
// }
$forms = [];
if ($values = old($this->column)) {
foreach ($values as $key => $data) {
if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
continue;
}
$forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)->fill($data);
}
} else {
foreach ($this->value ?? [] as $key => $data) {
if (isset($data['pivot'])) {
$data = array_merge($data, $data['pivot']);
}
if (is_array($data)) {
$forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)->fill($data);
}
}
}
return $forms;
}
public function prepare($input)
{
$form = $this->buildNestedForm($this->column, $this->builder);
$prepare = $form->prepare($input);
return collect($prepare)->reject(function ($item) {
return $item[NestedForm::REMOVE_FLAG_NAME] == 1;
})->map(function ($item) {
unset($item[NestedForm::REMOVE_FLAG_NAME]);
return $item;
})->toArray();
}
protected function getKeyName()
{
if (is_null($this->form)) {
return;
}
return 'id';
}
protected function buildNestedForm($column, \Closure $builder, $key = null)
{
$form = new NestedForm($column);
if ($this->form instanceof WidgetForm) {
$form->setWidgetForm($this->form);
} else {
$form->setForm($this->form);
}
$form->setKey($key);
call_user_func($builder, $form);
$form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
return $form;
}
public function render()
{
return $this->renderTable();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/RadioButton.php | src/Form/Field/RadioButton.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class RadioButton extends Radio
{
/**
* @var string
*/
protected $cascadeEvent = 'change';
protected function addScript()
{
$script = <<<'SCRIPT'
$('.radio-group-toggle label').click(function() {
$(this).parent().children().removeClass('active');
$(this).addClass('active');
});
SCRIPT;
Admin::script($script);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->addScript();
$this->addCascadeScript();
$this->addVariables([
'options' => $this->options,
'checked' => $this->checked,
]);
return parent::fieldRender();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Text.php | src/Form/Field/Text.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Text extends Field
{
use PlainInput;
use HasValuePicker;
/**
* @var string
*/
protected $icon = 'fa-pencil';
/**
* @var bool
*/
protected $withoutIcon = false;
/**
* Set custom fa-icon.
*
* @param string $icon
*
* @return $this
*/
public function icon($icon)
{
$this->icon = $icon;
return $this;
}
/**
* Render this filed.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$this->initPlainInput();
if (!$this->withoutIcon) {
$this->prepend('<i class="fa '.$this->icon.' fa-fw"></i>');
}
$this->defaultAttribute('type', 'text')
->defaultAttribute('id', $this->id)
->defaultAttribute('name', $this->elementName ?: $this->formatName($this->column))
->defaultAttribute('value', old($this->elementName ?: $this->column, $this->value()))
->defaultAttribute('class', 'form-control '.$this->getElementClassString())
->defaultAttribute('placeholder', $this->getPlaceholder())
->mountPicker()
->addVariables([
'prepend' => $this->prepend,
'append' => $this->append,
]);
return parent::render();
}
/**
* Add inputmask to an elements.
*
* @param array $options
*
* @return $this
*/
public function inputmask($options)
{
$options = json_encode_options($options);
$this->script = "$('{$this->getElementClassSelector()}').inputmask($options);";
return $this;
}
/**
* Add datalist element to Text input.
*
* @param array $entries
*
* @return $this
*/
public function datalist($entries = [])
{
$this->defaultAttribute('list', "list-{$this->id}");
$datalist = "<datalist id=\"list-{$this->id}\">";
foreach ($entries as $k => $v) {
$datalist .= "<option value=\"{$k}\">{$v}</option>";
}
$datalist .= '</datalist>';
return $this->append($datalist);
}
/**
* show no icon in font of input.
*
* @return $this
*/
public function withoutIcon()
{
$this->withoutIcon = true;
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Datetime.php | src/Form/Field/Datetime.php | <?php
namespace Encore\Admin\Form\Field;
class Datetime extends Date
{
protected $format = 'YYYY-MM-DD HH:mm:ss';
public function render()
{
$this->defaultAttribute('style', 'width: 160px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Date.php | src/Form/Field/Date.php | <?php
namespace Encore\Admin\Form\Field;
class Date extends Text
{
protected static $css = [
'/vendor/laravel-admin/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css',
];
protected static $js = [
'/vendor/laravel-admin/moment/min/moment-with-locales.min.js',
'/vendor/laravel-admin/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
];
protected $format = 'YYYY-MM-DD';
public function format($format)
{
$this->format = $format;
return $this;
}
public function prepare($value)
{
if ($value === '') {
$value = null;
}
return $value;
}
public function render()
{
$this->options['format'] = $this->format;
$this->options['locale'] = array_key_exists('locale', $this->options) ? $this->options['locale'] : config('app.locale');
$this->options['allowInputToggle'] = true;
$this->script = "$('{$this->getElementClassSelector()}').parent().datetimepicker(".json_encode($this->options).');';
$this->prepend('<i class="fa fa-calendar fa-fw"></i>')
->defaultAttribute('style', 'width: 110px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Editor.php | src/Form/Field/Editor.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Editor extends Field
{
protected static $js = [
'//cdn.ckeditor.com/4.5.10/standard/ckeditor.js',
];
public function render()
{
$this->script = "CKEDITOR.replace('{$this->id}');";
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Textarea.php | src/Form/Field/Textarea.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
class Textarea extends Field
{
use HasValuePicker;
/**
* Default rows of textarea.
*
* @var int
*/
protected $rows = 5;
/**
* @var string
*/
protected $append = '';
/**
* Set rows of textarea.
*
* @param int $rows
*
* @return $this
*/
public function rows($rows = 5)
{
$this->rows = $rows;
return $this;
}
/**
* {@inheritdoc}
*/
public function render()
{
if (!$this->shouldRender()) {
return '';
}
if (is_array($this->value)) {
$this->value = json_encode($this->value, JSON_PRETTY_PRINT);
}
$this->mountPicker(function ($btn) {
$this->addPickBtn($btn);
});
return parent::fieldRender([
'append' => $this->append,
'rows' => $this->rows,
]);
}
/**
* @param string $wrap
*/
protected function addPickBtn($btn)
{
$style = <<<'STYLE'
.textarea-picker {
padding: 5px;
border-bottom: 1px solid #d2d6de;
border-left: 1px solid #d2d6de;
border-right: 1px solid #d2d6de;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-color: #f1f2f3;
}
.textarea-picker .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
}
STYLE;
Admin::style($style);
$this->append = <<<HTML
<div class="text-right textarea-picker">
{$btn}
</div>
HTML;
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/UploadField.php | src/Form/Field/UploadField.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\File\UploadedFile;
trait UploadField
{
/**
* Upload directory.
*
* @var string
*/
protected $directory = '';
/**
* File name.
*
* @var null
*/
protected $name = null;
/**
* Storage instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $storage = '';
/**
* If use unique name to store upload file.
*
* @var bool
*/
protected $useUniqueName = false;
/**
* If use sequence name to store upload file.
*
* @var bool
*/
protected $useSequenceName = false;
/**
* Retain file when delete record from DB.
*
* @var bool
*/
protected $retainable = false;
/**
* @var bool
*/
protected $downloadable = true;
/**
* Configuration for setting up file actions for newly selected file thumbnails in the preview window.
*
* @var array
*/
protected $fileActionSettings = [
'showRemove' => false,
'showDrag' => false,
];
/**
* Controls the storage permission. Could be 'private' or 'public'.
*
* @var string
*/
protected $storagePermission;
/**
* @var array
*/
protected $fileTypes = [
'image' => '/^(gif|png|jpe?g|svg|webp)$/i',
'html' => '/^(htm|html)$/i',
'office' => '/^(docx?|xlsx?|pptx?|pps|potx?)$/i',
'gdocs' => '/^(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i',
'text' => '/^(txt|md|csv|nfo|ini|json|php|js|css|ts|sql)$/i',
'video' => '/^(og?|mp4|webm|mp?g|mov|3gp)$/i',
'audio' => '/^(og?|mp3|mp?g|wav)$/i',
'pdf' => '/^(pdf)$/i',
'flash' => '/^(swf)$/i',
];
/**
* @var string
*/
protected $pathColumn;
/**
* Initialize the storage instance.
*
* @return void.
*/
protected function initStorage()
{
$this->disk(config('admin.upload.disk'));
}
/**
* Set default options form image field.
*
* @return void
*/
protected function setupDefaultOptions()
{
$defaults = [
'overwriteInitial' => false,
'initialPreviewAsData' => true,
'msgPlaceholder' => trans('admin.choose_file'),
'browseLabel' => trans('admin.browse'),
'cancelLabel' => trans('admin.cancel'),
'showRemove' => false,
'showUpload' => false,
'showCancel' => false,
'dropZoneEnabled' => false,
'deleteExtraData' => [
$this->formatName($this->column) => static::FILE_DELETE_FLAG,
static::FILE_DELETE_FLAG => '',
'_token' => csrf_token(),
'_method' => 'PUT',
],
];
if ($this->form instanceof Form) {
$defaults['deleteUrl'] = $this->form->resource().'/'.$this->form->model()->getKey();
}
$defaults = array_merge($defaults, ['fileActionSettings' => $this->fileActionSettings]);
$this->options($defaults);
}
/**
* Set preview options form image field.
*
* @return void
*/
protected function setupPreviewOptions()
{
$initialPreviewConfig = $this->initialPreviewConfig();
$this->options(compact('initialPreviewConfig'));
}
/**
* @return array|bool
*/
protected function guessPreviewType($file)
{
$filetype = 'other';
$ext = strtok(strtolower(pathinfo($file, PATHINFO_EXTENSION)), '?');
foreach ($this->fileTypes as $type => $pattern) {
if (preg_match($pattern, $ext) === 1) {
$filetype = $type;
break;
}
}
$extra = ['type' => $filetype];
if ($filetype == 'video') {
$extra['filetype'] = "video/{$ext}";
}
if ($filetype == 'audio') {
$extra['filetype'] = "audio/{$ext}";
}
if ($this->downloadable) {
$extra['downloadUrl'] = $this->objectUrl($file);
}
return $extra;
}
/**
* Indicates if the underlying field is downloadable.
*
* @param bool $downloadable
*
* @return $this
*/
public function downloadable($downloadable = true)
{
$this->downloadable = $downloadable;
return $this;
}
/**
* Allow use to remove file.
*
* @return $this
*/
public function removable()
{
$this->fileActionSettings['showRemove'] = true;
return $this;
}
/**
* Indicates if the underlying field is retainable.
*
* @return $this
*/
public function retainable($retainable = true)
{
$this->retainable = $retainable;
return $this;
}
/**
* Set options for file-upload plugin.
*
* @param array $options
*
* @return $this
*/
public function options($options = [])
{
$this->options = array_merge($options, $this->options);
return $this;
}
/**
* Set disk for storage.
*
* @param string $disk Disks defined in `config/filesystems.php`.
*
* @throws \Exception
*
* @return $this
*/
public function disk($disk)
{
try {
$this->storage = Storage::disk($disk);
} catch (\Exception $exception) {
if (!array_key_exists($disk, config('filesystems.disks'))) {
admin_error(
'Config error.',
"Disk [$disk] not configured, please add a disk config in `config/filesystems.php`."
);
return $this;
}
throw $exception;
}
return $this;
}
/**
* Specify the directory and name for upload file.
*
* @param string $directory
* @param null|string $name
*
* @return $this
*/
public function move($directory, $name = null)
{
$this->dir($directory);
$this->name($name);
return $this;
}
/**
* Specify the directory upload file.
*
* @param string $dir
*
* @return $this
*/
public function dir($dir)
{
if ($dir) {
$this->directory = $dir;
}
return $this;
}
/**
* Set name of store name.
*
* @param string|callable $name
*
* @return $this
*/
public function name($name)
{
if ($name) {
$this->name = $name;
}
return $this;
}
/**
* Use unique name for store upload file.
*
* @return $this
*/
public function uniqueName()
{
$this->useUniqueName = true;
return $this;
}
/**
* Use sequence name for store upload file.
*
* @return $this
*/
public function sequenceName()
{
$this->useSequenceName = true;
return $this;
}
/**
* Get store name of upload file.
*
* @param UploadedFile $file
*
* @return string
*/
protected function getStoreName(UploadedFile $file)
{
if ($this->useUniqueName) {
return $this->generateUniqueName($file);
}
if ($this->useSequenceName) {
return $this->generateSequenceName($file);
}
if ($this->name instanceof \Closure) {
return $this->name->call($this, $file);
}
if (is_string($this->name)) {
return $this->name;
}
return $file->getClientOriginalName();
}
/**
* Get directory for store file.
*
* @return mixed|string
*/
public function getDirectory()
{
if ($this->directory instanceof \Closure) {
return call_user_func($this->directory, $this->form);
}
return $this->directory ?: $this->defaultDirectory();
}
/**
* Set path column in has-many related model.
*
* @param string $column
*
* @return $this
*/
public function pathColumn($column = 'path')
{
$this->pathColumn = $column;
return $this;
}
/**
* Upload file and delete original file.
*
* @param UploadedFile $file
*
* @return mixed
*/
protected function upload(UploadedFile $file)
{
$this->renameIfExists($file);
if (!is_null($this->storagePermission)) {
return $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
}
return $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
}
/**
* If name already exists, rename it.
*
* @param $file
*
* @return void
*/
public function renameIfExists(UploadedFile $file)
{
if ($this->storage->exists("{$this->getDirectory()}/$this->name")) {
$this->name = $this->generateUniqueName($file);
}
}
/**
* Get file visit url.
*
* @param $path
*
* @return string
*/
public function objectUrl($path)
{
if ($this->pathColumn && is_array($path)) {
$path = Arr::get($path, $this->pathColumn);
}
if (URL::isValidUrl($path)) {
return $path;
}
if ($this->storage) {
return $this->storage->url($path);
}
return Storage::disk(config('admin.upload.disk'))->url($path);
}
/**
* Generate a unique name for uploaded file.
*
* @param UploadedFile $file
*
* @return string
*/
protected function generateUniqueName(UploadedFile $file)
{
return md5(uniqid()).'.'.$file->getClientOriginalExtension();
}
/**
* Generate a sequence name for uploaded file.
*
* @param UploadedFile $file
*
* @return string
*/
protected function generateSequenceName(UploadedFile $file)
{
$index = 1;
$extension = $file->getClientOriginalExtension();
$original = $file->getClientOriginalName();
$new = sprintf('%s_%s.%s', $original, $index, $extension);
while ($this->storage->exists("{$this->getDirectory()}/$new")) {
$index++;
$new = sprintf('%s_%s.%s', $original, $index, $extension);
}
return $new;
}
/**
* Destroy original files.
*
* @return void.
*/
public function destroy()
{
if ($this->retainable) {
return;
}
if (method_exists($this, 'destroyThumbnail')) {
$this->destroyThumbnail();
}
if (!empty($this->original) && $this->storage->exists($this->original)) {
$this->storage->delete($this->original);
}
}
/**
* Set file permission when stored into storage.
*
* @param string $permission
*
* @return $this
*/
public function storagePermission($permission)
{
$this->storagePermission = $permission;
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/CheckboxButton.php | src/Form/Field/CheckboxButton.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class CheckboxButton extends Checkbox
{
/**
* @var string
*/
protected $cascadeEvent = 'change';
protected function addScript()
{
$script = <<<'SCRIPT'
$('.checkbox-group-toggle label').click(function(e) {
e.stopPropagation();
e.preventDefault();
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).find('input').prop('checked', false);
} else {
$(this).addClass('active');
$(this).find('input').prop('checked', true);
}
$(this).find('input').trigger('change');
});
SCRIPT;
Admin::script($script);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->addScript();
$this->addCascadeScript();
$this->addVariables([
'options' => $this->options,
'checked' => $this->checked,
]);
return parent::fieldRender();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Time.php | src/Form/Field/Time.php | <?php
namespace Encore\Admin\Form\Field;
class Time extends Date
{
protected $format = 'HH:mm:ss';
public function render()
{
$this->prepend('<i class="fa fa-clock-o fa-fw"></i>')
->defaultAttribute('style', 'width: 150px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Ip.php | src/Form/Field/Ip.php | <?php
namespace Encore\Admin\Form\Field;
class Ip extends Text
{
protected $rules = 'nullable|ip';
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/input-mask/jquery.inputmask.bundle.min.js',
];
/**
* @see https://github.com/RobinHerbots/Inputmask#options
*
* @var array
*/
protected $options = [
'alias' => 'ip',
];
public function render()
{
$this->inputmask($this->options);
$this->prepend('<i class="fa fa-laptop fa-fw"></i>')
->defaultAttribute('style', 'width: 130px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Captcha.php | src/Form/Field/Captcha.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form;
class Captcha extends Text
{
protected $rules = 'required|captcha';
protected $view = 'admin::form.captcha';
public function __construct($column, $arguments = [])
{
if (!class_exists(\Mews\Captcha\Captcha::class)) {
throw new \Exception('To use captcha field, please install [mews/captcha] first.');
}
$this->column = '__captcha__';
$this->label = trans('admin.captcha');
}
public function setForm(Form $form = null)
{
$this->form = $form;
$this->form->ignore($this->column);
return $this;
}
public function render()
{
$this->script = <<<EOT
$('#{$this->column}-captcha').click(function () {
$(this).attr('src', $(this).attr('src')+'?'+Math.random());
});
EOT;
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Image.php | src/Form/Field/Image.php | <?php
namespace Encore\Admin\Form\Field;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Image extends File
{
use ImageField;
/**
* {@inheritdoc}
*/
protected $view = 'admin::form.file';
/**
* Validation rules.
*
* @var string
*/
protected $rules = 'image';
/**
* @param array|UploadedFile $image
*
* @return string
*/
public function prepare($image)
{
if ($this->picker) {
return parent::prepare($image);
}
if (request()->has(static::FILE_DELETE_FLAG)) {
return $this->destroy();
}
$this->name = $this->getStoreName($image);
$this->callInterventionMethods($image->getRealPath());
$path = $this->uploadAndDeleteOriginal($image);
$this->uploadAndDeleteOriginalThumbnail($image);
return $path;
}
/**
* force file type to image.
*
* @param $file
*
* @return array|bool|int[]|string[]
*/
public function guessPreviewType($file)
{
$extra = parent::guessPreviewType($file);
$extra['type'] = 'image';
return $extra;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Hidden.php | src/Form/Field/Hidden.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Hidden extends Field
{
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/DatetimeRange.php | src/Form/Field/DatetimeRange.php | <?php
namespace Encore\Admin\Form\Field;
class DatetimeRange extends DateRange
{
protected $format = 'YYYY-MM-DD HH:mm:ss';
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/PlainInput.php | src/Form/Field/PlainInput.php | <?php
namespace Encore\Admin\Form\Field;
trait PlainInput
{
/**
* @var string
*/
protected $prepend;
/**
* @var string
*/
protected $append;
/**
* @param mixed $string
*
* @return $this
*/
public function prepend($string)
{
if (is_null($this->prepend)) {
$this->prepend = $string;
}
return $this;
}
/**
* @param mixed $string
*
* @return $this
*/
public function append($string)
{
if (is_null($this->append)) {
$this->append = $string;
}
return $this;
}
/**
* @return void
*/
protected function initPlainInput()
{
if (empty($this->view)) {
$this->view = 'admin::form.input';
}
}
/**
* @param string $attribute
* @param string $value
*
* @return $this
*/
protected function defaultAttribute($attribute, $value)
{
if (!array_key_exists($attribute, $this->attributes)) {
$this->attribute($attribute, $value);
}
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Currency.php | src/Form/Field/Currency.php | <?php
namespace Encore\Admin\Form\Field;
class Currency extends Text
{
/**
* @var string
*/
protected $symbol = '$';
/**
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/input-mask/jquery.inputmask.bundle.min.js',
];
/**
* @see https://github.com/RobinHerbots/Inputmask#options
*
* @var array
*/
protected $options = [
'alias' => 'currency',
'radixPoint' => '.',
'prefix' => '',
'removeMaskOnSubmit' => true,
];
/**
* Set symbol for currency field.
*
* @param string $symbol
*
* @return $this
*/
public function symbol($symbol)
{
$this->symbol = $symbol;
return $this;
}
/**
* Set digits for input number.
*
* @param int $digits
*
* @return $this
*/
public function digits($digits)
{
return $this->options(compact('digits'));
}
/**
* {@inheritdoc}
*/
public function prepare($value)
{
return (float) $value;
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->inputmask($this->options);
$this->prepend($this->symbol)
->defaultAttribute('style', 'width: 120px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Password.php | src/Form/Field/Password.php | <?php
namespace Encore\Admin\Form\Field;
class Password extends Text
{
public function render()
{
$this->prepend('<i class="fa fa-eye-slash fa-fw"></i>')
->defaultAttribute('type', 'password');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Email.php | src/Form/Field/Email.php | <?php
namespace Encore\Admin\Form\Field;
class Email extends Text
{
protected $rules = 'nullable|email';
public function render()
{
$this->prepend('<i class="fa fa-envelope fa-fw"></i>')
->defaultAttribute('type', 'email');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Nullable.php | src/Form/Field/Nullable.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Nullable extends Field
{
public function __construct()
{
}
public function __call($method, $parameters)
{
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/ValuePicker.php | src/Form/Field/ValuePicker.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
class ValuePicker
{
/**
* @var string
*/
protected $modal;
/**
* @var Text|File
*/
protected $field;
/**
* @var string
*/
protected $column;
/**
* @var string
*/
protected $selecteable;
/**
* @var string
*/
protected $separator;
/**
* @var bool
*/
protected $multiple = false;
/**
* ValuePicker constructor.
*
* @param string $selecteable
* @param string $column
* @param bool $multiple
* @param string $separator
*/
public function __construct($selecteable, $column = '', $multiple = false, $separator = ';')
{
$this->selecteable = $selecteable;
$this->column = $column;
$this->multiple = $multiple;
$this->separator = $separator;
}
/**
* @param int $multiple
*
* @return string
*/
protected function getLoadUrl()
{
$selectable = str_replace('\\', '_', $this->selecteable);
$args = [$this->multiple, $this->column];
return route(admin_get_route('handle-selectable'), compact('selectable', 'args'));
}
/**
* @param Field $field
* @param \Closure|null $callback
*/
public function mount(Field $field, \Closure $callback = null)
{
$this->field = $field;
$this->modal = sprintf('picker-modal-%s', $field->getElementClassString());
$this->addPickBtn($callback);
Admin::component('admin::components.filepicker', [
'url' => $this->getLoadUrl(),
'modal' => $this->modal,
'selector' => $this->field->getElementClassSelector(),
'separator' => $this->separator,
'multiple' => $this->multiple,
'is_file' => $this->field instanceof File,
'is_image' => $this->field instanceof Image,
'url_tpl' => $this->field instanceof File ? $this->field->objectUrl('__URL__') : '',
]);
}
/**
* @param \Closure|null $callback
*/
protected function addPickBtn(\Closure $callback = null)
{
$text = admin_trans('admin.browse');
$btn = <<<HTML
<a class="btn btn-primary" data-toggle="modal" data-target="#{$this->modal}">
<i class="fa fa-folder-open"></i> {$text}
</a>
HTML;
if ($callback) {
$callback($btn);
} else {
$this->field->addVariables(compact('btn'));
}
}
/**
* @param string $field
*
* @return array|\Illuminate\Support\Collection
*/
public function getPreview(string $field)
{
if (empty($value = $this->field->value())) {
return [];
}
if ($this->multiple) {
$value = explode($this->separator, $value);
}
return collect(Arr::wrap($value))->map(function ($item) use ($field) {
return [
'url' => $this->field->objectUrl($item),
'value' => $item,
'is_file' => $field == File::class,
];
});
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Button.php | src/Form/Field/Button.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Button extends Field
{
protected $class = 'btn-primary';
public function info()
{
$this->class = 'btn-info';
return $this;
}
public function on($event, $callback)
{
$this->script = <<<EOT
$('{$this->getElementClassSelector()}').on('$event', function() {
$callback
});
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Url.php | src/Form/Field/Url.php | <?php
namespace Encore\Admin\Form\Field;
class Url extends Text
{
protected $rules = 'nullable|url';
public function render()
{
$this->prepend('<i class="fa fa-internet-explorer fa-fw"></i>')
->defaultAttribute('type', 'url');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/RadioCard.php | src/Form/Field/RadioCard.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class RadioCard extends RadioButton
{
protected function addStyle()
{
$style = <<<'STYLE'
.card-group label {
cursor: pointer;
margin-right: 8px;
font-weight: 400;
}
.card-group .panel {
margin-bottom: 0px;
}
.card-group .panel-body {
padding: 10px 15px;
}
.card-group .active {
border: 2px solid #367fa9;
}
STYLE;
Admin::style($style);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->addStyle();
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/BelongsToMany.php | src/Form/Field/BelongsToMany.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class BelongsToMany extends MultipleSelect
{
use BelongsToRelation;
protected function addScript()
{
$script = <<<SCRIPT
;(function () {
var grid = $('.belongstomany-{$this->column()}');
var modal = $('#{$this->modalID}');
var table = grid.find('.grid-table');
var selected = $("{$this->getElementClassSelector()}").val() || [];
var rows = {};
table.find('tbody').children().each(function (index, tr) {
if ($(tr).find('.grid-row-remove').length > 0) {
rows[$(tr).find('.grid-row-remove').data('key')] = $(tr);
}
});
// open modal
grid.find('.select-relation').click(function (e) {
$('#{$this->modalID}').modal('show');
e.preventDefault();
});
// remove row
grid.on('click', '.grid-row-remove', function () {
val = $(this).data('key').toString();
var index = selected.indexOf(val);
if (index !== -1) {
selected.splice(index, 1);
delete rows[val];
}
$(this).parents('tr').remove();
$("{$this->getElementClassSelector()}").val(selected);
if (selected.length == 0) {
var empty = $('.belongstomany-{$this->column()}').find('template.empty').html();
table.find('tbody').append(empty);
}
});
var load = function (url) {
$.get(url, function (data) {
modal.find('.modal-body').html(data);
modal.find('.select').iCheck({
radioClass:'iradio_minimal-blue',
checkboxClass:'icheckbox_minimal-blue'
});
modal.find('.box-header:first').hide();
modal.find('input.select').each(function (index, el) {
if ($.inArray($(el).val().toString(), selected) >=0 ) {
$(el).iCheck('toggle');
}
});
});
};
var update = function (callback) {
$("{$this->getElementClassSelector()}")
.select2({data: selected})
.val(selected)
.trigger('change')
.next()
.addClass('hide');
table.find('tbody').empty();
Object.values(rows).forEach(function (row) {
row.find('td:last a').removeClass('hide');
row.find('td.column-__modal_selector__').remove();
table.find('tbody').append(row);
});
if (selected.length == 0) {
var empty = $('.belongstomany-{$this->column()}').find('template.empty').html();
table.find('tbody').append(empty);
} else {
table.find('.empty-grid').parent().remove();
}
callback();
};
modal.on('show.bs.modal', function (e) {
load("{$this->getLoadUrl(1)}");
}).on('click', '.page-item a, .filter-box a', function (e) {
load($(this).attr('href'));
e.preventDefault();
}).on('click', 'tr', function (e) {
$(this).find('input.select').iCheck('toggle');
e.preventDefault();
}).on('submit', '.box-header form', function (e) {
load($(this).attr('action')+'&'+$(this).serialize());
e.preventDefault();
return false;
}).on('ifChecked', 'input.select', function (e) {
if (selected.indexOf($(this).val()) < 0) {
selected.push($(this).val());
rows[$(e.target).val()] = $(e.target).parents('tr');
}
}).on('ifUnchecked', 'input.select', function (e) {
var val = $(this).val();
var index = selected.indexOf(val);
if (index !== -1) {
selected.splice(index, 1);
delete rows[$(e.target).val()];
}
}).find('.modal-footer .submit').click(function () {
update(function () {
modal.modal('toggle');
});
});
})();
SCRIPT;
Admin::script($script);
return $this;
}
protected function getOptions()
{
$options = [];
if ($this->value()) {
$options = array_combine($this->value(), $this->value());
}
return $options;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Fieldset.php | src/Form/Field/Fieldset.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class Fieldset
{
protected $name = '';
public function __construct()
{
$this->name = uniqid('fieldset-');
}
public function start($title)
{
$script = <<<SCRIPT
$('.{$this->name}-title').click(function () {
$("i", this).toggleClass("fa-angle-double-down fa-angle-double-up");
});
SCRIPT;
Admin::script($script);
return <<<HTML
<div>
<div style="height: 20px; border-bottom: 1px solid #eee; text-align: center;margin-top: 20px;margin-bottom: 20px;">
<span style="font-size: 16px; background-color: #ffffff; padding: 0 10px;">
<a data-toggle="collapse" href="#{$this->name}" class="{$this->name}-title">
<i class="fa fa-angle-double-up"></i> {$title}
</a>
</span>
</div>
<div class="collapse in" id="{$this->name}">
HTML;
}
public function end()
{
return '</div></div>';
}
public function collapsed()
{
$script = <<<SCRIPT
$("#{$this->name}").removeClass("in");
$(".{$this->name}-title i").toggleClass("fa-angle-double-down fa-angle-double-up");
SCRIPT;
Admin::script($script);
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Divider.php | src/Form/Field/Divider.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Divider extends Field
{
protected $title;
public function __construct($title = '')
{
$this->title = $title;
}
public function render()
{
if (empty($this->title)) {
return '<hr>';
}
return <<<HTML
<div style="height: 20px; border-bottom: 1px solid #eee; text-align: center;margin-top: 20px;margin-bottom: 20px;">
<span style="font-size: 18px; background-color: #ffffff; padding: 0 10px;">
{$this->title}
</span>
</div>
HTML;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Id.php | src/Form/Field/Id.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Id extends Field
{
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/BelongsToRelation.php | src/Form/Field/BelongsToRelation.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Grid\Selectable;
trait BelongsToRelation
{
/**
* @var string
*/
protected $modalID;
/**
* @var string
*/
protected $selectable;
/**
* BelongsToRelation constructor.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->setSelectable($arguments[0]);
parent::__construct($column, array_slice($arguments, 1));
}
/**
* @param string $selectable
*/
protected function setSelectable($selectable)
{
if (!class_exists($selectable) || !is_subclass_of($selectable, Selectable::class)) {
throw new \InvalidArgumentException(
"[Class [{$selectable}] must be a sub class of Encore\Admin\Grid\Selectable"
);
}
$this->selectable = $selectable;
}
/**
* @return string
*/
public function getSelectable()
{
return $this->selectable;
}
/**
* @param int $multiple
*
* @return string
*/
protected function getLoadUrl($multiple = 0)
{
$selectable = str_replace('\\', '_', $this->selectable);
$args = [$multiple];
return route(admin_get_route('handle-selectable'), compact('selectable', 'args'));
}
/**
* @return $this
*/
public function addHtml()
{
$trans = [
'choose' => admin_trans('admin.choose'),
'cancal' => admin_trans('admin.cancel'),
'submit' => admin_trans('admin.submit'),
];
$html = <<<HTML
<div class="modal fade belongsto" id="{$this->modalID}" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" style="border-radius: 5px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">{$trans['choose']}</h4>
</div>
<div class="modal-body">
<div class="loading text-center">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{$trans['cancal']}</button>
<button type="button" class="btn btn-primary submit">{$trans['submit']}</button>
</div>
</div>
</div>
</div>
HTML;
Admin::html($html);
return $this;
}
/**
* @return $this
*/
public function addStyle()
{
$style = <<<'STYLE'
.belongsto.modal tr {
cursor: pointer;
}
.belongsto.modal .box {
border-top: none;
margin-bottom: 0;
box-shadow: none;
}
.belongsto.modal .loading {
margin: 50px;
}
.belongsto.modal .grid-table .empty-grid {
padding: 20px !important;
}
.belongsto.modal .grid-table .empty-grid svg {
width: 60px !important;
height: 60px !important;
}
.belongsto.modal .grid-box .box-footer {
border-top: none !important;
}
STYLE;
Admin::style($style);
return $this;
}
/**
* @return \Encore\Admin\Grid
*/
protected function makeGrid()
{
/** @var Selectable $selectable */
$selectable = new $this->selectable();
return $selectable->renderFormGrid($this->value());
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->modalID = sprintf('modal-selector-%s', $this->getElementClassString());
$this->addScript()->addHtml()->addStyle();
$this->addVariables([
'grid' => $this->makeGrid(),
'options' => $this->getOptions(),
]);
$this->addCascadeScript();
return parent::fieldRender();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/CheckboxCard.php | src/Form/Field/CheckboxCard.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class CheckboxCard extends CheckboxButton
{
protected function addStyle()
{
$style = <<<'STYLE'
.card-group label {
cursor: pointer;
margin-right: 8px;
font-weight: 400;
}
.card-group .panel {
margin-bottom: 0px;
}
.card-group .panel-body {
padding: 10px 15px;
}
.card-group .active {
border: 2px solid #367fa9;
}
STYLE;
Admin::style($style);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->addStyle();
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/ListField.php | src/Form/Field/ListField.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
class ListField extends Field
{
/**
* Max list size.
*
* @var int
*/
protected $max;
/**
* Minimum list size.
*
* @var int
*/
protected $min = 0;
/**
* @var array
*/
protected $value = [''];
/**
* Set Max list size.
*
* @param int $size
*
* @return $this
*/
public function max(int $size)
{
$this->max = $size;
return $this;
}
/**
* Set Minimum list size.
*
* @param int $size
*
* @return $this
*/
public function min(int $size)
{
$this->min = $size;
return $this;
}
/**
* Fill data to the field.
*
* @param array $data
*
* @return void
*/
public function fill($data)
{
$this->data = $data;
$this->value = Arr::get($data, $this->column, $this->value);
$this->formatValue();
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if ($this->validator) {
return $this->validator->call($this, $input);
}
if (!is_string($this->column)) {
return false;
}
$rules = $attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
if (!Arr::has($input, $this->column)) {
return false;
}
$rules["{$this->column}.values.*"] = $fieldRules;
$attributes["{$this->column}.values.*"] = __('Value');
$rules["{$this->column}.values"][] = 'array';
if (!is_null($this->max)) {
$rules["{$this->column}.values"][] = "max:$this->max";
}
if (!is_null($this->min)) {
$rules["{$this->column}.values"][] = "min:$this->min";
}
$attributes["{$this->column}.values"] = $this->label;
return validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* {@inheritdoc}
*/
protected function setupScript()
{
$this->script = <<<SCRIPT
$('.{$this->column}-add').on('click', function () {
var tpl = $('template.{$this->column}-tpl').html();
$('tbody.list-{$this->column}-table').append(tpl);
});
$('tbody').on('click', '.{$this->column}-remove', function () {
$(this).closest('tr').remove();
});
SCRIPT;
}
/**
* {@inheritdoc}
*/
public function prepare($value)
{
return array_values($value['values']);
}
/**
* {@inheritdoc}
*/
public function render()
{
$this->setupScript();
Admin::style('td .form-group {margin-bottom: 0 !important;}');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Embeds.php | src/Form/Field/Embeds.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\EmbeddedForm;
use Encore\Admin\Form\Field;
use Encore\Admin\Widgets\Form as WidgetForm;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class Embeds extends Field
{
/**
* @var \Closure
*/
protected $builder = null;
/**
* Create a new HasMany field instance.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->column = $column;
if (count($arguments) == 1) {
$this->label = $this->formatLabel();
$this->builder = $arguments[0];
}
if (count($arguments) == 2) {
list($this->label, $this->builder) = $arguments;
}
}
/**
* Prepare input data for insert or update.
*
* @param array $input
*
* @return array
*/
public function prepare($input)
{
$form = $this->buildEmbeddedForm();
return $form->setOriginal($this->original)->prepare($input);
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if (!array_key_exists($this->column, $input)) {
return false;
}
$input = Arr::only($input, $this->column);
$rules = $attributes = [];
/** @var Field $field */
foreach ($this->buildEmbeddedForm()->fields() as $field) {
if (!$fieldRules = $field->getRules()) {
continue;
}
$column = $field->column();
/*
*
* For single column field format rules to:
* [
* 'extra.name' => 'required'
* 'extra.email' => 'required'
* ]
*
* For multiple column field with rules like 'required':
* 'extra' => [
* 'start' => 'start_at'
* 'end' => 'end_at',
* ]
*
* format rules to:
* [
* 'extra.start_atstart' => 'required'
* 'extra.end_atend' => 'required'
* ]
*/
if (is_array($column)) {
foreach ($column as $key => $name) {
$rules["{$this->column}.$name$key"] = $fieldRules;
}
$this->resetInputKey($input, $column);
} else {
$rules["{$this->column}.$column"] = $fieldRules;
}
/**
* For single column field format attributes to:
* [
* 'extra.name' => $label
* 'extra.email' => $label
* ].
*
* For multiple column field with rules like 'required':
* 'extra' => [
* 'start' => 'start_at'
* 'end' => 'end_at',
* ]
*
* format rules to:
* [
* 'extra.start_atstart' => "$label[start_at]"
* 'extra.end_atend' => "$label[end_at]"
* ]
*/
$attributes = array_merge(
$attributes,
$this->formatValidationAttribute($input, $field->label(), $column)
);
}
if (empty($rules)) {
return false;
}
return \validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* Format validation attributes.
*
* @param array $input
* @param string $label
* @param string $column
*
* @return array
*/
protected function formatValidationAttribute($input, $label, $column)
{
$new = $attributes = [];
if (is_array($column)) {
foreach ($column as $index => $col) {
$new[$col.$index] = $col;
}
}
foreach (array_keys(Arr::dot($input)) as $key) {
if (is_string($column)) {
if (Str::endsWith($key, ".$column")) {
$attributes[$key] = $label;
}
} else {
foreach ($new as $k => $val) {
if (Str::endsWith($key, ".$k")) {
$attributes[$key] = $label."[$val]";
}
}
}
}
return $attributes;
}
/**
* Reset input key for validation.
*
* @param array $input
* @param array $column $column is the column name array set
*
* @return void.
*/
public function resetInputKey(array &$input, array $column)
{
$column = array_flip($column);
foreach ($input[$this->column] as $key => $value) {
if (!array_key_exists($key, $column)) {
continue;
}
$newKey = $key.$column[$key];
/*
* set new key
*/
Arr::set($input, "{$this->column}.$newKey", $value);
/*
* forget the old key and value
*/
Arr::forget($input, "{$this->column}.$key");
}
}
/**
* Get data for Embedded form.
*
* Normally, data is obtained from the database.
*
* When the data validation errors, data is obtained from session flash.
*
* @return array
*/
protected function getEmbeddedData()
{
if ($old = old($this->column)) {
return $old;
}
if (empty($this->value)) {
return [];
}
if (is_string($this->value)) {
return json_decode($this->value, true);
}
return (array) $this->value;
}
/**
* Build a Embedded Form and fill data.
*
* @return EmbeddedForm
*/
protected function buildEmbeddedForm()
{
$form = new EmbeddedForm($this->getEmbeddedColumnName());
if ($this->form instanceof WidgetForm) {
$form->setParentWidgetForm($this->form);
} else {
$form->setParent($this->form);
}
call_user_func($this->builder, $form);
$form->fill($this->getEmbeddedData());
return $form;
}
/**
* Determine the column name to use with the embedded form.
*
* @return array|string
*/
protected function getEmbeddedColumnName()
{
if ($this->isNested()) {
return $this->elementName;
}
return $this->column;
}
/**
* Check if the field is in a nested form.
*
* @return bool
*/
protected function isNested()
{
return !empty($this->elementName);
}
/**
* Render the form.
*
* @return \Illuminate\View\View
*/
public function render()
{
return parent::fieldRender(['form' => $this->buildEmbeddedForm()]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Html.php | src/Form/Field/Html.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
class Html extends Field
{
/**
* Htmlable.
*
* @var string|\Closure
*/
protected $html = '';
/**
* @var string
*/
protected $label = '';
/**
* @var bool
*/
protected $plain = false;
/**
* Create a new Html instance.
*
* @param mixed $html
* @param array $arguments
*/
public function __construct($html, $arguments)
{
$this->html = $html;
$this->label = Arr::get($arguments, 0);
}
/**
* @return $this
*/
public function plain()
{
$this->plain = true;
return $this;
}
/**
* Render html field.
*
* @return string
*/
public function render()
{
if ($this->html instanceof \Closure) {
$this->html = $this->html->call($this->form->model(), $this->form);
}
if ($this->plain) {
return $this->html;
}
$viewClass = $this->getViewElementClasses();
return <<<EOT
<div class="{$viewClass['form-group']}">
<label class="{$viewClass['label']} control-label">{$this->label}</label>
<div class="{$viewClass['field']}">
{$this->html}
</div>
</div>
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/HasValuePicker.php | src/Form/Field/HasValuePicker.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
/**
* @mixin Field
*/
trait HasValuePicker
{
/**
* @var ValuePicker
*/
protected $picker;
/**
* @param string $picker
* @param string $column
*
* @return $this
*/
public function pick($picker, $column = '')
{
$this->picker = new ValuePicker($picker, $column);
return $this;
}
/**
* @param string $picker
* @param string $column
* @param string $separator
*/
public function pickMany($picker, $column = '', $separator = ';')
{
$this->picker = new ValuePicker($picker, $column, true, $separator);
return $this;
}
/**
* @param \Closure|null $callback
*
* @return $this
*/
protected function mountPicker(\Closure $callback = null)
{
$this->picker && $this->picker->mount($this, $callback);
return $this;
}
/**
* @return string
*/
public function getRules()
{
$rules = parent::getRules();
array_delete($rules, 'image');
return $rules;
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
*/
protected function renderFilePicker()
{
$this->mountPicker()
->setView('admin::form.filepicker')
->attribute('type', 'text')
->attribute('id', $this->id)
->attribute('name', $this->elementName ?: $this->formatName($this->column))
->attribute('value', old($this->elementName ?: $this->column, $this->value()))
->attribute('class', 'form-control '.$this->getElementClassString())
->attribute('placeholder', $this->getPlaceholder())
->addVariables([
'preview' => $this->picker->getPreview(get_called_class()),
]);
return Admin::component('admin::form.filepicker', $this->variables());
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/File.php | src/Form/Field/File.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class File extends Field
{
use UploadField;
use HasValuePicker;
/**
* Css.
*
* @var array
*/
protected static $css = [
'/vendor/laravel-admin/bootstrap-fileinput/css/fileinput.min.css?v=4.5.2',
];
/**
* Js.
*
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/bootstrap-fileinput/js/plugins/canvas-to-blob.min.js',
'/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.5.2',
];
/**
* Create a new File instance.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->initStorage();
parent::__construct($column, $arguments);
}
/**
* Default directory for file to upload.
*
* @return mixed
*/
public function defaultDirectory()
{
return config('admin.upload.directory.file');
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if (request()->has(static::FILE_DELETE_FLAG)) {
return false;
}
if ($this->validator) {
return $this->validator->call($this, $input);
}
/*
* If has original value, means the form is in edit mode,
* then remove required rule from rules.
*/
if ($this->original()) {
$this->removeRule('required');
}
/*
* Make input data validatable if the column data is `null`.
*/
if (Arr::has($input, $this->column) && is_null(Arr::get($input, $this->column))) {
$input[$this->column] = '';
}
$rules = $attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
$rules[$this->column] = $fieldRules;
$attributes[$this->column] = $this->label;
return \validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* Prepare for saving.
*
* @param UploadedFile|array $file
*
* @return mixed|string
*/
public function prepare($file)
{
if ($this->picker) {
return parent::prepare($file);
}
if (request()->has(static::FILE_DELETE_FLAG)) {
return $this->destroy();
}
$this->name = $this->getStoreName($file);
return $this->uploadAndDeleteOriginal($file);
}
/**
* Upload file and delete original file.
*
* @param UploadedFile $file
*
* @return mixed
*/
protected function uploadAndDeleteOriginal(UploadedFile $file)
{
$this->renameIfExists($file);
$path = null;
if (!is_null($this->storagePermission)) {
$path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
} else {
$path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
}
$this->destroy();
return $path;
}
/**
* Preview html for file-upload plugin.
*
* @return string
*/
protected function preview()
{
return $this->objectUrl($this->value);
}
/**
* Hides the file preview.
*
* @return $this
*/
public function hidePreview()
{
return $this->options([
'showPreview' => false,
]);
}
/**
* Initialize the caption.
*
* @param string $caption
*
* @return string
*/
protected function initialCaption($caption)
{
return basename($caption);
}
/**
* @return array
*/
protected function initialPreviewConfig()
{
$config = ['caption' => basename($this->value), 'key' => 0];
$config = array_merge($config, $this->guessPreviewType($this->value));
return [$config];
}
/**
* @param string $options
*/
protected function setupScripts($options)
{
$this->script = <<<EOT
$("input{$this->getElementClassSelector()}").fileinput({$options});
EOT;
if ($this->fileActionSettings['showRemove']) {
$text = [
'title' => trans('admin.delete_confirm'),
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
];
$this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filebeforedelete', function() {
return new Promise(function(resolve, reject) {
var remove = resolve;
swal({
title: "{$text['title']}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$text['confirm']}",
showLoaderOnConfirm: true,
cancelButtonText: "{$text['cancel']}",
preConfirm: function() {
return new Promise(function(resolve) {
resolve(remove());
});
}
});
});
});
EOT;
}
}
/**
* Render file upload field.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
if ($this->picker) {
return $this->renderFilePicker();
}
$this->options(['overwriteInitial' => true, 'msgPlaceholder' => trans('admin.choose_file')]);
$this->setupDefaultOptions();
if (!empty($this->value)) {
$this->attribute('data-initial-preview', $this->preview());
$this->attribute('data-initial-caption', $this->initialCaption($this->value));
$this->setupPreviewOptions();
/*
* If has original value, means the form is in edit mode,
* then remove required rule from rules.
*/
unset($this->attributes['required']);
}
$options = json_encode_options($this->options);
$this->setupScripts($options);
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/CascadeGroup.php | src/Form/Field/CascadeGroup.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class CascadeGroup extends Field
{
/**
* @var array
*/
protected $dependency;
/**
* @var string
*/
protected $hide = 'hide';
/**
* CascadeGroup constructor.
*
* @param array $dependency
*/
public function __construct(array $dependency)
{
$this->dependency = $dependency;
}
/**
* @param Field $field
*
* @return bool
*/
public function dependsOn(Field $field)
{
return $this->dependency['column'] == $field->column();
}
/**
* @return int
*/
public function index()
{
return $this->dependency['index'];
}
/**
* @return void
*/
public function visiable()
{
$this->hide = '';
}
/**
* @return string
*/
public function render()
{
return <<<HTML
<div class="cascade-group {$this->dependency['class']} {$this->hide}">
HTML;
}
/**
* @return void
*/
public function end()
{
$this->form->html('</div>')->plain();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/BelongsTo.php | src/Form/Field/BelongsTo.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
class BelongsTo extends Select
{
use BelongsToRelation;
protected function addScript()
{
$script = <<<SCRIPT
;(function () {
var grid = $('.belongsto-{$this->column()}');
var modal = $('#{$this->modalID}');
var table = grid.find('.grid-table');
var selected = $("{$this->getElementClassSelector()}").val();
var row = null;
// open modal
grid.find('.select-relation').click(function (e) {
$('#{$this->modalID}').modal('show');
e.preventDefault();
});
// remove row
grid.on('click', '.grid-row-remove', function () {
selected = null;
$(this).parents('tr').remove();
$("{$this->getElementClassSelector()}").val(null);
var empty = $('.belongsto-{$this->column()}').find('template.empty').html();
table.find('tbody').append(empty);
});
var load = function (url) {
$.get(url, function (data) {
modal.find('.modal-body').html(data);
modal.find('.select').iCheck({
radioClass:'iradio_minimal-blue',
checkboxClass:'icheckbox_minimal-blue'
});
modal.find('.box-header:first').hide();
modal.find('input.select').each(function (index, el) {
if ($(el).val() == selected) {
$(el).iCheck('toggle');
}
});
});
};
var update = function (callback) {
$("{$this->getElementClassSelector()}")
.select2({data: [selected]})
.val(selected)
.trigger('change')
.next()
.addClass('hide');
if (row) {
row.find('td:last a').removeClass('hide');
row.find('td:first').remove();
table.find('tbody').empty().append(row);
}
callback();
};
modal.on('show.bs.modal', function (e) {
load("{$this->getLoadUrl()}");
}).on('click', '.page-item a, .filter-box a', function (e) {
load($(this).attr('href'));
e.preventDefault();
}).on('click', 'tr', function (e) {
$(this).find('input.select').iCheck('toggle');
e.preventDefault();
}).on('submit', '.box-header form', function (e) {
load($(this).attr('action')+'&'+$(this).serialize());
return false;
}).on('ifChecked', 'input.select', function (e) {
row = $(e.target).parents('tr');
selected = $(this).val();
}).find('.modal-footer .submit').click(function () {
update(function () {
modal.modal('toggle');
});
});
})();
SCRIPT;
Admin::script($script);
return $this;
}
protected function getOptions()
{
$options = [];
if ($value = $this->value()) {
$options = [$value => $value];
}
return $options;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Listbox.php | src/Form/Field/Listbox.php | <?php
namespace Encore\Admin\Form\Field;
/**
* Class ListBox.
*
* @see https://github.com/istvan-ujjmeszaros/bootstrap-duallistbox
*/
class Listbox extends MultipleSelect
{
protected $settings = [];
protected static $css = [
'/vendor/laravel-admin/bootstrap-duallistbox/dist/bootstrap-duallistbox.min.css',
];
protected static $js = [
'/vendor/laravel-admin/bootstrap-duallistbox/dist/jquery.bootstrap-duallistbox.min.js',
];
public function settings(array $settings)
{
$this->settings = $settings;
return $this;
}
/**
* Set listbox height.
*
* @param int $height
*
* @return Listbox
*/
public function height($height = 200)
{
return $this->settings(['selectorMinimalHeight' => $height]);
}
/**
* {@inheritdoc}
*/
protected function loadRemoteOptions($url, $parameters = [], $options = [])
{
$ajaxOptions = json_encode(array_merge([
'url' => $url.'?'.http_build_query($parameters),
], $options));
$this->script = <<<EOT
$.ajax($ajaxOptions).done(function(data) {
var listbox = $("{$this->getElementClassSelector()}");
var value = listbox.data('value') + '';
if (value) {
value = value.split(',');
}
for (var key in data) {
var selected = ($.inArray(key, value) >= 0) ? 'selected' : '';
listbox.append('<option value="'+key+'" '+selected+'>'+data[key]+'</option>');
}
listbox.bootstrapDualListbox('refresh', true);
});
EOT;
return $this;
}
public function render()
{
$settings = array_merge([
'infoText' => trans('admin.listbox.text_total'),
'infoTextEmpty' => trans('admin.listbox.text_empty'),
'infoTextFiltered' => trans('admin.listbox.filtered'),
'filterTextClear' => trans('admin.listbox.filter_clear'),
'filterPlaceHolder' => trans('admin.listbox.filter_placeholder'),
'selectorMinimalHeight' => 200,
], $this->settings);
$settings = json_encode($settings);
$this->script .= <<<SCRIPT
$("{$this->getElementClassSelector()}").bootstrapDualListbox($settings);
SCRIPT;
$this->attribute('data-value', implode(',', (array) $this->value()));
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Rate.php | src/Form/Field/Rate.php | <?php
namespace Encore\Admin\Form\Field;
class Rate extends Text
{
public function render()
{
$this->prepend('')
->append('%')
->defaultAttribute('style', 'text-align:right;')
->defaultAttribute('placeholder', 0);
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/DateMultiple.php | src/Form/Field/DateMultiple.php | <?php
namespace Encore\Admin\Form\Field;
class DateMultiple extends Text
{
protected static $css = [
'/vendor/laravel-admin/flatpickr/dist/flatpickr.min.css',
'/vendor/laravel-admin/flatpickr/dist/shortcut-buttons-flatpickr/themes/light.min.css',
];
protected static $js = [
'/vendor/laravel-admin/flatpickr/dist/flatpickr.js',
'/vendor/laravel-admin/flatpickr/dist/shortcut-buttons-flatpickr/shortcut-buttons-flatpickr.min.js',
'/vendor/laravel-admin/flatpickr/dist/l10n/zh.js',
];
protected $format = 'YYYY-MM-DD';
public function format($format)
{
$this->format = $format;
return $this;
}
public function prepare($value)
{
if ($value === '') {
$value = null;
}
return $value;
}
public function render()
{
$this->options['format'] = $this->format;
$this->options['locale'] = array_key_exists('locale', $this->options) ? $this->options['locale'] : config('app.locale');
$this->options['allowInputToggle'] = true;
$this->script = "$('{$this->getElementClassSelector()}').flatpickr({mode: 'multiple',dateFormat: 'Y-m-d', locale: 'zh', plugins: [
ShortcutButtonsPlugin({
button: {
label: 'Clear',
},
onClick: (index, fp) => {
fp.clear();
fp.close();
}
})
]});";
$this->prepend('<i class="fa fa-calendar fa-fw"></i>')
->defaultAttribute('style', 'width: 100%');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Map.php | src/Form/Field/Map.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Map extends Field
{
protected $value = [
'lat' => null,
'lng' => null,
];
/**
* Column name.
*
* @var array
*/
protected $column = [];
/**
* Get assets required by this field.
*
* @return array
*/
public static function getAssets()
{
switch (config('admin.map_provider')) {
case 'tencent':
$js = '//map.qq.com/api/js?v=2.exp&key='.env('TENCENT_MAP_API_KEY');
break;
case 'google':
$js = '//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key='.env('GOOGLE_API_KEY');
break;
case 'yandex':
$js = '//api-maps.yandex.ru/2.1/?lang=ru_RU';
break;
default:
$js = '//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key='.env('GOOGLE_API_KEY');
}
return compact('js');
}
public function __construct($column, $arguments)
{
$this->column['lat'] = (string) $column;
$this->column['lng'] = (string) $arguments[0];
array_shift($arguments);
$this->label = $this->formatLabel($arguments);
$this->id = $this->formatId($this->column);
/*
* Google map is blocked in mainland China
* people in China can use Tencent map instead(;
*/
switch (config('admin.map_provider')) {
case 'tencent':
$this->useTencentMap();
break;
case 'google':
$this->useGoogleMap();
break;
case 'yandex':
$this->useYandexMap();
break;
default:
$this->useGoogleMap();
}
}
public function useGoogleMap()
{
$this->script = <<<EOT
(function() {
function initGoogleMap(name) {
var lat = $('#{$this->id['lat']}');
var lng = $('#{$this->id['lng']}');
var LatLng = new google.maps.LatLng(lat.val(), lng.val());
var options = {
zoom: 13,
center: LatLng,
panControl: false,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var container = document.getElementById("map_"+name);
var map = new google.maps.Map(container, options);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
lat.val(event.latLng.lat());
lng.val(event.latLng.lng());
});
}
initGoogleMap('{$this->id['lat']}{$this->id['lng']}');
})();
EOT;
}
public function useTencentMap()
{
$this->script = <<<EOT
(function() {
function initTencentMap(name) {
var lat = $('#{$this->id['lat']}');
var lng = $('#{$this->id['lng']}');
var center = new qq.maps.LatLng(lat.val(), lng.val());
var container = document.getElementById("map_"+name);
var map = new qq.maps.Map(container, {
center: center,
zoom: 13
});
var marker = new qq.maps.Marker({
position: center,
draggable: true,
map: map
});
if( ! lat.val() || ! lng.val()) {
var citylocation = new qq.maps.CityService({
complete : function(result){
map.setCenter(result.detail.latLng);
marker.setPosition(result.detail.latLng);
}
});
citylocation.searchLocalCity();
}
qq.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
});
qq.maps.event.addListener(marker, 'position_changed', function(event) {
var position = marker.getPosition();
lat.val(position.getLat());
lng.val(position.getLng());
});
}
initTencentMap('{$this->id['lat']}{$this->id['lng']}');
})();
EOT;
}
public function useYandexMap()
{
$this->script = <<<EOT
(function() {
function initYandexMap(name) {
ymaps.ready(function(){
var lat = $('#{$this->id['lat']}');
var lng = $('#{$this->id['lng']}');
var myMap = new ymaps.Map("map_"+name, {
center: [lat.val(), lng.val()],
zoom: 18
});
var myPlacemark = new ymaps.Placemark([lat.val(), lng.val()], {
}, {
preset: 'islands#redDotIcon',
draggable: true
});
myPlacemark.events.add(['dragend'], function (e) {
lat.val(myPlacemark.geometry.getCoordinates()[0]);
lng.val(myPlacemark.geometry.getCoordinates()[1]);
});
myMap.geoObjects.add(myPlacemark);
});
}
initYandexMap('{$this->id['lat']}{$this->id['lng']}');
})();
EOT;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Year.php | src/Form/Field/Year.php | <?php
namespace Encore\Admin\Form\Field;
class Year extends Date
{
protected $format = 'YYYY';
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Timezone.php | src/Form/Field/Timezone.php | <?php
namespace Encore\Admin\Form\Field;
use DateTimeZone;
class Timezone extends Select
{
protected $view = 'admin::form.select';
public function render()
{
$this->options = collect(DateTimeZone::listIdentifiers(DateTimeZone::ALL))->mapWithKeys(function ($timezone) {
return [$timezone => $timezone];
})->toArray();
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Color.php | src/Form/Field/Color.php | <?php
namespace Encore\Admin\Form\Field;
class Color extends Text
{
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/colorpicker/bootstrap-colorpicker.min.css',
];
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/colorpicker/bootstrap-colorpicker.min.js',
];
/**
* Use `hex` format.
*
* @return $this
*/
public function hex()
{
return $this->options(['format' => 'hex']);
}
/**
* Use `rgb` format.
*
* @return $this
*/
public function rgb()
{
return $this->options(['format' => 'rgb']);
}
/**
* Use `rgba` format.
*
* @return $this
*/
public function rgba()
{
return $this->options(['format' => 'rgba']);
}
/**
* Render this filed.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$options = json_encode($this->options);
$this->script = "$('{$this->getElementClassSelector()}').parent().colorpicker($options);";
$this->prepend('<i></i>')
->defaultAttribute('style', 'width: 140px');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/MultipleImage.php | src/Form/Field/MultipleImage.php | <?php
namespace Encore\Admin\Form\Field;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class MultipleImage extends MultipleFile
{
use ImageField;
/**
* {@inheritdoc}
*/
protected $view = 'admin::form.multiplefile';
/**
* Validation rules.
*
* @var string
*/
protected $rules = 'image';
/**
* Prepare for each file.
*
* @param UploadedFile $image
*
* @return mixed|string
*/
protected function prepareForeach(UploadedFile $image = null)
{
$this->name = $this->getStoreName($image);
$this->callInterventionMethods($image->getRealPath());
/* return tap($this->upload($image), function () {
$this->name = null;
}); */
/* Copied from single image prepare section and made necessary changes so the return
value is same as before, but now thumbnails are saved to the disk as well. */
$path = $this->upload($image);
$this->uploadAndDeleteOriginalThumbnail($image);
$this->name = null;
return $path;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Select.php | src/Form/Field/Select.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class Select extends Field
{
use CanCascadeFields;
/**
* @var array
*/
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/select2/select2.min.css',
];
/**
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/select2/select2.full.min.js',
];
/**
* @var array
*/
protected $groups = [];
/**
* @var array
*/
protected $config = [];
/**
* @var string
*/
protected $cascadeEvent = 'change';
/**
* Set options.
*
* @param array|callable|string $options
*
* @return $this|mixed
*/
public function options($options = [])
{
// remote options
if (is_string($options)) {
// reload selected
if (class_exists($options) && in_array(Model::class, class_parents($options))) {
return $this->model(...func_get_args());
}
return $this->loadRemoteOptions(...func_get_args());
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
if (is_callable($options)) {
$this->options = $options;
} else {
$this->options = (array) $options;
}
return $this;
}
/**
* @param array $groups
*/
/**
* Set option groups.
*
* eg: $group = [
* [
* 'label' => 'xxxx',
* 'options' => [
* 1 => 'foo',
* 2 => 'bar',
* ...
* ],
* ...
* ]
*
* @param array $groups
*
* @return $this
*/
public function groups(array $groups)
{
$this->groups = $groups;
return $this;
}
/**
* Load options for other select on change.
*
* @param string $field
* @param string $sourceUrl
* @param string $idField
* @param string $textField
*
* @return $this
*/
public function load($field, $sourceUrl, $idField = 'id', $textField = 'text', bool $allowClear = true)
{
if (Str::contains($field, '.')) {
$field = $this->formatName($field);
$class = str_replace(['[', ']'], '_', $field);
} else {
$class = $field;
}
$placeholder = json_encode([
'id' => '',
'text' => trans('admin.choose'),
]);
$strAllowClear = var_export($allowClear, true);
$script = <<<EOT
$(document).off('change', "{$this->getElementClassSelector()}");
$(document).on('change', "{$this->getElementClassSelector()}", function () {
var target = $(this).closest('.fields-group').find(".$class");
$.get("$sourceUrl",{q : this.value}, function (data) {
target.find("option").remove();
$(target).select2({
placeholder: $placeholder,
allowClear: $strAllowClear,
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
});
if (target.data('value')) {
$(target).val(target.data('value'));
}
$(target).trigger('change');
});
});
EOT;
Admin::script($script);
return $this;
}
/**
* Load options for other selects on change.
*
* @param array $fields
* @param array $sourceUrls
* @param string $idField
* @param string $textField
*
* @return $this
*/
public function loads($fields = [], $sourceUrls = [], $idField = 'id', $textField = 'text', bool $allowClear = true)
{
$fieldsStr = implode('.', $fields);
$urlsStr = implode('^', $sourceUrls);
$placeholder = json_encode([
'id' => '',
'text' => trans('admin.choose'),
]);
$strAllowClear = var_export($allowClear, true);
$script = <<<EOT
var fields = '$fieldsStr'.split('.');
var urls = '$urlsStr'.split('^');
var refreshOptions = function(url, target) {
$.get(url).then(function(data) {
target.find("option").remove();
$(target).select2({
placeholder: $placeholder,
allowClear: $strAllowClear,
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
}).trigger('change');
});
};
$(document).off('change', "{$this->getElementClassSelector()}");
$(document).on('change', "{$this->getElementClassSelector()}", function () {
var _this = this;
var promises = [];
fields.forEach(function(field, index){
var target = $(_this).closest('.fields-group').find('.' + fields[index]);
promises.push(refreshOptions(urls[index] + "?q="+ _this.value, target));
});
});
EOT;
Admin::script($script);
return $this;
}
/**
* Load options from current selected resource(s).
*
* @param string $model
* @param string $idField
* @param string $textField
*
* @return $this
*/
public function model($model, $idField = 'id', $textField = 'name')
{
if (!class_exists($model)
|| !in_array(Model::class, class_parents($model))
) {
throw new \InvalidArgumentException("[$model] must be a valid model class");
}
$this->options = function ($value) use ($model, $idField, $textField) {
if (empty($value)) {
return [];
}
$resources = [];
if (is_array($value)) {
if (Arr::isAssoc($value)) {
$resources[] = Arr::get($value, $idField);
} else {
$resources = array_column($value, $idField);
}
} else {
$resources[] = $value;
}
return $model::find($resources)->pluck($textField, $idField)->toArray();
};
return $this;
}
/**
* Load options from remote.
*
* @param string $url
* @param array $parameters
* @param array $options
*
* @return $this
*/
protected function loadRemoteOptions($url, $parameters = [], $options = [])
{
$ajaxOptions = [
'url' => $url.'?'.http_build_query($parameters),
];
$configs = array_merge([
'allowClear' => true,
'placeholder' => [
'id' => '',
'text' => trans('admin.choose'),
],
], $this->config);
$configs = json_encode($configs);
$configs = substr($configs, 1, strlen($configs) - 2);
$ajaxOptions = json_encode(array_merge($ajaxOptions, $options));
$this->script = <<<EOT
$.ajax($ajaxOptions).done(function(data) {
$("{$this->getElementClassSelector()}").each(function(index, element) {
$(element).select2({
data: data,
$configs
});
var value = $(element).data('value') + '';
if (value) {
value = value.split(',');
$(element).val(value).trigger("change");
}
});
});
EOT;
return $this;
}
/**
* Load options from ajax results.
*
* @param string $url
* @param $idField
* @param $textField
*
* @return $this
*/
public function ajax($url, $idField = 'id', $textField = 'text')
{
$configs = array_merge([
'allowClear' => true,
'placeholder' => $this->label,
'minimumInputLength' => 1,
], $this->config);
$configs = json_encode($configs);
$configs = substr($configs, 1, strlen($configs) - 2);
$this->script = <<<EOT
$("{$this->getElementClassSelector()}").select2({
ajax: {
url: "$url",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data.data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
}),
pagination: {
more: data.next_page_url
}
};
},
cache: true
},
$configs,
escapeMarkup: function (markup) {
return markup;
}
});
EOT;
return $this;
}
/**
* Set config for select2.
*
* all configurations see https://select2.org/configuration/options-api
*
* @param string $key
* @param mixed $val
*
* @return $this
*/
public function config($key, $val)
{
$this->config[$key] = $val;
return $this;
}
/**
* {@inheritdoc}
*/
public function readOnly()
{
//移除特定字段名称,增加MultipleSelect的修订
//没有特定字段名可以使多个readonly的JS代码片段被Admin::script的array_unique精简代码
$script = <<<'EOT'
$("form select").on("select2:opening", function (e) {
if($(this).attr('readonly') || $(this).is(':hidden')){
e.preventDefault();
}
});
$(document).ready(function(){
$('select').each(function(){
if($(this).is('[readonly]')){
$(this).closest('.form-group').find('span.select2-selection__choice__remove').remove();
$(this).closest('.form-group').find('li.select2-search').first().remove();
$(this).closest('.form-group').find('span.select2-selection__clear').first().remove();
}
});
});
EOT;
Admin::script($script);
return parent::readOnly();
}
/**
* {@inheritdoc}
*/
public function render()
{
$configs = array_merge([
'allowClear' => true,
'placeholder' => [
'id' => '',
'text' => $this->label,
],
], $this->config);
$configs = json_encode($configs);
if (empty($this->script)) {
$this->script = "$(\"{$this->getElementClassSelector()}\").select2($configs);";
}
if ($this->options instanceof \Closure) {
if ($this->form) {
$this->options = $this->options->bindTo($this->form->model());
}
$this->options(call_user_func($this->options, $this->value, $this));
}
$this->options = array_filter($this->options, 'strlen');
$this->addVariables([
'options' => $this->options,
'groups' => $this->groups,
]);
$this->addCascadeScript();
$this->attribute('data-value', implode(',', (array) $this->value()));
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/TimeRange.php | src/Form/Field/TimeRange.php | <?php
namespace Encore\Admin\Form\Field;
class TimeRange extends DateRange
{
protected $format = 'HH:mm:ss';
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/MultipleFile.php | src/Form/Field/MultipleFile.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class MultipleFile extends Field
{
use UploadField;
/**
* Css.
*
* @var array
*/
protected static $css = [
'/vendor/laravel-admin/bootstrap-fileinput/css/fileinput.min.css?v=4.5.2',
];
/**
* Js.
*
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/bootstrap-fileinput/js/plugins/canvas-to-blob.min.js',
'/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.5.2',
'/vendor/laravel-admin/bootstrap-fileinput/js/plugins/sortable.min.js?v=4.5.2',
];
/**
* Create a new File instance.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->initStorage();
parent::__construct($column, $arguments);
}
/**
* Default directory for file to upload.
*
* @return mixed
*/
public function defaultDirectory()
{
return config('admin.upload.directory.file');
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if (request()->has(static::FILE_DELETE_FLAG)) {
return false;
}
if ($this->validator) {
return $this->validator->call($this, $input);
}
$attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
$attributes[$this->column] = $this->label;
list($rules, $input) = $this->hydrateFiles(Arr::get($input, $this->column, []));
return \validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* Hydrate the files array.
*
* @param array $value
*
* @return array
*/
protected function hydrateFiles(array $value)
{
if (empty($value)) {
return [[$this->column => $this->getRules()], []];
}
$rules = $input = [];
foreach ($value as $key => $file) {
$rules[$this->column.$key] = $this->getRules();
$input[$this->column.$key] = $file;
}
return [$rules, $input];
}
/**
* Sort files.
*
* @param string $order
*
* @return array
*/
protected function sortFiles($order)
{
$order = explode(',', $order);
$new = [];
$original = $this->original();
foreach ($order as $item) {
$new[] = Arr::get($original, $item);
}
return $new;
}
/**
* Prepare for saving.
*
* @param UploadedFile|array $files
*
* @return mixed|string
*/
public function prepare($files)
{
if (request()->has(static::FILE_DELETE_FLAG)) {
if ($this->pathColumn) {
return $this->destroyFromHasMany(request(static::FILE_DELETE_FLAG));
}
return $this->destroy(request(static::FILE_DELETE_FLAG));
}
if (is_string($files) && request()->has(static::FILE_SORT_FLAG)) {
return $this->sortFiles($files);
}
$targets = array_map([$this, 'prepareForeach'], $files);
// for create or update
if ($this->pathColumn) {
$targets = array_map(function ($target) {
return [$this->pathColumn => $target];
}, $targets);
}
return array_merge($this->original(), $targets);
}
/**
* @return array|mixed
*/
public function original()
{
if (empty($this->original)) {
return [];
}
return $this->original;
}
/**
* Prepare for each file.
*
* @param UploadedFile $file
*
* @return mixed|string
*/
protected function prepareForeach(UploadedFile $file = null)
{
$this->name = $this->getStoreName($file);
return tap($this->upload($file), function () {
$this->name = null;
});
}
/**
* Preview html for file-upload plugin.
*
* @return array
*/
protected function preview()
{
$files = $this->value ?: [];
return array_values(array_map([$this, 'objectUrl'], $files));
}
/**
* Initialize the caption.
*
* @param array $caption
*
* @return string
*/
protected function initialCaption($caption)
{
if (empty($caption)) {
return '';
}
$caption = array_map('basename', $caption);
return implode(',', $caption);
}
/**
* @return array
*/
protected function initialPreviewConfig()
{
$files = $this->value ?: [];
$config = [];
foreach ($files as $index => $file) {
if (is_array($file) && $this->pathColumn) {
$index = Arr::get($file, $this->getRelatedKeyName(), $index);
$file = Arr::get($file, $this->pathColumn);
}
$preview = array_merge([
'caption' => basename($file),
'key' => $index,
], $this->guessPreviewType($file));
$config[] = $preview;
}
return $config;
}
/**
* Get related model key name.
*
* @return string
*/
protected function getRelatedKeyName()
{
if (is_null($this->form)) {
return;
}
return $this->form->model()->{$this->column}()->getRelated()->getKeyName();
}
/**
* Allow to sort files.
*
* @return $this
*/
public function sortable()
{
$this->fileActionSettings['showDrag'] = true;
return $this;
}
/**
* @param string $options
*/
protected function setupScripts($options)
{
$this->script = <<<EOT
$("input{$this->getElementClassSelector()}").fileinput({$options});
EOT;
if ($this->fileActionSettings['showRemove']) {
$text = [
'title' => trans('admin.delete_confirm'),
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
];
$this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filebeforedelete', function() {
return new Promise(function(resolve, reject) {
var remove = resolve;
swal({
title: "{$text['title']}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$text['confirm']}",
showLoaderOnConfirm: true,
cancelButtonText: "{$text['cancel']}",
preConfirm: function() {
return new Promise(function(resolve) {
resolve(remove());
});
}
});
});
});
EOT;
}
if ($this->fileActionSettings['showDrag']) {
$this->addVariables([
'sortable' => true,
'sort_flag' => static::FILE_SORT_FLAG,
]);
$this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filesorted', function(event, params) {
var order = [];
params.stack.forEach(function (item) {
order.push(item.key);
});
$("input{$this->getElementClassSelector()}_sort").val(order);
});
EOT;
}
}
/**
* Render file upload field.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$this->attribute('multiple', true);
$this->setupDefaultOptions();
if (!empty($this->value)) {
$this->options(['initialPreview' => $this->preview()]);
$this->setupPreviewOptions();
}
$options = json_encode($this->options);
$this->setupScripts($options);
return parent::render();
}
/**
* Destroy original files.
*
* @param string $key
*
* @return array
*/
public function destroy($key)
{
$files = $this->original ?: [];
$path = Arr::get($files, $key);
if (!$this->retainable && $this->storage->exists($path)) {
/* If this field class is using ImageField trait i.e MultipleImage field,
we loop through the thumbnails to delete them as well. */
if (isset($this->thumbnails) && method_exists($this, 'destroyThumbnailFile')) {
foreach ($this->thumbnails as $name => $_) {
$this->destroyThumbnailFile($path, $name);
}
}
$this->storage->delete($path);
}
unset($files[$key]);
return $files;
}
/**
* Destroy original files from hasmany related model.
*
* @param int $key
*
* @return array
*/
public function destroyFromHasMany($key)
{
$files = collect($this->original ?: [])->keyBy($this->getRelatedKeyName())->toArray();
$path = Arr::get($files, "{$key}.{$this->pathColumn}");
if (!$this->retainable && $this->storage->exists($path)) {
$this->storage->delete($path);
}
$files[$key][Form::REMOVE_FLAG_NAME] = 1;
return $files;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/DateRange.php | src/Form/Field/DateRange.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class DateRange extends Field
{
protected static $css = [
'/vendor/laravel-admin/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css',
];
protected static $js = [
'/vendor/laravel-admin/moment/min/moment-with-locales.min.js',
'/vendor/laravel-admin/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
];
protected $format = 'YYYY-MM-DD';
/**
* Column name.
*
* @var array
*/
protected $column = [];
public function __construct($column, $arguments)
{
$this->column['start'] = $column;
$this->column['end'] = $arguments[0];
array_shift($arguments);
$this->label = $this->formatLabel($arguments);
$this->id = $this->formatId($this->column);
$this->options(['format' => $this->format]);
}
/**
* {@inheritdoc}
*/
public function prepare($value)
{
if ($value === '') {
$value = null;
}
return $value;
}
public function render()
{
$this->options['locale'] = array_key_exists('locale', $this->options) ? $this->options['locale'] : config('app.locale');
$startOptions = json_encode($this->options);
$endOptions = json_encode($this->options + ['useCurrent' => false]);
$class = $this->getElementClassSelector();
$this->script = <<<EOT
$('{$class['start']}').datetimepicker($startOptions);
$('{$class['end']}').datetimepicker($endOptions);
$("{$class['start']}").on("dp.change", function (e) {
$('{$class['end']}').data("DateTimePicker").minDate(e.date);
});
$("{$class['end']}").on("dp.change", function (e) {
$('{$class['start']}').data("DateTimePicker").maxDate(e.date);
});
EOT;
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/HasMany.php | src/Form/Field/HasMany.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form;
use Encore\Admin\Form\Field;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Widgets\Form as WidgetForm;
use Illuminate\Database\Eloquent\Relations\HasMany as Relation;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/**
* Class HasMany.
*/
class HasMany extends Field
{
/**
* Relation name.
*
* @var string
*/
protected $relationName = '';
/**
* Form builder.
*
* @var \Closure
*/
protected $builder = null;
/**
* Form data.
*
* @var array
*/
protected $value = [];
/**
* View Mode.
*
* Supports `default` and `tab` currently.
*
* @var string
*/
protected $viewMode = 'default';
/**
* Available views for HasMany field.
*
* @var array
*/
protected $views = [
'default' => 'admin::form.hasmany',
'tab' => 'admin::form.hasmanytab',
'table' => 'admin::form.hasmanytable',
];
/**
* Options for template.
*
* @var array
*/
protected $options = [
'allowCreate' => true,
'allowDelete' => true,
];
/**
* Distinct fields.
*
* @var array
*/
protected $distinctFields = [];
/**
* Create a new HasMany field instance.
*
* @param $relationName
* @param array $arguments
*/
public function __construct($relationName, $arguments = [])
{
$this->relationName = $relationName;
$this->column = $relationName;
if (count($arguments) == 1) {
$this->label = $this->formatLabel();
$this->builder = $arguments[0];
}
if (count($arguments) == 2) {
list($this->label, $this->builder) = $arguments;
}
}
/**
* Get validator for this field.
*
* @param array $input
*
* @return bool|\Illuminate\Contracts\Validation\Validator
*/
public function getValidator(array $input)
{
if (!array_key_exists($this->column, $input)) {
return false;
}
$input = Arr::only($input, $this->column);
/** unset item that contains remove flag */
foreach ($input[$this->column] as $key => $value) {
if ($value[NestedForm::REMOVE_FLAG_NAME]) {
unset($input[$this->column][$key]);
}
}
$form = $this->buildNestedForm($this->column, $this->builder);
$rules = $attributes = [];
/* @var Field $field */
foreach ($form->fields() as $field) {
if (!$fieldRules = $field->getRules()) {
continue;
}
$column = $field->column();
if (is_array($column)) {
foreach ($column as $key => $name) {
$rules[$name.$key] = $fieldRules;
}
$this->resetInputKey($input, $column);
} else {
$rules[$column] = $fieldRules;
}
$attributes = array_merge(
$attributes,
$this->formatValidationAttribute($input, $field->label(), $column)
);
}
Arr::forget($rules, NestedForm::REMOVE_FLAG_NAME);
if (empty($rules)) {
return false;
}
$newRules = [];
$newInput = [];
foreach ($rules as $column => $rule) {
foreach (array_keys($input[$this->column]) as $key) {
$newRules["{$this->column}.$key.$column"] = $rule;
if (isset($input[$this->column][$key][$column]) &&
is_array($input[$this->column][$key][$column])) {
foreach ($input[$this->column][$key][$column] as $vkey => $value) {
$newInput["{$this->column}.$key.{$column}$vkey"] = $value;
}
}
}
}
if (empty($newInput)) {
$newInput = $input;
}
$this->appendDistinctRules($newRules);
return \validator($newInput, $newRules, $this->getValidationMessages(), $attributes);
}
/**
* Set distinct fields.
*
* @param array $fields
*
* @return $this
*/
public function distinctFields(array $fields)
{
$this->distinctFields = $fields;
return $this;
}
/**
* Append distinct rules.
*
* @param array $rules
*/
protected function appendDistinctRules(array &$rules)
{
foreach ($this->distinctFields as $field) {
$rules["{$this->column}.*.$field"] = 'distinct';
}
}
/**
* Format validation attributes.
*
* @param array $input
* @param string $label
* @param string $column
*
* @return array
*/
protected function formatValidationAttribute($input, $label, $column)
{
$new = $attributes = [];
if (is_array($column)) {
foreach ($column as $index => $col) {
$new[$col.$index] = $col;
}
}
foreach (array_keys(Arr::dot($input)) as $key) {
if (is_string($column)) {
if (Str::endsWith($key, ".$column")) {
$attributes[$key] = $label;
}
} else {
foreach ($new as $k => $val) {
if (Str::endsWith($key, ".$k")) {
$attributes[$key] = $label."[$val]";
}
}
}
}
return $attributes;
}
/**
* Reset input key for validation.
*
* @param array $input
* @param array $column $column is the column name array set
*
* @return void.
*/
protected function resetInputKey(array &$input, array $column)
{
/**
* flip the column name array set.
*
* for example, for the DateRange, the column like as below
*
* ["start" => "created_at", "end" => "updated_at"]
*
* to:
*
* [ "created_at" => "start", "updated_at" => "end" ]
*/
$column = array_flip($column);
/**
* $this->column is the inputs array's node name, default is the relation name.
*
* So... $input[$this->column] is the data of this column's inputs data
*
* in the HasMany relation, has many data/field set, $set is field set in the below
*/
foreach ($input[$this->column] as $index => $set) {
/*
* foreach the field set to find the corresponding $column
*/
foreach ($set as $name => $value) {
/*
* if doesn't have column name, continue to the next loop
*/
if (!array_key_exists($name, $column)) {
continue;
}
/**
* example: $newKey = created_atstart.
*
* Σ( ° △ °|||)︴
*
* I don't know why a form need range input? Only can imagine is for range search....
*/
$newKey = $name.$column[$name];
/*
* set new key
*/
Arr::set($input, "{$this->column}.$index.$newKey", $value);
/*
* forget the old key and value
*/
Arr::forget($input, "{$this->column}.$index.$name");
}
}
}
/**
* Prepare input data for insert or update.
*
* @param array $input
*
* @return array
*/
public function prepare($input)
{
$form = $this->buildNestedForm($this->column, $this->builder);
return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
}
/**
* Build a Nested form.
*
* @param string $column
* @param \Closure $builder
* @param null $model
*
* @return NestedForm
*/
protected function buildNestedForm($column, \Closure $builder, $model = null)
{
$form = new Form\NestedForm($column, $model);
if ($this->form instanceof WidgetForm) {
$form->setWidgetForm($this->form);
} else {
$form->setForm($this->form);
}
call_user_func($builder, $form);
$form->hidden($this->getKeyName());
$form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
return $form;
}
/**
* Get the HasMany relation key name.
*
* @return string
*/
protected function getKeyName()
{
if (is_null($this->form)) {
return;
}
return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
}
/**
* Set view mode.
*
* @param string $mode currently support `tab` mode.
*
* @return $this
*
* @author Edwin Hui
*/
public function mode($mode)
{
$this->viewMode = $mode;
return $this;
}
/**
* Use tab mode to showing hasmany field.
*
* @return HasMany
*/
public function useTab()
{
return $this->mode('tab');
}
/**
* Use table mode to showing hasmany field.
*
* @return HasMany
*/
public function useTable()
{
return $this->mode('table');
}
/**
* Build Nested form for related data.
*
* @throws \Exception
*
* @return array
*/
protected function buildRelatedForms()
{
if (is_null($this->form)) {
return [];
}
$model = $this->form->model();
$relation = call_user_func([$model, $this->relationName]);
if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
}
$forms = [];
/*
* If redirect from `exception` or `validation error` page.
*
* Then get form data from session flash.
*
* Else get data from database.
*/
if ($values = old($this->column)) {
foreach ($values as $key => $data) {
if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
continue;
}
$model = $relation->getRelated()->replicate()->forceFill($data);
$forms[$key] = $this->buildNestedForm($this->column, $this->builder, $model)
->fill($data);
}
} else {
if (empty($this->value)) {
return [];
}
foreach ($this->value as $data) {
$key = Arr::get($data, $relation->getRelated()->getKeyName());
$model = $relation->getRelated()->replicate()->forceFill($data);
$forms[$key] = $this->buildNestedForm($this->column, $this->builder, $model)
->fill($data);
}
}
return $forms;
}
/**
* Setup script for this field in different view mode.
*
* @param string $script
*
* @return void
*/
protected function setupScript($script)
{
$method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
call_user_func([$this, $method], $script);
}
/**
* Setup default template script.
*
* @param string $templateScript
*
* @return void
*/
protected function setupScriptForDefaultView($templateScript)
{
$removeClass = NestedForm::REMOVE_FLAG_CLASS;
$defaultKey = NestedForm::DEFAULT_KEY_NAME;
/**
* When add a new sub form, replace all element key in new sub form.
*
* @example comments[new___key__][title] => comments[new_{index}][title]
*
* {count} is increment number of current sub form count.
*/
$script = <<<EOT
var index = 0;
$('#has-many-{$this->column}').off('click', '.add').on('click', '.add', function () {
var tpl = $('template.{$this->column}-tpl');
index++;
var template = tpl.html().replace(/{$defaultKey}/g, index);
$('.has-many-{$this->column}-forms').append(template);
{$templateScript}
return false;
});
$('#has-many-{$this->column}').off('click', '.remove').on('click', '.remove', function () {
$(this).closest('.has-many-{$this->column}-form').find('input').removeAttr('required');
$(this).closest('.has-many-{$this->column}-form').hide();
$(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
return false;
});
EOT;
Admin::script($script);
}
/**
* Setup tab template script.
*
* @param string $templateScript
*
* @return void
*/
protected function setupScriptForTabView($templateScript)
{
$removeClass = NestedForm::REMOVE_FLAG_CLASS;
$defaultKey = NestedForm::DEFAULT_KEY_NAME;
$script = <<<EOT
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
var \$navTab = $(this).siblings('a');
var \$pane = $(\$navTab.attr('href'));
if( \$pane.hasClass('new') ){
\$pane.remove();
}else{
\$pane.removeClass('active').find('.$removeClass').val(1);
}
if(\$navTab.closest('li').hasClass('active')){
\$navTab.closest('li').remove();
$('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
}else{
\$navTab.closest('li').remove();
}
});
var index = 0;
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
index++;
var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
$('#has-many-{$this->column} > .nav').append(navTabHtml);
$('#has-many-{$this->column} > .tab-content').append(paneHtml);
$('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
{$templateScript}
});
if ($('.has-error').length) {
$('.has-error').parent('.tab-pane').each(function () {
var tabId = '#'+$(this).attr('id');
$('li a[href="'+tabId+'"] i').removeClass('hide');
});
var first = $('.has-error:first').parent().attr('id');
$('li a[href="#'+first+'"]').tab('show');
}
EOT;
Admin::script($script);
}
/**
* Setup default template script.
*
* @param string $templateScript
*
* @return void
*/
protected function setupScriptForTableView($templateScript)
{
$removeClass = NestedForm::REMOVE_FLAG_CLASS;
$defaultKey = NestedForm::DEFAULT_KEY_NAME;
/**
* When add a new sub form, replace all element key in new sub form.
*
* @example comments[new___key__][title] => comments[new_{index}][title]
*
* {count} is increment number of current sub form count.
*/
$script = <<<EOT
var index = 0;
$('#has-many-{$this->column}').on('click', '.add', function () {
var tpl = $('template.{$this->column}-tpl');
index++;
var template = tpl.html().replace(/{$defaultKey}/g, index);
$('.has-many-{$this->column}-forms').append(template);
{$templateScript}
return false;
});
$('#has-many-{$this->column}').on('click', '.remove', function () {
var first_input_name = $(this).closest('.has-many-{$this->column}-form').find('input[name]:first').attr('name');
if (first_input_name.match('{$this->column}\\\[new_')) {
$(this).closest('.has-many-{$this->column}-form').remove();
} else {
$(this).closest('.has-many-{$this->column}-form').hide();
$(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
$(this).closest('.has-many-{$this->column}-form').find('input').removeAttr('required');
}
return false;
});
EOT;
Admin::script($script);
}
/**
* Disable create button.
*
* @return $this
*/
public function disableCreate()
{
$this->options['allowCreate'] = false;
return $this;
}
/**
* Disable delete button.
*
* @return $this
*/
public function disableDelete()
{
$this->options['allowDelete'] = false;
return $this;
}
/**
* Render the `HasMany` field.
*
* @throws \Exception
*
* @return \Illuminate\View\View
*/
public function render()
{
if (!$this->shouldRender()) {
return '';
}
if ($this->viewMode == 'table') {
return $this->renderTable();
}
// specify a view to render.
$this->view = $this->views[$this->viewMode];
list($template, $script) = $this->buildNestedForm($this->column, $this->builder)
->getTemplateHtmlAndScript();
$this->setupScript($script);
return parent::fieldRender([
'forms' => $this->buildRelatedForms(),
'template' => $template,
'relationName' => $this->relationName,
'options' => $this->options,
]);
}
/**
* Render the `HasMany` field for table style.
*
* @throws \Exception
*
* @return mixed
*/
protected function renderTable()
{
$headers = [];
$fields = [];
$hidden = [];
$scripts = [];
/* @var Field $field */
foreach ($this->buildNestedForm($this->column, $this->builder)->fields() as $field) {
if (is_a($field, Hidden::class)) {
$hidden[] = $field->render();
} else {
/* Hide label and set field width 100% */
$field->setLabelClass(['hidden']);
$field->setWidth(12, 0);
$fields[] = $field->render();
$headers[] = $field->label();
}
/*
* Get and remove the last script of Admin::$script stack.
*/
if ($field->getScript()) {
$scripts[] = array_pop(Admin::$script);
}
}
/* Build row elements */
$template = array_reduce($fields, function ($all, $field) {
$all .= "<td>{$field}</td>";
return $all;
}, '');
/* Build cell with hidden elements */
$template .= '<td class="hidden">'.implode('', $hidden).'</td>';
$this->setupScript(implode("\r\n", $scripts));
// specify a view to render.
$this->view = $this->views[$this->viewMode];
return parent::fieldRender([
'headers' => $headers,
'forms' => $this->buildRelatedForms(),
'template' => $template,
'relationName' => $this->relationName,
'options' => $this->options,
]);
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/KeyValue.php | src/Form/Field/KeyValue.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Support\Arr;
class KeyValue extends Field
{
/**
* @var array
*/
protected $value = ['' => ''];
/**
* Fill data to the field.
*
* @param array $data
*
* @return void
*/
public function fill($data)
{
$this->data = $data;
$this->value = Arr::get($data, $this->column, $this->value);
$this->formatValue();
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if ($this->validator) {
return $this->validator->call($this, $input);
}
if (!is_string($this->column)) {
return false;
}
$rules = $attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
if (!Arr::has($input, $this->column)) {
return false;
}
$rules["{$this->column}.keys.*"] = 'distinct';
$rules["{$this->column}.values.*"] = $fieldRules;
$attributes["{$this->column}.keys.*"] = __('Key');
$attributes["{$this->column}.values.*"] = __('Value');
return validator($input, $rules, $this->getValidationMessages(), $attributes);
}
protected function setupScript()
{
$this->script = <<<SCRIPT
$('.{$this->column}-add').on('click', function () {
var tpl = $('template.{$this->column}-tpl').html();
$('tbody.kv-{$this->column}-table').append(tpl);
});
$('tbody').on('click', '.{$this->column}-remove', function () {
$(this).closest('tr').remove();
});
SCRIPT;
}
public function prepare($value)
{
return array_combine($value['keys'], $value['values']);
}
public function render()
{
$this->setupScript();
Admin::style('td .form-group {margin-bottom: 0 !important;}');
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/Slider.php | src/Form/Field/Slider.php | <?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Form\Field;
class Slider extends Field
{
protected static $css = [
'/vendor/laravel-admin/AdminLTE/plugins/ionslider/ion.rangeSlider.css',
'/vendor/laravel-admin/AdminLTE/plugins/ionslider/ion.rangeSlider.skinNice.css',
];
protected static $js = [
'/vendor/laravel-admin/AdminLTE/plugins/ionslider/ion.rangeSlider.min.js',
];
protected $options = [
'type' => 'single',
'prettify' => false,
'hasGrid' => true,
];
public function render()
{
$option = json_encode($this->options);
$this->script = "$('{$this->getElementClassSelector()}').ionRangeSlider($option);";
return parent::render();
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
z-song/laravel-admin | https://github.com/z-song/laravel-admin/blob/67c441eb78ecc5437e59775d89770cd9c2cb1e05/src/Form/Field/ImageField.php | src/Form/Field/ImageField.php | <?php
namespace Encore\Admin\Form\Field;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image as InterventionImage;
use Intervention\Image\ImageManagerStatic;
use Symfony\Component\HttpFoundation\File\UploadedFile;
trait ImageField
{
/**
* Intervention calls.
*
* @var array
*/
protected $interventionCalls = [];
/**
* Thumbnail settings.
*
* @var array
*/
protected $thumbnails = [];
/**
* Default directory for file to upload.
*
* @return mixed
*/
public function defaultDirectory()
{
return config('admin.upload.directory.image');
}
/**
* Execute Intervention calls.
*
* @param string $target
*
* @return mixed
*/
public function callInterventionMethods($target)
{
if (!empty($this->interventionCalls)) {
$image = ImageManagerStatic::make($target);
foreach ($this->interventionCalls as $call) {
call_user_func_array(
[$image, $call['method']],
$call['arguments']
)->save($target);
}
}
return $target;
}
/**
* Call intervention methods.
*
* @param string $method
* @param array $arguments
*
* @throws \Exception
*
* @return $this
*/
public function __call($method, $arguments)
{
if (static::hasMacro($method)) {
return $this;
}
if (!class_exists(ImageManagerStatic::class)) {
throw new \Exception('To use image handling and manipulation, please install [intervention/image] first.');
}
$this->interventionCalls[] = [
'method' => $method,
'arguments' => $arguments,
];
return $this;
}
/**
* Render a image form field.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$this->options(['allowedFileTypes' => ['image'], 'msgPlaceholder' => trans('admin.choose_image')]);
return parent::render();
}
/**
* @param string|array $name
* @param int $width
* @param int $height
*
* @return $this
*/
public function thumbnail($name, int $width = null, int $height = null)
{
if (func_num_args() == 1 && is_array($name)) {
foreach ($name as $key => $size) {
if (count($size) >= 2) {
$this->thumbnails[$key] = $size;
}
}
} elseif (func_num_args() == 3) {
$this->thumbnails[$name] = [$width, $height];
}
return $this;
}
/**
* Destroy original thumbnail files.
*
* @return void.
*/
public function destroyThumbnail()
{
if ($this->retainable) {
return;
}
foreach ($this->thumbnails as $name => $_) {
/* Refactoring actual remove lofic to another method destroyThumbnailFile()
to make deleting thumbnails work with multiple as well as
single image upload. */
if (is_array($this->original)) {
if (empty($this->original)) {
continue;
}
foreach ($this->original as $original) {
$this->destroyThumbnailFile($original, $name);
}
} else {
$this->destroyThumbnailFile($this->original, $name);
}
}
}
/**
* Remove thumbnail file from disk.
*
* @return void.
*/
public function destroyThumbnailFile($original, $name)
{
$ext = @pathinfo($original, PATHINFO_EXTENSION);
// We remove extension from file name so we can append thumbnail type
$path = @Str::replaceLast('.'.$ext, '', $original);
// We merge original name + thumbnail name + extension
$path = $path.'-'.$name.'.'.$ext;
if ($this->storage->exists($path)) {
$this->storage->delete($path);
}
}
/**
* Upload file and delete original thumbnail files.
*
* @param UploadedFile $file
*
* @return $this
*/
protected function uploadAndDeleteOriginalThumbnail(UploadedFile $file)
{
foreach ($this->thumbnails as $name => $size) {
// We need to get extension type ( .jpeg , .png ...)
$ext = pathinfo($this->name, PATHINFO_EXTENSION);
// We remove extension from file name so we can append thumbnail type
$path = Str::replaceLast('.'.$ext, '', $this->name);
// We merge original name + thumbnail name + extension
$path = $path.'-'.$name.'.'.$ext;
/** @var \Intervention\Image\Image $image */
$image = InterventionImage::make($file);
$action = $size[2] ?? 'resize';
// Resize image with aspect ratio
$image->$action($size[0], $size[1], function (Constraint $constraint) {
$constraint->aspectRatio();
})->resizeCanvas($size[0], $size[1], 'center', false, '#ffffff');
if (!is_null($this->storagePermission)) {
$this->storage->put("{$this->getDirectory()}/{$path}", $image->encode(), $this->storagePermission);
} else {
$this->storage->put("{$this->getDirectory()}/{$path}", $image->encode());
}
}
$this->destroyThumbnail();
return $this;
}
}
| php | MIT | 67c441eb78ecc5437e59775d89770cd9c2cb1e05 | 2026-01-04T15:05:15.717211Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.