2015-09-29 43 views
0

在我的形式,每一行都有它的提交按钮,你需要检查前的复选框,您可以通过其他错误它应该删除它。复选框阵列验证笨

问:我的复选框in_array,但如果我不检查框,然后按提交不通过笨form_validation错误。我已经使用$this->form_validation->set_rules('selected[]', 'Selected', 'required');但错误没有显示。

是什么使得它越来越form_validation错误工作的最佳解决方案?

查看

<?php echo form_open('admin/design/layout/delete'); ?> 
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?> 
<div class="table-responsive"> 
    <table class="table table-striped table-bordered table-hover"> 
     <thead> 
      <tr> 
       <td style="width: 1px;" class="text-center"> 
        <input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /> 
       </td> 
       <td>Layout Name</td> 
       <td class="text-right">Action</td> 
      </tr> 
     </thead> 
     <tbody> 
      <?php if ($layouts) { ?> 
       <?php foreach ($layouts as $layout) { ?> 
        <tr> 
         <td class="text-center"><?php if (in_array($layout['layout_id'], $selected)) { ?> 
           <input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" checked="checked" /> 
          <?php } else { ?> 
           <input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" /> 
          <?php } ?> 
         </td> 
         <td><?php echo $layout['name']; ?></td> 
         <td class="text-right"> 
          <button type="submit" class="btn btn-danger">Delete</button> 
          <a href="<?php echo $layout['edit']; ?>" class="btn btn-primary">Edit</a> 
         </td> 
        </tr> 
       <?php } ?> 
      <?php } else { ?> 

      <?php } ?> 
     </tbody> 
    </table> 
</div> 

</div> 
<?php echo form_close(); ?> 

控制器功能

public function delete() { 

    $this->load->library('form_validation'); 

    $this->form_validation->set_rules('selected[]', 'Selected', 'required'); 

    if ($this->form_validation->run() == FALSE) { 
     echo "Error"; 
     $this->get_list(); 
    } else { 
     $selected_post = $this->input->post('selected'); 
     if (isset($selected_post)) { 
      foreach ($selected_post as $layout_id) { 
      } 
      echo "Deleted $layout_id"; 
      $this->get_list(); 
     }   
    } 
} 
+0

尝试没有[]方盒子http://stackoverflow.com/questions/6179325/codeigniter-checkbox-array – Linus

+0

仍未显示错误。 – user4419336

回答

1

它不会每场验证。 selected[]选择的规则意味着,当您提交表单,它应该至少有一个选定的项目。现在你已经提交了独立提交表单的按钮,不管它们在dom中的哪个位置,以及选中了哪些复选框。 目前,它是相同的,因为你将有一个在最后提交按钮。

我想补充一些JavaScript,并设置如果未选中该复选框,可以禁用该字段:

<script> 
    $(function() { 
     $('input:checkbox').on('change', function() { 
      if($(this).is(':checked')) { 
       $(this).closest('tr').find('button:submit').prop('disabled', false); 
      } 
      else { 
       $(this).closest('tr').find('button:submit').prop('disabled', true); 
      } 
     }) 
    }) 
</script> 

并添加disabled到您的提交按钮:

<button type="submit" class="btn btn-danger" disabled>Delete</button>

这是不是服务器端验证,但可以实现防止未经检查的按钮复选框。