Checkbox Array Validation Codeigniter - codeigniter

On my form each row has it's on submit button and you need to check the check box before you can delete it else it should through error.
Question: My checkbox is in_array but if I do not check the box and then press submit it does not through the codeigniter form_validation error. I have used $this->form_validation->set_rules('selected[]', 'Selected', 'required'); But error not showing up.
What is the best solution in making it getting form_validation error to work?
View
<?php echo form_open('admin/design/layout/delete'); ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td style="width: 1px;" class="text-center">
<input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" />
</td>
<td>Layout Name</td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php if ($layouts) { ?>
<?php foreach ($layouts as $layout) { ?>
<tr>
<td class="text-center"><?php if (in_array($layout['layout_id'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" />
<?php } ?>
</td>
<td><?php echo $layout['name']; ?></td>
<td class="text-right">
<button type="submit" class="btn btn-danger">Delete</button>
Edit
</td>
</tr>
<?php } ?>
<?php } else { ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php echo form_close(); ?>
Controller Function
public function delete() {
$this->load->library('form_validation');
$this->form_validation->set_rules('selected[]', 'Selected', 'required');
if ($this->form_validation->run() == FALSE) {
echo "Error";
$this->get_list();
} else {
$selected_post = $this->input->post('selected');
if (isset($selected_post)) {
foreach ($selected_post as $layout_id) {
}
echo "Deleted $layout_id";
$this->get_list();
}
}
}

It won't validate per field. selected[] selector in rules means, when you submit your form, it should be at least one selected item. Now you have submit buttons, which are independently submit the form, no matter where are they in the dom, and which checkboxes are selected.
Currently it the same, as you would have one submit button at the end.
I would add some javascript, and set if the checkbox is not selected, you can disable that field:
<script>
$(function() {
$('input:checkbox').on('change', function() {
if($(this).is(':checked')) {
$(this).closest('tr').find('button:submit').prop('disabled', false);
}
else {
$(this).closest('tr').find('button:submit').prop('disabled', true);
}
})
})
</script>
And add disabled to your submit buttons:
<button type="submit" class="btn btn-danger" disabled>Delete</button>
It's not a server side validation, but you can achieve to prevent push the button next unchecked checkboxes.

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>

Delete Data using code igniter not working

I'm trying to delete data by id but it doesn't work.
I have some code like this.
Controller :
public function delete()
{
if (isset($_GET['del'])) {
$ii = $this->input->post('id');
$this->P6_model->delete($ii);
$this->load->view('p6home');
}
}
Model :
public function delete($i)
{
return $this->db->delete('contacts', array('id' => $i));
}
Routes :
$route['deldata'] = 'p6/delete';
View :
foreach ($contacts as $data) {
?>
<tr>
<input type="hidden" name="id" value="<?=$data->id?>"/>
<td data-label="Name"><?=$data->name?></td>
<td data-label="address"><?=$data->address?></td>
<td data-label="phone"><?=$data->phone?></td>
<td>
<button class="positive ui button">Update</button>
<button class="negative ui button" onclick="return confirm('Are you sure?')" name="del" href="deldata">Delete</button>
</td>
</tr>
<?php
}
?>
Thanks before.
you must have declared base_url, right? Use that in your link to redirect a page. Also, give the get parameter in the URL itself. POST will not work without a form. This should work for you. View:
<?php
foreach ($contacts as $data) {
?>
<tr>
<td data-label="Name"><?=$data->name?></td>
<td data-label="address"><?=$data->address?></td>
<td data-label="phone"><?=$data->phone?></td>
<td>
<button class="positive ui button">Update</button>
<button class="negative ui button" onclick="return confirm('Are you sure?')" name="del" href="<?php echo base_url('deldata')."/$data->id"; ?>">Delete</button>
</td>
</tr>
<?php
}
?>
Controller:
public function delete($id)
{
$this->P6_model->delete($id);
$this->load->view('p6home'); //instead of loading the view here, try redirecting to a controller function and load the view there.
}

You did not select a file to upload, file upload error in Codeigniter

I'm trying to add singer information with image. the information can be successfully added without image but if i try to insert data with image, error occurred with "You did not select a file to upload" message.
My controller function is this...
public function add_edit_singer($id = '')
{
if($this->input->post('save_singer_info')){
$post=$this->input->post();
$add=array(
'name'=>$post['sname'],
'bio'=>$post['bio']
);
$img1=$_FILES['photo']['name'];
if($img1){
$config['upload_path'] = 'images/singer/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$error = $this->upload->display_errors();
$this->session->set_flashdata('info',$error);
redirect('admin/singer_manager');
}
$data = array('upload_data' => $this->upload->data());
$image = $data['upload_data']['file_name'];
$add['image']=$image;
}
else{
$add['image']='no_image.jpg';
}
$table='tbl_singer';
if($this->singer_manager->add($add,$table)){
$this->session->set_flashdata('info',"Artist/Band Information Added Successfully.");
redirect('admin/singer_manager');
}
else{
redirect('admin/singer_manager');
}
}
else{
$data['main_content']='admin/singer/add_edit_singer_view';
if($id != '')
$data['editdata'] = $this->common_model->get_where('tbl_singer', array('id' => $id));
$this->load->view('admin/include/template_view',$data);
}
}
my Model function is...
function add($data,$table){
$name = $data['name'];
$res = $this->db->insert($table,$data);
if($res)
{
return true;
}
else
{
return false;
}
}
and my Form is...
<form role="form" enctype="multipart/form-data" action="<?php echo base_url('admin/singer_manager/add_edit_singer/' . $id); ?>"
method="post"
id="user_form">
<table class="table table-hover">
<tr>
<td>Singer Name</td>
<td>
<input type="text" class="form-control required" name="sname"
value="<?php if (isset($name)) {
echo $name;
} ?>"/>
</td>
</tr>
<tr>
<td>Bio</td>
<td>
<textarea class="form-control required" name="bio">
<?php if (isset($bio)) {
echo $bio;
} ?>
</textarea>
</td>
</tr>
<tr>
<td>Image</td>
<td>
<?php if (isset($image)) {?>
<div class="row">
<div class="col-xs-6 col-md-4">
<a href="<?php echo base_url().'images/singer/'.$image;?>" class="thumbnail">
<img src="<?php echo base_url().'images/singer/'.$image;?>" width="120" height="140" id="img_prev" />
</a>
</div>
</div>
<?php
} ?>
<input type="file" name="photo" size="20" />
</td>
</tr>
<tr>
<td colspan="2">
<?php if (isset($id)) { ?><input type="hidden" name="id" value="<?php echo $id; ?>" /><?php } ?>
<input type="submit" class="btn btn-success" id="btn_save" name="save_singer_info"value="Save"/>
<input type="reset" class="btn btn-info" id="reset"/>
<input type="button" class="btn btn-danger" value="Cancel"onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>
change
$this->upload->do_upload()
to
$this->upload->do_upload('photo')
may be it solve the problem

Fetch the entered quantity box values from multiple quantity box to cart page in magento

I am new to Magento.
I am displaying the attributes in table format using foreach in product detail page.
Problem i am facing is when i enter the value in any quantity box, it takes the last quantity value to the cart page since i am using foreach loop to display the quantity box.I need to display the exact value which i have entered in the quantity box.
Code:
<table border="1" style="width:100%;">
<thead>
<tr>
<th>Fabric</th>
<th>Color</th>
<th>Required Qty</th>
<th>Total Cost</th>
<th>Cart</th>
</tr>
</thead>
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'fabric');
$buttonTitle = $this->__('Add to Cart');
$i=0;foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
$i++;
if($i==1) continue;
?>
<tbody>
<tr>
<td>
<?php echo $attributeArray[$option['value']] = $option['label'];
?>
</td>
<td>
<select name="color" id="color">
<option>Select Color</option>
<?php
$color = Mage::getModel('eav/config')->getAttribute('catalog_product', 'fabric_color');
$j=0;foreach ( $color->getSource()->getAllOptions(true, true) as $option_color){
$j++;
if($j==1) continue;?>
<option value="<?php echo $option_color['value'];?>" price="<?php echo $option_color['price'];?>"><?php echo $option_color['label'];?></option>
<? }
?>
</select>
</td>
<td>
<?php if($_product->isSaleable()): ?>
<div class="add-to-cart">
<?php if(!$_product->isGrouped()): ?>
<label for="qty"><?php echo $this->__('Qty:') ?></label>
<div class="qty_pan">
<input type="text" name="qty" id="qty<?=$i;?>" maxlength="12" value="1" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</td>
<td ><span class="qty<?=$i;?>" id=""><?php echo $_product->getPrice();?></span></td>
<td>
<button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
<!-- <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>-->
<?php //echo $this->getChildHtml('', true, true) ?>
</td>
</tr>
</tbody>
<?php }?>
</table>
Screenshot:
https://imageshack.us/scaled/large/12/detailpage.png
Any help is appreciated!.
I Got The solution.
We can use Query String to fetch the quantity values to cart.
Yourdomain.com/checkout/cart/add?product=getId();?>&qty=1
You can use the above querystring in href.
Hope this Helps.

JToolbar frontend submit value on click

I'm building a joomla component and I can't find a solution to the following. In my front end I'm using the joomlas build in class JToolbar to handle events on click like edit, delete so one.
<form action="<?php echo JRoute::_('index.php');?>" method="post"
name="termForm" id="adminForm">
<table class="stripeMe">
<tbody>
<thead>
<tr>
<th>Begriff</th>
<th>Definition</th>
<?php if ($user->authorize('com_glossary', 'edit', 'glossary', 'all')): ?><th>Published</th> <?php endif; ?>
</tr>
</thead>
<?php foreach($this->items as $i => $item): ?>
<tr>
<td>
<span class="title"><?php echo $item->tterm; ?></span>
<?php if ($user->authorize('com_glossary', 'edit', 'bearbeiten', 'all')):?>
<?php echo $this->getEdit(); ?><?php endif; ?>
</td>
<td><?php echo $item->tdefinition; ?></td>
<?php if ($user->authorize('com_glossary', 'edit', 'bearbeiten', 'all')): ?>
<td><?php echo $this->getPublished(); ?></td> <?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div>
<input type="hidden" name="task" value="" /> <input type="hidden"
name="id" value="" onclick="submitbutton(<?php echo count( $item->id ); ?>);" /> <input type="hidden"
name="option" value="com_glossary" /> <input type="hidden"
name="controller" value="bearbeiten" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
I would like to pass to id of the selected row to the sub-controller on button event and I don't really know how to do it
Here you have some useful tips about using JToolbar on the frontend http://docs.joomla.org/How_to_use_the_JToolBar_class_in_the_frontend
I have done it once in the past, and from what I remember I did some tricks in order to make it work.
1.) Firstly remove the "id" input and add the following one at the end of your form:
<input type="hidden" name="boxchecked" value="0" />
2.) Secondly make sure Mootools is attached to the source
3.) Finally: There, where you started your foreach loop, after "tr" tag add another table column:
<td><?php echo JHTML::_('grid.id', $i, $item->id ); ?></td>
Don't forget to create a column heading in thead for this column.
These steps will create a checkbox in the first cell of every row and make the form able to send selected field's id with request.
edit:
tbody tag is in wrong place, it's supposed to be after thead tag. Also there is no use of attaching events to hidden input as they won't be triggered
Cheers
Peter

Resources