thehiredgun / formkit
用于管理Laravel中数据提交和表单的合并前后端包
v0.8.0
2017-11-21 01:18 UTC
Requires
- php: >=7.0.0
- laravel/framework: ^5.4
This package is not auto-updated.
Last update: 2024-09-29 02:26:56 UTC
README
一套帮助管理Laravel中表单提交的精美工具
简介
FormKit是一个包含两个部分的包
- FormKit\SubmissionKit大大简化了在后台管理数据提交和表单所需的工作
- FormKit\TemplateKit大大减少了使用Blade & Bootstrap构建外观优雅的表单所需的前端模板量
- 结合使用,开发者可以快速构建出全面的解决方案来管理各种类型的数据,然后根据需要进行调整
安装
推荐通过Composer安装
composer require thehiredgun/formkit
或者,将其添加到您的composer.json文件中
"require": {
...,
"thehiredgun/formkit": "^1.0",
...
}
SubmissionKit 快速入门
用于传统Web应用程序
我们将使用单个(!)控制器方法来管理获取表单和处理表单提交:在routes/web.php中
Route::match(['get', 'post'], '/books/{book}/edit', 'BookController@form'); Route::match(['get', 'post'], '/books/add', 'BookController@form');
然后,在app/Http/Controllers/BookController.php中
... use App\Models\Eloquent\Book; use Illuminate\Http\Request; use TheHiredGun\FormKit\SubmissionKit\SubmissionKit; ... public function form(Request $request, Book $book = null) { // define your rules for the form. // multi-dimensional array is the preferred style, but you can use an array of strings, as well $rules = [ 'title' => [ 'required', 'string', ], 'author' => [ 'required', 'string', ], 'published_on' => [ 'required', 'date_format:Y-m-d', ], ]; $form = new SubmissionKit($request, $rules); // if the form has been submitted if ($request->isMethod('post')) { $form->validate(); // validate the form $form->setProperties($book); // set the properties on the $book where the values are valid if ($form->isValid()) { $book->save(); return redirect()->route('books'); } } return view('books.form', [ 'book' => $book, 'errors' => $submissionKit->getErrors(), ]); }
SubmissionKit 用于RESTful API的使用
在这里,我们将使用SubmissionKit在两个独立的方法中:一个用于POST,另一个用于PUT,在routes/api.php中
Route::post('/books', 'BookController@post'); Route::put('/books/{book}', 'BookController@put');
和BookController
... public function post(Request $request) { $rules = [ 'title' => [ 'required', 'string', ], 'author' => [ 'required', 'string', ], 'published_on' => [ 'required', 'date_format:Y-m-d', ], ]; $form = new SubmissionKit($request, $rules); $form->validate(); // validate the form $form->setProperties(new Book()); // set the properties on the $book where the values are valid if ($form->isValid()) { $book->save(); return response($book, 201); } return response([ 'errors' => $submissionKit->getErrors(), ], 400); } public function put(Request $request, Book $book) { $rules = [ 'title' => [ 'required', 'string', ], 'author' => [ 'required', 'string', ], 'published_on' => [ 'required', 'date_format:Y-m-d', ], ]; $form = new SubmissionKit($request, $rules); $form->validate(); // validate the form $form->setProperties($book); // set the properties on the $book where the values are valid if ($form->isValid()) { $book->save(); return response(200); } return response([ 'errors' => $submissionKit->getErrors(), ], 400); }