How to insert multiple value data in codeigniter - codeigniter

In my select option I have value with two numbers Example value="163, 162"
I have a model function where can insert the first value number which would be category id 163
Var Dump
array(2) { [0]=> string(3) "163" [1]=> string(4) " 162" }
Question: I need to add parent_id = " . $this->db->escape($category['parent_id']) . " but not sure how to get the second value number and set it as the parent_id = " . $this->db->escape($category['parent_id']) . " parent id would be example 162
Model Function
public function page_update($page_id, $data) {
$this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");
if (isset($data['categories'])) {
foreach ($data['categories'] as $category) {
//$data_sample = explode(',', $category['category_id']);
//var_dump($data_sample);
//exit;
$this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET
page_id = '" . (int)$page_id . "',
category_id = " . $this->db->escape($category['category_id']) . "
");
}
}
}
View
<div class="form-group">
<label class="col-sm-2">Category</label>
<div class="col-sm-10">
<select class="form-control" name="categories[1][category_id]">
<option value="0">-- No Category Required --</option>
<?php foreach ($categories as $category) {?>
<?php if ($category['category_id'] == $category_id) {?>
<option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>" selected="selected">
<?php echo $category['name'];?></option>
<?php } else { ?>
<option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
<?php }?>
</select>
</div>
</div>

It is quite easy and preferable to use Codeigniter syntax, in case you might want to have a look, this code does the same as #Arcanix answered but uses CI Active Record syntax,
public function page_update($page_id, $data)
{
$this->db->delete('page_to_category', array('page_id' => (int)$page_id));
if (isset($data['categories']))
{
foreach ($data['categories'] as $category)
{
$data_sample = array_map("trim",explode(',', $category['category_id']));
$insert_data = array(
'page_id' => (int)$page_id,
'category_id' => $this->db->escape($data_sample[0])
);
$this->db->insert('page_to_category', $insert_data);
}
}
}

The answer would be something like this:
public function page_update($page_id, $data) {
$this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");
if (isset($data['categories'])) {
foreach ($data['categories'] as $category) {
$data_sample = array_map("trim",explode(',', $category['category_id']));
//Here $data_sample[0] will always be your category id and $data_sample[1] will be your parent id
$this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET
page_id = '" . (int)$page_id . "',
category_id = " . $this->db->escape($data_sample[0]) . "
");
}
}
}
Here $data_sample[0] will always be your category id and $data_sample[1] will be your parent id

If you want to do multiple inserts, You can do it with active records. First create an array of datas which you want to insert, and then use insert_batch method
$insertdata = array(
array(
'email' => 'email' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'email' => 'some data' ,
'name' => 'some data' ,
'date' => 'some data '
)
);
$this->db->insert('mytable', $insertdata);
You can get more info from here Insert methods used in CodeIgniter

Related

Dependent dropdown, second dropdown not populated, Codeigniter

I have a dependent drop down that get the category on the first drop down and should get the subcategory on the second drop down but the subcategory drop down isn't populated. I have something like this in my Model:
public function category()
{
$response = array();
$this->search(array(), 'date_created');
$this->db->select('*');
$query = $this->db->get('categories');
$response = $query->result_array();
return $response;
}
public function sub_category($parent_id)
{
$query = $this->db->get_where('sub_categories', array('parent_id' => $parent_id));
return $query->result_array();
}
And then something like this on my Controller:
public function edit_product($id)
{
$data['title'] = 'Update Product';
$this->load->view('../admin/template/admin_header');
$products = new Admin_model;
$data['products'] = $products->edit_product($id);
$data['category'] = $this->Admin_model->category();
$data['subcategory'] = $this->Admin_model->sub_category($data['products']->category_id);
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/products/manage_product', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
public function insert_product()
{
$productData = array();
if ($this->input->post('productData')) {
$this->form_validation->set_rules('category_id', 'Category', 'required');
$this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required');
$this->form_validation->set_rules('product_name', 'Product Name', 'required');
$this->form_validation->set_rules('department', 'Department', 'required');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('status', 'Status', 'required');
if ($this->form_validation->run() == true) {
$ori_filename = $_FILES['product_image']['name'];
$update_image = time() . "" . str_replace(' ', '-', $ori_filename);
$config = [
'upload_path' => './images/products',
'allowed_types' => 'gif|jpg|png',
'file_name' => $update_image,
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('product_image')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view(base_url('admin/products'), $error);
} else {
$image = $this->upload->data('file_name');
$productData = array(
'category_id' => $this->input->post('category_id'),
'sub_category_id' => $this->input->post('sub_category_id'),
'product_name' => $this->input->post('product_name'),
'department' => $this->input->post('department'),
'description' => $this->input->post(htmlentities('description')),
'status' => $this->input->post('status'),
'upload_path' => $image
);
$img = new Admin_model;
$img->insert_product($productData);
$this->session->set_flashdata('status', 'Package InsertedSuccesfully');
redirect(base_url('admin/products'));
}
}
}
$data['title'] = 'Insert Product';
$data['category'] = $this->Admin_model->category();
$data['subcategory'] = $this->Admin_model->get_subcategory();
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/products/manage_product', $data);
$this->load->view('../admin/template/admin_footer');
}
And then the view:
<div class="form-group">
<label for="" class="control-label"> Category</label>
<select name="category_id" id="category" class="custom-select select">
<option value="">Select Category</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row['id'] . '"';
if (isset($products) && $row['id'] == $products->category_id) {
echo ' selected';
}
echo '>' . $row['category'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category_id" id="subcategory" class="custom-select select">
<option value="">Select Sub Category</option>
<?php
foreach ($subcategory as $row) {
echo '<option value="' . $row['id'] . '"';
if ($row['id'] == $products->sub_category_id) {
echo ' selected';
}
echo '>' . $row['sub_category'] . '</option>';
}
?>
</select>
</div>
And here's the script. I'm not really familiar at AJAX so i tried to ask and get answers here which helps me progress but I still can't populate the subcategory drop down.
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
console.log(parent_id)
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {
parent_id: parent_id
},
success: function(data) {
$('#subcategory').html(data);
console.log(data)
}
});
} else {
$('#subcategory').html('<option value="">Select Category First</option>');
}
});
});
Also, here's what I get in the console
The result from $this->Admin_model->sub_category(...) is an array.
echo works on string values only, which is why you're getting the error. You'll need to loop over the result array (in admin/get_subcategory) and print the values one by one. Also surround each value with an <option> tag so the result can be placed in the select box without further modification:
public function get_subcategory() {
if ($this->input->post('parent_id')) {
$subcategories = $this->Admin_model->sub_category($this->input->post('parent_id'));
foreach ($subcategories as $subcategory) {
echo '<option value="'.$subcategory['id'].'">'.$subcategory['sub_category'].'</option>';
}
}
}

Test Driven Laravel : Invalid Argument supplied for foreach

So i have a form with multiple fields like below
<ul class="list-group list-group-flush">
#foreach ($group as $perm)
<li class="list-group-item">{{$perm->name}}
<div class="float-right">
<select name="perms[{{$perm->id}}]" class="form-control">
<option value="1">Yes</option>
<option value="0" selected>No</option>
</select>
</div>
</li>
#endforeach
</ul>
My controller is like below
public function permission(int $id)
{
$permission = request()->perms;
foreach ($permission as $perm => $status)
{
if($status == 1)
{
//echo $perm . " " . $status;
$user_perm = User_perms::create([
'user_id' => $id,
'perm_id' => $perm,
]);
}
}
$user = Users::find($id);
return redirect($user->path());
}
This code does what I want but I have a test
public function permissions_applied_for_user()
{
$this->withoutExceptionHandling();
//create a user
$this->post('/users/add', $this->data());
$user = Users::first();
//first clear out all data from user_perm table for specific user
$response = $this->post('/users/permission/' . $user->id, [
'user_id' => $user->id,
'perm_id' => '1',
]);
$this->assertCount(1, User_perms::all());
$response->assertRedirect('/users/view/' . $user->id);
//$response->assertOk();
//second insert all new permissions into the table
}
which throws the exception invalid argument supplied for foreach any advice on what I'm doing wrong?

Magento: show admin product category in dropdown

I want to show the category selection as a drop down instead of it rendering with a +sign
magento/admin/product/new product product category selection
See below image for reference.
Here is the code, You can just create bellow function under the block or helper with your module.
function getCategoriesTreeView() {
// Get category collection
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
// Arrange categories in required array
$categoryList = array();
foreach ($categories as $catId => $category) {
if (isset($category['name'])) {
$categoryList[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $catId
);
}
}
return $categoryList;
}
Now its time for design, bellow is the code which will give you the category drop down.
<select id="categorylist" name="categorylist">
<option value="">Select Category</option>
<?php
$categoriesTreeView = getCategoriesTreeView();
foreach($categoriesTreeView as $value)
{
$catName = $value['label'];
$catId = $value['value'];
$catLevel = $value['level'];
$space = ' ';
for($i=1; $i<$catLevel; $i++){
$space = $space." ";
}
$catName = $space.$catName;
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $catName ?></option>
<?php
}
?>
</select>

CakePHP Js Helper - Update 3 Dropdown menus dynamically

i'm using CakePHP 2.6.1
I have a cakephp form to handle accesses with these 3 dropdown menues:
location->facility->department
I want them to be dynamic populated and so i followed this tutorial http://marnienickelson.com/2014/10/11/dynamic-dropdowns-with-cakephp-2-x/
It works well, except one little problem. If i change the "location", the "facility" Dropdown menu is filled correctly, but the "department" menu stays blank...
My AccessesController.php
public function add() {
if ($this->request->is('post')) {
$this->Access->create();
if ($this->Access->save($this->request->data)) {
$this->Session->setFlash(__('The access has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The access could not be saved. Please, try again.'));
}
}
$titles = $this->Access->Title->find('list');
$locations = $this->Access->Facility->Location->find('list');
$systems = $this->Access->System->find('list');
$this->set(compact('titles', 'locations', 'facilities', 'departments', 'systems'));
}
My get_by_location.ctp (and i have an equal file called get_by_facility.ctp)
<?php foreach ($facilities as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And at the end of my add.ctp
<?php
$this->Js->get('#AccessLocationId')->event('change',
$this->Js->request(array(
'controller'=>'facilities',
'action'=>'getByLocation'
), array(
'update'=>'#AccessFacilityId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
$this->Js->get('#AccessFacilityId')->event('change',
$this->Js->request(array(
'controller'=>'departments',
'action'=>'getByFacility'
), array(
'update'=>'#AccessDepartmentId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
I know the second event'change' isnt recognized and thats why my 3rd dropdown stays blank... Is there an other event then 'change'? Or could i put these two ajax requests in one?
This Blog helped me alot Euromarks blog
I just changed my get_by_location.ctp file:
<?php
if (!empty($facilities)) {
echo '<option value="">' . __('pleaseSelect') . '</option>';
foreach ($facilities as $k => $v) {
echo '<option value="' . $k . '">' . h($v) . '</option>';
}
} else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
So if first dropdown is changed, the second one will display "please select".

Codeigniter: Interdependent dropdown lists. Completed code

I have a series of interdependent select lists which work correctly outside CI. When I tried to implement it in Codeigniter, I am not coming on as the first selectlist is not populated, either the echoing is not properly code or I dont know what. This question here will refer to just the first select list, that is, you will not see any jquery, because the first gets populated directly from the database without any "function change".
so here are the modules:
VIEW
<?php echo form_open('control_form/add_all'); ?>
<label for="f_state">State<span class="red">*</span></label>
<select id="f_state" name="f_state">
<option value=""></option>
<?php
foreach($result as $row)
{
echo '<option value="' . $row->pais_id . '">' . $row->pais_name . '</option>';
}
?>
</select>
<label for="f_city">City<span class="red">*</span></label>
<!--this will be filled based on the tree selection above-->
<select id="f_city" name="f_city" id="f_city_label">
<option value=""></option>
</select>
<label for="f_membername">Member Name<span class="red">*</span></label>
<input type="text" name="f_membername"/>
<?php echo form_close(); ?>
CONTROL
public function add_all()
{
#Validate entry form information
$this->load->model('model_form','', TRUE);
$this->form_validation->set_rules('f_state', 'State', 'required');
$this->form_validation->set_rules('f_city', 'City', 'required');
$this->form_validation->set_rules('f_membername', 'Member Name', 'required');
$data['city'] = $this->model_form->get_state(); //gets the available groups for the dropdown
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_form_all', $data); # parece ser que vuelve a meter los mismos datos que tenia la Form
}
else
{
#Add Member to Database
$this->model_form->add_all();
$this->load->view('view_form_success');
}
}
MODEL
<?php
class Model_form extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_state()
{
$query = $this->db->query('SELECT pais_id, pais_name FROM pais');
return $query->result();
}
function add_all()
{
$v_state = $this->input->post('f_state');
$v_membername = $this->input->post('f_membername');
$data = array(
'pais_id' => NULL,
'pais_name' => $v_state
);
$this->db->insert('members', $data);
}
}
You are not sending $result to the view, you need something like:
$data['result'] = ...//get some data
$this->load->view('view_form_all',$data);
If the list you want to display is the cities list, then you need to change in your view:
foreach($city as $row)
{
echo '<option value="' . $row->pais_id . '">' . $row->pais_name . '</option>';
}
since in your controller you are doing:
$data['city'] = $this->model_form->get_state();

Resources