WinterCMS创建带有表单验证的数据录入组件Component

前一篇已经介绍过在WinterCMS的方法,那一篇是非常简单的创建了一个数据列表的调用,这篇内容创建一个进阶版的component,实现前端实现表单的验证和数据保存。

文件结构

核心文件 awardForm.php

components目录下创建awardfForm.php

<?php namespace Julian\Library\Components;
use Cms\Classes\ComponentBase;
use Input;
use Validator;
use ValidationException;
use Redirect;
use Julian\Library\Models\Award;
use Flash;

class AwardForm extends ComponentBase{
    public function componentDetails(){
        return [
            'name' => 'Award Form',
            'description' => 'Enter Awards'
        ];
    }

    public function onSave(){
        
        $validator = Validator::make(
            //Data
            [
                'award_title' => Input::get('award_title')
            ],
            //Rules
            [
                'award_title' => 'required|min:5'
            ]
        );

        if($validator->fails()){
            //Flash::error('Award title at least 5 characters');
            throw new ValidationException($validator);
        }else{
            $award = new Award();
            $award->award_title = Input::get('award_title');
            $award->slug = str_slug(Input::get('award_title'));
            $award->save();
            Flash::success('Award added!');
        }


    }
}

前端文件 /awardform/default.htm

components目录下创建/awardform/default.htm

<form data-request="onSave" data-request-validate data-request-flash>
    <label>Award Title</label>
    <input type="text" name="award_title">
    <span data-validate-for="award_title"></span>
    <button type="submit" data-attach-loading>Save Award</button>
</form>

注册Component

找到Plugin所在目录下的Plugin.php文件,找到registerComponents(),return[]中添加

'Julian\Library\Components\AwardForm' => 'awardform'

Post Comment