Banner Images not being reinserted correct to database - codeigniter

When I update my banner_image it should delete the ones from the database Then re insert the ones that are set.
Currently what it does is deletes the banner image but then re inserts blank banner_image
But should remove that enitre row.
Question How to make sure when I update it that will remove the images rows that are no longer selected and not re insert them
public function update($bid = NULL, $data = array()) {
$banner_update = array('banner_title' => $data['banner_title'], 'banner_status' => $data['banner_status']);
$this->db->where('bid', $bid);
$this->db->update('banner', $banner_update);
$this->db->where('bid', $bid)->delete('banner_image');
if (isset($data['banner_image'])) {
$banner_images = array();
$i = 0;
foreach ($data['banner_image'] as $image) {
$banner_images[$i] = array(
'bid' => $bid,
'banner_image' => $image['image'],
);
$i++;
}
$this->db->insert_batch('banner_image', $banner_images);
}
}
View
<?php echo form_open($action);?>
<div class="container">
<div class="card mt-3">
<div class="card-body">
<?php if (validation_errors()) {?>
<?php unset($_POST);?>
<div class="bg-error-warning">
<ul>
<?php echo validation_errors('<li>', '</li>');?>
</ul>
</div>
<?php }?>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p>Banner Title</p>
<div class="form-group">
<input type="text" name="banner_title" value="<?php echo $banner_title;?>" placeholder="Enter Banner Title" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<table id="images" class="table table-striped table-bordered">
<tbody>
<tr>
<td>
<button type="button" onclick="addImage();" data-toggle="tooltip" title="Add Banner!" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td>
<a href="" id="thumb-image<?php echo $image_row; ?>" data-toggle="image">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" class="img-thumbnail"/></a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input-image<?php echo $image_row; ?>" />
</td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p>Banner Status</p>
<div class="form-group">
<?php $options = array('0' => 'Disabled', '1' => 'Enabled'); echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));?>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<button type="submit" class="btn btn-block btn-dark">Create Banner</button>
</div>
</div>
</div>
</div>
</div>
</div>
<?php echo form_close();?>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage() {
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<a href="" id="thumb-image' + image_row + '" data-toggle="image" >';
html += '<img src="<?php echo $placeholder; ?>" width="100" height="100" class="img-thumbnail" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input-image' + image_row + '" />'
html += '</a>';
html += '</td>';
html += '<td class="text-left">';
html += '<button type="button" onclick="$(\'#image-row' + image_row + '\').remove();" data-toggle="tooltip" title="Remove Banner!" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button>'
html += '</td>';
html += '<script>';
html += '$(document).ready(function(){';
html += '$(\'[data-toggle="tooltip"]\').tooltip();';
html += '});';
html += '<\/script>';
$('#images tbody').append(html);
image_row++;
}
</script>

Have got it working just had to put empty in the foreach loop
public function update($bid = NULL, $data = array()) {
$banner_update = array('banner_title' => $data['banner_title'], 'banner_status' => $data['banner_status']);
// Updates the main banner table
$this->db->where('bid', $bid);
$this->db->update('banner', $banner_update);
// Removes banners so can have clean insert of new banners selected
$this->db->where('bid', $bid);
$this->db->delete('banner_image');
// Inserts new banner images & saved ones.
if ($this->input->post('banner_image')) {
foreach ($this->input->post('banner_image') as $image) {
if (!empty($image['image'])) {
$this->db->insert('banner_image', array('bid' => $bid, 'banner_image' => $image['image']));
}
}
}
}

Related

ajax only works once a refresh

I was doing a cart section where you can change your product quantity, at first i did it with a normal form, but i change it to ajax because i want to the page doesn´t need to refresh at all to show you your new quantity with your new price and your new total, so i did the following:
$('.actform').on('submit', function(ev) {
var id2 = $(this);
$.ajax({
type: $(id2).attr('method'),
url: $(id2).attr('action'),
data: $(id2).serialize(),
success: function(data) {
$('.container').load(' .container');
},
error: function() {
alert('Ha ocurrido un error');
}
});
ev.preventDefault();
});
It was all okay when you change 1 product for first time, but the second time the forms submits like it doesn´t have ajax, to fix this problem i replaced $('.container').load(' .container'); to $('.container').load(window.location.reload(false)); and it works, but i wanna know if there is another way to do it because this reload stutters a bit the page reload and it looks weird
cart.php whithout ajax (if you need to see):
<main id="main" class="main">
<?php if(!empty($_SESSION['cart'])){ ?>
<div class="container">
<h2 class="carrito-title">Mi Carrito</h2>
<div class="container2">
<div class="container-cart">
<table>
<thead>
<tr>
<th class="product-image">Imagen</th>
<th class="product-name">Producto</th>
<th class="product-price">Precio</th>
<th class="product-quantity">Cantidad (Modificar)</th>
<th class="product-total">Total</th>
<th class="product-remove">Eliminar</th>
</tr>
</thead>
<tbody>
<?php
$total= 0;
foreach($_SESSION['cart'] as $indice=>$producto){
$ID = $producto['ID'];
$select_products = $connect->prepare("SELECT * FROM `productos` WHERE id=$ID") or die('query failed');
$select_products->execute();
$list_products = $select_products->fetchAll(PDO::FETCH_ASSOC);
foreach($list_products as $product){
$nombre= $product['nombre'];
$precio= $product['precio'];
$codigo = $product['codigo'];
$imagen = "media/productos/$codigo.png";
?>
<tr>
<td class="product-image">
<img src="<?php echo $imagen?>" alt="<?php $nombre?>">
</td>
<td class="product-name">
<h2 class="name"><?php echo $nombre?></h2>
</td>
<td class="product-price"><h2 class="precio">$<?php echo number_format($precio, 0, ',', '.') ; ?></h2></td>
<td class="product-quantity">
<form action="backend/actProduct.php" method="post" class="actform" id="<?php echo $ID ?>">
<div class="cantidad">
<div class="cantidad-container">
<input type="hidden" name="id" min="1" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<input type="number" class="nro updateCant" onchange="btnCart.click()" name="cantidadupd" value="<?php echo $producto['CANTIDAD'];?>">
<button name="btnCart" value="Update" type="submit" class="actualizar"><i class="fa-solid fa-rotate"></i></button>
</div>
</div>
</form>
</td>
<?php
$sub_total = $precio * $producto['CANTIDAD'];
$total = $total + $sub_total;
?>
<td><h2 class="subtotal">$<?php echo number_format($sub_total, 0, ',', '.'); ?></h2></td>
<td>
<form action="backend/deleteProduct.php" method="post">
<input type="hidden" name="id" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<button class="delete" name="btnCart" type="submit" value="Remove" onclick="return confirm('Seguro que quieres eliminar este artículo?');">X</button>
</form>
</td>
</tr>
<?php
}};
?>
</tbody>
</table>
</div>
<?php if(isset($_SESSION['cart'])){ ?>
<div class="nocart">
<div class="final">
<h5 class="final-price preciofinal">Precio sin Impuestos: $<?php echo number_format($total, 0, ',', '.');?></h5>
<form action="backend/emptyCart.php" method="post" class="emptyform" id="<?php echo $ID ?>">
<input type="hidden" name="empty">
<button name="btnCart" type="submit" class ="vaciar" value="Empty" onclick="return confirm('¿Desea vaciar el carrito?');">Vaciar carrito</button>
</form>
</div>
<?php
if ($rol=='representante'){
?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<a class="checkout-btn" href="clientes.php">Seleccionar cliente</a>
</div>
<?php
}else{?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<form action="backend/fincompra.php" method="post" onsubmit="showLoad()">
<button name="btnFinCart" class ="checkout-btn" onclick="return confirm('¿Está seguro que desea finalizar la compra?');" value="Fin" >Finalizar compra</button>
</form>
</div>
<?php
}
?>
</div>
</div>
<?php }?>
</div>
<?php }else{
echo '
<div class="nosesion">
<h2 class="cartvacio">El carrito esta vacío</h2>
<a class="comprar-btn" href="productos.php">Comprar ahora</a>
</div>
';
}?>
</main>

Can't make carousel work in php: CodeIgniter

I have added a carousel in a container but it remains static showing the first pic. Though the carousel buttons are visible but not active. The code is:
<div class="col-xl-8 col-lg-8 col-md-7 mb-5 mb-md-0">
<div id="" class="pt-0 pt-md-4 pt-lg-5">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<?php if (!empty($event)) {
foreach ($event as $key => $value) {
?>
<li data-target="#carouselExampleIndicators" data-slide-to="<?= $key ?>" <?php if ($key == 0) { ?> class="active" <?php } ?>></li>
<?php }
} ?>
</ol>
<div class="carousel-inner">
<?php if (!empty($event)) {
foreach ($event as $key => $value) {
$date = date('d', strtotime($value['datetime']));
$month = date('F', strtotime($value['datetime']));
$year = date('Y', strtotime($value['datetime']));
$seconds = strtotime($value['datetime']) - time();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
$cdate = date("Y-m-d H:i:s", strtotime($value['datetime']));
if ($cdate > date("Y-m-d H:i:s")) {
?>
<div class="carousel-item <?php if ($key == 0) { ?>active<?php } ?>">
<div class="row">
<div class="col-md-12 col-lg-6 mb-4 mb-md-0">
<div class="d-flex align-items-center justify-content-between w-100">
<!--<div class="images-craus">-->
<!-- <img src="<?= base_url() ?>/images/upcomingevents/<?= $value['image1'] ?>">-->
<!--</div>-->
<div class="dates">
<h3 class="months"><?= $month ?> <?= $date ?><br><?= $year ?></h3>
<h3 class="team"><?= $cdate ?> <br><?= $value['team1'] ?> vs <?= $value['team2'] ?></h3>
</div>
<!--<div class="images-craus">-->
<!-- <img src="<?= base_url() ?>/images/upcomingevents/<?= $value['image2'] ?>">-->
<!--</div>-->
</div>
</div>
<div class="col-md-12 col-lg-6 mb-4 mb-md-0">
<div class="details1">
<div class="pt-0 pt-md-4 pb-3">
<h5 class="text-white text-center">Next Match<br><?= $value['team1'] ?> vs <?= $value['team2'] ?></h5>
</div>
<div class="button-20 d-flex">
<button type="button" class="btn btn-danger"><?= $days ?> day</button>
<button type="button" class="btn btn-danger"><?= $hours ?> hr</button>
<button type="button" class="btn btn-danger"><?= $minutes ?>min</button>
</div>
</div>
</div>
</div>
</div>
<?php }
}
} ?>
</div>
I tried looking at bootstrap feature but couldn't really work it out. Mind you this carousel also have a table list which shows on the right side of the container. I am not sharing it code as table is working fine.

How can fixed the codeigniter cart update issue

I am unable to update cart on checkout page. I do not know what is Happen.
Here is my code.
function update_cart()
{
$rowid =$this->input->post('rowid');
$price =$this->input->post('price');
$qty = $this->input->post('qty');
$pr = preg_replace( '/,/', '', $price);
$amount = $pr * $qty;
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
redirect('checkout');
}
Here is my car view code .I am trying to update cart value here.No error showing. I unable to solve .Any help .Only update cart is not working . Other functionality is working good .add to cart delete to cart but update to cart does not working . I create session table and also try other suggestion and solution form stack overflow.
<form action="<?=base_url()?>cart/update_cart" method="post">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">
<div class="row">
<div class="col-xs-6">
<h5><span class="glyphicon glyphicon-shopping-cart"></span> Shopping Cart</h5>
</div>
<div class="col-xs-6">
<a href="<?=base_url()?>">
<button type="button" class="btn btn-primary btn-sm btn-block">
<span class="glyphicon glyphicon-share-alt"></span> Continue shopping
</button>
</a>
</div>
</div>
</div>
</div>
<div class="panel-body">
<?php $i = 1; ?>
<?php
//print_r($this->cart->contents() );
//die;
foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
<div class="row">
<div class="col-xs-2">
<img class="img-responsive" src="<?=base_url()?>uploads/product/<?=$items['image'];?>" />
</div>
<div class="col-xs-4">
<h5 class="product-name">
<strong><?php echo $items['name']; ?>
</strong>
<?=$items['options'];?>
</h5>
</div>
<div class="col-xs-6">
<div class="col-xs-6 text-right">
<h6><strong><?= $this->cart->format_number($items['price']); ?>
<span class="text-muted">x</span></strong></h6>
</div>
<div class="col-xs-4">
<?php //echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'size' => '1')); ?>
<input type="text" name="qty" min="1" value="<?=$items['qty'] ?>" maxlength="1" style="width: 50%;">
<input type="hidden" name="price" value="<?=$items['price'] ?>">
<input type="hidden" name="name" value="<?=$items['name'] ?>">
<input type="hidden" name="description" value="<?=$items['description'] ?>">
</div>
<div class="col-xs-2">
<a href="<?=base_url()?>cart/remove/<?=$items['rowid']?>">
<button type="button" class="btn btn-link btn-xs">
<span class="glyphicon glyphicon-trash" onclick="confirm('Are you sure want to delete')";> </span>
</button>
</a>
</div>
</div>
</div>
<hr>
<?php $i++; ?>
<?php endforeach; ?>
at view .... use only two input
<input type="text" name="qty[]" min="1" value="<?=$items['qty'] ?>" maxlength="1" style="width: 50%;">
<input type="hidden" name="rowid[]" value="<?=$items['rowid'] ?>">
at controller
you only need to change qty if you are going to update a cart
function update_cart()
{
for ($i=0; $i < count($_POST) - 1; $i++) {
$data = array(
'rowid' => $_POST['rowid'][$i],
'qty' => $_POST['qty'][$i]
);
$this->cart->update($data);
}
redirect('checkout');
}

how to make ajax call inside a edit form view in laravel

i have created a form for editing the record from db there is different time slots and i want to make delete function for them so i made a ajax call but am confused in URL www.hostname.com/dental/public/admin/manageschedule/1/api/ajax 404 (Not Found)
how to call ajax inside a laravel edit form
here is what i have done:
#extends('admin.layouts.app_inner')
#section('htmlheader_title')
Home
#endsection
#section('content')
#if (count($errors))
#foreach($errors->all() as $error)
<div class="alert alert-danger"><i class="fa fa-fw fa-close"></i> {{ $error }}</div>
#endforeach
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>Success</h4>
{{ $message }}
</div>
#endif
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title text-green"><b>Add Schedule</b></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
{!! Form::model($doctors, ['method' => 'PATCH','route' => ['manageschedule.update', $doctors->doctor_id],'class' => 'form-horizontal','files'=>true]) !!}
<div class="form-group">
<label class="col-md-3 control-label"> Select Doctor :</label>
<div class="col-md-5">
<select class="form-control" required name="doctor_name">
<?php $results = DB::select(DB::raw("SELECT day FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' Order BY id DESC ")); ?>
<option value="{{$doctors->doctor_name}}" SELECTED="YES">{{$doctors->doctor_name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" required> Day :</label>
<div class="col-md-5">
<div class="md-checkbox-inline">
<?php $day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
#foreach($day as $days)
<input name="day[]" value="<?php echo $days; ?>" type="checkbox" class="md-checkbox" <?php
foreach ($results as $row) {
if ($row->day == $days) {
echo 'checked="checked"';
} else {
}
}
?> >
<label for="checkbox7"> <?php echo $days; ?> </label>
#endforeach
</div>
</div>
</div>
<?php foreach ($results as $row) { $d=$row->day;}
$result= DB::select(DB::raw("SELECT * FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' And day='".$d."' "));
?>
<div class="form-group">
<label class="col-md-3 control-label" required>Time slots</label>
<div class="col-md-6">
<table class="table table-bordered" id="employee_table" width="50%" >
<th>Start Time</th>
<th>End Time</th>
<th>Manage</th>
<?php foreach ($result as $key=>$vari) {
$id = $vari->id;
?>
<tr id="row1">
<td><div class="input-group ">
<input type="text" class="form-control" id="time" placeholder="Start Time" name="s_time[]" value="<?php echo $vari->start_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<td><div class="input-group ">
<input type="text" class="form-control" id="time1" placeholder="Start Time" name="e_time[]" value="<?php echo $vari->end_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<?php if ($key == 0) { ?>
<td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' disabled></td>
<?php } else { ?>
<td><span class='delete' id='del_<?php echo $id; ?>'><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' id='del_<?php echo $id; ?>' ></td>
</tr>
<?php }
}
?>
</table>
<a type="button" onclick="add_rows();" class="fa fa-plus-circle btn btn-primary"> Add More Time Slots</a>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"> Per Patient Time :</label>
<div class="col-md-5">
<div class=" input-daterange">
<input type="text" name="p_time" class="form-control" placeholder="Set per patient time" id="time1" value="<?php
echo $result[0]->p_time; ?>">
<span class="help-block"> You can set only minute </span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Visibility :</label>
<div class="col-md-5">
<input type="radio" id="checkbox2_5" value="Yes" name="visible" class="md-radiobtn" <?php
foreach($result as $check)
{
if($check->visibility=='Yes'){ echo 'checked="checked"';}else{}
} ?> >
<label for="checkbox2_5"> Yes </label>
<input type="radio" id="checkbox2_10" value="No" name="visible" class="md-radiobtn" <?php foreach($result as $check)
{
if($check->visibility=='No'){ echo 'checked="checked"';}else{}
} ?>>
<label for="checkbox2_10"> No </label>
</div>
</div>
<br><br>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"id="submit">Update Schedule </button>
</div>
{!! Form::close() !!}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time').timepicker();
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time1').timepicker();
})
});
</script>
<script type="text/javascript">
function add_rows()
{
$rowno = $("#employee_table tr").length;
$rowno = $rowno + 1;
$("#employee_table tr:last").after("<tr id='row" + $rowno + "'><td><div class='input-group '><input type='text' class='form-control' placeholder='Start Time' name='s_time[]' onclick=showtime('row" + $rowno + "')><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><div class='input-group '><input type='text' class='form-control' id='time1' placeholder='End Time' name='e_time[]'><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' onclick=delete_row('row" + $rowno + "')></td></tr>");
}
function delete_row(rowno)
{
$('#' + rowno).remove();
}
</script>
<script type="text/javascript">
//Variant Deleting script///
$(document).ready(function () {
// Delete
$('.delete').click(function () {
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
alert('Are you sure you want to delete?');
$.ajax({
url: 'api/ajax',
type: 'delete',
data: {id: deleteid},
success: function (response) {
// Removing row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
}
});
});
});
</script>
<meta name="_token" content="{!! csrf_token() !!}" />
#endsection
here is my controller of api
Route::post('ajax','Controller#ajax')->name('ajax');
here is my web route:
Route::get('/', function () {
return view('auth.login');
});
Route::post('/', function () {
return view('auth.login')->with('successMsg','Please Select A role .');
});
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.home');
Route::resource('managedoctor', 'AddDocController');
Route::resource('managefront', 'AddFrontController');
Route::resource('managepatient', 'AddPatientController');
Route::resource('manageschedule', 'AddScheduleController');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('doctor')->group(function() {
Route::get('/login', 'Auth\DoctorLoginController#showLoginForm')->name('doctor.login');
Route::post('/login', 'Auth\DoctorLoginController#login')->name('doctor.login.submit');
Route::get('/', 'DoctorController#index')->name('doctor.home');
Route::get('/logout', 'Auth\DoctorLoginController#logout')->name('doctor.logout');
});
Route::prefix('frontdesk')->group(function() {
Route::get('/login', 'Auth\FrontdeskLoginController#showLoginForm')->name('frontdesk.login');
Route::post('/login', 'Auth\FrontdeskLoginController#login')->name('frontdesk.login.submit');
Route::get('/', 'FrontdeskController#index')->name('frontdesk.home');
Route::get('/logout', 'Auth\FrontdeskLoginController#logout')->name('frontdesk.logout');
});
my issue is resolved now the mistake i have done is i was not using the same route group in which am calling the controller with AUTH method

Multidimensional input with codeigniter not setting second array correct

On my controller function get form I get my banner images and I also use multidimensional array in my view
For some reason, the second banner_image title not showing but the value has been placed on the first array instead?
print_r($_POST)
Question How am I able to make sure that no matter how many banner images I select it can set the multidimensional array correct for each post.
public function getForm()
{
$banner_id = $this->uri->segment(5);
if ($banner_id)
{
$data['action'] = 'admin/design/banners/edit/' . $banner_id;
} else {
$data['action'] = 'admin/design/banners/add';
}
$banner_info = $this->admin_model_banner->getBanner($banner_id);
if ($this->input->post('banner_name')) {
$data['banner_name'] = $this->input->post('banner_name');
} elseif (!empty($banner_info)) {
$data['banner_name'] = $banner_info['banner_name'];
} else {
$data['banner_name'] = '';
}
if ($this->input->post('banner_status')) {
$data['banner_status'] = $this->input->post('banner_status');
} elseif (!empty($banner_info)) {
$data['banner_status'] = $banner_info['status'];
} else {
$data['banner_status'] = '';
}
$banner_images = array();
$banner_images_post = $this->input->post('banner_image');
if (isset($banner_images_post)) {
$banner_images = $this->input->post('banner_image');
} elseif (isset($banner_id)) {
$banner_images = $this->admin_model_banner->getBannerImages($banner_id);
}
$data['banner_images'] = array();
foreach ($banner_images as $banner_image)
{
if (is_file(FCPATH . 'image/' . $banner_image['image'])) {
$image = $banner_image['image'];
$thumb = $banner_image['image'];
} else {
$image = '';
$thumb = 'catalog/no_image.jpg';
}
$data['banner_images'][] = array(
'image' => $image,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'title' => $banner_image['title'],
'sort_order' => $banner_image['sort_order']
);
}
$data['placeholder'] = $this->model_tool_image->resize('catalog/no_image.jpg', 100, 100);
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('design/banner_form_view', $data);
}
View
<?php echo $header;?>
<div class="container">
<?php
$form = array(
'id' => '',
'role' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart($action, $form);?>
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Banner Status</label>
<div class="col-lg-10">
<input type="text" name="banner_name" class="form-control" placeholder="Enter Banner Name" value="<?php echo $banner_name;?>" size="50"/>
<?php echo form_error('banner_name', '<div class="text-danger" style="margin-top: 2rem;">', '</div>'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Banner Name</label>
<div class="col-lg-10">
<?php
$options = array('1' => 'Enabled', '0' => 'Disabled');
echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));
?>
</div>
</div>
<table id="images" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left">Title</td>
<td class="text-left">Image</td>
<td>Sort Order</td>
</tr>
</thead>
<tbody>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td class="text-left">
<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" value="<?php echo $banner_image['title']; ?>" class="form-control">
</td>
<td class="text-left">
<a href="" id="thumb_image_<?php echo $image_row; ?>" data-toggle="image" class="img-thumbnail">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" />
</a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input_image_<?php echo $image_row; ?>" /></td>
<td class="text-right"><input type="text" name="banner_image[<?php echo $image_row; ?>][sort_order]" value="<?php echo $banner_image['sort_order']; ?>" placeholder="Sort Order" class="form-control" /></td>
<td class="text-left">
<button type="button" onclick="$('#image-row<?php echo $image_row; ?>').remove();" class="btn btn-danger"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td colspan="3"></td>
<td class="text-left">
<button type="button" onclick="addImage();" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
</tfoot>
</table>
</div>
<div class="panel-footer">
<div class="text-right"><button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</button></div>
</div>
</div>
<?php echo form_close();?>
</div>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage()
{
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" class="form-control" value="">';
html += '</td>';
html += '<td class="text-left">';
html += '<a href="" id="thumb_image_' + image_row + '" data-toggle="image" class="img-thumbnail">';
html += '<img src="<?php echo $placeholder; ?>" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '</a>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input_image_' + image_row + '" />';
html += '</td>';
html += '<td class="text-right">';
html += '<input type="text" name="banner_image[' + image_row + '][sort_order]" value="" placeholder="Sort Order" class="form-control" />';
html += '</td>';
html += '</tr>';
$('#images tbody').append(html);
image_row++;
}
</script>
Solved
After doing some investigation I found problem was to do with
name="banner_image[<?php echo $image_row; ?>][title]"
On script, I forgot to add it like
name="banner_image[' + image_row + '][title]"
Working now

Resources