One checked check box only for each row - php

I have a table where by each row has 3 columns: name, enable, disable. The enable and disable column have a check box and as the name states, I am trying to do only one ticked checkbox per row. These are my codes (for each row and for the two columns) so far:
<?php foreach($customers as $customer):?>
<tr>
<td align="center"><?php echo $customer;?></td>
<?php
$check = FALSE;
if($user_customer != FALSE)
foreach($user_customer as $object)
foreach($object as $current_customer)
if($current_customer == $customer)
$check = TRUE;
?>
<td align='center'>
<?php
if($check == FALSE)
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
<td align='center'>
<?php
if($check == TRUE)
$data = array('name' => 'disable[]', 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => 'disable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
</tr>
<?php endforeach?>
After I submit my form it will store the values into the database accordingly however I do not want the user to be able to tick two check boxes at once. I tried using radio buttons but that limits to one check per column. I am trying to make it per row, any help?
P.S. I prefer not to use any Javascript.
EDIT, I added a counter for every row, so it'll be radio_1 for the first row etc, this is the part I edited:
<td align='center'>
<?php
if($check == FALSE)
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => TRUE);
echo form_radio($data);
?>
</td>
<td align='center'>
<?php
if($check == TRUE)
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => TRUE);
echo form_radio($data);
?>
</td>
EDIT 2, this was how I used to retrieve it in my controller function:
// These were the arrays that I assigned to each checkbox according to the column
$enable = $this->input->post('enable');
$disable = $this->input->post('disable');
// I used it for inserting and deleting values
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
$delete = $this->home_model->delete_customer($user_id, $disable);

Eventually I managed to solve my problem without using javascript.
First of all, in my view I use one hidden input and one checkbox input in the td. As you can see below, there are two different arrays. The hidden input array is named disable[] and the checkbox array which would contain all the checked checkbox value when form is submitted, is named enable[].
The hidden input array disable[] will always submit the values no matter what. So now we have all the customer names in the disable[] array.
View:
<td align='center'>
<input type="hidden" value="<?php echo $customer?>" name='disable[]'>
<?php
if($check == FALSE)
{
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => FALSE);
}
else
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
Now this is where I manipulate the arrays to get the values I want. In my case, my database table has only two columns which is the user_id and customer. I just add and delete everytime the user wants to enable or disable his/her customer. That's why I want to get both arrays.
Controller:
// Array containing selected/checked customers
$enable = $this->input->post('enable');
// Array containing all customers
$disable = $this->input->post('disable');
// Loop through selected customers
foreach($enable as $index => $value)
{
// Check if customer exists in database
if( $this->home_model->check_customer($user_id, $enable[$index]) )
{
// If exists, unset from enable to prevent duplicate insert
unset($enable[$index]);
}
/* Unset the remaining
(or all selected customers if it doesn't exists in DB)
selected customers from disable array */
$key = array_search($value, $disable);
unset($disable[$key]);
}
Now in the same controller, just do 3 simple checks to see whether the ensure which query to execute, like if there are customers to insert and delete, if there are only customers to insert, or if there are only customers to delete
// Check enable and disable array are not empty
if( ! empty($enable) && ! empty($disable) )
{
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
$delete = $this->home_model->delete_customer($user_id, $disable);
}
// If enable array is not empty but disable is empty, insert only
elseif( ! empty($enable) && empty($disable) )
{
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
}
// If enable is empty but disable is not empty, delete only
elseif( empty($enable) && ! empty($disable) )
{
$delete = $this->home_model->delete_customer($user_id, $disable);
}
/*** Proceed with whatever you want to do like go to new page etc ***/

Related

multi insert row & table codeigniter

i have 1 form new customer, which will insert into 2 table('tbcust' & 'tbcp'). I add button 'add new contact person' for insert row in table 'tcp', the button save in form will insert multiple table. table 'tbcust' is ok, but row 'nama_pt' in table 'tbcp' just passing 1 character.
CONTROLLER
public function post_multiple_table(){
$this->load->model('Multiple_model', 'multi_model', TRUE);
$cust_input_data = array();
//$cp_input_data = array();
$cust_input_data['nama_pt'] = $this->input->post('nama_pt');
$cust_input_data['tipe'] = $this->input->post('tipe');
$cust_input_data['alamat'] = $this->input->post('alamat');
$cust_input_data['email_cust'] = $this->input->post('email_cust');
$cust_input_data['notelp'] = $this->input->post('notelp');
$cust_input_data['nofax'] = $this->input->post('nofax');
$this->form_validation->set_rules('nama_orang[]', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nama_pt', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nohp[]', 'nohp', 'required|trim|xss_clean');
$this->form_validation->set_rules('email[]', 'email', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE){
echo validation_errors(); // tampilkan apabila ada error
}else{
$nm = $this->input->post('nama_orang');
$result = array();
foreach($nm AS $key => $val){
$result[] = array(
"nama_orang" => $_POST['nama_orang'][$key],
"nama_pt" => $_POST['nama_pt'][$key],
"nohp" => $_POST['nohp'][$key],
"email" => $_POST['email'][$key]
);
}
model
public function create_multiple_tabel($nama_pt, $nama_orang){
$this->db->insert('tbcust', $nama_pt);
$this->db->insert_batch('tbcp', $nama_orang);
}
and this the form & database
Check in table tbcp if your row nama_pt have length set 1, and put 15 or higher if need.

drop down value not being submitted to post array

Currently working with a php project in which I connect to a database in phpmyadmin. I'm currently implementing my one to many relationship and on one of my forms there is a drop down list with the list of categorys(foreign key) that a product in my database can have, however when I check the post array, and the array that contains all the values for the insert query everything is there except the foreign key.
Drop down list and array of values:
<select name="Category_ID">
<?php
foreach ($category as $cat) {
echo '<option value="' . $cat['ID'] . '">' . $cat['ID'] . '</option>';
}
?>
</select>
Array (
[authorName] => Hiroshi Sakurazaka
[bookName] => All You Need Is Kill
[costPrice] => 59
[sellPrice] => 99
[productCatID] => )
Could not insert book
Heres the file that converts the data in the formdata array into an object:
<?php
require_once 'product.php'; //Connecting to the product class
require_once 'Classes/productTable.php'; //Connecting to the TableGateway
require_once 'Classes/Connection.php'; //Connecting to the Connection class
require_once 'validateProduct.php';//Connecting to the product validation
require_once 'utils/functions.php';
//start_session();
//
//if (!is_logged_in()) {
// header("Location: login_form.php");
//}
echo '<pre>';
print_r($_POST);
echo '</pre>';
$formdata = array();
$errors = array();
validate($formdata, $errors);
if (empty($errors)) {
$AuthorName = $formdata['AuthorName'];
$BookName = $formdata['BookName'];
$costPrice = $formdata['CostPrice'];
$sellPrice = $formdata['sellPrice'];
$productCatID = $formdata['productCatID'];
echo '<pre>';
print_r($formdata);
echo 'Form Data array';
echo '</pre>';
$connection = Connection::getInstance();
$gateway = new productTable($connection);
$id = $gateway->insert($AuthorName, $BookName, $costPrice, $sellPrice, $productCatID);
header('Location: viewProducts.php');
}
else {
require 'createProductForm.php';
}
Heres the function in the table gateway that inserts the object into the database:
> public function insert($authorName, $bookName, $costPrice, $sellPrice,
> $productCatID) {
> $sql = "INSERT INTO "
> . "`product`(`AuthorName`, `BookName`, `CostPrice`, `sellPrice`, `productCatID`)"
> . " VALUES (:authorName,:bookName,:costPrice,:sellPrice,:productCatID)";
> $statement = $this->connection->prepare($sql);
> $params = array(
> "authorName" => $authorName,
> "bookName" => $bookName,
> "costPrice" => $costPrice,
> "sellPrice" => $sellPrice,
> "productCatID" => $productCatID
> );
> print_r($params);
> $status = $statement->execute($params);
>
> if (!$status) {
> die("Could not insert book");
> }
>
> $id = $this->connection->lastInsertId();
>
> return $id; }
can somebody please tell me what I'm missing?
Your select has the name of Category_ID not productCatID. If you expecting GET/POST data coming in under productCatID you need to name your select productCatID.
Solved my problem finally, so I'll post how I did it. For debuging my code and to see what values were being passed into the $POST array and the $formdata array, I used print_r to post each array if there was a problem and heres what I got:
$POST Array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[productCatID] => 4
[createProduct] => Create Product
)
form data array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[ProductCatID] =>
)
As you can see the $POST array was getting the value from the drop down list just fine, it was the form data array that was the issue. Embarrassingly the issue was just a simple typo error that was quickly resolved in my validation script.
With foreach you have to explicitly request access to the key, so if you don't, you'll only get the array values.
Just do this to debug (outside of the <select>):
foreach($category as $key=>$cat){
var_dump($cat['ID'], $cat, $key);
}
And I think you'll see where the actual data you need is.
(also, you seem to be running without strict errors and notices on, which is crucial for debugging and might show you some notices when array keys you try to access don't exist)

How to insert data to database from multiple select dropdown in codeigniter?

I have drop down which is look like the following
<select class="selectpicker form-control" multiple name="category[]">
<option value="1" id="MENTAL HEALTH">MENTAL HEALTH</option>
<option value="2" id="SUICIDE SUPPORT">SUICIDE SUPPORT</option>
<option value="3" id="HEALTH">HEALTH</option>
<option value="4" id="SUPPORT">SUPPORT</option>
</select>
In my controller I have the following code to get that data from the dropdown
public function save()
{
$ctgry= ($this->input->post('category'));
$orgName= ($this->input->post('InputName'));
$streetNo= ($this->input->post('StreetNo'));
$streetName= ($this->input->post('StreetName'));
$suburb= ($this->input->post('Suburb'));
$state= ($this->input->post('state'));
$postCode= ($this->input->post('PostCode'));
$count = count($ctgry);
$supprtGroup = array(
'name' => $orgName,
'street_no' => $streetNo,
'street' => $streetName,
'suburb' => $suburb,
'state' => $state,
'pc' => $postCode
);
$supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);
$j = 0;
i = 0;
$sc_id = 0
echo 'aa';//just for error checking purpose
if ($count > 1)
{
echo ' aa1';//just for error checking purpose
while ($i > $count)
{
echo ' aa2';//just for error checking purpose
$support_category = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $ctgry[$j]
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
$i++;
echo $sc_id;//just for error checking purpose
}
}
else
{
echo ' aa3';//just for error checking purpose
$support_category = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $ctgry[$j]
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
echo $sc_id;//just for error checking purpose
}
echo'bb';//just for error checking purpose
}
The following is my model class
function addSupportGroup($supprtGroup=NULL)
{
$this->db->insert('support_group', $supprtGroup);
return $this->db->insert_id();
}
function addSupportrCategory($support_category=NULL)
{
$this->db->insert('support_category', $support_category);
return $this->db->insert_id();
}
When select multiple values from dropdown the out put as follows
aa aa1bb
Could anyone give me an answer why this is happening, if it is a single value
selected from the dropdown its saving to the DB fine I search every similar
posts but couldn't find the answer.
I can't see where $count is defined in your question so I don't know what it's value is meant to be, however, if you are getting "aa1" as output you are saying that it's bigger than 1.
With your while() you're saying that $i must be bigger than $count but $i equals 0 so therefore the while loop won't start.
If you are just wanting to loop through the categories it would be easier to just:
$supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);
foreach ($ctgry as $cat) {
$insert = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $cat
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
}
This will work because the dropdown will always be picked up as an array.
You should also look at adding some validation to this!
Hope this helps!

Codeigniter BUG?: Form validation class getting confused with arrays

I need to create a form with the same group of fields (data is from database)
For example:
Group 1: Description field, Amount field, Others fields
Group 2: Description field, Amount field, Others fields
Group 3: Description field, Amount field, Others fields
So in my view I loop the database values:
$i = 0;
foreach ($data_from_db as $data) {
$description = array(
'name' => 'description[]',
'id' => 'description_field['.$i.']',
'value' => set_value('description[]', $data->description)
);
echo form_label(lang('reward_description'), 'description_field['.$i.']');
echo form_textarea($description);
echo form_error('description[]');
// more fields generated here in similar ways
$i++
}
In my controller I have:
$this->form_validation->set_rules('description[]', 'lang:project_edit_description', 'required');
// more similar rules here
According to the Codeigniter documentation this is the correct way to do it, but its no working correctly.
Codeigniter is getting confused with the validation messages.
For example, if I leave intentionally one of the descriptions fields empty and submit the form, I get the validation error message in all the groups (I get "the Description field is required" also for group 1, 2 and 3)
Just set rules for each indexed field. Following snippets show a working example (Improve it as you require):
Test controller:
function index()
{
if ($_POST)
{
foreach ($_POST as $key => $value)
{
if ($key == 'description' && is_array($value))
{
foreach ($value as $i => $vector)
{
// set rule for each index
$this->form_validation->set_rules('description[' . $i . ']', 'description ' . ($i + 1), 'trim|required');
}
}
}
$this->form_validation->run();
}
$this->load->view('test');
}
Test view views/test.php:
<?php
echo form_open('');
$data_from_db = $_POST ? $_POST['description'] : array('aaa', 'bbb', 'ccc');
$i = 0;
foreach ($data_from_db as $data)
{
$description = array(
'name' => 'description[]',
'value' => set_value('description[]', $data)
);
echo form_label('description ' . ($i + 1) . ':');
echo form_textarea($description);
echo '<br>';
// set error for each index
echo form_error('description[' . $i . ']');
// more fields generated here in similar ways
$i ++;
}
echo form_submit('mysubmit', 'Try it');
echo form_close();
?>
This code will show The description x field is required. only in the empty fields.

how to give permission to user on their own pods pages content with 'add' and 'edit' options only?

How to give permission to user on their own pods pages content with 'add' and 'edit' options only? I am using PHP, Apache, MySql and wordpress.
Please, give me code examples.
I am using following code:
<?php
$object = new Pod('dreams');
$object->ui = array('title' => 'My Pod' ,'add_fields' => array('name' ,'position','photo','bio','eom'),'edit_fields' => array('name' ,'position','photo','bio','eom','approved'));
//load Pod
$pod = new Pod('dreams');
if(current_user_can('administrator')) {
//set publicForm() visible fields for admins
$object->ui = array('title' => 'My Dream' ,'add_fields' => array('name' ,'position','photo','bio','eom'),'edit_fields' => array('name' ,'position','photo','bio','eom','approved'));
pods_ui_manage($object);
} else if(is_user_logged_in()) {
// Get the last URL variable
$slug = pods_url_variable('1');
$Edit = new Pod('team', $slug);
$name = $Edit->get_field('name');
$author_id = $Edit->get_field('author_id'); // GET AUTHOR FROM POD
$user_id = $current_user->ID;
global $current_user; // GET USER INFO
get_currentuserinfo();
$object->ui = array('title' => 'My Dream' ,'add_fields' => array('name' ,'position','photo','bio','eom'),'edit_fields' => array('name' ,'position','photo','bio','eom','approved'));
pods_ui_manage($object);
// $edit_listing = (($author_id == $current_user->ID) || (current_user_can('manage_options') == true) ? true : false); //
}; ?> <br/><br/>
<table>
<div><h1>Create a Dream</h1>
<p>What is this Dream, what do I want to do, accomplish, achieve?</p>
<p>Does this Dream involve someone else?</p>
<p>What tools are available to help achieve this Dream?</p>
<p>What steps can I take to help me achieve this Dream?</p>
<?php $pod->publicForm($fields); ?>
</div></table>
Now the user can also see and edit all other user posts. But this should not be so.
In your "ui" array, you want to add an additional 'where' and 'edit_where' clause.
'where' => 'p.author_id = ' . $user_id,
'edit_where' => array('author_id' => $user_id)

Categories