1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765 |
- <?php
- namespace Dcat\Admin;
- use Closure;
- use Dcat\Admin\Actions\Action;
- use Dcat\Admin\Contracts\Repository;
- use Dcat\Admin\Form\AbstractTool;
- use Dcat\Admin\Form\Builder;
- use Dcat\Admin\Form\Concerns;
- use Dcat\Admin\Form\Condition;
- use Dcat\Admin\Form\Field;
- use Dcat\Admin\Form\NestedForm;
- use Dcat\Admin\Traits\HasBuilderEvents;
- use Dcat\Admin\Traits\HasFormResponse;
- use Dcat\Admin\Widgets\DialogForm;
- use Illuminate\Contracts\Support\MessageProvider;
- use Illuminate\Contracts\Support\Renderable;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Http\Request;
- use Illuminate\Support\Arr;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Fluent;
- use Illuminate\Support\MessageBag;
- use Illuminate\Support\Str;
- use Illuminate\Support\Traits\Macroable;
- use Illuminate\Validation\Validator;
- use Symfony\Component\HttpFoundation\Response;
- /**
- * Class Form.
- *
- * @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\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\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\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 = '')
- * @method Field\Captcha captcha()
- * @method Field\Listbox listbox($column, $label = '')
- * @method Field\SelectResource selectResource($column, $label = '')
- * @method Field\File file($column, $label = '')
- * @method Field\Image image($column, $label = '')
- * @method Field\MultipleFile multipleFile($column, $label = '')
- * @method Field\MultipleImage multipleImage($column, $label = '')
- * @method Field\HasMany hasMany($column, $labelOrCallback, $callback = null)
- * @method Field\Tree tree($column, $label = '')
- * @method Field\Table table($column, $labelOrCallback, $callback = null)
- * @method Field\ListField list($column, $label = '')
- * @method Field\Timezone timezone($column, $label = '')
- * @method Field\KeyValue keyValue($column, $label = '')
- * @method Field\Tel tel($column, $label = '')
- * @method Field\Markdown markdown($column, $label = '')
- * @method Field\Range range($start, $end, $label = '')
- */
- class Form implements Renderable
- {
- use HasBuilderEvents,
- HasFormResponse,
- Concerns\HasEvents,
- Concerns\HasFiles,
- Concerns\HasSteps,
- Concerns\HandleCascadeFields,
- Concerns\HasRows,
- Concerns\HasTabs,
- Macroable {
- __call as macroCall;
- }
- /**
- * Remove flag in `has many` form.
- */
- const REMOVE_FLAG_NAME = '_remove_';
- /**
- * Available fields.
- *
- * @var array
- */
- protected static $availableFields = [
- 'button' => Field\Button::class,
- 'checkbox' => Field\Checkbox::class,
- 'currency' => Field\Currency::class,
- 'date' => Field\Date::class,
- 'dateRange' => Field\DateRange::class,
- 'datetime' => Field\Datetime::class,
- 'datetimeRange' => Field\DatetimeRange::class,
- 'decimal' => Field\Decimal::class,
- 'display' => Field\Display::class,
- 'divider' => Field\Divide::class,
- 'embeds' => Field\Embeds::class,
- 'editor' => Field\Editor::class,
- 'email' => Field\Email::class,
- 'hidden' => Field\Hidden::class,
- 'id' => Field\Id::class,
- 'ip' => Field\Ip::class,
- 'map' => Field\Map::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,
- '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,
- 'captcha' => Field\Captcha::class,
- 'listbox' => Field\Listbox::class,
- 'selectResource' => Field\SelectResource::class,
- 'file' => Field\File::class,
- 'image' => Field\Image::class,
- 'multipleFile' => Field\MultipleFile::class,
- 'multipleImage' => Field\MultipleImage::class,
- 'hasMany' => Field\HasMany::class,
- 'tree' => Field\Tree::class,
- 'table' => Field\Table::class,
- 'list' => Field\ListField::class,
- 'timezone' => Field\Timezone::class,
- 'keyValue' => Field\KeyValue::class,
- 'tel' => Field\Tel::class,
- 'markdown' => Field\Markdown::class,
- 'range' => Field\Range::class,
- ];
- /**
- * Collected field assets.
- *
- * @var array
- */
- protected static $collectedAssets = [];
- /**
- * Form field alias.
- *
- * @var array
- */
- public static $fieldAlias = [];
- /**
- * @var Repository
- */
- protected $repository;
- /**
- * @var Closure
- */
- protected $callback;
- /**
- * @var Request
- */
- protected $request;
- /**
- * @var bool
- */
- protected $useAjaxSubmit = true;
- /**
- * Model of the form.
- *
- * @var Fluent
- */
- protected $model;
- /**
- * @var \Illuminate\Validation\Validator
- */
- protected $validator;
- /**
- * @var Builder
- */
- protected $builder;
- /**
- * Resource path for this form page.
- *
- * @var string
- */
- protected $resource;
- /**
- * Data for save to current model from input.
- *
- * @var array
- */
- protected $updates = [];
- /**
- * Input data.
- *
- * @var array
- */
- protected $inputs = [];
- /**
- * Ignored saving fields.
- *
- * @var array
- */
- protected $ignored = [];
- /**
- * @var bool
- */
- protected $isSoftDeletes = false;
- /**
- * @var MessageBag
- */
- protected $validationMessages;
- /**
- * @var Condition[]
- */
- protected $conditions = [];
- /**
- * Create a new form instance.
- *
- * @param Repository|Model|\Illuminate\Database\Eloquent\Builder|string $model
- * @param \Closure $callback
- * @param Request $request
- */
- public function __construct($repository = null, ?Closure $callback = null, Request $request = null)
- {
- $this->repository = $repository ? Admin::repository($repository) : null;
- $this->callback = $callback;
- $this->request = $request ?: request();
- $this->builder = new Builder($this);
- $this->isSoftDeletes = $repository ? $this->repository->isSoftDeletes() : false;
- $this->model(new Fluent());
- $this->prepareDialogForm();
- $this->callResolving();
- }
- /**
- * Create a form instance.
- *
- * @param mixed ...$params
- *
- * @return $this
- */
- public static function make(...$params)
- {
- return new static(...$params);
- }
- /**
- * @param Field $field
- *
- * @return $this
- */
- public function pushField(Field $field)
- {
- $field->setForm($this);
- $this->builder->fields()->push($field);
- $width = $this->builder->getWidth();
- $field->width($width['field'], $width['label']);
- $field::collectAssets();
- return $this;
- }
- /**
- * Get specify field.
- *
- * @param string|null $name
- *
- * @return Field|Collection|Field[]|null
- */
- public function field($name = null)
- {
- return $this->builder->field($name);
- }
- /**
- * @return Collection|Field[]
- */
- public function fields()
- {
- $fields = $this->builder->fields();
- if ($steps = $this->builder->stepBuilder()) {
- $fields = $fields->merge($steps->fields());
- }
- return $fields;
- }
- /**
- * @param $column
- *
- * @return $this
- */
- public function removeField($column)
- {
- $this->builder->removeField($column);
- return $this;
- }
- /**
- * @return bool
- */
- public function isCreating()
- {
- return $this->builder->isCreating();
- }
- /**
- * @return bool
- */
- public function isEditing()
- {
- return $this->builder->isEditing();
- }
- /**
- * @return bool
- */
- public function isDeleting()
- {
- return $this->builder->isDeleting();
- }
- /**
- * @param Fluent $model
- *
- * @return Fluent|void
- */
- public function model(Fluent $model = null)
- {
- if ($model === null) {
- return $this->model;
- }
- $this->model = $model;
- }
- /**
- * Get resource id.
- *
- * @return mixed
- */
- public function getKey()
- {
- return $this->builder()->getResourceId();
- }
- /**
- * Disable submit with ajax.
- *
- * @param bool $disable
- *
- * @return $this
- */
- public function disableAjaxSubmit(bool $disable = true)
- {
- $this->useAjaxSubmit = ! $disable;
- return $this;
- }
- /**
- * @return bool
- */
- public function allowAjaxSubmit()
- {
- return $this->useAjaxSubmit === true;
- }
- /**
- * @param \Closure $closure
- *
- * @return $this;
- */
- public function wrap(\Closure $closure)
- {
- $this->builder->wrap($closure);
- return $this;
- }
- /**
- * @return Builder
- */
- public function builder()
- {
- return $this->builder;
- }
- /**
- * @return string
- */
- public function getElementId()
- {
- return $this->builder->getElementId();
- }
- /**
- * @return Repository
- */
- public function repository()
- {
- return $this->repository;
- }
- /**
- * Generate a edit form.
- *
- * @param $id
- *
- * @return $this
- */
- public function edit($id)
- {
- $this->builder->mode(Builder::MODE_EDIT);
- $this->builder->setResourceId($id);
- $this->model(new Fluent($this->repository->edit($this)));
- return $this;
- }
- /**
- * Add a fieldset to form.
- *
- * @param string $title
- * @param Closure $setCallback
- *
- * @return Field\Fieldset
- */
- public function fieldset(string $title, Closure $setCallback)
- {
- $fieldset = new Field\Fieldset();
- $this->html($fieldset->start($title))->plain();
- $setCallback($this);
- $this->html($fieldset->end())->plain();
- return $fieldset;
- }
- /**
- * Destroy data entity and remove files.
- *
- * @param $id
- *
- * @return mixed
- */
- public function destroy($id)
- {
- try {
- $this->builder->setResourceId($id);
- $this->builder->mode(Builder::MODE_DELETE);
- $data = $this->repository->getDataWhenDeleting($this);
- $this->model(new Fluent($data));
- $this->setFieldOriginalValue();
- $this->build();
- if (($response = $this->callDeleting()) instanceof Response) {
- return $response;
- }
- $result = $this->repository->destroy($this, $data);
- if (($response = $this->callDeleted($result)) instanceof Response) {
- return $response;
- }
- $response = [
- 'status' => $result ? true : false,
- 'message' => $result ? trans('admin.delete_succeeded') : trans('admin.delete_failed'),
- ];
- } catch (\Throwable $exception) {
- $response = Admin::makeExceptionHandler()->handle($exception);
- if ($response instanceof Response) {
- return $response;
- }
- $response = $response ?: [
- 'status' => false,
- 'message' => $exception->getMessage() ?: trans('admin.delete_failed'),
- ];
- }
- return response()->json($response);
- }
- /**
- * Store a new record.
- *
- * @param array|null $data
- * @param string|string $redirectTo
- *
- * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\Http\JsonResponse|Response
- */
- public function store(?array $data = null, $redirectTo = null)
- {
- if ($data) {
- $this->request->replace($data);
- }
- $data = $data ?: $this->request->all();
- if ($response = $this->beforeStore($data)) {
- return $response;
- }
- $this->updates = $this->prepareInsert($this->updates);
- $id = $this->repository->store($this);
- $this->builder->setResourceId($id);
- if (($response = $this->callSaved($id))) {
- return $response;
- }
- if ($response = $this->responseMultipleStepsDonePage()) {
- return $response;
- }
- if (! $id) {
- return $this->error(trans('admin.save_failed'));
- }
- return $this->redirect(
- $this->redirectUrl($id, $redirectTo),
- trans('admin.save_succeeded')
- );
- }
- /**
- * Before store.
- *
- * @param array $data
- *
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|Response|void
- */
- protected function beforeStore(array $data)
- {
- $this->inputs = $data;
- $this->build();
- $this->prepareStepFormFields($this->inputs);
- if (($response = $this->callSubmitted())) {
- return $response;
- }
- // Validate step form.
- if ($this->isStepFormValidationRequest()) {
- return $this->validateStepForm($this->inputs);
- }
- if ($response = $this->handleUploadFile($this->inputs)) {
- return $response;
- }
- if ($response = $this->handleFileDeleteBeforeCreate($this->inputs)) {
- $this->deleteFileInStepFormStashData($this->inputs);
- return $response;
- }
- if ($response = $this->handleFileDeleteWhenCreating($this->inputs)) {
- $this->deleteFileInStepFormStashData($this->inputs);
- return $response;
- }
- // Handle validation errors.
- if ($validationMessages = $this->validationMessages($this->inputs)) {
- return $this->validationErrorsResponse($validationMessages);
- }
- if (($response = $this->prepare($this->inputs))) {
- $this->deleteFilesWhenCreating($this->inputs);
- return $response;
- }
- }
- /**
- * Prepare input data for insert or update.
- *
- * @param array $data
- *
- * @return Response|null
- */
- protected function prepare($data = [])
- {
- $this->inputs = $this->removeIgnoredFields($data);
- if (($response = $this->callSaving()) instanceof Response) {
- return $response;
- }
- $this->updates = $this->inputs;
- }
- /**
- * Remove ignored fields from input.
- *
- * @param array $input
- *
- * @return array
- */
- public function removeIgnoredFields($input)
- {
- Arr::forget($input, $this->ignored);
- $ignored = $this->fields()->map(function (Field $field) {
- if ($field instanceof Field\Display || $field->getAttribute('readonly') || $field->getAttribute('disabled')) {
- return $field->column();
- }
- })->filter()->toArray();
- if ($ignored) {
- Arr::forget($input, $ignored);
- }
- return $input;
- }
- /**
- * Get or set data for insert or update.
- *
- * @param array $updates
- *
- * @return $this|array
- */
- public function updates(array $updates = null)
- {
- if ($updates === null) {
- return $this->updates;
- }
- $this->updates = array_merge($this->updates, $updates);
- return $this;
- }
- /**
- * Handle orderable update.
- *
- * @param int $id
- * @param array $input
- *
- * @return Response
- */
- protected function handleOrderable(array $input = [])
- {
- if (array_key_exists('_orderable', $input)) {
- $updated = $input['_orderable'] == 1
- ? $this->repository->moveOrderUp()
- : $this->repository->moveOrderDown();
- return $updated
- ? $this->ajaxResponse(__('admin.update_succeeded'))
- : $this->error(__('admin.nothing_updated'));
- }
- }
- /**
- * Handle update.
- *
- * @param $id
- * @param array|null $data
- * @param string|null $redirectTo
- *
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse||Response
- */
- public function update(
- $id,
- ?array $data = null,
- $redirectTo = null
- ) {
- if ($data) {
- $this->request->replace($data);
- }
- $data = $data ?: $this->request->all();
- if ($response = $this->beforeUpdate($id, $data)) {
- return $response;
- }
- $this->updates = $this->prepareUpdate($this->updates);
- $updated = $this->repository->update($this);
- if (($response = $this->callSaved($updated))) {
- return $response;
- }
- if (! $updated) {
- return $this->error(trans('admin.update_succeeded'));
- }
- return $this->redirect(
- $this->redirectUrl($id, $redirectTo),
- trans('admin.update_succeeded')
- );
- }
- /**
- * Before update.
- *
- * @param array $data
- *
- * @return Response|void
- */
- protected function beforeUpdate($id, array &$data)
- {
- $this->builder->setResourceId($id);
- $this->builder->mode(Builder::MODE_EDIT);
- $this->inputs = $data;
- $this->model(new Fluent($this->repository->getDataWhenUpdating($this)));
- $this->build();
- $this->setFieldOriginalValue();
- if ($response = $this->callSubmitted()) {
- return $response;
- }
- if ($uploadFileResponse = $this->handleUploadFile($this->inputs)) {
- return $uploadFileResponse;
- }
- $isEditable = $this->isEditable($this->inputs);
- $this->inputs = $this->handleEditable($this->inputs);
- $this->inputs = $this->handleFileDelete($this->inputs);
- $this->inputs = $this->handleHasManyValues($this->inputs);
- if ($response = $this->handleOrderable($this->inputs)) {
- return $response;
- }
- // Handle validation errors.
- if ($validationMessages = $this->validationMessages($this->inputs)) {
- return $this->validationErrorsResponse(
- $isEditable ? Arr::dot($validationMessages->toArray()) : $validationMessages
- );
- }
- if ($response = $this->prepare($this->inputs)) {
- return $response;
- }
- }
- /**
- * @param array $inputs
- *
- * @return array
- */
- protected function handleHasManyValues(array $inputs)
- {
- foreach ($inputs as $column => &$input) {
- $field = $this->builder()->field($column);
- if (is_array($input) && $field instanceof Field\HasMany) {
- $keyName = $field->getKeyName();
- foreach ($input as $k => &$v) {
- if (! array_key_exists($keyName, $v)) {
- $v[$keyName] = $k;
- }
- if (empty($v[NestedForm::REMOVE_FLAG_NAME])) {
- $v[NestedForm::REMOVE_FLAG_NAME] = null;
- }
- }
- }
- }
- return $inputs;
- }
- /**
- * @param $key
- * @param $redirectTo
- *
- * @return string|null
- */
- public function redirectUrl($key, $redirectTo = null)
- {
- if ($redirectTo) {
- return $redirectTo;
- }
- $resourcesPath = $this->builder->isCreating() ?
- $this->getResource(0) : $this->getResource(-1);
- if ($this->request->get('after-save') == 1) {
- // continue editing
- if ($this->builder->isEditing() && $this->isAjaxRequest()) {
- return;
- }
- return rtrim($resourcesPath, '/')."/{$key}/edit";
- }
- if ($this->request->get('after-save') == 2) {
- // continue creating
- return rtrim($resourcesPath, '/').'/create';
- }
- if ($this->request->get('after-save') == 3) {
- // view resource
- return rtrim($resourcesPath, '/')."/{$key}";
- }
- return $this->request->get(Builder::PREVIOUS_URL_KEY) ?: $resourcesPath;
- }
- /**
- * Check if request is from editable.
- *
- * @param array $input
- *
- * @return bool
- */
- protected function isEditable(array $input = [])
- {
- return array_key_exists('_editable', $input);
- }
- /**
- * Handle editable update.
- *
- * @param array $input
- *
- * @return array
- */
- protected function handleEditable(array $input = [])
- {
- if (array_key_exists('_editable', $input)) {
- $name = $input['name'];
- $value = $input['value'];
- Arr::forget($input, ['pk', 'value', 'name']);
- Arr::set($input, $name, $value);
- }
- return $input;
- }
- /**
- * Prepare input data for update.
- *
- * @param array $updates
- *
- * @return array
- */
- public function prepareUpdate(array $updates)
- {
- $prepared = [];
- /** @var Field $field */
- foreach ($this->builder->fields() as $field) {
- $columns = $field->column();
- // If column not in input array data, then continue.
- if (! Arr::has($updates, $columns)) {
- continue;
- }
- $value = $this->getDataByColumn($updates, $columns);
- $value = $field->prepare($value);
- if (is_array($columns)) {
- foreach ($columns as $name => $column) {
- Arr::set($prepared, $column, $value[$name]);
- }
- } elseif (is_string($columns)) {
- Arr::set($prepared, $columns, $value);
- }
- }
- return $prepared;
- }
- /**
- * Prepare input data for insert.
- *
- * @param $inserts
- *
- * @return array
- */
- public function prepareInsert($inserts)
- {
- $this->prepareHasOneRelation($inserts);
- foreach ($inserts as $column => $value) {
- if (is_null($field = $this->getFieldByColumn($column))) {
- unset($inserts[$column]);
- continue;
- }
- $inserts[$column] = $field->prepare($value);
- }
- $prepared = [];
- foreach ($inserts as $key => $value) {
- Arr::set($prepared, $key, $value);
- }
- return $prepared;
- }
- /**
- * Is input data is has-one relation.
- *
- * @param array $inserts
- */
- public function prepareHasOneRelation(array &$inserts)
- {
- $relations = [];
- $this->builder->fields()->each(function ($field) use (&$relations) {
- $column = $field->column();
- if (is_array($column)) {
- foreach ($column as $v) {
- if (Str::contains($v, '.')) {
- $first = explode('.', $v)[0];
- $relations[$first] = null;
- }
- }
- return;
- }
- if (Str::contains($column, '.')) {
- $first = explode('.', $column)[0];
- $relations[$first] = null;
- }
- });
- foreach ($relations as $first => $v) {
- if (isset($inserts[$first])) {
- $inserts = array_merge($inserts, Arr::dot([$first => $inserts[$first]]));
- }
- }
- }
- /**
- * Ignore fields to save.
- *
- * @param string|array $fields
- *
- * @return $this
- */
- public function ignore($fields)
- {
- $this->ignored = array_merge($this->ignored, (array) $fields);
- return $this;
- }
- /**
- * Get primary key name of model.
- *
- * @return string
- */
- public function keyName()
- {
- if (! $this->repository) {
- return 'id';
- }
- return $this->repository->getKeyName();
- }
- /**
- * @return string|void
- */
- public function createdAtColumn()
- {
- if (! $this->repository) {
- return;
- }
- return $this->repository->getCreatedAtColumn();
- }
- /**
- * @return string|void
- */
- public function updatedAtColumn()
- {
- if (! $this->repository) {
- return;
- }
- return $this->repository->getUpdatedAtColumn();
- }
- /**
- * @param array $data
- * @param string|array $columns
- *
- * @return array|mixed
- */
- protected function getDataByColumn($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;
- }
- }
- /**
- * Find field object by column.
- *
- * @param $column
- *
- * @return mixed
- */
- protected function getFieldByColumn($column)
- {
- return $this->builder->fields()->first(
- function (Field $field) use ($column) {
- if (is_array($field->column())) {
- return in_array($column, $field->column());
- }
- return $field->column() == $column;
- }
- );
- }
- /**
- * Set original data for each field.
- *
- * @return void
- */
- protected function setFieldOriginalValue()
- {
- $data = $this->model()->toArray();
- $this->builder->fields()->each(function (Field $field) use ($data) {
- $field->setOriginal($data);
- });
- }
- /**
- * @example
- * $form->if(true)->then(function (Form $form) {
- * $form->text('name');
- * });
- *
- * $form->if(function (Form $form) {
- * return $form->model()->id > 5;
- * })->then(function (Form $form) {
- * $form->text('name');
- * });
- *
- * $form->if(true)->now(function (Form $form) {
- * $form->text('name');
- * });
- *
- * $form->if(true)->creating(function (Form $form) {});
- *
- * $form->if(true)->removeField('name');
- *
- * @param bool|\Closure $condition
- *
- * @return Condition
- */
- public function if($condition)
- {
- return $this->conditions[] = new Condition($condition, $this);
- }
- /**
- * @return void
- */
- protected function rendering()
- {
- $this->build();
- if ($this->isCreating()) {
- $this->callCreating();
- return;
- }
- $this->fillFields($this->model()->toArray());
- $this->callEditing();
- }
- /**
- * @param array $data
- *
- * @return void
- */
- public function fillFields(array $data)
- {
- $this->builder->fields()->each(function (Field $field) use ($data) {
- if (! in_array($field->column(), $this->ignored, true)) {
- $field->fill($data);
- }
- });
- }
- /**
- * @return void
- */
- protected function build()
- {
- if ($callback = $this->callback) {
- $callback($this);
- }
- foreach ($this->conditions as $condition) {
- $condition->process();
- }
- }
- /**
- * Get validation messages.
- *
- * @param array $input
- *
- * @return MessageBag|bool
- */
- public function validationMessages($input)
- {
- $failedValidators = [];
- /** @var Field $field */
- foreach ($this->builder->fields() as $field) {
- if (! $validator = $field->getValidator($input)) {
- continue;
- }
- if (($validator instanceof Validator) && ! $validator->passes()) {
- $failedValidators[] = [$field, $validator];
- }
- }
- $message = $this->mergeValidationMessages($failedValidators);
- if ($message->any() && $this->builder->isCreating()) {
- $this->deleteFilesWhenCreating($input);
- }
- return $message->any() ? $message : false;
- }
- /**
- * @param string|array|MessageProvider $column
- * @param string|array $messages
- *
- * @return $this
- */
- public function responseValidationMessages($column, $messages = null)
- {
- if ($column instanceof MessageProvider) {
- return $this->responseValidationMessages($column->getMessageBag()->getMessages());
- }
- if (! $this->validationMessages) {
- $this->validationMessages = new MessageBag();
- }
- if (! $column) {
- return $this;
- }
- if (is_array($column)) {
- foreach ($column as $k => &$v) {
- $v = (array) $v;
- }
- $this->validationMessages->merge($column);
- } elseif ($messages) {
- $this->validationMessages->merge([$column => (array) $messages]);
- }
- return $this;
- }
- /**
- * Merge validation messages from input validators.
- *
- * @param array $validators
- *
- * @return MessageBag
- */
- protected function mergeValidationMessages($validators)
- {
- $messageBag = new MessageBag();
- foreach ($validators as $value) {
- [$field, $validator] = $value;
- $messageBag = $messageBag->merge($field->formatValidatorMessages($validator->messages()));
- }
- if ($this->validationMessages) {
- return $messageBag->merge($this->validationMessages);
- }
- return $messageBag;
- }
- /**
- * Get or set action for form.
- *
- * @param string|null $action
- *
- * @return $this|string
- */
- public function action($action = null)
- {
- $value = $this->builder->action($action);
- if ($action === null) {
- return $value;
- }
- return $this;
- }
- /**
- * Set field and label width in current form.
- *
- * @param int $fieldWidth
- * @param int $labelWidth
- *
- * @return $this
- */
- public function width($fieldWidth = 8, $labelWidth = 2)
- {
- $this->builder->fields()->each(function ($field) use ($fieldWidth, $labelWidth) {
- /* @var Field $field */
- $field->width($fieldWidth, $labelWidth);
- });
- $this->builder->width($fieldWidth, $labelWidth);
- return $this;
- }
- /**
- * Set view for form.
- *
- * @param string $view
- *
- * @return $this
- */
- public function view($view)
- {
- $this->builder->view($view);
- return $this;
- }
- /**
- * Get or set title for form.
- *
- * @param string $title
- *
- * @return $this
- */
- public function title($title = null)
- {
- $this->builder->title($title);
- return $this;
- }
- /**
- * Tools setting for form.
- *
- * @param Closure|string|AbstractTool|Renderable|Action|array $callback
- *
- * @return $this;
- */
- public function tools($callback)
- {
- if ($callback instanceof Closure) {
- $callback->call($this, $this->builder->tools());
- return $this;
- }
- if (! is_array($callback)) {
- $callback = [$callback];
- }
- foreach ($callback as $tool) {
- $this->builder->tools()->append($tool);
- }
- return $this;
- }
- /**
- * @param bool $disable
- *
- * @return $this
- */
- public function disableHeader(bool $disable = true)
- {
- $this->builder->disableHeader($disable);
- return $this;
- }
- /**
- * @param bool $disable
- *
- * @return $this
- */
- public function disableFooter(bool $disable = true)
- {
- $this->builder->disableFooter($disable);
- return $this;
- }
- /**
- * Disable form submit.
- *
- * @return $this
- */
- public function disableSubmitButton(bool $disable = true)
- {
- $this->builder->footer()->disableSubmit($disable);
- return $this;
- }
- /**
- * Disable form reset.
- *
- * @return $this
- */
- public function disableResetButton(bool $disable = true)
- {
- $this->builder->footer()->disableReset($disable);
- return $this;
- }
- /**
- * Disable View Checkbox on footer.
- *
- * @return $this
- */
- public function disableViewCheck(bool $disable = true)
- {
- $this->builder->footer()->disableViewCheck($disable);
- return $this;
- }
- /**
- * Disable Editing Checkbox on footer.
- *
- * @return $this
- */
- public function disableEditingCheck(bool $disable = true)
- {
- $this->builder->footer()->disableEditingCheck($disable);
- return $this;
- }
- /**
- * Disable Creating Checkbox on footer.
- *
- * @return $this
- */
- public function disableCreatingCheck(bool $disable = true)
- {
- $this->builder->footer()->disableCreatingCheck($disable);
- return $this;
- }
- /**
- * Disable `view` tool.
- *
- * @return $this
- */
- public function disableViewButton(bool $disable = true)
- {
- $this->builder->tools()->disableView($disable);
- return $this;
- }
- /**
- * Disable `list` tool.
- *
- * @return $this
- */
- public function disableListButton(bool $disable = true)
- {
- $this->builder->tools()->disableList($disable);
- return $this;
- }
- /**
- * Disable `delete` tool.
- *
- * @return $this
- */
- public function disableDeleteButton(bool $disable = true)
- {
- $this->builder->tools()->disableDelete($disable);
- return $this;
- }
- /**
- * Footer setting for form.
- *
- * @param Closure $callback
- *
- * @return $this
- */
- public function footer(Closure $callback)
- {
- call_user_func($callback, $this->builder->footer());
- return $this;
- }
- /**
- * Get current resource route url.
- *
- * @param int $slice
- *
- * @return string
- */
- public function getResource($slice = -2)
- {
- $path = $this->resource ?: $this->request->getUri();
- $segments = explode('/', trim($path, '/'));
- if ($slice != 0) {
- $segments = array_slice($segments, 0, $slice);
- }
- return url(implode('/', $segments));
- }
- /**
- * Set resource path.
- *
- * @param string $resource
- *
- * @return $this
- */
- public function resource(string $resource)
- {
- if ($resource) {
- $this->resource = admin_url($resource);
- }
- return $this;
- }
- /**
- * Render the form contents.
- *
- * @return string
- */
- public function render()
- {
- try {
- $this->rendering();
- $this->callComposing();
- return $this->builder->render();
- } catch (\Throwable $e) {
- return Admin::makeExceptionHandler()->handle($e);
- }
- }
- /**
- * Get or set input data.
- *
- * @param string $key
- * @param null $value
- *
- * @return array|mixed
- */
- public function input($key, $value = null)
- {
- if (is_null($value)) {
- return Arr::get($this->inputs, $key);
- }
- return Arr::set($this->inputs, $key, $value);
- }
- /**
- * @param string|array $keys
- *
- * @return void
- */
- public function deleteInput($keys)
- {
- Arr::forget($this->inputs, $keys);
- }
- /**
- * @param int $width
- * @param Closure $callback
- *
- * @return $this
- */
- public function block(int $width, \Closure $callback)
- {
- $layout = $this->builder->layout();
- $callback($form = $layout->form());
- $layout->column($width, $form);
- return $this;
- }
- /**
- * @param int $width
- *
- * @return $this
- */
- public function setDefaultBlockWidth(int $width)
- {
- $this->builder->setDefaultBlockWidth($width);
- return $this;
- }
- /**
- * @return $this
- */
- protected function prepareDialogForm()
- {
- DialogForm::prepare($this);
- return $this;
- }
- /**
- * @param Closure $callback
- *
- * @return bool|void
- */
- public function inDialog(\Closure $callback = null)
- {
- if (! $callback) {
- return DialogForm::is();
- }
- if (DialogForm::is()) {
- $callback($this);
- }
- }
- /**
- * Create a dialog form.
- *
- * @param string|null $title
- *
- * @return DialogForm
- */
- public static function dialog(?string $title = null)
- {
- return new DialogForm($title);
- }
- /**
- * Register custom field.
- *
- * @param string $abstract
- * @param string $class
- *
- * @return void
- */
- public static function extend($abstract, $class)
- {
- static::$availableFields[$abstract] = $class;
- }
- /**
- * @return array
- */
- public static function extensions()
- {
- return static::$availableFields;
- }
- /**
- * Set form field alias.
- *
- * @param string $field
- * @param string $alias
- *
- * @return void
- */
- public static function alias($field, $alias)
- {
- static::$fieldAlias[$alias] = $field;
- }
- /**
- * 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;
- }
- /**
- * Getter.
- *
- * @param string $name
- *
- * @return array|mixed
- */
- public function __get($name)
- {
- return $this->input($name);
- }
- /**
- * Setter.
- *
- * @param string $name
- * @param mixed $value
- */
- public function __set($name, $value)
- {
- return Arr::set($this->inputs, $name, $value);
- }
- /**
- * Generate a Field object and add to form builder if Field exists.
- *
- * @param string $method
- * @param array $arguments
- *
- * @return Field
- */
- public function __call($method, $arguments)
- {
- if (static::hasMacro($method)) {
- return $this->macroCall($method, $arguments);
- }
- if ($className = static::findFieldClass($method)) {
- $column = Arr::get($arguments, 0, '');
- $element = new $className($column, array_slice($arguments, 1));
- $this->pushField($element);
- return $element;
- }
- admin_error('Error', "Field type [$method] does not exist.");
- return new Field\Nullable();
- }
- }
|