问题:如果选择新的复选框,它将更新数据,但是当我取消选中所有现有复选框时,它将无法正常工作。即使我取消选中多个复选框并保留一个复选框,它仍然有效。当我选中所有未选中的复选框来更新数据时,它只是不起作用。任何建议将不胜感激
这是我正在使用get join table ID的模型:
public function getProfileCampaigns($campaignIds = true) {
$campaignData = array();
$campaignProfiles = Yii::app()->db->createCommand()->select('campaign_id')
->from('campaign_profiles')
->where('profile_id = :profile_id',array(':profile_id' => $this->profile_id))
->queryAll();
// Check if need to send only campaign ids
if ($campaignIds) {
foreach ($campaignProfiles as $campaignProfile) {
$campaignData[] = $campaignProfile['campaign_id'];
}
}
return $campaignData;
}
这是我执行更新操作的控制器:
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$model->setScenario(Profile::SCENARIO_UPDATE);
// Get active campaigns
$campaigns = Campaign::model()->findAll();
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
// Check if profile have any releated profile
$model->campaignIds = $model->getProfileCampaigns();
if(isset($_POST['Profile']))
{
$model->attributes=$_POST['Profile'];
if($model->validate()) {
$model->save();
// Check if any campaign choosed
if ($_POST['Profile']['campaignIds']) {
Yii::app()->db->createCommand()->delete('campaign_profiles', 'profile_id = :profile_id', array(':profile_id' => $model->profile_id));
foreach ($_POST['Profile']['campaignIds'] as $campaignId) {
$campaignProfile = new CampaignProfile();
$campaignProfile->setIsNewRecord(true);
$campaignProfile->campaign_id = $campaignId;
$campaignProfile->profile_id = $model->profile_id;
$campaignProfile->save();
}
Yii::app()->user->setFlash('success', 'The Profile was successfully updated.');
$this->redirect(array('update','id'=>$model->profile_id));
}
}
}
$this->render('update',array(
'model' => $model,
'campaignListData' =>$campaigns,
));
}
这是用于选择要更新的复选框的表格:
<div class="form-group">
<?php echo $form->labelEx($model,'campaignIds'); ?>
<div class="col-sm-9">
<?php echo $form->checkBoxList($model, 'campaignIds', CHtml::listData($campaignListData, 'id', 'name')); ?>
<?php echo $form->error($model,'campaignIds'); ?>
</div>
</div>
答案 0 :(得分:0)
这是因为仅将选定的复选框作为表单数据发送。如果未选中任何复选框,则不会发送任何数据,因此可能使用了模型的默认/旧值。
您可以使用uncheckValue
设置来定义未选中复选框时将发送的默认值:
<div class="form-group">
<?php echo $form->labelEx($model,'campaignIds'); ?>
<div class="col-sm-9">
<?php echo $form->checkBoxList(
$model,
'campaignIds',
CHtml::listData($campaignListData, 'id', 'name'),
['uncheckValue' => '']
); ?>
<?php echo $form->error($model,'campaignIds'); ?>
</div>
</div>
从1.1.7版本开始,提供了一个名为'uncheckValue'的特殊选项。它可用于设置未选中该复选框时将返回的值。默认情况下,此值为“”。在内部,将显示一个隐藏字段,因此当未选中该复选框时,我们仍然可以获得该值。如果将'uncheckValue'设置为NULL,则不会显示任何隐藏字段。
https://www.yiiframework.com/doc/api/1.1/CHtml#activeCheckBoxList-detail