Magento configuration product to custom laravel configurable product using ajax - laravel

Currently I am trying to convert Magento Configurable product to Custom Laravel configurable product.
In step one I am displaying all the attributes from backend
Step 1: Select Attributes
(Here I have displayed all the attributes from backend)
My view blade code:
<div class="container">
<div class="row p-b-35">
<div class="form-group">
#foreach($attributes as $attribute)
<div class="form-check complete">
<input type="checkbox" id="{{$attribute->id}}" name="attribute[]" value="{{$attribute->id}}">
<label for="{{$attribute->id}}">
{{$attribute->name}}
</label>
</div>
#endforeach
</div>
</div>
<button class="btn btn-cons btn-primary" id="stepOne">Next</button>
</div>
Once the user check the attribute I have use ajax to store the attribute id
Ajax code:
$('#stepOne').click(function(e){
e.preventDefault();
var attribute = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
attribute += $(this).val() + ",";
}
});
$.ajax({
url: "/configStepOne",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
attribute:attribute,
},
success:function(response){
$('#successMsg').show();
$('#stepOneResponse').append(response.html);
},
error: function(response) {
console.log(response.responseJSON.message);
},
});
});
In my controller method (configStepOne):
public function configStepOne(Request $request) {
if (!is_null(Session::get('attributes'))) {
Session::forget('attributes');
}
Session::put('attributes', $request->attribute);
$config_attribute_array = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
}
$html = "";
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$html .= '<p class="small hint-text m-b-20">'.$config_attr->name.'</p>';
foreach($config_attr->options as $option) {
$html .= '<div class="form-check complete">';
$html .= '<input type="checkbox" id="'.$config_attr->name. '-' .$option->id.'-'.$option->option.'" name="option[]" value="'.$option->id.'">';
$html .= '<label for="'.$config_attr->name.'-'.$option->id.'-'.$option->option.'">'.$option->option.'</label>';
$html .= '</div>';
}
$html .= '<br>';
}
return response()->json(['success'=>'Successfully', 'html' => $html]);
}
Here I am trying to get the attributes respective options from backend and append the response to blade view
Step 2: Attribute Values
In my blade view I have:
<div id="stepOneResponse">
</div>
<button class="btn btn-cons btn-primary" id="stepTwo">Next</button>
From Ajax append the blade view is updated as:
<div id="stepOneResponse">
<p class="small hint-text m-b-20">Color</p>
<div class="form-check complete"><input type="checkbox" id="Color-1-Red" name="option[]" value="1"><label for="Color-1-Red">Red</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-2-Black" name="option[]" value="2"><label for="Color-2-Black">Black</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-7-Blue" name="option[]" value="7"><label for="Color-7-Blue">Blue</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-8-Green" name="option[]" value="8"><label for="Color-8-Green">Green</label></div>
<br>
<p class="small hint-text m-b-20">Size</p>
<div class="form-check complete"><input type="checkbox" id="Size-3-XL" name="option[]" value="3"><label for="Size-3-XL">XL</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-4-SM" name="option[]" value="4"><label for="Size-4-SM">SM</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-9-medium" name="option[]" value="9"><label for="Size-9-medium">medium</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-10-Extra small" name="option[]" value="10"><label for="Size-10-Extra small">Extra small</label></div>
<br>
<p class="small hint-text m-b-20">Format</p>
<div class="form-check complete"><input type="checkbox" id="Format-13-Download" name="option[]" value="13"><label for="Format-13-Download">Download</label></div>
<div class="form-check complete"><input type="checkbox" id="Format-14-DVD" name="option[]" value="14"><label for="Format-14-DVD">DVD</label></div>
<br>
</div>
<button class="btn btn-cons btn-primary" id="stepTwo">Next</button>
Ajax code:
$('#stepTwo').click(function(e){
e.preventDefault();
var option = "";
var option_id = "";
$("#stepOneResponse :checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
option += $(this).val() + ",";
option_id += $(this).attr('id') + ",";
}
});
$.ajax({
url: "/configStepTwo",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
option:option,
option_id:option_id,
},
success:function(response){
$('#successMsg').show();
console.log(response);
$('#stepTwoImageResponse').append(response.imageHtml);
$('#stepTwoPriceResponse').append(response.priceHtml);
$('#stepTwoQtyResponse').append(response.qtyHtml);
$('#count').text(response.count);
},
error: function(response) {
console.log(response.responseJSON.message);
},
});
});
In controller method configStepTwo:
public function configStepTwo(Request $request) {
if (!is_null(Session::get('options'))) {
// Session::forget('option');
}
Session::put('options', $request->option);
Session::put('options_id', $request->option_id);
$config_attribute = "";
$config_attribute_opt_string = "";
$config_attribute_array = [];
$config_attribute_opt_array = [];
$config_attribute_opt_array_id = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
// dd($config_attribute_array);
}
if (!is_null(Session::get('options'))) {
$config_attribute_opt = Session::get('options');
$config_attribute_opt = substr($config_attribute_opt, 0, -1);
$config_attribute_opt_array = explode(',', $config_attribute_opt);
// dd($config_attribute_opt_array);
}
if (!is_null(Session::get('options_id'))) {
$config_attribute_opt_id = Session::get('options_id');
// $config_attribute_opt_id = strstr($config_attribute_opt_id, '-', true);
$config_attribute_opt_id = substr($config_attribute_opt_id, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_id);
}
foreach ($config_attribute_opt_array_id as $key => $value) {
$config_attribute_opt_string .= strstr($value, '-', true). ',';
// $config_attribute_opt_string .= $value. ',';
}
$config_attribute_opt_string = substr($config_attribute_opt_string, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_string);
$array_count = array_count_values($config_attribute_opt_array_id);
$count = 1;
foreach ($array_count as $key => $value) {
$count *= $value;
}
Session::put('count', $count);
$imageHtml = "";
$imageHtml .= '<div class="form-group col-lg-4" id="multi_config_image" style="display: none">
<label for="type">Select attribute </label>
<select name="image_attribute_id" class="form-control" id="image_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$imageHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$imageHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$imageHtml .= '<div id="image_option_id">';
$imageHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="file" name="option_image" class="form-control" >';
$imageHtml .= '</div>';
$imageHtml .= '</div>';
}
$imageHtml .= '</div>';
$priceHtml = "";
$priceHtml .= '<div class="form-group col-lg-4" id="multi_config_price" style="display: none">
<label for="type">Select attribute </label>
<select name="price_attribute_id" class="form-control" id="price_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$priceHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$priceHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$priceHtml .= '<div id="price_option_id">';
$priceHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="text" name="option_price[]" class="form-control" >';
$priceHtml .= '</div>';
$priceHtml .= '</div>';
}
$priceHtml .= '</div>';
$qtyHtml = "";
$qtyHtml .= '<div class="form-group col-lg-4" id="multi_config_qty" style="display: none">
<label for="type">Select attribute </label>
<select name="qty_attribute_id" class="form-control" id="qty_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$qtyHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$qtyHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$qtyHtml .= '<div id="qty_option_id">';
$qtyHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="text" name="option_qty[]" class="form-control" >';
$qtyHtml .= '</div>';
$qtyHtml .= '</div>';
}
$qtyHtml .= '</div>';
return response()->json(['success'=>'Successfully',
'imageHtml' => $imageHtml,
'priceHtml' => $priceHtml,
'qtyHtml' => $qtyHtml,
'count' => $count,
]);
}
Here When user select the attribute option , option are stored and used in next step where user can store the option value with respect to attribute
Step 3: Bulk Images, Price and Quantity
After selecting "Apply unique price by attribute to each sku"
View file
<p class="small hint-text m-b-10 m-t-20">
Price
</p>
<div class="form-check">
<input type="radio" name="price" id="price1">
<label for="price1">
Apply single of price to all SKUs
</label>
</div>
<div class="form-check">
<input type="radio" name="price" id="price2">
<label for="price2">
Apply unique prices by attribute to each SKU
</label>
</div>
<div class="form-check">
<input type="radio" name="price" id="price3" checked="checked">
<label for="price3">
Skip price at this time
</label>
</div>
<div class="form-group col-lg-4">
<input type="text" class="form-control" name="single_config_price" id="single_config_price" style="display: none" placeholder="Please enter Price">
</div>
<div id="stepTwoPriceResponse">
</div>
<button class="btn btn-cons btn-primary" id="stepThree">Next</button>
Here I have shown only for price response. Please consider it that Image and Quantity section too
Here I have tried to append all the attribute select option .. and when user select the attribute another input section appear respectively where the user can enter the attribute option value
When user hit next
Ajax is call having code
$('#stepThree').click(function(e){
e.preventDefault();
var option = "";
$("input[name='option_price[]']").each(function () {
if($(this).val()) {
option += $(this).val() + ",";
}
});
console.log(option);
$.ajax({
url: "/configStepThree",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
option:option,
},
success:function(response){
$('#successMsg').show();
console.log(response);
$("#tabImageNav").removeClass("active");
$("#tabImage").removeClass("active");
$('#tabDetailNav').addClass('active');
$('#tabDetail').addClass('active');
$('#table').append(response.table);
},
error: function(response) {
// $('#nameErrorMsg').text(response.responseJSON.errors.message);
console.log(response.responseJSON.message);
},
});
});
});
In configStepThree method from controller
public function configStepThree(Request $request) {
if (!is_null(Session::get('mulit_options'))) {
// Session::forget('mulit_options');
}
Session::put('mulit_options', $request->option);
$config_attribute = "";
$config_attribute_opt_string = "";
$config_attribute_array = [];
$config_attribute_opt_array = [];
$config_attribute_opt_array_id = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
}
if (!is_null(Session::get('options'))) {
$config_attribute_opt = Session::get('options');
$config_attribute_opt = substr($config_attribute_opt, 0, -1);
$config_attribute_opt_array = explode(',', $config_attribute_opt);
}
if (!is_null(Session::get('options_id'))) {
$config_attribute_opt_id = Session::get('options_id');
$config_attribute_opt_id = substr($config_attribute_opt_id, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_id);
}
foreach ($config_attribute_opt_array_id as $key => $value) {
$config_attribute_opt_string .= strstr($value, '-', true). ',';
}
$count = Session::get('count');
$table = "";
$table .= '<table class="table table-hover " >';
$table .= '<thead>';
$table .= '<tr>';
$table .= '<th style="width:30%">Image</th>';
$table .= '<th style="width:30%">SKU</th>';
$table .= '<th style="width:40%">Quantity</th>';
foreach ($config_attribute_array as $key => $attribute) {
$config_attr = Attributee::findOrFail($attribute);
$table .= '<th style="width:40%">'.$config_attr->name.'</th>';
}
$table .= '<th style="width:40%">Price</th>';
$table .= '</tr>';
$table .= '</thead>';
$table .= '<tbody>';
//This is what I want as collection
$collection = [
[
'Color' => 'Red',
'Size' => 'XL',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Red',
'Size' => 'SM',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'XL',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'SM',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
]
];
// dd($collection);
// for ($i=1; $i <= $count; $i++) {
foreach ($collection as $key => $value) {
$table .= '<tr>';
$table .= '<td class="v-align-middle semi-bold"><img src="../assets/img/thumbnail.jpg" class="img-thumbnail"><span class="badge bage-alert bagde-top">'.$value['image_count'].'</span></td>';
$table .= '<td class="v-align-middle">Simple but not simpler</td>';
$table .= '<td class="v-align-middle semi-bold">'.$value['qty'].'</td>';
foreach ($config_attribute_array as $key => $attribute) {
$config_attr = Attributee::findOrFail($attribute);
$table .= '<td class="v-align-middle semi-bold">'.$value[''.$config_attr->name.''].'</td>';
}
$table .= '<td class="v-align-middle semi-bold">'.$value['price'].'</td>';
$table .='</tr>';
}
// }
$table .= '</tbody>';
$table .= '</table>';
return response()->json(['success'=>'Successfully',
'table' => $table,
]);
}
Step : 4 Summary Table
view blade file code
Here I want to display all the values respective from previous steps.
Note
$collection = [
[
'Color' => 'Red',
'Size' => 'XL',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Red',
'Size' => 'SM',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'XL',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'SM',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
]
];
is static collection that I have manually created. I want this collection to be created dynamically iterating the values from previous step. Please let me know how can I achieve this.
Please do not judge me on my code. I am bit new to this and my code is not clean and I have repeated the code not following DRY principle.

Related

Convert Magento Configurable product to Custom Laravel Configurable product using Ajax

Currently I am trying to convert Magento Configurable product to Custom Laravel configurable product.
In step one I am displaying all the attributes from backend
Step 1: Select Attributes
(Here I have displayed all the attributes from backend)
my view blade code
<div class="container">
<div class="row p-b-35">
<div class="form-group">
#foreach($attributes as $attribute)
<div class="form-check complete">
<input type="checkbox" id="{{$attribute->id}}" name="attribute[]" value="{{$attribute->id}}">
<label for="{{$attribute->id}}">
{{$attribute->name}}
</label>
</div>
#endforeach
</div>
</div>
<button class="btn btn-cons btn-primary" id="stepOne">Next</button>
</div>
once the user check the attribute I have use ajax to store the attribute id
ajax code
$('#stepOne').click(function(e){
e.preventDefault();
var attribute = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
attribute += $(this).val() + ",";
}
});
$.ajax({
url: "/configStepOne",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
attribute:attribute,
},
success:function(response){
$('#successMsg').show();
$('#stepOneResponse').append(response.html);
},
error: function(response) {
console.log(response.responseJSON.message);
},
});
});
In mine controller method (configStepOne)
public function configStepOne(Request $request) {
if (!is_null(Session::get('attributes'))) {
Session::forget('attributes');
}
Session::put('attributes', $request->attribute);
$config_attribute_array = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
}
$html = "";
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$html .= '<p class="small hint-text m-b-20">'.$config_attr->name.'</p>';
foreach($config_attr->options as $option) {
$html .= '<div class="form-check complete">';
$html .= '<input type="checkbox" id="'.$config_attr->name. '-' .$option->id.'-'.$option->option.'" name="option[]" value="'.$option->id.'">';
$html .= '<label for="'.$config_attr->name.'-'.$option->id.'-'.$option->option.'">'.$option->option.'</label>';
$html .= '</div>';
}
$html .= '<br>';
}
return response()->json(['success'=>'Successfully', 'html' => $html]);
}
Here I am trying to get the attributes respective options from backend and append the response to blade view
Step 2: Attribute Values
In mine blade view I have
<div id="stepOneResponse">
</div>
<button class="btn btn-cons btn-primary" id="stepTwo">Next</button>
From ajax append the blade view is updated as
<div id="stepOneResponse">
<p class="small hint-text m-b-20">Color</p>
<div class="form-check complete"><input type="checkbox" id="Color-1-Red" name="option[]" value="1"><label for="Color-1-Red">Red</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-2-Black" name="option[]" value="2"><label for="Color-2-Black">Black</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-7-Blue" name="option[]" value="7"><label for="Color-7-Blue">Blue</label></div>
<div class="form-check complete"><input type="checkbox" id="Color-8-Green" name="option[]" value="8"><label for="Color-8-Green">Green</label></div>
<br>
<p class="small hint-text m-b-20">Size</p>
<div class="form-check complete"><input type="checkbox" id="Size-3-XL" name="option[]" value="3"><label for="Size-3-XL">XL</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-4-SM" name="option[]" value="4"><label for="Size-4-SM">SM</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-9-medium" name="option[]" value="9"><label for="Size-9-medium">medium</label></div>
<div class="form-check complete"><input type="checkbox" id="Size-10-Extra small" name="option[]" value="10"><label for="Size-10-Extra small">Extra small</label></div>
<br>
<p class="small hint-text m-b-20">Format</p>
<div class="form-check complete"><input type="checkbox" id="Format-13-Download" name="option[]" value="13"><label for="Format-13-Download">Download</label></div>
<div class="form-check complete"><input type="checkbox" id="Format-14-DVD" name="option[]" value="14"><label for="Format-14-DVD">DVD</label></div>
<br>
</div>
<button class="btn btn-cons btn-primary" id="stepTwo">Next</button>
ajax code :
$('#stepTwo').click(function(e){
e.preventDefault();
var option = "";
var option_id = "";
$("#stepOneResponse :checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
option += $(this).val() + ",";
option_id += $(this).attr('id') + ",";
}
});
$.ajax({
url: "/configStepTwo",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
option:option,
option_id:option_id,
},
success:function(response){
$('#successMsg').show();
console.log(response);
$('#stepTwoImageResponse').append(response.imageHtml);
$('#stepTwoPriceResponse').append(response.priceHtml);
$('#stepTwoQtyResponse').append(response.qtyHtml);
$('#count').text(response.count);
},
error: function(response) {
console.log(response.responseJSON.message);
},
});
});
In Controller method configStepTwo
public function configStepTwo(Request $request) {
if (!is_null(Session::get('options'))) {
// Session::forget('option');
}
Session::put('options', $request->option);
Session::put('options_id', $request->option_id);
$config_attribute = "";
$config_attribute_opt_string = "";
$config_attribute_array = [];
$config_attribute_opt_array = [];
$config_attribute_opt_array_id = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
// dd($config_attribute_array);
}
if (!is_null(Session::get('options'))) {
$config_attribute_opt = Session::get('options');
$config_attribute_opt = substr($config_attribute_opt, 0, -1);
$config_attribute_opt_array = explode(',', $config_attribute_opt);
// dd($config_attribute_opt_array);
}
if (!is_null(Session::get('options_id'))) {
$config_attribute_opt_id = Session::get('options_id');
// $config_attribute_opt_id = strstr($config_attribute_opt_id, '-', true);
$config_attribute_opt_id = substr($config_attribute_opt_id, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_id);
}
foreach ($config_attribute_opt_array_id as $key => $value) {
$config_attribute_opt_string .= strstr($value, '-', true). ',';
// $config_attribute_opt_string .= $value. ',';
}
$config_attribute_opt_string = substr($config_attribute_opt_string, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_string);
$array_count = array_count_values($config_attribute_opt_array_id);
$count = 1;
foreach ($array_count as $key => $value) {
$count *= $value;
}
Session::put('count', $count);
$imageHtml = "";
$imageHtml .= '<div class="form-group col-lg-4" id="multi_config_image" style="display: none">
<label for="type">Select attribute </label>
<select name="image_attribute_id" class="form-control" id="image_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$imageHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$imageHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$imageHtml .= '<div id="image_option_id">';
$imageHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="file" name="option_image" class="form-control" >';
$imageHtml .= '</div>';
$imageHtml .= '</div>';
}
$imageHtml .= '</div>';
$priceHtml = "";
$priceHtml .= '<div class="form-group col-lg-4" id="multi_config_price" style="display: none">
<label for="type">Select attribute </label>
<select name="price_attribute_id" class="form-control" id="price_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$priceHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$priceHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$priceHtml .= '<div id="price_option_id">';
$priceHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="text" name="option_price[]" class="form-control" >';
$priceHtml .= '</div>';
$priceHtml .= '</div>';
}
$priceHtml .= '</div>';
$qtyHtml = "";
$qtyHtml .= '<div class="form-group col-lg-4" id="multi_config_qty" style="display: none">
<label for="type">Select attribute </label>
<select name="qty_attribute_id" class="form-control" id="qty_attribute_id">
<option value="">Select</option>';
foreach($config_attribute_array as $value) {
$config_attr = Attributee::findOrFail($value);
$qtyHtml .= '<option value="'.$config_attr->name.'">'.$config_attr->name.'</option>';
}
$qtyHtml .= '</select>';
foreach($config_attribute_opt_array as $value) {
$config_opt = AttributeOption::findOrFail($value);
$qtyHtml .= '<div id="qty_option_id">';
$qtyHtml .= '<div class="row '.$config_opt->attribute->name.'" style="display: none;">'. $config_opt->option.'<input type="text" name="option_qty[]" class="form-control" >';
$qtyHtml .= '</div>';
$qtyHtml .= '</div>';
}
$qtyHtml .= '</div>';
return response()->json(['success'=>'Successfully',
'imageHtml' => $imageHtml,
'priceHtml' => $priceHtml,
'qtyHtml' => $qtyHtml,
'count' => $count,
]);
}
Here When user select the attribute option , option are stored and used in next step where user can store the option value with respect to attribute
Step 3: Bulk Images, Price and Quantity
After selecting "Apply unique price by attribute to each sku"
View file
<p class="small hint-text m-b-10 m-t-20">
Price
</p>
<div class="form-check">
<input type="radio" name="price" id="price1">
<label for="price1">
Apply single of price to all SKUs
</label>
</div>
<div class="form-check">
<input type="radio" name="price" id="price2">
<label for="price2">
Apply unique prices by attribute to each SKU
</label>
</div>
<div class="form-check">
<input type="radio" name="price" id="price3" checked="checked">
<label for="price3">
Skip price at this time
</label>
</div>
<div class="form-group col-lg-4">
<input type="text" class="form-control" name="single_config_price" id="single_config_price" style="display: none" placeholder="Please enter Price">
</div>
<div id="stepTwoPriceResponse">
</div>
<button class="btn btn-cons btn-primary" id="stepThree">Next</button>
Here I have shown only for price response. Please consider it that Image and Quantity section too
Here I have tried to append all the attribute select option .. and when user select the attribute another input section appear respectively where the user can enter the attribute option value
When user hit next
Ajax is call having code
$('#stepThree').click(function(e){
e.preventDefault();
var option = "";
$("input[name='option_price[]']").each(function () {
if($(this).val()) {
option += $(this).val() + ",";
}
});
console.log(option);
$.ajax({
url: "/configStepThree",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
option:option,
},
success:function(response){
$('#successMsg').show();
console.log(response);
$("#tabImageNav").removeClass("active");
$("#tabImage").removeClass("active");
$('#tabDetailNav').addClass('active');
$('#tabDetail').addClass('active');
$('#table').append(response.table);
},
error: function(response) {
// $('#nameErrorMsg').text(response.responseJSON.errors.message);
console.log(response.responseJSON.message);
},
});
});
});
In configStepThree method from controller
public function configStepThree(Request $request) {
if (!is_null(Session::get('mulit_options'))) {
// Session::forget('mulit_options');
}
Session::put('mulit_options', $request->option);
$config_attribute = "";
$config_attribute_opt_string = "";
$config_attribute_array = [];
$config_attribute_opt_array = [];
$config_attribute_opt_array_id = [];
if (!is_null(Session::get('attributes'))) {
$config_attribute = Session::get('attributes');
$config_attribute = substr($config_attribute, 0, -1);
$config_attribute_array = explode(',', $config_attribute);
}
if (!is_null(Session::get('options'))) {
$config_attribute_opt = Session::get('options');
$config_attribute_opt = substr($config_attribute_opt, 0, -1);
$config_attribute_opt_array = explode(',', $config_attribute_opt);
}
if (!is_null(Session::get('options_id'))) {
$config_attribute_opt_id = Session::get('options_id');
$config_attribute_opt_id = substr($config_attribute_opt_id, 0, -1);
$config_attribute_opt_array_id = explode(',', $config_attribute_opt_id);
}
foreach ($config_attribute_opt_array_id as $key => $value) {
$config_attribute_opt_string .= strstr($value, '-', true). ',';
}
$count = Session::get('count');
$table = "";
$table .= '<table class="table table-hover " >';
$table .= '<thead>';
$table .= '<tr>';
$table .= '<th style="width:30%">Image</th>';
$table .= '<th style="width:30%">SKU</th>';
$table .= '<th style="width:40%">Quantity</th>';
foreach ($config_attribute_array as $key => $attribute) {
$config_attr = Attributee::findOrFail($attribute);
$table .= '<th style="width:40%">'.$config_attr->name.'</th>';
}
$table .= '<th style="width:40%">Price</th>';
$table .= '</tr>';
$table .= '</thead>';
$table .= '<tbody>';
//This is what I want as collection
$collection = [
[
'Color' => 'Red',
'Size' => 'XL',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Red',
'Size' => 'SM',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'XL',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'SM',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
]
];
// dd($collection);
// for ($i=1; $i <= $count; $i++) {
foreach ($collection as $key => $value) {
$table .= '<tr>';
$table .= '<td class="v-align-middle semi-bold"><img src="../assets/img/thumbnail.jpg" class="img-thumbnail"><span class="badge bage-alert bagde-top">'.$value['image_count'].'</span></td>';
$table .= '<td class="v-align-middle">Simple but not simpler</td>';
$table .= '<td class="v-align-middle semi-bold">'.$value['qty'].'</td>';
foreach ($config_attribute_array as $key => $attribute) {
$config_attr = Attributee::findOrFail($attribute);
$table .= '<td class="v-align-middle semi-bold">'.$value[''.$config_attr->name.''].'</td>';
}
$table .= '<td class="v-align-middle semi-bold">'.$value['price'].'</td>';
$table .='</tr>';
}
// }
$table .= '</tbody>';
$table .= '</table>';
return response()->json(['success'=>'Successfully',
'table' => $table,
]);
}
Step : 4 Summary Table
view blade file code
Here I want to display all the values respective from previous steps.
Note
$collection = [
[
'Color' => 'Red',
'Size' => 'XL',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Red',
'Size' => 'SM',
'Format' => 'Download',
'price' => '200',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'XL',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
],
[
'Color' => 'Black',
'Size' => 'SM',
'Format' => 'Download',
'price' => '300',
'qty' => '1',
'image' => 'path',
'image_count' => '0'
]
];
is static collection that I have manually created. I want this collection to be created dynamically iterating the values from previous step. Please let me know how can I achieve this.
Please do not judge me on my code. I am bit new to this and my code is not clean and I have repeated the code not following DRY principle.
For image reference please checkout this link magento configuration product to custom laravel configurable product using ajax

How to multiupload images in Codeigniter

I'm trying to do multi upload photos to the form in Codeigniter 3. When I want to upload photos, clicking upload sends me the entire form and adds only one photo. If anyone could give me tips on how to do this, I would be grateful. I could do it as two separate forms but then it doesn't work as I would like.
My form view
<form method='post' action='<?php echo base_url();?>ads/create' enctype='multipart/form-data'>
<div class="form-group row">
<label for="email" class="col-4 col-form-label text-uppercase text-right">Tytuł :</label>
<div class="col-8">
<input type="text" class="form-control" name="title" value="<?php echo set_value('title'); ?>">
</div>
</div>
<div class="form-group row">
<label for="message" class="col-4 col-form-label text-uppercase text-right">Opis ogłoszenia:</label>
<div class="col-8">
<textarea name="description" id="message" cols="70" rows="5"
class="form-control" ><?php echo set_value('description'); ?></textarea>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-4 col-form-label text-uppercase text-right">Osoba do kontaktu:</label>
<div class="col-8">
<input type="text" class="form-control" name="contact" value="<?php echo set_value('contact'); ?>">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-4 col-form-label text-uppercase text-right">Adres email:</label>
<div class="col-8">
<input type="text" class="form-control" name="email" <?php if ( logged_in() == true )
{ echo "value='".$user->email."' disabled"; } ?> >
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-4 col-form-label text-uppercase text-right">Numer telefonu:</label>
<div class="col-8">
<input type="text" class="form-control" name="phone" value="<?php echo set_value('phone'); ?>">
</div>
</div>
<div class="form-group row">
<label for="message" class="col-4 col-form-label text-uppercase text-right">Zdjęcia:</label>
</div>
<hr>
<input type='file' name='files[]' multiple=""> <br/><br/>
<input id="submit" type='submit' value='Upload' name='upload' />
<strong><?php if(isset($totalFiles)) echo "Successfully uploaded ".count($totalFiles)." files"; ?></strong>
<div class="form-group row">
<div class="col-12 text-center">
<button class="btn btn-primary w-50 mt-3">Dodaj</button>
</div>
</div>
<?php echo form_close(); ?>
And my controller
public function create()
{
$user_id = $this->session->userdata( 'id' );
$where = array( 'id' => $user_id);
$user = $this->Site_model->get_single('users', $where);
$data['user'] = $user;
if ( !empty( $_POST ) )
{
if ( $this->form_validation->run( 'site_ads_create' ) == true )
{
if ( logged_in() == true )
{
$data = array(
'email' => $this->session->userdata( 'email' ),
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'category_id' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 1,
);
}
else
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'category_id' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->input->post( 'email' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 0,
);
}
$count = count($_FILES['files']['name']);
for($i=0;$i<$count;$i++){
if(!empty($_FILES['files']['name'][$i])){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
$config['upload_path'] = 'images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5000';
$config['file_name'] = $this->input->post( 'title' , true );
$this->load->library('upload',$config);
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$data['totalFiles'][] = $filename;
}
}
}
$this->Site_model->create( 'ads' , $data );
$ad_id = $this->Site_model->last_id();
if ($this->input->post('promo' , true ) == 'tak' )
{
$this->session->set_userdata('promo_id', $ad->id);
redirect( 'ads/promo' );
}
$this->session->set_flashdata( 'alert' , 'Ad has been added.' );
//refresh();
}
else
{
$this->session->set_flashdata( 'alert' , validation_errors() );
//refresh();
}
}
$data['cities'] = $this->Site_model->get_cities('cities', 'name', 'asc');
$data['categories'] = $this->Site_model->get_categories();
$this->load->view( 'create' , $data );
}
You should change
if($this->upload->do_upload('file')){
into
if($this->upload->do_upload('files')){
Future reference Check the link to learn how to upload multiple files in codeigniter
Multiple upload in codeigniter
in this example you you have single image upload and multiple image upload different folders.
if ($param =="upload") {
$config['upload_path'] = './uploads/user_profil/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 15000;
$config['file_name'] = $this->input->post('user_profile')."_profil_image_".mt_rand(100000,900000);
$this->load->library('upload', $config, 'user_profile'); // Create custom object for cover upload
$this->user_profile->initialize($config);
if ( !empty($this->user_profile->do_upload('user_profil_image') ) )
{
$error = array('error' => $this->user_profile->display_errors());
$file_name_profile_picture = $this->input->post('user_profil_image_actual');
$upload_data = $this->user_profile->data();
$file_name_profile_picture = $upload_data['file_name'];
}
else
{
$file_name_profile_picture ="";
}
//map photos
$config_galery['upload_path'] = './uploads/map_profile/';
$config_galery['allowed_types'] = 'gif|jpg|png';
$config_galery['max_size'] = 15000;
$config_galery['file_name'] = $this->input->post('name')."_user_profilm_map_".mt_rand(100000,900000);
$this->load->library('upload', $config_galery, 'map_profile'); // Create custom object for cover upload
$this->map_profile->initialize($config_galery);
if ( !empty($this->map_profile->do_upload('map_profile_image')) )
{
$error = array('error' => $this->map_profile->display_errors());
$map_profile_image =$this->input->post('map_profile_image_actual');
$upload_data1 = $this->map_profile->data();
$map_profile_image = $upload_data1['file_name'];
} else {
$map_profile_image="";
}
if(!empty($_FILES['userfile']['name'])){
$b = $this->doupload_gallery();
$galery_photo_links = json_encode(json_decode($b, true));
} else {
// default empty state
$galery_photo_links ="[]";
}
if (!empty($this->input->post('profile_qr_id'))) {
$data_update_qr_status = array(
'statusi' => 1,
'table_name' => "table_name_db"
);
$this->db->where('profile_qr_id', $this->input->post('profile_qr_id'));
$this->db->update('table_name', $data_update_qr_status);
}
$this->db->insert('table_name', $data);
// ridirect
redirect(base_url('admin/uploads_view'), 'refresh');
}

Laravel filter reset after next page click in paginate

I have created a table were showing data. I also add few filters to filter data. Using paginate I show 20 records per page. After select filter and click search records in table filter with paginating on the first page but as soon as I click next page filters getting reset. How to stop filters from getting reset?
Below is my code,
public function index()
{
$agos = DB::table('orders')
->leftJoin('companies', 'orders.company_id', '=', 'companies.id')
->select(DB::raw('orders.id, companies.name, orders.type, orders.data, orders.currency, orders.price, orders.status, DATE_FORMAT(orders.created_at,"%M %d, %Y") as created_at '))
->where('orders.merchant', '=', 'agos')
->where(function ($query) {
$status = Input::has('status') ? Input::get('status') : null;
$company = Input::has('company') ? Input::get('company') : null;
$from = Input::has('from_date') ? Input::get('from_date') : null;
$to = Input::has('to_date') ? Input::get('to_date') : null;
$from = date("Y-m-d", strtotime($from));
$to = date("Y-m-d", strtotime($to));
if ( isset($status) ) {
$query->where('orders.status', '=', $status);
}
if ( isset($company) ) {
$query->where('companies.name', '=', $company);
}
if ( !empty($from) && !empty($to) ) {
$query->whereBetween('orders.created_at', [$from, $to]);
}
})->orderBy('orders.created_at', 'desc')
->paginate(20);
return $agos;
}
Blade file code,
#extends('layouts.agos')
#section('title', Translator::transSmart('app.Common Clerk(AGOS)', 'Common Clerk(AGOS)'))
#section('styles')
#parent
{{ Html::skinForVendor('jquery-textext/all.css') }}
#endsection
#section('scripts')
#parent
{{ Html::skinForVendor('jquery-textext/all.js') }}
#endsection
#section('content')
<div class="admin-managing-member-index">
<div class="row">
<div class="col-sm-12">
{{ Form::open(array('route' => array('agos::index'), 'class' => 'form-search')) }}
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'company';
$translate = Translator::transSmart('app.Company', 'Company');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{ Form::select($name, $companies->pluck('name', 'name'), Request::get($name), array('id' => $name, 'title' => $translate, 'class' => 'form-control', 'title' => $name, 'placeholder' => '')) }}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'status';
$translate = Translator::transSmart('app.Status', 'Status');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{Form::select($name, Utility::constant('agos_status', true), Request::get($name), array('id' => $name, 'class' => 'form-control', 'title' => $translate, 'placeholder' => ''))}}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'from_date';
$translate = Translator::transSmart('app.From', 'From');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'to_date';
$translate = Translator::transSmart('app.To', 'To');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 toolbar">
<div class="btn-toolbar pull-right">
<div class="btn-group">
{{
Html::linkRouteWithIcon(
null,
Translator::transSmart('app.Search', 'Search'),
'fa-search',
array(),
[
'title' => Translator::transSmart('app.Search', 'Search'),
'class' => 'btn btn-theme search-btn',
'onclick' => "$(this).closest('form').submit();"
]
)
}}
</div>
</div>
</div>
</div>
{{ Form::close() }}
</div>
</div>
<div class="row" >
<div class="col-sm-12">
<hr />
</div>
</div><br>
<div class="row" style="background-color:#FFFFFF">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-condensed table-crowded">
<thead>
<tr>
<th>{{Translator::transSmart('app.#', '#')}}</th>
<th></th>
<th>{{Translator::transSmart('app.Company', 'Company')}}</th>
<th>{{Translator::transSmart('app.Products', 'Products')}}</th>
<th>{{Translator::transSmart('app.Total Price', 'Total Price')}}</th>
<th>{{Translator::transSmart('app.Status', 'Status')}}</th>
<th>{{Translator::transSmart('app.Created At', 'Created At')}}</th>
<th></th>
</tr>
</thead>
<tbody>
#if($orders->isEmpty())
<tr>
<td class="text-center empty" colspan="14">
--- {{ Translator::transSmart('app.No Record.', 'No Record.') }} ---
</td>
</tr>
#endif
<?php $count = 0;?>
#foreach($orders as $order)
<tr>
<td>{{++$count}}</td>
<td></td>
<td>{{$order->name}}</td>
<td>
#php
$json = $order->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['name']. ', ';
}
$data = rtrim($data, ', ');
#endphp
{{$data}}
</td>
<td>
#if(empty($order->price) || $order->price == 0)
{{'Quotation'}}
#else
{{CLDR::showPrice($order->price, $order->currency, Config::get('money.precision'))}}
#endif
</td>
<td>{{Utility::constant(sprintf('agos_status.%s.name', $order->status))}}</td>
<td>{{$order->created_at}}</td>
<td class="item-toolbox">
{{
Html::linkRouteWithIcon(
'agos::edit',
Translator::transSmart('app.Edit', 'Edit'),
'fa-pencil',
['id' => $order->id],
[
'title' => Translator::transSmart('app.Edit', 'Edit'),
'class' => 'btn btn-theme'
]
)
}}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="pagination-container">
#php
$query_search_param = Utility::parseQueryParams();
#endphp
{!! $orders->render() !!}
</div>
</div>
</div>
</div>
#endsection
Controller Code,
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Can someone help me?
Try to append the request in the results:
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
$queryArgs = Input::only(['status','company','from_date', 'to_date']);
$orders->appends($queryArgs);
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Then in your template:
<div class="pagination-container">
{!! $orders->render(); !!}
</div>
try to use in your Blade view
$orders->links()

Foreach in Yajra DataTable Laravel

I'm trying to put a foreach loop inside my datatable but it wont work,
P.S. if I remove the foreach everything works fine already,
attached here is my code
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) {
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
'.foreach ($colors as $color){.'
<option value="test">test</option>'.}.'
</select>
</div>';
return $return;
});
That won't work, you're attaching a foreach into a string
What you may do is perform the foreach first to prepare the items you want to attach in that string.
E.g.,
<option>something</option>
<option>something more</option>
Before setting the $return do the foreach:
->addColumn('add_color', function($row) {
$options = ''
// here we prepare the options
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="'.$row->id.'">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>' . $options . '</select>
</div>';
return $return;
})
You need to perform foreach outside your return. and then you also need no use or import the $color variable inside your data table. something like this ..
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) use ($colors) {
$options = '';
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
</select>
</div>';
return $return;
});

Codeigniter Mysql Ajax Pagination sort and search

I have to do a codeigniter crud operation. But now i want to add pagination search and sort for that.I used lots of tutorials to do that. But i can't understand. To anyone who knows please help me to do that. Thank you.
controller
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->library('form_validation');
}
// load user_list view
public function index()
{
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_list');
}
// show all the users in view
public function fillgrid(){
$this->user_model->fillgrid();
}
function fetch_record(){
$this->user_model->fetch_record();
}
// validate and insert new user data
public function create(){
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$this->user_model->create();
}
}
// edit user
public function edit(){
$id = $this->uri->segment(3);
$this->db->where('id',$id);
$data['query'] = $this->db->get('user');
$data['id'] = $id;
$this->load->view('admin_pages/user_edit', $data);
}
// update validation
public function update(){
$res['error']="";
$res['success']="";
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else{
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'));
$this->db->where('id', $this->input->post('hidden'));
$this->db->update('user', $data);
$res['success'] = '<div class="alert alert-success">One record updated Successfully</div>';
}
header('Content-Type: application/json');
echo json_encode($res);
exit;
}
//delete user
public function delete(){
$id = $this->input->POST('id');
$this->db->where('id', $id);
$this->db->delete('user');
echo'<div class="alert alert-success">One record deleted Successfully</div>';
exit;
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function fillgrid(){
$this->db->order_by("id", "desc");
$data = $this->db->get('user');
foreach ($data->result() as $row){
$edit = base_url().'index.php/user_controller/edit/';
$delete = base_url().'index.php/user_controller/delete/';
echo "<tr>
<td>$row->firstname</td>
<td>$row->lastname</td>
<td>$row->email</td>
<td>$row->contact_no</td>
<td>$row->address</td>
<td>$row->created</td>
<td><a href='$edit' data-id='$row->id' class='btnedit' title='edit'><i class='glyphicon glyphicon-pencil' title='edit'></i></a> <a href='$delete' data-id='$row->id' class='btndelete' title='delete'><i class='glyphicon glyphicon-remove'></i></a></td>
</tr>";
}
exit;
}
public function create(){
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'),
'created'=>date('d/m/y'));
$this->db->insert('user', $data);
echo'<div class="alert alert-success">One record inserted Successfully</div>';
exit;
}
private function edit(){}
private function delete(){}
//2015.7.26
//set table name to be used by all functions
var $table = 'user';
function fetch_record($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get($this->user);
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function record_count()
{
return $this->db->count_all_results('user');
}
//2015.7.26
}
//2015.7.26
public function pagination(){
$page_number = $this->input->post('page_number');
$item_par_page = 2;
$position = ($page_number*$item_par_page);
$result_set = $this->db->query("SELECT * FROM user LIMIT ".$position.",".$item_par_page);
$total_set = $result_set->num_rows();
$page = $this->db->get('user') ;
$total = $page->num_rows();
//break total recoed into pages
$total = ceil($total/$item_par_page);
if($total_set>0){
$entries = null;
// get data and store in a json array
foreach($result_set->result() as $row){
$entries[] = $row;
}
$data = array(
'TotalRows' => $total,
'Rows' => $entries
);
$this->output->set_content_type('application/json');
echo json_encode(array($data));
}
exit;
}
view
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/user_controller/create" method="POST">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstname">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First name">
</div>
<!--/First Name-->
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastname">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
</div>
<!--/Last Name-->
<!-- email-->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
<input class="form-control" name="email" type="email" placeholder="Enter email">
</div>
</div>
<!-- email-->
<!--Contact-->
<div class="form-group">
<label class="sr-only" for="contact_no">Contact</label>
<input type="text" class="form-control" name="contact_no" id="contact_no" placeholder="contact number">
</div>
<!--/Contact-->
<!--Address-->
<div class="form-group">
<label class="sr-only" for="address">Address</label>
<input type="text" name="address" class="form-control" id="exampleInputPassword2" placeholder="Address">
</div>
<!--/Address-->
<!--submit-->
<input type="submit" class="btn btn-success" id="exampleInputPassword2" value="submit">
<!--/submit-->
</div>
</form>
</div>
<table class="table">
<thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Contact</th><th>Address</th><th>created</th><th>Action</th></tr></thead>
<tbody id="fillgrid">
</tbody>
<tfoot></tfoot>
</table>
<!-- //2015.7.26-->
<div class="row clear-fix">
<div class="col-md-4 pull-right">
<button id="previous" class="btn btn-sm btn-primary">Previous</button>
<lable>Page <lable id="page_number" name="page_number" ></lable> of <lable id="total_page" name="total_page"></lable></lable>
<button id="next" class="btn btn-sm btn-primary">Next</button>
</div>
</div>
<div style="text-align: center">
<!--//2015.7.26-->
</div>
</div>
</div>
<script>
$(document).ready(function (){
//fill data
var btnedit='';
var btndelete = '';
fillgrid();
// add data
$("#frmadd").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:data
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
function fillgrid(){
$("#loader").show();
$.ajax({
url:'<?php echo base_url() ?>index.php/user_controller/fillgrid',
type:'GET'
}).done(function (data){
$("#fillgrid").html(data);
$("#loader").hide();
btnedit = $("#fillgrid .btnedit");
btndelete = $("#fillgrid .btndelete");
var deleteurl = btndelete.attr('href');
var editurl = btnedit.attr('href');
//delete record
btndelete.on('click', function (e){
e.preventDefault();
var deleteid = $(this).data('id');
if(confirm("are you sure")){
$("#loader").show();
$.ajax({
url:deleteurl,
type:'POST' ,
data:'id='+deleteid
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
}
});
//edit record
btnedit.on('click', function (e){
e.preventDefault();
var editid = $(this).data('id');
$.colorbox({
href:"<?php echo base_url()?>index.php/user_controller/edit/"+editid,
top:50,
width:500,
onClosed:function() {fillgrid();}
});
});
});
}
});
</script>
i think you have to check your db field name it will work definitely you are missing some db field name...

Resources