我在舞者和舞蹈之间有 HABTM 关系。一切似乎都按预期进行,除了在 edit.ctp 上编辑我的舞蹈时,CakePHP 显示了一个下拉框,而不是我期望的多选框。让我疯狂的是,多选框以另一种方式与 edit.ctp 一起编辑舞者!我不明白为什么它可以以一种方式工作,但不能以另一种方式工作。
这是我的舞蹈模型,定义了舞蹈和舞者之间的关系:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasAndBelongsToMany associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'Dancer' => array(
'className' => 'Dancer',
'joinTable' => 'dancers_dances',
'foreignKey' => 'dance_id',
'associationForeignKey' => 'dancer_id',
'unique' => 'keepExisting',
)
);
这是我的舞蹈 Controller :
public function edit($id = null) {
if (!$this->Dance->exists($id)) {
throw new NotFoundException(__('Invalid dance'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Dance->save($this->request->data)) {
$this->Session->setFlash(__('The dance has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The dance could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Dance.' . $this->Dance->primaryKey => $id));
$this->request->data = $this->Dance->find('first', $options);
}
$users = $this->Dance->User->find('list');
$dancers = $this->Dance->Dancer->find('list');
$this->set(compact('users', 'dancers'));
}
这是我的舞蹈 View 的 edit.ctp
<div class="dances form">
<?php echo $this->Form->create('Dance'); ?>
<fieldset>
<legend><?php echo __('Edit Dance'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('dance_name');
echo $this->Form->input('users_id');
echo $this->Form->input('Dancers');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('Dance.id')), null, __('Are you sure you want to delete # %s?', $this->Form->value('Dance.id'))); ?></li>
<li><?php echo $this->Html->link(__('List Dances'), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Dancers'), array('controller' => 'dancers', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Dancers'), array('controller' => 'dancers', 'action' => 'add')); ?> </li>
</ul>
</div>
我认为相关的表格是: 舞者, 舞者舞蹈, 跳舞
在 dancers_dances 表上,我有以下列: ID, 舞者_id, dance_id
请告诉我更多信息是否有帮助。
提前致谢。
最佳答案
首先,您可以删除 HABTM 定义中的大多数设置,因为您已经在使用 Cake Conventions;
public $hasAndBelongsToMany = array(
'Dancer' => array(
'unique' => 'keepExisting',
)
);
但问题在于表单内输入的名称,该名称应该是单数,并以其相关的模型命名;
echo $this->Form->input('Dancer');
您可以在此处查看手册中的一些示例(在本节中查找“标签”示例):
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
关于forms - Cakephp 2.3.1 HABTM 编辑表单显示下拉框而不是多选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445529/