0

我有一个带有“地址”表的 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`)
)

这个项目中有一个页面要求用户提供送货地址和账单地址,我不确定如何构造表单输入的名称以允许同一数据库字段的多个实例在一个页面上

在视图中,我尝试使用别名来分隔地址字段的两个实例

IE-

<?=$this->Form->input('Shipaddress.zip', array('label' => 'Zip Code'));?>
...
<?=$this->Form->input('Billaddress.zip', array('label' => 'Zip Code'));?>

然后在视图中,我尝试分离两个实例,验证两者,并设置适当的 $this->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();

不幸的是,这似乎不起作用,而且我担心我已经走得太远试图让这项工作......

有人可以在正确的方向上给我一个正确的方向吗?

4

1 回答 1

0

Figured out how to do it on my own...

in /app/Model i created 'ShippingAddress.php' and 'BillingAddress.php', Both Extend "Address"

//ShippingAddress.php
<?php  
App::uses('Address', 'Model');
class ShippingAddress extends Address { 
} 

//BillingAddress.php
<?php  
App::uses('Address', 'Model');
class BillingAddress extends Address { 
} 

To prevent the new models from using tables named after them, we edit the parent Address.php and set $useTable so that both extended models use Addresses Table

//Address.php
...
public $useTable = 'addresses';
...

then its just a matter of inserting the two instances of the input fields into the view... no renaming models, no modifying validationErrors, it just works :)

于 2013-07-11T19:09:59.553 回答