Catalyst::Controller::FormBuilder 的使用
(2010-08-17 星期二)
Catalyst::Controller::FormBuilder 用于提供一个表单输入框,同 Moose 不兼容。
使用时需要去掉 Moose 语法,同时需要安装
Moo***::Emulate::Class::Accessor::Fast
测试环境:
os: winxp
perl: strawberry perl 5.12.1
padre: 0.68
catalyst: 5.80025
Moose: 1.09
一、如何去掉 Moose 语法
Moose 结构的 controller 结构如下:
package Test::Controller::Person; use Moose; use namespace::autoclean; BEGIN { extends 'Catalyst::Controller' }
sub default : Private { ... };
__PACKAGE__->meta->make_immutable; 1;
|
取消 Moose 结构的 controller 结构如下:
package Test::Controller::Person; use base 'Catalyst::Controller::FormBuilder','Catalyst::Controller';
sub default : Private { ... }; 1;
|
以上只需要将对应的 Moose 语句删除即可。
二、 Catalyst::Controller::FormBuilder 的具体使用
1、需要在 root/forms/controller/action 下创建对应的 .fb 文件
如对应 controller person 的 action edit ,需要建立 root/forms/person/edit.fb 文件,格式大致如下,注意缩进排版:
name: person_edit method: post fields: firstname: label: First Name type: text size: 30 required: 1 lastname: label: Last Name type: text size: 30 required: 1 |
2、编辑对应的 template 文件,以 TTSite 为例,编辑 root/src/person/edit.tt2 文件:
[% META title = "Edit a person" %] [% FormBuilder.render %] |
3、在 view 中需要启动 .tt2 支持。我的文件:lib/Test/View/HTML.pm,添加:
__PACKAGE__->config({ INCLUDE_PATH => [ Test->path_to( 'root', 'src' ), Test->path_to( 'root', 'lib' ) ], PRE_PROCESS => 'config/main', WRAPPER => 'site/wrapper', ERROR => 'error.tt2', ## 添加下面这一行 TEMPLATE_EXTENSION => '.tt2', TIMER => 0, render_die => 1, });
|
4、书写具体的 action,编辑文件: lib/Test/Controller/Person.pm:
sub edit : Local Form { my ( $self, $c, $id ) = @_; my $person = $c->model('TestDB::People')->find_or_new( { id => $id } ); if ( $self->formbuilder->submitted && $self->formbuilder->validate ) { # form was submitted and it validated
$person->firstname( $self->formbuilder->field('firstname') ); $person->lastname( $self->formbuilder->field('lastname') ); $person->update_or_insert; $c->stash->{message} = ( $id > 0 ? 'Updated ' : 'Added ' ) . $person->name; $c->forward('list'); } else { # first time through, or invalid form
if ( !$id ) { $c->stash->{message} = 'Adding a new person'; } $self->formbuilder->field( name => 'firstname', value => $person->firstname ); $self->formbuilder->field( name => 'lastname', value => $person->lastname ); } }
sub add : Local { my ( $self, $c ) = @_; $c->response->redirect( $c->uri_for('edit') ); # 如果希望在服务器端跳转,如下书写 #$c->stash->{template} = 'person/edit.tt2'; #$c->forward('edit', []); } |
完整例子程序:
阅读(862) | 评论(0) | 转发(2) |