Catalyst::Manual::Tutorial::09_AdvancedCRUD::09_Fo
时间:2010-08-30 来源:horsley
sudo cpan HTML::FormHandler::Model::DBIC |
Makefile.PL 中也需添加:
requires 'HTML::FormHandler::Model::DBIC'; |
HTML::FormHandler 表单创建
在 controllers 中使用 FormHandler
FormHandler doen't have a Catalyst base controller, because interfacing to a form is only a couple of lines of code.
创建一个 Book 表单
创建目录 lib/MyApp/Form. 创建文件: lib/MyApp/Form/Book.pm:
package MyApp::Form::Book; |
添加一个 Action 用于显示和保存表单
文件 lib/MyApp/Controller/Books.pm 顶部添加:
use MyApp::Form::Book; |
添加方法:
sub create : Chained('base') PathPart('create') Args(0) { |
这两个方法其实可以合并,但我们后面编写 'edit' 的时候需要调用 'form',所以分离出来。
创建显示表单的模板页面
编辑 root/src/books/form.tt2 :
[% META title = 'Create/Update Book' %] |
添加一个 Create 链接
编辑 root/src/books/list.tt2 ,文件底部添加 :
... |
此链接用于指向 HTML::FormHandler-based 表单.
测试 HTML::FormHandler Create Form
用 Ctrl-C 杀掉服务进程(如果服务进程在的话),重启服务:
$ script/myapp_server.pl |
以用户 test01 登录(密码: mypass). 进入图书列表页面,点击刚加的 HTML::Formhandler "Create" 链接,填入以下内容:
Title = "Internetworking with TCP/IP Vol. II" |
点击提交, 会看到"Book created" 信息。
注意: 'Author' 为选择列表输入,只有数据库中存在的 authors 才能输入。 'ratings' 域只能输入整数。
Add Constraints
编辑 lib/MyApp/Form/Book.pm 。
限制 title 长度和设为必填:
has_field 'title' => ( minlength => 5, maxlength => 40, required => 1 ); |
设定 rating 的输入范围:
has_field 'rating' => ( type => 'Integer', range_start => 1, range_end => 5 ); |
'authors' 关系为 'many-to-many' ,所以这里我们设置为Multiple to,允许选择多个作者,同时设为必填:
has_field 'authors' => ( type => 'Multiple', label_column => 'last_name', |
注意: FormHandler 会自动的去除输入域的首尾空字符。你想实现更多的功能,参考这里 HTML::FormHandler::Manual。 Try Out the Updated Form
$ script/myapp_server.pl |
以用户 test01登录,尝试下各种错误输入,比如: 标题小于5个字符,非数字的 rating ,rating 为0或6,等等。还可以试下选择一个,两个,或者没有作者。
Create the 'edit' method
编辑 lib/MyApp/Controller/Books.pm 添加方法:
sub edit : Chained('object') PathPart('edit') Args(0) { |
编辑 root/src/books/list.tt2, 在 "Delete" 下添加 'edit' 链接:
<td> |
Try Out the Edit/Update Feature
$ script/myapp_server.pl |
以用户 test01登录,访问 http://localhost:3000/books/list . 点击 "Internetworking with TCP/IP Vol. II" 旁边的 "Edit" 链接,将 rating 改为 3,将标题的 "II" 改为 2,添加 Stevens 为第二作者 (通过点击选择添加), 然后提交。页面会返回到书目列表,能够看到提示信息"Book edited" 。你可以自行体验其他特性。
更多的 FormHandler 文档
HTML::FormHandler::Manual
HTML::FormHandler
#formhandler on irc.perl.org |
本章结束