Yii 2.0隐藏字段值不能使用javascript修改

时间:2015-05-10 08:23:41

标签: yii yii2 yii-components yii2-advanced-app

在我的模型中,我有一个隐藏的字段。我正在使用javascript(jQuery)修改其值。但是当我将表单提交给模型时,它仍然包含其初始值而不是通过javascript修改的值。我已检查是否javascript正在修改值,并确认正在修改值。但是当提交表单时,它正在发送初始值。 代码如下:

<?php
/*Model -- wrong_answers is my hidden field*/
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;

class QuestionModel extends Model
{ 
    public $quiz_id = null; 
    public $question = '';
    public $choices = ''; 
    public $explanation ="";
    public $hints = array();
    public $correct_answer = "";
    public $wrong_answers = '{}';//when populating from already  entered data use {"a":"as"} format instead of {'a':'as'}
    public $wrong_answer = "";
    public function rules()
    {
    
        return [
            
            [['quiz_id'], 'safe']  , 
            [['question'], 'required']  ,  
            [['correct_answer'], 'required']  ,  
            [['wrong_answers'], 'safe']  ,      
            [['wrong_answer'], 'safe']  ,   
            [['explanation'],'required']
            
       ];
    }
    public function get_quiz($quiz_id) {
    	$ret = array();
	     $command =  Yii::$app->db->createCommand("CALL get_quiz(:qz_id)");
	     $command->bindParam(":qz_id", $this->quiz_id);
	      
	     $result = $command->queryAll(); 
	     if(sizeof($result) > 0)  {
		     $ret = $result[0] ; 
		     
	     }
	     return $ret;
        
    }
    public function save_question() {
    
    	$ret = false;
    	//echo "quiz- id is ".$this->quiz_id;
        $quiz_details = $this->get_quiz($this->quiz_id);
    	 if(sizeof($quiz_details)) {
    	 		$quiz_data = $quiz_details['quiz_data'];
    	 		$quiz_data   = json_decode($quiz_data); 
    	 		$choices = [];
    	 		echo $this->wrong_answers;
    	 		exit;
    	 		$wrong_answers_array = json_decode($this->wrong_answers);
    	 		if($this->wrong_answer)
    	 			array_push($wrong_answers_array, $this->wrong_answer);
    	 			print_r($wrong_answers_array);
    	 			exit;
    	 		foreach($wrong_answers_array as $wr_ans) {
	    	 		array_push($choices,array('choice'=>$wr_ans));
    	 		}
    	 		$question_data = array('question'=>$this->question,'explanation'=>$this->explanation,'choices'=>$choices);
    	 	 	$ret = false;     
    	 }  	     
    	 return $ret;
        
   
	    
    }
    
    public function getHint($key) {
	    return $this->hints[$key];
    }
    
}

  

Controller - actionAdd_question是动作

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter; 
use app\models\QuizModel;  
use app\models\QuestionModel;  
use yii\web\UploadedFile;

global $username;
class QuizController extends Controller
{ 
     
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    } 
    
     public function actionEntry()
    {
    }
     
    public function actionView_all() {
    	   $request = Yii::$app->request;
    	   $layout_params=array(
    			'username'=>'admin',
    			'sidebar_menu1_class' =>'active',
    			'sidebar_menu12_class' =>'active',
    			'dash_title' => 'Courses',
    			'dash_sub_title'=>'View all'
    			
    		);
    		
    		$message = '';
    		$data = array();
       		$layout_params['scripts'] = array("view-all-modules.js");
       		
	        /*$model = new ViewAllCompaniesModel();
       		$pagination_data = $model->getTotalCompanies();
       		 
       		$layout_params['js_variables'] = array(
       			'totalCompanyPages'=>$pagination_data['total_page_count'], 
       			'csrfToken' => "'".$request->csrfToken."'" ,
       			'csrfTokenName' => "'".$request->csrfParam."'"
       		
       		
       		);
       		*/
	     	return $this->render('view-all-modules', [
            	'layout_params'=>$layout_params,
            	'message' =>$message,
            	'data' =>$data
            ]);

    }
    
    public function actionAdd() {
	           	 
    	
    		$layout_params=array(
    			'username'=>'admin',
    			'sidebar_menu1_class' =>'active',
    			'sidebar_menu12_class' =>'active',
    			'dash_title' => 'Quiz',
    			'dash_sub_title'=>'Add new quiz'
    			
    		);
        $message = array();
        
        
        $request = Yii::$app->request;
    	$proceed = true;
    	$parent_course_id = null;
	    $req_params  = $_POST;  
    		 
    	 

        $layout_params['scripts'] = array("add-quiz.js");
        
        $model  = new QuizModel(); 
         
         if(!$model->quiz_id) {
         
	         if ($model->load($request->post()) && $model->validate()) {
                	$params = $request->post(); 
                
 
            
                  	 
	        	     
                		$model->save_quiz();
          
         	 
         	         	 
	        	    
	           
             
		        	 
          
		        	 $message['title'] = 'Wow !';
		        	 $message['body'] = 'Successfully added quiz '.$model->quiz_title;
		       
		       
		      } else {
			      
		      }
        } else {
	        
        }
         
        
                  
    	 return $this->render('add-quiz', ['model' => $model,
            	'layout_params'=>$layout_params,
            	'message' =>$message
        ]);
        //return $this->render('add-company',$data);
    }
    public function actionSave() {
	    //print_r($_POST);
    }
    public function actionAdd_question() {
    	print_r($_POST);
    	$layout_params=array(
    			'username'=>'admin',
    			'sidebar_menu1_class' =>'active',
    			'sidebar_menu12_class' =>'active',
    			'dash_title' => 'Quiz',
    			'dash_sub_title'=>'Add question'
    			
    		);
    	  $request = Yii::$app->request;
        $message = array();
    	   $layout_params['scripts'] = array("add-question.js");
        
    	   $model  = new QuestionModel(); 
    	   
	      if($request->get('q_id')) {
	         $model->quiz_id = $request->get('q_id');
	       	if ($model->load($request->post()) && $model->validate()) {
                	 $model->save_question();
            
               	 	
             } else {
	             echo "yo yo";
             }
             return $this->render('add-question', ['model' => $model,
               	 		'layout_params'=>$layout_params,
               	 		'message' =>$message
               	 ]);
	      
	      } else { 
	      }
	      
    }
    public function actionIndex()
    {         
    	$data = array(
    		'layout_params'=>array(
    		'username'=>'admin',
    		'sidebar_menu11_class' =>'active'
    	)
    	);//
	   
  
         
    }
     public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
 }

  

查看       

    /*Assigning the parameters to be accessible by layouts*/

  foreach($layout_params as $layout_param => $value) {

      $this->params[$layout_param] = $value;

   }
   ?>

    <div class="form-group">

    </div>

<div class="col-md-12">
<div class="box box-primary">
                <div class="box-header">
                  <h3 class="box-title">Add Question</h3>
                </div><!-- /.box-header -->
                <!-- form start -->


<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

                    <input type = 'hidden' id = 'test' name = 'test' />
                  <div class="box-body">
                  <?php if(isset($message)&&sizeof($message)): ?>
                    <div class="form-group">
                        <div class="callout callout-info  alert-dismissible">
                        <h4><?php if(isset($message['title']))echo $message['title'];?></h4>
                        <p>
                            <?php if(isset($message['body']))echo $message['body'];?>

                        </p>
                       </div>
                    </div>
                    <?php endif;?>

                    <div class="form-group"> 
                      <?= $form->field($model, 'question')->textInput(array('class'=>'form-control')); ?>
                    </div>





                    <div class="form-group">

                         <?= $form->field($model, 'correct_answer')->textInput(array("class"=>"form-control",'id'=>'correct_answer')); ?>
                        <?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?> 
                        <?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?> 

                     </div>  
                     <div class="form-group">

                         <?= $form->field($model, 'wrong_answer')->textInput(array("class"=>"form-control ",'id'=>'wrong_answer')); ?>
                          <button id = 'add-answer' type = "button">Add Another</button>
                        <?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?> 
                        <?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?> 

                     </div>  
                     <div class="form-group" id ='wrong-group'>
                         <h3>Wrong Answers</h3>
                         <!-- The following dummy html is used for generating html inside javascript -->
                         <ul class="edit-list-dummy" id ="edit-list-dummy">
                            <li> <button class="btn btn-danger" id = 'dummy-wrong-ans-delete' onClick = "deleteWrongAnswer(this.name)" type ="button">Delete</button>&nbsp;<span id ='dummy-wrong-answer'>Hello I am a wrong answer here</span>
                         </ul>
                         <ul class="edit-list"  id = 'wrong-answers'>
                          </ul>
                     </div>
                     <div class="form-group">

                         <?= $form->field($model, 'explanation')->textArea(array("class"=>"form-control",'id'=>'explanation')); ?>
                     </div>



                  </div><!-- /.box-body --> <div class="box-footer">
        <?= Html::submitButton('Save Question', ['class' => 'btn btn-primary','onclick'=>'this.preventDefault']) ?>                            

                  </div>
<?php ActiveForm::end(); ?>                
              </div>
</div>
  

Javascript - #wrong_answers是我隐藏的输入ID

var  wrongAnswers = {};//{1:answer1,2:answer2...};
var randCount = 0;//radom count for setting as wrongAnswers attribute
//initialise wrong answers json from database
$(document).ready(function() { 
    console.log($('#wrong_answers').val());
	 wrongAnswers =  jQuery.parseJSON($('#wrong_answers').val());
	 console.log(wrongAnswers);
	 $('#add-answer').click(function() {
	    var wrongAns = $('#wrong_answer').val().trim();
	    if(wrongAns) {
	        wrongAnswers[randCount] = wrongAns;
	        randCount++;
	        generateWrongAnswers();
	        $('#wrong_answer').val("");
	       // alert($('#wrong_answers').val());
	    }
	 });
	 
	 
	 
	  generateWrongAnswers();	
	 	 
	 	  	
}); 

function generateWrongAnswers() {
     
     $('#wrong-group').hide();
    var html = '';
    for(var wrongIdx in wrongAnswers) {
        //console.log("w is  ".wrongAnsIdx);
    	$('#dummy-wrong-answer').html(wrongAnswers[wrongIdx]);	
    	$('#dummy-wrong-ans-delete').attr('name',wrongIdx);
    	 
    	html += $('#edit-list-dummy').html(); 
    }
    if(html) { 
        $('#wrong-group').show();
    	$('#wrong-answers').html(html);
    }
    var jsonData = JSON.stringify(wrongAnswers);
   
   $('#wrong_answers').val(jsonData);
   // $('#test').val(jsonData);
    //$('#correct_answer').val("Mallu");
   // alert($('#wrong_answers').val());
}
function deleteWrongAnswer(idx) {
    delete wrongAnswers[idx];
    generateWrongAnswers() ;
}

1 个答案:

答案 0 :(得分:0)

Finall解决了它。问题是,我意外地包含了两个具有相同id的隐藏输入字段。删除了一个并解决了