CakePHP validationErrors empty (validation = true; saveAll = false; validationErrors = null) - validation

Good afternoon.
2 days I have been reading different forums and similar situations regarding the problem that occurs to me, however I have not succeeded in correcting it.
This is my situation:
Order Model
class Order extends AppModel {
public $belongsTo = array("Client", "OrderType");
public $hasMany = array(
'OrderDetail' => array(
'className' => 'OrderDetail',
'foreignKey' => 'order_id',
'counterCache' => true
)
);
public $validate = array(
'client_id' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Favor seleccione un Cliente'
)
),
'date_from' => array(
'required' => array(
'rule' => array('email', 'notEmpty'),
'message' => 'Favor ingresar correo'
)
)
);
}
OrderDetail Model
class OrderDetail extends AppModel {
public $belongsTo = array('Product', 'Smell', 'Order');
public $validate = array(
'product_id' => array(
'required' => true,
'rule' => array('notEmpty'),
'message' => 'Debe ingresar un Producto'
),
'quantity' => array(
'required' => true,
'rule' => array('notEmpty'),
'message' => 'Debe ingresar una Cantidad'
)
);
}
OrdersController Controller
class OrdersController extends AppController {
public function index() {
$this->set('title_for_layout', 'Ordenes');
$this->layout="panel";
}
/* Function para Pruebas */
public function test($mode = null) {
$this->set('title_for_layout', 'Ordenes de Prueba');
$this->layout="panel";
$data = $this->Order->Client->find('list', array('fields' => array('id', 'nombre'), 'order' => array('nombre ASC')));
$this->set('clients', $data);
$data = $this->Order->OrderDetail->Product->find('list', array('fields' => array('id', 'name'), 'order' => array('name ASC')));
$this->set('products', $data);
$data = $this->Order->OrderDetail->Smell->find('list', array('fields' => array('id', 'name'), 'order' => array('name ASC')));
$this->set('smells', $data);
if(is_null($mode)) {
$this -> render('Tests/index');
}
if($mode == 'new') {
$this -> render('Tests/new');
// Guardar Nueva Orden
if ($this->request->is('post')) {
/*
$validates = $this->Order->validates($this->request->data);
debug($validates);
$saved = $this->Order->saveAll($this->request->data);
debug($saved);
debug($this->validationErrors);
*/
if($this->Order->saveAll($this->request->data)) {
$this->Session->setFlash('Nueva Orden Creada', 'flash_success');
return $this->redirect('/orders/test');
} else {
$this->Session->setFlash('La orden no pudo ser creada, favor revise el formulario','default',array('class' => 'alert alert-danger center'));
return $this->redirect('/orders/test/new');
}
}
}
}
/* Function para Servicio */
public function service($mode = null) {
$this->set('title_for_layout', 'Ordenes de Servicio');
$this->layout="panel";
if(is_null($mode)) {
$this -> render('Services/index');
}
if($mode == 'new') {
$this -> render('Services/new');
}
}
/* Function para Retiros */
public function removal($mode = null) {
$this->set('title_for_layout', 'Ordenes de Retiro');
$this->layout="panel";
if(is_null($mode)) {
$this -> render('Removals/index');
}
if($mode == 'new') {
$this -> render('Removals/new');
}
}
}
OrderDetailController Controller
Do not exist (I assumed that I do not need it for this purpose)
Order/Test/new.ctp
<div class="matter">
<div class="container">
<!-- Today status. jQuery Sparkline plugin used. -->
<!-- Today status ends -->
<div class="row">
<div class="col-md-12">
<div class="widget">
<div class="widget-head">
<div class="pull-left">Nueva Orden de Prueba</div>
<div class="clearfix"></div>
</div>
<div class="widget-content">
<div class="padd">
<!-- Content goes here -->
<!-- Flash Message -->
<div class="form-group">
<div class="col-lg-12">
<?php echo $this->Session->flash(); ?>
</div>
</div>
<?php echo $this->Form->create('Order', array('class'=>'form-horizontal', 'novalidate'=>'novalidate')); ?>
<h3>Datos del Cliente</h3>
<div class="widget">
<div class="widget-content">
<div class="padd">
<!-- Cliente y Tipo Orden -->
<div class="form-group">
<label class="control-label col-lg-1">Cliente *</label>
<div class="col-lg-5">
<?php echo $this->Form->input('Order.0.client_id', array('label'=>false, 'class'=>'form-control chosen-select', 'placeholder'=>'Seleccione Cliente', 'type'=>'select','options' => $clients, 'empty' => 'Seleccione Cliente')); ?>
</div>
<div class="col-lg-1">
<?php echo $this->Html->link('Nuevo Cliente', '/clients/add', array('class'=>'btn btn-primary')); ?>
</div>
<?php echo $this->Form->input('Order.0.order_type_id', array('label'=>false, 'class'=>'form-control', 'placeholder'=>'Ingrese Tipo de Orden', 'type'=>'hidden', 'value'=>3)); ?>
</div>
</div>
</div>
</div>
<h3>Vigencia tentativa de la Prueba</h3>
<div class="widget">
<div class="widget-content">
<div class="padd">
<div class="form-group">
<label class="control-label col-lg-1">Desde</label>
<div class="col-lg-2">
<?php echo $this->Form->input('Order.0.date_from', array('label'=>false, 'class'=>'form-control datepicker', 'placeholder'=>'Desde', 'type'=>'text')); ?>
</div>
<label class="control-label col-lg-1">Hasta</label>
<div class="col-lg-2">
<?php echo $this->Form->input('Order.0.date_to', array('label'=>false, 'class'=>'form-control datepicker', 'placeholder'=>'Hasta', 'type'=>'text')); ?>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<h3 class="pull-left">Elementos a incorporar en Prueba</h3>
<button type="button" class="btn addRow pull-right btn-primary"><i class="fa fa-plus"></i> Agregar Item</button>
</div>
</div>
<div class="widget">
<div class="widget-content">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Cantidad</th>
<th>Aroma</th>
<th>Nº Registro</th>
<th width="90px;">Acciones</th>
</tr>
</thead>
<tbody>
<?php for ($i=0;$i<10;$i++) { ?>
<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $this->Form->input('OrderDetail.'.$i.'.product_id', array('label'=>false, 'class'=>'form-control chosen-select', 'type'=>'select', 'options' => $products, 'empty' => 'Seleccione Item', 'disabled' => 'disabled')); ?></td>
<td><?php echo $this->Form->input('OrderDetail.'.$i.'.quantity', array('label'=>false, 'class'=>'form-control', 'placeholder'=>'Cantidad', 'type'=>'text', 'disabled' => 'disabled')); ?></td>
<td><?php echo $this->Form->input('OrderDetail.'.$i.'.smell_id', array('label'=>false, 'class'=>'form-control chosen-select', 'placeholder'=>'Aromas', 'type'=>'select', 'options' => $smells, 'empty' => 'Seleccione Aroma', 'disabled' => 'disabled')); ?></td>
<td><?php echo $this->Form->input('OrderDetail.'.$i.'.product_number', array('label'=>false, 'class'=>'form-control', 'placeholder'=>'Identificador de Item', 'type'=>'text', 'disabled' => 'disabled')); ?></td>
<td>
<center>
<?php if($i!=0) { ?>
<button type="button" class="btn removeRow btn-xs btn-danger"><i class="fa fa-times"></i> Borrar</button>
<?php } ?>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- Content ends here -->
</div>
</div>
<div class="widget-foot">
<!-- Botones -->
<div class="form-group">
<div class="col-lg-12">
<?php echo $this->Form->button('Crear Orden', array('class' => array('btn', 'btn-success', 'pull-right'), 'type'=>'submit')); ?>
</div>
</div>
</div>
<?php echo $this->Form->end(); ?>
</div>
</div>
</div>
</div>
</div>
And Now --- The Problem
When I press "Crear Orden" (Save) Button, and Debug this situation I Obtain this...
/app/Controller/OrdersController.php (line 36)
true -> This is debug($this->Order->validates($this->request->data))
/app/Controller/OrdersController.php (line 38)
false -> This is debug($this->Order->saveAll($this->request->data))
/app/Controller/OrdersController.php (line 39)
null -> This is debug($this->validationErrors)
If I enter all correctly, the form is saved successfully. Each field in its respective table, even as a "multiple records".
The problem is that I can not display error messages, because it indicates that the validation is "true"
Please, if you can help me.
Thanks a lot.
Regards,

Related

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()

Ajax action called twice

I need to improve a client's website and I had detect an strange error in their behaivour.
When the web call one ajax action, it is called twice. I have breakpoints in js call and in the PHP action code, and the js run once (it is good) but PHP run twice.
I don't know what else test.
I had checked:
No break links (favicons, or css and js resources, etc)
At begining of the event which call the actio, I just had event.preventDefault();
At the ending of this event, I had added: return false;
At the form tag, I have this: onsubmit="event.returnValue = false; return false;"
Edit: I have this issue over all browsers.
Edit II: code
The action in the controller:
public function getMapOffers() {
$temporal = $this->getOffers('all');
return $temporal;
}
public function getOffers($offerType = 'all',$opciones=false) {
// loadModels
$this->loadModel('Offer');
$this->autoRender = false; // We don't render a view in this example
//$this->request->onlyAllow('ajax'); // No direct access via browser URL
$this->loadModel('Customer');
$customer = $this->Auth->user();
$customer['googleaddress'] = $this->Customer->getDetaultGoogleAddress($customer);
$latitude_customer = isset($customer['latitude']) ? $customer['latitude'] : 0;
$longitude_customer = isset($customer['longitude']) ? $customer['longitude'] : 0;
$data = array();
$options = array();
//$pagination_limit = 600;
$page = isset($this->request->data['page']) ? $this->request->data['page'] : NULL;
$latitude = isset($this->request->data['latitude']) ? $this->request->data['latitude'] : $latitude_customer;
$longitude = isset($this->request->data['longitude']) ? $this->request->data['longitude'] : $longitude_customer;
$category = isset($this->request->data['category']) ? $this->request->data['category'] : '';
$keyword = isset($this->request->data['keyword']) ? $this->request->data['keyword'] : '';
//jfc
$nacionales = isset($this->request->data['nacionales']) && $this->request->data['nacionales'] === "true" ? TRUE : FALSE;
if( $nacionales ){
$array_filters = array('national' => 1, 'map' => 'true', 'page' => $page, 'keyword' => $keyword, 'category' => $category, 'latitude' => $latitude, 'longitude' => $longitude);
}
else{
$array_filters = array('map' => 'true', 'page' => $page, 'keyword' => $keyword, 'category' => $category, 'latitude' => $latitude, 'longitude' => $longitude);
}
//!jfc
if ($offerType == 'featured') {
$isFeaturedRequest = true;
}
if ($offerType == 'lastminute') {
$isLastMinuteRequest = true;
}
if ($offerType == 'all') {
$isFeaturedRequest = true;
$isLastMinuteRequest = true;
$data['page'] = $page;
$options['page'] = $page;
}
if(isset($this->request->data['firstsearch']) && intval($this->request->data['firstsearch']) < 2){
$options['limit'] = 100;
}
$result = $this->Offer->getPublishedOffers($array_filters, $options);
$data['total'] = 10000;
$data['map'] = true;
$data['offers'] = $this->prepareOfferContent($result['offers'],$opciones);
if ($isFeaturedRequest) {
$data['featured'] = $this->prepareOfferContent($result['featured'],$opciones);
}
if ($isLastMinuteRequest) {
$data['lastminute'] = $this->prepareOfferContent($result['lastminute'],$opciones);
}
if (isset($data['offers']) && empty($data['offers'])) {
$data['offers'] = '';
}
if (isset($data['featured']) && empty($data['featured'])) {
$data['featured'] = '';
}
if (isset($data['lastminute']) && empty($data['lastminute'])) {
$data['lastminute'] = '';
}
$temporal2 = json_encode($data);
/*try{
file_put_contents('offers.log', print_r($data, true));
}
catch (Exception $e){
//json_encode($e);
}*/
return $temporal2;
}
ctp file:
<!--Search-->
<div class="row">
<form id="offer-search" class="form form-horizontal" method="post" action="#" accept-charset="UTF-8" onsubmit="event.returnValue = false; return false;">
<div class="col-md-12">
<h1>Buscador de ofertas</h1>
<div class="col-sm-3 offer-search-item">
<input type="hidden" value="1" name="data[firstsearch]" id="firstsearch" />
<?php echo $this->Form->input('keyword' , array('class'=>'form-control' ,'id' => 'keywordoffersearch', 'placeholder' => 'Nombre de oferta', 'label' => false )); ?>
</div>
<div class="col-sm-4 offer-search-item" id="divDireccion">
<div class="input-group">
<span class="input-group-addon" id="mapcurrentgeoposition" title="<?php echo __('I want to send my current position') ?>"><i class="icon-screenshot"></i></span>
<?php
if( $customer['googleaddress'] === Configure::read("App.DefaultDataGoogleMaps") ||$customer['googleaddress'] === Configure::read("App.DefaultDataGoogleMaps").", Madrid, Madrid, 28013" ){
//todo: quitar el OR, está por un error en la página de perfil
$customer['googleaddress'] = "";
}
echo $this->Form->input('googlemapsaddress' , array('class'=>'form-control' ,'id' => 'googlemapsaddress', 'placeholder' => 'Ubicación', 'label' => false , 'default' => $customer['googleaddress'] ));
echo $this->Form->input('latitude', array('type' => 'hidden', 'value' => $latitude , 'id' => 'latitude' ) );
echo $this->Form->input('longitude', array('type' => 'hidden', 'value' => $longitude, 'id' => 'longitude' ) );
?>
</div>
</div>
<div class="col-sm-3 offer-search-item">
<?php echo $this->Form->input('categories', array('options' => $categories,'empty' => __('Todos los sectores'), 'class'=>'form-control', 'label' => false, 'id' => 'categorymapfilter'));?>
</div>
<div class="col-sm-2 offer-search-item">
<button type="submit" id="submitOfferFilter" class="btn btn-default btn-success"><i class="icon-refresh"></i> <?php echo __('Actualizar ofertas') ?></button>
</div>
<div class="col-sm-12 offer-search-item">
<?php echo $this->Form->input('nacionales', array('onchange' => 'changeNacionales(this);', 'type' => 'checkbox', 'label' => 'Mostrarme sólo las ofertas nacionales.' , 'id' => 'chkNacionales' ) ); ?>
</div>
</div>
</form>
</div>
<hr class="normal">
<!--./Search-->
<!--Map-->
<div class="row" style="position: relative">
<div id="loadingMap" class="col-lg-12" style="position: absolute;z-index: 9999; background-color: #f5f6f6; width: 100%">
<p class="text-center" style="height: 400px; position: relative">
<?php echo $this->Html->image("loading.gif", array('width' => '32', 'height' => '32', 'style' => 'position: absolute; top: 50%')) ?>
</p>
</div>
<div class="col-md-12">
<div id="map-canvas" class="map map_canvas"></div>
<hr class="hr-normal">
</div>
</div>
<!--./Map-->
<!-- Last Minute -->
<div id="lastMinuteList" class="row" style="margin: 0 -30px">
</div>
<hr class="offers-separator" style="margin: 20px -30px;">
<!-- ./Last Minute -->
<!--Offers-->
<div class="row" style="position: relative">
<div id="loadingOffers" class="col-lg-12" style="position: absolute;z-index: 9999; background-color: #f5f6f6; width: 100%">
<p class="text-center" >
<?php echo $this->Html->image("loading.gif", array('width' => '32', 'height' => '32', 'style' => 'position: absolute; top: 50%')) ?>
</p>
</div>
<div id="featuredOffers" class="hide">
<div class="row">
<p class="view-all-featured-wrapper align-left featured-title">
<span class="lead"><img width="20" src="/img/mobile/ic_destacado.png" /> Ofertas destacadas</span>
<button id="view-all-featured" class="btn btn-link bnt-xs pull-right">
<span id="message-link-featured">
<i class="icon-chevron-down"></i> Mostrar todas</span>
</button>
</p>
</div>
<div clas="row">
<div id='lista-main'>
<div id="mi-lista-contenedor" class="row" style="position: relative">
<ul id='mi-lista'>
</ul>
</div>
<div class="controls center">
<button class="btn prev"><i class="icon-chevron-left"></i></button>
<button class="btn next"><i class="icon-chevron-right"></i></button>
</div>
</div>
</div>
</div>
<div id="offers" style="display: none">
<!-- Featured -->
<!-- <div id="featuredOffers" class="hide">
<div class="row">
<p class="view-all-featured-wrapper align-left featured-title">
<span class="lead"><img width="20" src="/img/mobile/ic_destacado.png" /> Ofertas destacadas</span>
<button id="view-all-featured" class="btn btn-link bnt-xs pull-right">
<span id="message-link-featured">
<i class="icon-chevron-down"></i> Mostrar todas</span>
</button>
</p>
</div>
<div clas="row">
<div id='lista-main'>
<div id="mi-lista-contenedor" class="row" style="position: relative">
<ul id='mi-lista'>
</ul>
</div>
<div class="controls center">
<button class="btn prev"><i class="icon-chevron-left"></i></button>
<button class="btn next"><i class="icon-chevron-right"></i></button>
</div>
</div>
</div>
</div>-->
<hr class="offers-separator">
<!-- List offers -->
<div class="list-offers row">
<div id="filterList"></div>
</div>
<!-- ./List offers -->
<!-- Paginator -->
<!-- <div id="paginator-offers" class="text-center"></div>-->
</div>
</div>
<!--./Offers-->
<?php echo $this->element('customer/mapoffers') ?>
<!-- JFC appbanner -->
<div class="row">
<div class="col-sm-12">
<div style="text-align:center;">
<a title="<?php echo __("Descarga la APP de Start Discount Club en tu móvil"); ?>" href="/pages/descarga-app-start-club/">
<img style="margin: 15px 25px 0; max-width: 90%;" src="/img/banner_footer.jpg" />
</a>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var espublic=false;
function changeNacionales(that){
var divDireccion = $("#divDireccion");
if( $(that).is(':checked') ){
divDireccion.hide('slow');
}
else{
divDireccion.show('slow');
}
}
</script>
Ajax call:
this.getListOffers = function(options){
var that = this;
var config = options ? options : {};
var page = config.page ? config.page : 1;
var data = {
'page': page,
'keyword': this.$keywordOfferSearch.val(),
'category': this.$categoryMapFilter.val(),
'latitude': this.$latitude.val(),
'longitude': this.$longitude.val(),
'nacionales': this.$chkNacionales.prop( "checked" ),
'firstsearch': this.$firstsearch
};
//console.log("--------DATA-------");
//console.log(data);
//console.log("------END DATA-----");
$.ajax({
'type': 'post',
'url': this.urlAPI,
'data': data,
'dataType': 'json',
success: function( locations ) {
that.$firstsearch += 1;
that.createListOffers( locations );
if (offerMapDesktop.mapType === "mobile") {
that.setListLoaded({'state': true});
}
},
error: function(e) {
$.jGrowl(messages.error.basic);
}
});
};
Solved, there was other js file with other ajax call...

How to Show Codeigniter Validation Errors in Popup using AJAX

Hello Everybody I am new with Codeigniter I have a Registration form Popup.When User tries to Register. it register with using ajax but when user input invalid details it should shows Codeigniter Error Messages but it won't and popup automatically closed. what should i do. plz help
This is My Controller Function:-
public function register(){
$title['pageTitle'] = 'Register Page';
$this->load->library('form_validation');
$this->load->model('User_model');
$this->form_validation->set_error_delimiters('<div class = "error">','</div>');
$this->form_validation->set_rules('firstname','First Name','trim|required|alpha|min_length[3]|max_length[30]');
$this->form_validation->set_rules('lastname','Last Name','trim|required|alpha|min_length[3]|max_length[30]');
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('password','Password','trim|required|md5');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|md5|matches[password]');
if($this->form_validation->run() == false){
echo validation_errors();
}else {
$data['userdata'] = $this->User_model->addUser();
}
}
This is My Model funtion :-
public function addUser(){
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
);
$q = $this->db->insert($this->tablename,$data);
return $result = $q->result_array();
}
This is My View(Popup):-
<div class="modal fade login_form" id="signin_model" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content pdng_mdls">
<div class="modal-header model_hdngs">
<i class="fa fa-times" aria-hidden="true"></i>
<h4 class="modal-title" id="exampleModalLabel"></h4>
</div>
<div class="modal-body">
<div class="mdl_hdrs">
<?php echo form_label('Create Your Account', 'createyouraccount'); ?>
</div>
<?php
$attributes = array('name' => 'myform','id'=>'reg_form');
echo form_open('',$attributes); ?>
<div class="row">
<div class="col-sm-6">
<?php echo form_label('First Name:', 'firstname'); ?>
<?php echo form_input(array('id' => 'firstname','class'=>'inpt_bhg cracnt','name' => 'firstname','placeholder'=>'First Name'));?>
<span class="text-danger"><?php echo form_error('firstname'); ?></span>
</div>
<div class="col-sm-6">
<?php echo form_label('Last Name:', 'lastname'); ?>
<?php echo form_input(array('id' => 'lastname','class'=>'inpt_bhg cracnt','name' => 'lastname','placeholder'=>'Last Name'));?>
<span class="text-danger"><?php echo form_error('lastname'); ?></span>
</div>
<div class="col-sm-12">
<?php echo form_label('Email:', 'email'); ?>
<?php echo form_input(array('id' => 'email','class'=>'inpt_bhg cracnt','name' => 'email','placeholder'=>'Email Address'));?>
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="col-sm-12">
<?php echo form_label('Password:', 'password'); ?>
<?php echo form_password(array('id' => 'registerpassword','class'=>'inpt_bhg cracnt','name' => 'password','placeholder'=>'Password'));?>
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="col-sm-12">
<?php echo form_label('Confirm Password:', 'password'); ?>
<?php echo form_password(array('id' => 'registerpassword','class'=>'inpt_bhg cracnt','name' => 'cpassword','placeholder'=>'Confirm Password'));?>
<span class="text-danger"><?php echo form_error('cpassword'); ?></span>
</div>
</div>
<div class="progress model_progress_bar" id="example-progress-bar-hierarchy-container">
</div>
<div class="ps_str">Password Strength</div>
<span id = "example-getting-started-text"></span>
<div class="final_sbmt_btns">
<?php echo form_submit('submit', 'Create Account','class="finl_sbmt_btns"');?>
</div>
</form>
<div class="go_backs">Go Back</div>
</div>
</div>
</div>
</div>
And This is my AJAX :-
<script type="text/javascript">
$(document).ready(function() {
$('#reg_form').submit(function(){
$.ajax({
type: "POST",
url: BASE_URL + "User_Controller/register/",
data: $("#reg_form").serialize(),
success: function(res){
alert(res);
}
});
});
});
</script>

model not inserting select option

My model is not inserting my modify and access data that I select on my view.If my select option on my view is select option 1 it inserts value 0 even though 1 selected. Not sure why on model or view its not inserting the correct one?
Each controller has its own modify and access select option i would like to be able to insert if select 1 for enable or 0 disbale?
How can I make the both select options work with my model so inserts correct what have chosen.
Model Function
<?php
class Model_user_group extends CI_Model {
public function addUserGroup() {
$name = $this->input->post('name');
$controllers = $this->input->post('controller');
$access = $this->input->post('access');
$modify = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => strtolower($name),
'controller' => $controllers[$i],
'access' => $access,
'modify' => $modify
);
$this->db->insert($this->db->dbprefix . 'user_group', $data);
}
}
View
<?php echo Modules::run('admin/common/header/index');?>
<div id="wrapper">
<?php echo Modules::run('admin/common/menu/index');?>
<div id="page-wrapper" >
<div id="page-inner">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left" style="padding-top: 7.5px"><h1 class="panel-title"><?php echo $title;?></h1></div>
<div class="pull-right">
Cancel
<button type="submit" onclick="submit()" class="btn btn-primary">Save</button>
</div>
</div>
<div class="panel-body">
<?php echo validation_errors('<div class="alert alert-warning text-center">', '</div>'); ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open_multipart('admin/users_group_add', $data);?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php $data1 = array('id' => 'name', 'name' => 'name', 'class' => 'form-control', 'value' => set_value('name'));?>
<?php echo form_input($data1);?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<?php foreach ($controllers as $controller) {?>
<tbody>
<tr>
<td>
<?php echo ucfirst(str_replace("_"," ", $controller));?>
<input type="hidden" name="controller[]" value="<?php echo $controller;?>" />
</td>
<td>
<select name="access" class="form-control">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
</td>
<td>
<select name="modify" class="form-control">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<?php echo form_close();?>
</div>
</div>
</div><!-- # Page Inner End -->
</div><!-- # Page End -->
</div><!-- # Wrapper End -->
<?php echo Modules::run('admin/common/footer/index');?>
Your view file seems has access and modify option for each controller. But your input name is same.So the value of $access and $modify is the last input value. You can solve this way.Give access and modify input name as array
<select name="access[]" class="form-control">
...
<select name="modify[]" class="form-control">
Now your model
$name = $this->input->post('name');
$controllers = $this->input->post('controller');
$accesses = $this->input->post('access');
$modifies = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => strtolower($name),
'controller' => $controllers[$i],
'access' => $accesses[$i],
'modify' => $modifies[$i]
);
$this->db->insert($this->db->dbprefix . 'user_group', $data);
}
Hope you understand and solves your problem

form validation with array not working

On my form I have some check boxes. And they are in an array. When I submit my form for some reason it clears the Modify check boxes. And then when go back to look not checked.
I have know what's causing issue is $this->form_validation->set_rules('permission[modify]', '', 'callback_modify_check_edit')
It does not seem to like, permission[modify] or permission[modify][] on the set_rules
How am I able to solve this?
Controller Edit Function:
public function edit() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
$this->form_validation->set_rules('user_group_id', 'User Group Id', 'required');
$this->form_validation->set_rules('permission[modify]', '', 'callback_modify_check_edit');
if ($this->form_validation->run($this) == FALSE) {
$this->getForm();
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$this->db->select('permission');
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('user_group_id', $this->session->userdata('user_group_id'));
$user_group_query = $this->db->get();
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
$this->session->set_flashdata('success', 'Congratulations you have successfully modified' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
redirect('admin/users_group');
}
}
public function modify_check_edit() {
if (!in_array('users_group', $this->session->userdata('modify'))) {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to edit' );
}
}
View Form:
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'users_group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'users_group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php
$data_user_name = array(
'id' => 'name',
'name' => 'name',
'class' => 'form-control',
'value' => $name
)
;?>
<?php echo form_input($data_user_name);?>
</div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Id', 'user_group_id', $data);?>
<div class="col-sm-10">
<?php
$data_user_group_id = array(
'id' => 'user_group_id',
'name' => 'user_group_id',
'class' => 'form-control',
'value' => $user_group_id
)
;?>
<?php echo form_input($data_user_group_id);?>
</div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Access Permission', 'permission_access', $data);?>
<div class="col-sm-10">
<div class="well well-sm" style="height: 200px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $access)) { ?>
<?php
$data_checked = array(
'name' => 'permission[access][]',
'id' => 'permission_access',
'value' => $permission,
'checked' => TRUE,
);
echo form_checkbox($data_checked);
?>
<?php echo $permission; ?>
<?php } else { ?>
<?php
$data_not_checked = array(
'name' => 'permission[access][]',
'id' => 'permission_access',
'value' => $permission,
'checked' => FALSE,
);
echo form_checkbox($data_not_checked);
?>
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);">Select All</a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);">Unselect All</a></div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Modify Permission', 'permission_modify', $data);?>
<div class="col-sm-10">
<div class="well well-sm" style="height: 200px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $modify)) { ?>
<?php
$data = array(
'name' => 'permission[modify][]',
'id' => 'permission_modify',
'value' => $permission,
'checked' => TRUE,
);
echo form_checkbox($data);
?>
<?php echo $permission; ?>
<?php } else { ?>
<?php
$data = array(
'name' => 'permission[modify][]',
'id' => 'permission_modify',
'value' => $permission,
'checked' => FALSE,
);
echo form_checkbox($data);
?>
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);">Select All</a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);">Unselect All</a></div>
</div>
<?php echo form_close();?>
After a good half hour trying to figure it out it was mostly part of the call back not to working with th set_rules() for permission[modify]
Just fixed code here for call back and seems to be working now.
public function modify_check_edit() {
$this->load->library('form_validation');
if (is_array($this->session->userdata('modify'))) {
$permission = !in_array('users_group', $this->session->userdata('modify'));
if ($permission) {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to one' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
return FALSE;
} else {
return TRUE;
}
return TRUE;
} else {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to one' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
return FALSE;
}
}

Resources