[eluser]Nezar[/eluser]
Hi all,
Maybe this is gonna be useful for some body :
1. Sql :
Code:
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`id`, `title`) VALUES
(1, 'Post1'),
(2, 'Post2'),
(3, 'Post3'),
(4, 'Post4'),
(5, 'Post5');
2. Create my_form_helper.php under application/helper
Code:
<?php
function MY_set_checkbox($name, $value, $source = null)
{
if(in_array($value, $source) && !$_POST){
return 'checked';
}
return set_checkbox($name, $value);
}
?>
3. Model :
<?php
Code:
class Post extends CI_Model
{
function getPosts()
{
$q = $this->db->get('posts');
$rows= array();
foreach($q->result() as $row)
{
$rows[] = $row;
}
return $rows;
}
}
4. Controller :
Code:
<?php
class Posts extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('post');
}
function index()
{
$this->load->libraries = array('database', 'form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('txt', 'E-Mail', 'required');
$this->form_validation->set_rules('chk', '', '');
$data = array();
$data['posts'] = $this->post->getPosts();
if ($this->form_validation->run() == FALSE)
{
$this->load->view('posts/index', $data);
}
else
{
echo "formsuccess";
$this->load->view('posts/index', $data);
}
}
}
5. View :
Code:
<?php echo form_open('posts'); ?>
<?php echo form_input('title', set_value('title')). '<br>'; ?>
<?php echo form_input('txt', set_value('txt')). '<br>'; ?>
<?php
foreach($posts as $post){
echo form_checkbox('chk[]', $post->id, MY_set_checkbox('chk', $post->id, array(2,5))) . $post->title. '<br>';
}
?>
<?php echo form_submit('submit', ' Save '); ?>
<?php echo form_close(); ?>
Code:
MY_set_checkbox Function takes 3 param :
Code:
1. The Checkbox name
2. Value
3. Array of values which maybe saved in your database