2013-02-24 67 views
1

假設我有3個表property_details,property_feature_details,property_feature_relations如何保存在cakephp hasMany關係中檢查的多個複選框值?

PropertyDetail模型與PropertyFeatureRelation具有許多關係。

當時saveing我的數據陣列看起來像這樣:

$this->data = array('PropertyDetail' => array('name'=>'xyz'),'PropertyFeatureRelation' => array('0' => array('feature_id'=>1),'1' => array('feature_id'=>5),'2' => array('feature_id'=>0),'3' => array('feature_id'=>0))); 

這些feature_ids值從複選框出來。那些被檢查他們是包含ids值和非檢查有0值。但是在子表中保存所有的數據爲零和非零。

其實我想保存那些只被選中的複選框值。請不要提供任何手動控制器邏輯。幫我。

回答

0

我解釋你這是有問題的答案,其調查我的例子

你可以使用如下多個複選框語法:

           $answers=array(); 
            $tmp_ans=$question['Answer']; 
            for($j=0;$j < count($tmp_ans);$j++) 
            $answers[$tmp_ans[$j]['id']]=$tmp_ans[$j]['answer'];    
            echo '<li>'; 
             echo $this->Form->input('Answer', array(
             'type' => 'select', 
             'name'=>'Answer['.$question['Question']['id'].']', 
             'class'=>'test', 
             'label'=>false, 
             'multiple' => 'checkbox', 
             'options' =>$answers , 
             )); 

            echo '</li>'; 

後,你將有隻有這些問題的答案,你已經檢查過別人不會發表任何帖子以便保存數據,您可以使用下面的語法

if(!empty($this->data['Answer'])){ 

       foreach ($this->data['Answer'] as $key=>$val): 

        if(!empty($val)): 
          if(is_array($val)): 

           foreach ($val as $ans): 
            $post_data['UserAnswer']['id']=''; 
            $post_data['UserAnswer']['survey_id']=$id; 
            $post_data['UserAnswer']['user_id']=$this->Auth->user('id'); 
            $post_data['UserAnswer']['question_id']=$key; 
            $post_data['UserAnswer']['answer_id']=$ans; 
            $this->UserAnswer->save($post_data['UserAnswer']); 
           endforeach; 
          else: 
            $post_data['UserAnswer']['id']=''; 
            $post_data['UserAnswer']['survey_id']=$id; 
            $post_data['UserAnswer']['user_id']=$this->Auth->user('id'); 
            $post_data['UserAnswer']['question_id']=$key; 
            $post_data['UserAnswer']['answer_id']=$val; 
            $this->UserAnswer->save($post_data['UserAnswer']); 

          endif; 

        endif; 
       endforeach; 

      } 
相關問題