123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764 |
- <?php
- namespace Dcat\Admin;
- use Closure;
- use Dcat\Admin\Form\Builder;
- use Dcat\Admin\Form\Condition;
- use Dcat\Admin\Form\Field;
- use Dcat\Admin\Form\Row;
- use Dcat\Admin\Form\Tab;
- use Dcat\Admin\Contracts\Repository;
- use Dcat\Admin\Traits\HasBuilderEvents;
- use Dcat\Admin\Widgets\ModalForm;
- use Illuminate\Contracts\Support\MessageProvider;
- use Illuminate\Contracts\Support\Renderable;
- use Illuminate\Http\Request;
- use Illuminate\Support\Arr;
- 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;
- use Dcat\Admin\Form\Concerns;
- /**
- * 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\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\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($column, $label = '')
- * @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\BootstrapFile bootstrapFile($column, $label = '')
- * @method Field\BootstrapImage bootstrapImage($column, $label = '')
- * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
- * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
- */
- class Form implements Renderable
- {
- use HasBuilderEvents,
- Concerns\HasEvents,
- Concerns\HasFiles,
- 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,
- 'color' => Field\Color::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,
- 'bootstrapFile' => Field\BootstrapFile::class,
- 'bootstrapImage' => Field\BootstrapImage::class,
- 'bootstrapMultipleFile' => Field\BootstrapMultipleFile::class,
- 'bootstrapMultipleImage' => Field\BootstrapMultipleImage::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 Form\Tab
- */
- protected $tab = null;
- /**
- * Field rows in form.
- *
- * @var Row[]
- */
- protected $rows = [];
- /**
- * @var bool
- */
- protected $isSoftDeletes = false;
- /**
- * @var MessageBag
- */
- protected $validationMessages;
- /**
- * @var Condition[]
- */
- protected $conditions = [];
- /**
- * Create a new form instance.
- *
- * @param Repository $model
- * @param \Closure $callback
- */
- public function __construct(Repository $repository, ?Closure $callback = null, Request $request = null)
- {
- $this->repository = Admin::repository($repository);
- $this->callback = $callback;
- $this->request = $request ?: request();
- $this->builder = new Builder($this);
- $this->isSoftDeletes = $this->repository->isSoftDeletes();
- $this->setModel(new Fluent());
- $this->prepareModalForm();
- $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->setWidth($width['field'], $width['label']);
- $field::collectAssets();
- return $this;
- }
- /**
- * Get specify field.
- *
- * @param string $name
- * @return Field
- */
- public function field($name)
- {
- return $this->builder->field($name);
- }
- /**
- * @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();
- }
- /**
- * @return Fluent
- */
- public function model()
- {
- return $this->model;
- }
- /**
- * @param Fluent $model
- */
- public function setModel(Fluent $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 getFormId()
- {
- return $this->builder->getFormId();
- }
- /**
- * @return Repository
- */
- public function repository()
- {
- return $this->repository;
- }
- /**
- * Generate a edit form.
- *
- * @param $id
- *
- * @return $this
- */
- public function edit($id)
- {
- $this->builder->setMode(Builder::MODE_EDIT);
- $this->builder->setResourceId($id);
- $this->setFieldValue();
- 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;
- }
- /**
- * Use tab to split form.
- *
- * @param string $title
- * @param Closure $content
- *
- * @return $this
- */
- public function tab($title, Closure $content, $active = false)
- {
- $this->getTab()->append($title, $content, $active);
- return $this;
- }
- /**
- * Get Tab instance.
- *
- * @return Tab
- */
- public function getTab()
- {
- if (is_null($this->tab)) {
- $this->tab = new Tab($this);
- }
- return $this->tab;
- }
- /**
- * Destroy data entity and remove files.
- *
- * @param $id
- *
- * @return mixed
- */
- public function destroy($id)
- {
- try {
- $this->builder->setResourceId($id);
- $this->builder->setMode(Builder::MODE_DELETE);
- $data = $this->repository->getDataWhenDeleting($this);
- $this->setModel(new Fluent($data));
- $this->build();
- if (($response = $this->callDeleting()) instanceof Response) {
- return $response;
- }
- $this->repository->destroy($this, $data);
- if (($response = $this->callDeleted()) instanceof Response) {
- return $response;
- }
- $response = [
- 'status' => true,
- 'message' => trans('admin.delete_succeeded'),
- ];
- } catch (\Throwable $exception) {
- $response = Admin::makeExceptionHandler()->handleDestroyException($exception);
- $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)
- {
- $data = $data ?: $this->request->all();
- $this->build();
- if (($response = $this->callSubmitted())) {
- return $response;
- }
- if ($response = $this->handleUploadFile($data)) {
- return $response;
- }
- if ($response = $this->handleFileDeleteBeforeCreate($data)) {
- return $response;
- }
- if ($response = $this->handleFileDeleteWhenCreating($data)) {
- return $response;
- }
- // Handle validation errors.
- if ($validationMessages = $this->validationMessages($data)) {
- return $this->makeValidationErrorsResponse($validationMessages);
- }
- if (($response = $this->prepare($data))) {
- $this->deleteFilesWhenCreating($data);
- return $response;
- }
- $this->updates = $this->prepareInsert($this->updates);
- $id = $this->repository->store($this);
- $this->builder->setResourceId($id);
- if (($response = $this->callSaved())) {
- return $response;
- }
- return $this->redirect(
- $this->getRedirectUrl($id, $redirectTo),
- trans('admin.save_succeeded')
- );
- }
- /**
- * Get ajax response.
- *
- * @param $message
- * @param null $redirect
- * @param bool $status
- * @return bool|\Illuminate\Http\JsonResponse
- */
- public function ajaxResponse($message, $redirect = null, bool $status = true)
- {
- if ($this->isAjaxRequest()) {
- return response()->json([
- 'status' => $status,
- 'message' => $message,
- 'redirect' => $redirect,
- ]);
- }
- return false;
- }
- /**
- * ajax but not pjax
- *
- * @return bool
- */
- public function isAjaxRequest()
- {
- return $this->request->ajax() && ! $this->request->pjax();
- }
- /**
- * Prepare input data for insert or update.
- *
- * @param array $data
- *
- * @return Response|null
- */
- protected function prepare($data = [])
- {
- $this->inputs = array_merge($this->removeIgnoredFields($data), $this->inputs);
- if (($response = $this->callSaving()) instanceof Response) {
- return $response;
- }
- $this->updates = $this->inputs;
- }
- /**
- * Remove ignored fields from input.
- *
- * @param array $input
- *
- * @return array
- */
- protected function removeIgnoredFields($input)
- {
- Arr::forget($input, $this->ignored);
- return $input;
- }
- /**
- * Get data for insert or update.
- *
- * @return array
- */
- public function getUpdates(): array
- {
- return $this->updates;
- }
- /**
- * Set data for insert or update.
- *
- * @param array $updates
- * @return $this
- */
- public function setUpdates(array $updates)
- {
- $this->updates = array_merge($this->updates, $updates);
- return $this;
- }
- /**
- * Handle orderable update.
- *
- * @param int $id
- * @param array $input
- *
- * @return bool||Response
- */
- protected function handleOrderable(array $input = [])
- {
- if (array_key_exists('_orderable', $input)) {
- $input['_orderable'] == 1 ? $this->repository->moveOrderUp() : $this->repository->moveOrderDown();
- return $this->ajaxResponse(__('admin.update_succeeded'));
- }
- }
- /**
- * 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
- )
- {
- $data = $data ?: $this->request->all();
- $this->builder->setResourceId($id);
- $this->builder->setMode(Builder::MODE_EDIT);
- $this->build();
- if (($response = $this->callSubmitted())) {
- return $response;
- }
- if ($uploadFileResponse = $this->handleUploadFile($data)) {
- return $uploadFileResponse;
- }
- $isEditable = $this->isEditable($data);
- $data = $this->handleEditable($data);
- $data = $this->handleFileDelete($data);
- $this->setModel(new Fluent($this->repository->getDataWhenUpdating($this)));
- $this->setFieldOriginalValue();
- if ($response = $this->handleOrderable($data)) {
- return $response;
- }
- // Handle validation errors.
- if ($validationMessages = $this->validationMessages($data)) {
- return $this->makeValidationErrorsResponse(
- $isEditable ? Arr::dot($validationMessages->toArray()) : $validationMessages
- );
- }
- if (($response = $this->prepare($data))) {
- return $response;
- }
- $this->updates = $this->prepareUpdate($this->updates);
- $this->repository->update($this);
- if (($result = $this->callSaved())) {
- return $result;
- }
- return $this->redirect(
- $this->getRedirectUrl($id, $redirectTo),
- trans('admin.update_succeeded')
- );
- }
- /**
- * @param array|MessageBag $validationMessages
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
- */
- protected function makeValidationErrorsResponse($validationMessages)
- {
- if (! $this->isAjaxRequest()) {
- return back()->withInput()->withErrors($validationMessages);
- }
- return response()->json([
- 'errors' => is_array($validationMessages) ? $validationMessages : $validationMessages->getMessages()
- ], 422);
- }
- /**
- * Get redirect response.
- *
- * @param string $url
- * @param array|string $options
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
- */
- public function redirect(?string $url, $options = null)
- {
- if (is_string($options)) {
- $message = $options;
- $options = [];
- } else {
- $message = $options['message'] ?? null;
- }
- $status = (bool) ($options['status'] ?? true);
- if ($this->isAjaxRequest()) {
- $message = $message ?: trans('admin.save_succeeded');
- return $this->ajaxResponse($message, $url, $status);
- }
- $status = (int) ($options['status_code'] ?? 302);
- if ($message) {
- admin_alert($message);
- }
- return redirect($url, $status);
- }
- /**
- * @param $key
- * @param $redirectTo
- * @return string|false
- */
- public function getRedirectUrl($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 false;
- }
- 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
- * @param bool $oneToOneRelation If column is one-to-one relation.
- *
- * @return array
- */
- public function prepareUpdate(array $updates, $oneToOneRelation = false)
- {
- $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;
- }
- if ($this->invalidColumn($columns, $oneToOneRelation)) {
- 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;
- }
- /**
- * @param string|array $columns
- * @param bool $oneToOneRelation
- *
- * @return bool
- */
- protected function invalidColumn($columns, $oneToOneRelation = false)
- {
- foreach ((array) $columns as $column) {
- if ((!$oneToOneRelation && Str::contains($column, '.')) ||
- ($oneToOneRelation && !Str::contains($column, '.'))) {
- return true;
- }
- }
- return false;
- }
- /**
- * 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
- *
- */
- 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 getKeyName()
- {
- return $this->repository->getKeyName();
- }
- /**
- * @return Repository
- */
- public function getRepository(): Repository
- {
- return $this->repository;
- }
- /**
- * @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()
- {
- $values = $this->model->toArray();
- $this->builder->fields()->each(function (Field $field) use ($values) {
- $field->setOriginal($values);
- });
- }
- /**
- * Set all fields value in form.
- *
- * @return void
- */
- protected function setFieldValue()
- {
- $this->callEditing();
- $data = $this->model->toArray();
- $this->builder->fields()->each(function (Field $field) use ($data) {
- if (!in_array($field->column(), $this->ignored)) {
- $field->fill($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()
- {
- if ($isEditing = $this->isEditing()) {
- $this->setModel(new Fluent($this->repository->edit($this)));
- }
- $this->build();
- if ($isEditing) {
- $this->setFieldValue();
- } else {
- $this->callCreating();
- }
- }
- /**
- * @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[] = $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 \Illuminate\Validation\Validator[] $validators
- *
- * @return MessageBag
- */
- protected function mergeValidationMessages($validators)
- {
- $messageBag = new MessageBag();
- foreach ($validators as $validator) {
- $messageBag = $messageBag->merge($validator->messages());
- }
- if ($this->validationMessages) {
- return $messageBag->merge($this->validationMessages);
- }
- return $messageBag;
- }
- /**
- * Set action for form.
- *
- * @param string $action
- *
- * @return $this
- */
- public function setAction($action)
- {
- $this->builder->setAction($action);
- return $this;
- }
- /**
- * @return string
- */
- public function getAction()
- {
- return $this->builder->getAction();
- }
- /**
- * Set field and label width in current form.
- *
- * @param int $fieldWidth
- * @param int $labelWidth
- *
- * @return $this
- */
- public function setWidth($fieldWidth = 8, $labelWidth = 2)
- {
- $this->builder->fields()->each(function ($field) use ($fieldWidth, $labelWidth) {
- /* @var Field $field */
- $field->setWidth($fieldWidth, $labelWidth);
- });
- $this->builder->setWidth($fieldWidth, $labelWidth);
- return $this;
- }
- /**
- * Set view for form.
- *
- * @param string $view
- *
- * @return $this
- */
- public function setView($view)
- {
- $this->builder->setView($view);
- return $this;
- }
- /**
- * Set title for form.
- *
- * @param string $title
- *
- * @return $this
- */
- public function setTitle($title = '')
- {
- $this->builder->setTitle($title);
- return $this;
- }
- /**
- * Add a row in form.
- *
- * @param Closure $callback
- *
- * @return $this
- */
- public function row(Closure $callback)
- {
- $this->rows[] = new Row($callback, $this);
- return $this;
- }
- /**
- * @return Row[]
- */
- public function getRows()
- {
- return $this->rows;
- }
- /**
- * Tools setting for form.
- *
- * @param Closure $callback
- * @return $this;
- */
- public function tools(Closure $callback)
- {
- $callback->call($this, $this->builder->getTools());
- 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->getFooter()->disableSubmit($disable);
- return $this;
- }
- /**
- * Disable form reset.
- *
- * @return $this
- */
- public function disableResetButton(bool $disable = true)
- {
- $this->builder->getFooter()->disableReset($disable);
- return $this;
- }
- /**
- * Disable View Checkbox on footer.
- *
- * @return $this
- */
- public function disableViewCheck(bool $disable = true)
- {
- $this->builder->getFooter()->disableViewCheck($disable);
- return $this;
- }
- /**
- * Disable Editing Checkbox on footer.
- *
- * @return $this
- */
- public function disableEditingCheck(bool $disable = true)
- {
- $this->builder->getFooter()->disableEditingCheck($disable);
- return $this;
- }
- /**
- * Disable Creating Checkbox on footer.
- *
- * @return $this
- */
- public function disableCreatingCheck(bool $disable = true)
- {
- $this->builder->getFooter()->disableCreatingCheck($disable);
- return $this;
- }
- /**
- * Disable `view` tool.
- *
- * @return $this
- */
- public function disableViewButton(bool $disable = true)
- {
- $this->builder->getTools()->disableView($disable);
- return $this;
- }
- /**
- * Disable `list` tool.
- *
- * @return $this
- */
- public function disableListButton(bool $disable = true)
- {
- $this->builder->getTools()->disableList($disable);
- return $this;
- }
- /**
- * Disable `delete` tool.
- *
- * @return $this
- */
- public function disableDeleteButton(bool $disable = true)
- {
- $this->builder->getTools()->disableDelete($disable);
- return $this;
- }
- /**
- * Footer setting for form.
- *
- * @param Closure $callback
- * @return $this
- */
- public function footer(Closure $callback)
- {
- call_user_func($callback, $this->builder->getFooter());
- return $this;
- }
- /**
- * Get current resource route url.
- *
- * @param int $slice
- *
- * @return string
- */
- public function getResource($slice = -2)
- {
- $path = $this->resource ?: app('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()->renderException($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
- */
- public function block(int $width, \Closure $callback)
- {
- $layout = $this->builder->layout();
- $layout->column($width, $callback($layout->form()));
- }
- /**
- * @param int $width
- * @return $this
- */
- public function setDefaultBlockWidth(int $width)
- {
- $this->builder->setDefaultBlockWidth($width);
- return $this;
- }
- /**
- * @return $this
- */
- protected function prepareModalForm()
- {
- ModalForm::prepare($this);
- return $this;
- }
- /**
- * @param Closure $callback
- * @return bool|void
- */
- public function inModal(\Closure $callback = null)
- {
- if (! $callback) {
- return ModalForm::is();
- }
- if (ModalForm::is()) {
- $callback($this);
- }
- }
- /**
- * Create a modal form.
- *
- * @param string|null $title
- * @return ModalForm
- */
- public static function modal(?string $title = null)
- {
- return new ModalForm($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 getExtensions()
- {
- 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 $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();
- }
- }
|