我确信这种问题必须在cakephp(我最近开始使用)中很常见,但我还没有找到一个明确的答案.
在我的数据库中,我在一对多的关系中拥有称为客户和联系人的表格(Customer hasMany Contact; Contact belongsTo Customer).当我将记录添加到联系人表(/ contacts/add)时,我可以从包含数据库中所有客户的选择框中选择客户(customer_id).如何设置以便我可以先选择客户(/ customers/view/6),然后为该特定客户添加联系人(例如/ contacts/add/6); 然后从"添加联系人"表单中删除选择框(可能用隐藏的customer_id字段替换它)?
有几种方法可以做到这一点,但我认为最好的方法是使用命名参数.
基本上,在您的views/customers/view.ctp中,您将customer_id添加到contacts/add链接:
$html->link(__('Add contact', true), array('controller' => 'contacts', 'action' => 'add', 'customer_id' => $customer['Customer']['id']));
Run Code Online (Sandbox Code Playgroud)
并在您的views/contacts/add.ctp中检查命名参数并使用隐藏字段:
if (isset($this->params['named']['customer_id'])) {
echo $form->input('customer_id', array('type' => 'hidden', 'value' => $this->params['named']['customer_id']));
} else {
echo $form->input('customer_id');
}
Run Code Online (Sandbox Code Playgroud)
或已选择合适客户的选择:
echo $form->input('customer_id', array('selected' => @$this->params['named']['customer_id']));
Run Code Online (Sandbox Code Playgroud)