как вставить значение динамических полей ввода в таблицу mysql с помощью cakephp2.8.5

#cakephp

#cakephp

Вопрос:

Пожалуйста, кто-нибудь, помогите мне, заранее спасибо, я новичок в Cakephp. Я использую версию Cakephp 2.8.5. В моем проекте у меня есть форма, в которой я выбираю пользователя из выпадающего списка. При выборе пользователя ниже появятся текстовые поля с названием курса и ценой. Это делается с помощью jquery.

Но моя проблема в том, как вставить имя пользователя, название курса и цену в базу данных mysql в качестве примера

             column 1  | column2                | column 3
            ragith      ITIL Foundation, CAPM    $200,$400
 

Моя страница просмотра — add_price.ctp
На этой странице вы найдете

                 <div class="form-group" id="divprice"> 

                   </div>  where the Course name and Price textboxes are displaying through jquery

                My full view page as below
                <head>
                <?php echo $this->Html->script('jquery.js'); ?>
                <script>
                 $(document).ready(function(){
                    $('#user').change(function(){         
                     var nameIdVal = $(this).val(); 
                     $.ajax({

                           type: "POST",
                           url: '/invl_exams/userprice',
                           cache: "false",
                           data: {userid:nameIdVal}, 
                           success : function(result){
                           //alert(result);
                           $('#divprice').html(result);                           

                           } 
                      }); 

                    });

                  });

             // using Ajax serialize to insert into DB

             $(document).ready(function(){
            $('.btn').click(function(event){ 
              event.preventDefault();                         

                 $.ajax({                            
                        method: "POST", 
                        url: "/invl_exams/submitprice",               
                        cache: "false",                   
                        data: $('#addPriceForm').serialize(),                  
                        dataType: "text",   
                        success: function(strMessage){
                        //alert(strMessage); 
                        //console.log(strMessage); 
                          //$('#msg').html(strMessage);  

                        },
                        error: function(strMessage){
                          //alert('error'); 
                          console.log('error');    
                        }            
                     });     

                    clearData();              
            });            
          });

      function clearData()
      {
        $('#addPriceForm :input').each(function(){
           $(this).val('');    

        });         
      }    
                </script>
                </head>
                <body>
                <div id="content">
                <div class="col-md-3">
                  <div id="msg"></div>
                 <form class="form-horizontal" role="form" accept-charset="utf-8" method="post" id="ExamAddExamForm"  action="/invl_exams/users/priceSubmit">  
                 <div style="display:none;"><input type="hidden" value="POST" name="_method"></div>

                  <div class="form-group">
                    <label for="ExamUsername">Users</label>  
                    <select class="form-control" required="required" id="user" name="data[Exam][userid][]"> 
                     <option value="">-- Select --</option>
                    <?php foreach($users as $username): ?>   
                     <option value="<?php echo $username['users']['id']?>"><?php echo $username['users']['username']?>
                     </option>
                    <?php endforeach;  ?> 
                    </select> 
                    <label id="ExamUsername-error" class="error" for="ExamUsername"></label>       
                  </div>

                   <!--On selecting username showing the Courses with price textboxes in this id here -->  
                   <div class="form-group" id="divprice"> 

                   </div>

                  <div class="form-group">  
                    <button class="btn btn-default">Submit</button> 
                  </div>
                </form>
                </div><br class="clearall">
                </div>

                </body>

                routes.php

                Router::connect('/userprice', array('controller' => 'users', 'action' => 'showprice'));

Router::connect('/submitprice', array('controller' => 'users', 'action' => 'price_submit'));

                Controller Page is UsersController.php

                <?php
                App::uses('CakeEmail', 'Network/Email');
                class UsersController extends AppController
                {
                   public function showprice()
                   {
                      $this->loadModel('Exam');   
                      $id = $_POST['userid'];
                      //echo $id;
                      //die();        
                      if($id!=0)  
                      {  

                         $allPrice = $this->Exam->query("select * from exams where username = $id");   

                        $total_price = $allPrice[0]['exams']['exam'];                  
                         $price = explode(',',$total_price);                    

                //This table will be displayed after selecting the user from combobox

                         echo "<table class='tblrow' width='450px'>";  
                         for($i=0;$i<count($price);$i  ) 
                         {
                          //echo $price[$i];
                          echo "<tr>";
                          echo "<td><b>Course:</b><input type='' name='course[]' value='$price[$i]'></td>";
                          echo "<td><b>Price:</b><input type='text' name='price[]' value=''></td>";
                          echo "</tr>";
                          echo "<tr><td>amp;nbsp;</td></tr>"; 
                         }
                         echo "</table>";                      
                      }
                      else 
                      {
                        echo "No results found";                   
                      }

                       die();                  
                   }

         // This function is for inserting into the Mysql database table       
         public function price_submit() 
          {            
            // print_r($_POST);
             if(isset($_POST['data'])) 
             {            
                 $this->loadModel('Price');
                 $priceData = $_POST['data']; 
                 $this->Price->create();
                 if($this->Price->save($priceData))
                 {
                   echo "Data added successfully";  

                 }           
              }     

             $this->loadModel('User');
             //$userData = $this->User->find('all');
             $userData =  $this->User->query("select * from users where id!= 15 and id!= 8");     
             $this->set('users',$userData);            
          }                  
                }

                Model page is User.ctp

                <?php
                //App::uses ('AppModel','Model'); 
                class User extends AppModel{

                  public $validate = array(
                        'username' => array(

                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Username is required'
                            ),
                            'isUnique' => array(
                            'rule' => 'isUnique',
                            'message' => 'This username has already been taken') 

                        ),        
                        'password' => array(

                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'A password is required' 
                            ),
                           'isUnique' => array(
                            'rule' => 'isUnique',
                            'message' => 'Password has already been taken')  
                        ), 
                        'full_name' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Full name is required' 
                            )
                        ),
                        /*'role' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Role is required'   
                            )
                        ) */
                       'email' => array(
                       array(
                        'rule' => array('email'),
                        'massage' => 'Please enter a valid email address',
                             ),
                          ), 
                          'secondary_email' => array(
                       array(
                        'rule' => array('email'),
                        'massage' => 'Please enter a valid email address',
                             ),
                          ),      
                      'phone' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Phone is required'  
                            )
                        ),
                        'secondary_phone' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Phone is required'  
                            )
                        ),
                        'location' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Loacation is required'  
                            )
                        ),
                        'business_name' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Business Name is required'  
                            )
                        ),
                        'document' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Document is required'  
                            )
                        ),
                        'doc_file' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Document is required'  
                            )
                        ),
                        'pname' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Name is required'  
                            )
                        ),
                        'pemail' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Please enter a Valid Email Id'  
                            )
                        ),
                        'pOfc_phone' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Please enter a Phone Number'  
                            )
                        ),
                        'pdesignation' => array(
                            'required' => array(
                                'rule' => 'notBlank',
                                'message' => 'Designation is Required'  
                            )
                        ),                    
                    );                    
                } 


                ?>
 

Комментарии:

1. как работает ваша функция сохранения в контроллере??

2. На самом деле я использовал сериализацию формы ajax для вставки в базу данных Mysql

3. Вы можете использовать serialize, но вам все равно нужна функция для сохранения ваших данных … если url: ‘/ invl_exams/userprice’ — это ваш URL, тогда должна быть логика для сохранения ваших значений..

4. то, что вы делаете, лучше, поскольку оно не перезагружает боузер .. но вы должны хорошо отладить и выяснить, поступает ли ваш запрос в cntroller.. Это будет легко, если вы будете следовать соглашению cakephp..

5. Если событие щелчка не работает, вы можете попробовать отправить событие..