Categories
php

laravel Form magic 方法

laravel 的form 对象 有magic方法 可以快速添加表单项

/**
 * Class Form.
 *
 * @method Field\Text           text($name, $label = '')
 * @method Field\Password       password($name, $label = '')
 * @method Field\Checkbox       checkbox($name, $label = '')
 * @method Field\CheckboxButton checkboxButton($name, $label = '')
 * @method Field\CheckboxCard   checkboxCard($name, $label = '')
 * @method Field\Radio          radio($name, $label = '')
 * @method Field\RadioButton    radioButton($name, $label = '')
 * @method Field\RadioCard      radioCard($name, $label = '')
 * @method Field\Select         select($name, $label = '')
 * @method Field\MultipleSelect multipleSelect($name, $label = '')
 * @method Field\Textarea       textarea($name, $label = '')
 * @method Field\Hidden         hidden($name, $label = '')
 * @method Field\Id             id($name, $label = '')
 * @method Field\Ip             ip($name, $label = '')
 * @method Field\Url            url($name, $label = '')
 * @method Field\Color          color($name, $label = '')
 * @method Field\Email          email($name, $label = '')
 * @method Field\Mobile         mobile($name, $label = '')
 * @method Field\Slider         slider($name, $label = '')
 * @method Field\File           file($name, $label = '')
 * @method Field\Image          image($name, $label = '')
 * @method Field\Date           date($name, $label = '')
 * @method Field\Datetime       datetime($name, $label = '')
 * @method Field\Time           time($name, $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($name, $label = '')
 * @method Field\Currency       currency($name, $label = '')
 * @method Field\SwitchField    switch($name, $label = '')
 * @method Field\Display        display($name, $label = '')
 * @method Field\Rate           rate($name, $label = '')
 * @method Field\Divider        divider($title = '')
 * @method Field\Decimal        decimal($column, $label = '')
 * @method Field\Html           html($html)
 * @method Field\Tags           tags($column, $label = '')
 * @method Field\Icon           icon($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 mixed                handle(Request $request)
 */

真实调用的方法

 /**
     * Generate a Field object and add to form builder if Field exists.
     *
     * @param string $method
     * @param array  $arguments
     *
     * @return Field|$this
     */
    public function __call($method, $arguments)
    {
        if (!$this->hasField($method)) {
            return $this;
        }

        $class = BaseForm::$availableFields[$method];

        $field = new $class(Arr::get($arguments, 0), array_slice($arguments, 1));

        return tap($field, function ($field) {
            $this->pushField($field);
        });
    }
Categories
php

laravel-admin 添加文件导入

安装excel 包

composer require maatwebsite/excel

新增一个action操作

php artisan admin:action WeinpinhuiUser/ImportAction --name="导入"
<?php

namespace App\Admin\Actions\WeinpinhuiUser;

use App\Imports\WeipinhuiUser\ImportWeipinhuiUser;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;


class ImportAction extends Action
{
    protected $selector = '.import-action';

    public function handle(Request $request)
    {
        // $request ...
        try{
            // $request ...
            $file = $request-> file('file');
            Excel::import(new ImportWeipinhuiUser(),$file);

            return $this->response()->success('数据导入成功')->refresh();
        }catch (\Exception $e){
            return $this->response()->error($e -> getMessage());
        }

    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-action">导入</a>
HTML;
    }

    public function form()
    {
        $this
            ->file('file', '请选择文件')
            ->options(['showPreview' => false,
                'allowedFileExtensions'=>['xlsx','xls'],
                'showUpload'=>false
            ]);
    }

    public function handleActionPromise()
    {
        $resolve = <<<SCRIPT
var actionResolverss = function (data) {
            $('.modal-footer').show()
            $('.tips').remove()
            var response = data[0];
            var target   = data[1];

            if (typeof response !== 'object') {
                return $.admin.swal({type: 'error', title: 'Oops!'});
            }

            var then = function (then) {
                if (then.action == 'refresh') {
                    $.admin.reload();
                }

                if (then.action == 'download') {
                    window.open(then.value, '_blank');
                }

                if (then.action == 'redirect') {
                    $.admin.redirect(then.value);
                }
            };

            if (typeof response.html === 'string') {
                target.html(response.html);
            }

            if (typeof response.swal === 'object') {
                $.admin.swal(response.swal);
            }

            if (typeof response.toastr === 'object') {
                $.admin.toastr[response.toastr.type](response.toastr.content, '', response.toastr.options);
            }

            if (response.then) {
              then(response.then);
            }
        };

        var actionCatcherss = function (request) {
            $('.modal-footer').show()
            $('.tips').remove()

            if (request && typeof request.responseJSON === 'object') {
                $.admin.toastr.error(request.responseJSON.message, '', {positionClass:"toast-bottom-center", timeOut: 10000}).css("width","500px")
            }
        };
SCRIPT;

        Admin::script($resolve);

        return <<<SCRIPT
         $('.modal-footer').hide()
         let html = `<div class='tips' style='color: blue;font-size: 15px;'>正在处理中<img src="data:image/gif;base64,R0lGODlhEAAQAPQAAP///1VVVfr6+np6eqysrFhYWG5ubuPj48TExGNjY6Ojo5iYmOzs7Lq6utjY2ISEhI6OjgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoLLoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYAqrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0UaFBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA=="><\/div>`
         $('.modal-header').append(html)
process.then(actionResolverss).catch(actionCatcherss);
SCRIPT;
    }
}

在列表工具按钮添加导入action

 $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportAction());
        });

界面渲染已完成

现在处理数据保存

添加数据保存对象

php artisan make:import WeipinHuiUser/ImportWeipinhuiUser --model=App\Models\WeipinhuiUser
<?php

namespace App\Imports\Member;

use App\Models\MemberModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class ImportWeinpinhuiUser implements ToModel,WithStartRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        // 0代表的是第一列 以此类推
        // $row 是每一行的数据
        return new WeipinhuiUser([
             'employee_no' => $row[0],
            'name' => $row[1]
        ]);
    }


    /**
     * 从第几行开始处理数据 就是不处理标题
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
}

注意:对应的model添加对应属性为可批量处理

class WeipinhuiUser extends Model
{
    use HasFactory;

    protected $fillable = ['employee_no', 'name'];
}
Categories
php

laravel-admin form

  protected function form()
    {

        $form = new Form(new InfusionTicket());

        $form->select('clinic_id', "诊所信息")->options(Clinic::all()->pluck('name', 'id'))->required();
        $form->date('date', __('Date'))->default(date('Y-m-d'))->required();
        $form->select('inject', __('Inject'))->options(['静脉输液'=>'静脉输液',"肌肉(皮下)注射"=>"肌肉(皮下)注射","抽血"=>"抽血"])->required();
        $form->number('ticket', __('Ticket'))->required();
        $form->select('time_index', __('时间'))->options(InfusionTicketController::$timeArray)->required();
        $form->hidden('time');

        $form->saving(function ($form){

            $timeIndex = $form->time_index;
            Log::debug('数据');
            Log::debug($timeIndex);
            $time = InfusionTicketController::$timeArray[$timeIndex];
            Log::debug($time);
            $form->time= $time;
        });
        //保存后回调
        $form->saved(function ($form){
            Log::debug("执行创建");
            $model = $form->model();
            $clinicId = $model->clinic_id;
            $inject = $model->inject=='静脉输液'?'jmsy':'default';
            $date = $model->date;
            $dateFormat = Carbon::parse($date)->format('Y-m-d');
            $timeIndex = $model->time_index;
            $ticket = $model->ticket;
            Redis::select(2);
            $key = 'infusion-tickets:'.$clinicId.':'.$inject.':'.$dateFormat.':'.$timeIndex;
            Log::info($key);
            Redis::set($key,$ticket);

        });

        return $form;
  

在form表单中设置time为不可见(一定要设置time 不然无法保存time信息)

上述代码在保存时 添加time信息

在保存后 把对应信息 存储在redis中

 protected function detail($id)
    {
        $show = new Show(InfusionTicket::findOrFail($id));
        $show->panel()->tools(function ( \Encore\Admin\Show\Tools $tools) {
            $tools->disableEdit();
        });

        $show->clinic('诊所信息', function ($clinic)  {
            $clinic->setResource('/admin/clinics/');
            $clinic->field('name',__('Name'));
        });
        $show->field('date', __('Date'));
        $show->field('inject', __('Inject'));
        $show->field('ticket', __('Ticket'));
        $show->field('time', __('Time'));

        return $show;
    }

详情页面 屏蔽“编辑”按钮

 public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static:: deleted(function (InfusionTicket $model) {
            Log::debug("模型删除");
            $clinicId = $model->clinic_id;
            $inject = $model->inject=='静脉输液'?'jmsy':'default';
            $date = $model->date;
            $dateFormat = Carbon::parse($date)->format('Y-m-d');
            $timeIndex = $model->time_index;
            Redis::select(2);
            $key = 'infusion-tickets:'.$clinicId.':'.$inject.':'.$dateFormat.':'.$timeIndex;
            Log::info($key);
            Redis::del($key);
        });
    }

在数据模型中 增加删除回调 删除redis值