List with multiple checkbox

4 0
8
Viewed: 43 701 times
Version: Unknown (update)
Category: Tutorials
    Written by: matkaz matkaz
    Updated by: matkaz matkaz
    Created: Aug 18, 2010
    Updated: 15 years ago

    You are viewing revision #2 of this wiki article.
    This is the latest version of this article.
    You may want to see the changes made in this revision.

    « previous (#1)

    It is a common case coders often come accross. For example the purpose of these checkbox is to mark records to be deleted

    First of all lets define a very useful 'polymorphic' form. I am sure you will use it a lot now !

    <?php
    /**
     * PolymorphicForm.php in 'models' directory
     */
    class PolymorphicForm extends CFormModel
    {
      private $data = array();
    
      public function __get($key) {
        return (isset($this->data[$key]) ? $this->data[$key] : null);
      }
    
      public function __set($key, $value) {
        $this->data[$key] = $value;
      }
    }
    ?>
    

    Continuing with models, lets define a table 'Example' with fields : keyExample, Field_one, Field_two. You know how to do it don't you ? ...

    Then in the controller ExampleAction.php, the action dealing with the list of this table 'Example'

    ...
    // an over simplified 'list' action	
    public function actionList ()
    {
      $form = new PolymorphicForm;
    
      $this->render("list", array(
        "models" => Example::model()->findAll(),
        "form"   => $form, 
      ));
    }
    ...
    

    Then the view defined in file list.php

    <script language="javascript">
      function byebye ()
      {
        // need a confirmation before submiting
        if (confirm('Are you sure ?'))			
          $("#myForm").submit ();
      }
    
      $(document).ready(function(){
        // powerful jquery ! Clicking on the checkbox 'checkAll' change the state of all checkbox  
        $('.checkAll').click(function () {
          $("input[type='checkbox']:not([disabled='disabled'])").attr('checked', this.checked);
        });
      });
    </script>
    
    <?php echo CHtml::beginForm("index.php?r=Example/delete", "post", array("id"=>"myForm")); ?>
    
    <table>
      <tr>
        <th><?php echo "Blabla" ?></th>
        <th><?php echo "Blabla bis"; ?></th>
        <th>
    	All <?php echo CHtml::activeCheckBox($form, "checkAll", array ("class" => "checkAll")); ?>
    	<button
      	  type="button"				
    	  onClick="byebye()"
    	>
    	  Delete
    	</button>
        </th>
      </tr>
    
      <?php foreach($models as $n=>$rec): ?>
      <tr>
        <td>
    	<?php echo CHtml::encode($rec->Field_one); ?>
        </td>
        <td>
    	<?php echo CHtml::encode($rec->Field_two); ?>
        </td>
        <td>
    	<?php echo CHtml::activeCheckBox($form, "checkRecord_$rec->keyExample"); ?>
        </td>
      </tr>
      <?php endforeach; ?>
    
    </table>
    <?php echo CHtml::endForm(); ?>
    
    

    Finally the trick to deal with these checkboxs in ExampleAction.php

    ...
    /**
    * Deletes a range of model
    * If deletion is successful, the browser will be redirected to the "list" page.
    */
    public function actionDelete()
    {
      // I want a post	
      if(Yii::app()->request->isPostRequest)
      {
        // parse $_POST variables
        foreach($_POST["PolymorphicForm"] as $key => $val) {
          // is one a these checkbox ?
          if (strstr ($key, "checkRecord")) {
            // checkbox in state checked ?
            if ($val == 1) {
              // get the key of the record
              $ar = explode ("_", $key);
              // deleting record 
              $model = Example::model()->findByPk ($ar[1])->delete ();
            }
          }
        }
        $this->redirect(array("list"));
      }	
      else
        throw new CHttpException(400,"Invalid request. Please do not repeat this request again.");
    }
    
    ...
    

    The result can be tested, calling http://myHttpServer/myApp?r=Example/list

    I hope this will be useful for some of the Yii coders.