我有一个带有“地址”表的Cakephp项目,其中包含以下结构:
CREATE TABLE `addresses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`company` varchar(50) NOT NULL,
`address1` varchar(50) NOT NULL,
`address2` varchar(50) DEFAULT NULL,
`city` varchar(40) NOT NULL,
`state` varchar(2) NOT NULL,
`country` varchar(2) NOT NULL,
`zip` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
)
此项目中有一个页面要求用户提供送货地址和帐单地址,并且我不确定如何构造表单输入的名称以允许在一个页面上显示相同数据库字段的多个实例< / p>
在View中,我试图使用别名来分隔地址字段的两个实例
即.-
<?=$this->Form->input('Shipaddress.zip', array('label' => 'Zip Code'));?>
...
<?=$this->Form->input('Billaddress.zip', array('label' => 'Zip Code'));?>
然后在视图中,我试图分离两个实例,验证两个实例,并设置适当的$ this-&gt; validationError值以正确显示错误到正确的字段视图
// place in arrays with proper model name ['Address']
$ship_array['Address'] = $this->request->data['Shipaddress'];
$bill_array['Address'] = $this->request->data['Billaddress'];
//Set Data to model, Validate Against model, change model name in validationErrors to match aliased fields, and remove validationErrors for ['Address']
$this->Address->set($ship_array);
$shipping_valid = $this->Address->validates(array('fieldList' => array('name', 'company', 'address1', 'address2', 'city', 'state', 'country', 'zip')));
$this->validationErrors['Shipaddress'] = $this->validationErrors['Address'];
$this->validationErrors['Address'] = array();
//Do it again for Billing Address fields
$this->Address->set($bill_array);
$billing_valid = $this->Address->validates(array('fieldList' => array('name', 'company', 'address1', 'address2', 'city', 'state', 'country', 'zip')));
$this->validationErrors['Billaddress'] = $this->validationErrors['Address'];
$this->validationErrors['Address'] = array();
不幸的是,这似乎不起作用,我担心我试图让这项工作走得太远......
有人可以正确指导我如何正确地完成这项工作吗?
答案 0 :(得分:0)
想出如何自己做...
//ShippingAddress.php
<?php
App::uses('Address', 'Model');
class ShippingAddress extends Address {
}
//BillingAddress.php
<?php
App::uses('Address', 'Model');
class BillingAddress extends Address {
}
为防止新模型使用以它们命名的表,我们编辑父Address.php并设置$ useTable,以便两个扩展模型都使用地址表
//Address.php
...
public $useTable = 'addresses';
...
那么只需将输入字段的两个实例插入到视图中......没有重命名模型,没有修改validationErrors,它只是起作用:)