atk14 / zip-field
ZipField是用于在ATK14应用程序中输入和验证邮政编码的表单字段
v0.2.7
2024-08-15 16:51 UTC
Requires
- php: >=5.6.0
Requires (Dev)
- atk14/core: dev-master
- atk14/forms: dev-master
- atk14/tester: *
README
ZipField是用于在ATK14应用程序的表单中输入邮政编码的字段。
安装
只需使用Composer即可
cd path/to/your/atk14/project/
composer require atk14/zip-field
可选地,您可以将在项目中创建ZipField文件的符号链接
ln -s ../../vendor/atk14/zip-field/src/app/fields/zip_field.php app/fields/zip_field.php
在ATK14应用程序中的使用
ZipField有is_valid_for()方法,用于在所选国家/地区上下文中进行重新验证。
在表单中
<?php
// file: app/forms/users/create_new_form.php
class CreateNewForm extends ApplicationForm {
function set_up(){
// ...
$this->add_field("zip", new ZipField([
"label" => "ZIP Code",
]));
$this->add_field("country",new ChoiceField([
"label" => "Country",
"choices" => [
"CZ" => "Czech Republic",
"SK" => "Slovakia",
"AT" => "Austria",
"PL" => "Poland",
// ...
],
]));
}
}
在控制器中
<?php
// file: app/controllers/users_controller.php
class UsersController extends ApplicationController {
function create_new(){
// ...
if($this->request->post() && ($d = $this->form->validate($this->params))){
// postal code re-validation for the selected country
if(!$this->form->fields["zip"]->is_valid_for($d["country"],$d["zip"],$err)){
$this->form->set_error("zip",$err);
return;
}
$user = User::CreateNewRecord($d);
// ...
}
}
}
可以设置ZipField只接受来自一个特定国家的邮政编码。在这种情况下不需要重新验证。
<?php
// file: app/forms/users/create_new_form.php
class CreateNewForm extends ApplicationForm {
function set_up(){
// ...
$this->add_field("zip", new ZipField([
"label" => "ZIP Code",
"country" => "CZ"
]));
}
}
可以指定无效邮政编码或格式提示的错误消息
<?php
// file: app/forms/users/create_new_form.php
class CreateNewForm extends ApplicationForm {
function set_up(){
// ...
$this->add_field("zip", new ZipField([
"error_messages" => [
"invalid" => _("Invalid ZIP code"),
],
"format_hints" => [
"CZ" => _("Please use format NNN NN"),
"AT" => _("Please use format NNNN"),
],
]));
}
}
测试
composer update --dev
cd test
../vendor/bin/run_unit_tests