Ajax action called twice - ajax

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...

Related

I want to make fullcalendar with codeigniter,,but somehow I encounter this error

I encounter this error. Please help me if you know the solution
Severity: Error
Message: Call to undefined function form_open()
Filename: views/index.php
Line Number: 33
index.php (view)
Calendar Display
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/moment.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/jquery-ui.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/jquery.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/fullcalendar/fullcalendar.min.css" />
<script src="<?php echo base_url(); ?>assets/fullcalendar/fullcalendar.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar-3.9.0/locale/es.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Calendar</h1>
<div id="calendar">
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Calendar Event</h4>
</div>
<div class="modal-body">
<?php echo form_open(site_url('calendar/add_event'), array("class" => "form-horizontal")) ?>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Event Name</label>
<div class="col-md-8 ui-front">
<input type="text" class="form-control" name="name" value="">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Description</label>
<div class="col-md-8 ui-front">
<input type="text" class="form-control" name="description">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Start Date</label>
<div class="col-md-8">
<input type="text" class="form-control" name="start_date">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">End Date</label>
<div class="col-md-8">
<input type="text" class="form-control" name="end_date">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Add Event">
<?php echo form_close() ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->
<script type="text/javascript">
$(document).ready(function() {
var date_last_clicked + null;
$('#calendar').fullCalendar({
eventSources: [
{
events: function(start, end, timezone, callback) {
$.ajax({
url: '<?php echo base_url() ?>calendar/get_events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(msg) {
var events = msg.events;
callback(events);
}
});
}
},
]
dayClick: function(date, jsEvent, view) {
date_last_clicked = $(this);
$(this).css('background-color', '#bed7f3');
$('#addModal').modal();
},
});
});
</script>
<style>
#calendar{
width: 800px;
margin: 0px auto;
}
</style>
</body>
Calendar.php (controller)
class Calendar extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model("calendar_model");
}
public function index()
{
$this->load->helper('url');
$this->load->view('index', array());
}
public function get_events()
{
// Our Start and End Dates
$start = $this->input->get('start');
$end = $this->input->get('end');
$startdt = new DateTime('now'); // setup a local datetime
$startdt->setTimestamp($start); // Set the date based on timestamp
$start_format = $startdt->format('Y-m-d H:i:s');
$enddt = new DateTime('now'); // setup a local datetime
$enddt->setTimestamp($end); // Set the date based on timestamp
$end_format = $enddt->format('Y-m-d H:i:s');
$events = $this->calendar_model->get_events($start_format, $end_format);
$data_events = array();
foreach($events->result() as $r) {
$data_events[] = array(
"id" => $r->ID,
"title" => $r->title,
"description" => $r->description,
"end" => $r->end,
"start" => $r->start
);
}
echo json_encode(array("events" => $data_events));
exit();
}
public function add_event()
{
/* Our calendar data */
$name = $this->input->post("name", TRUE);
$desc = $this->input->post("description", TRUE);
$start_date = $this->input->post("start_date", TRUE);
$end_date = $this->input->post("end_date", TRUE);
if(!empty($start_date)) {
$sd = DateTime::createFromFormat("Y/m/d H:i", $start_date);
$start_date = $sd->format('Y-m-d H:i:s');
$start_date_timestamp = $sd->getTimestamp();
} else {
$start_date = date("Y-m-d H:i:s", time());
$start_date_timestamp = time();
}
if(!empty($end_date)) {
$ed = DateTime::createFromFormat("Y/m/d H:i", $end_date);
$end_date = $ed->format('Y-m-d H:i:s');
$end_date_timestamp = $ed->getTimestamp();
} else {
$end_date = date("Y-m-d H:i:s", time());
$end_date_timestamp = time();
}
$this->calendar_model->add_event(array(
"title" => $name,
"description" => $desc,
"start" => $start_date,
"end" => $end_date
)
);
redirect(site_url("calendar"));
}
}
Calendar_model.php (model)
class Calendar_model extends CI_Model {
public function get_events($start, $end){
return $this->db->where("start >=", $start)->where("end <=", $end)->get('calendar_events');
}
public function add_event($data)
{
$this->db->insert('calendar_events', $data);
}
public function get_event($id)
{
return $this->db->where("ID", $id)->get('calendar_events');
}
public function update_event($id, $data)
{
$this->db->where("ID", $id)->update('calendar_events', $data);
}
public function delete_event($id)
{
$this->db->where("ID", $id)->delete('calendar_events');
}
}
From the HTML it seems there is a markup issue. But anyway you need to make sure that the Form helper and URL helpers are both loaded in the function you want to use.
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('index', array());
}

gallery images does not get updated in database

I have an event management company website. https://redcarpetevents.in. the only issue is i cannot update the image gallery. i can upload new images, that works fine. but when i edit the images already in the database, it is not getting updated.
routes.php
Route::get('admin/editGalleryForm/{type}/{editId}', array('as'=>'editGalleryForm','before'=>'authAdmin','uses'=>'AdminController#editGalleryForm'));
Route::post('admin/editGallery', array('as'=>'editGallery','before'=>'csrf|xss_clean|authAdmin','uses'=>'FormController#editGallery'));
Model.php
public static function editGallery($data){
$gallery = Gallery::find($data['editId']);
$gallery->type = $data['type'];
$gallery->tag = $data['tag'];
$gallery->position = $data['order'];
if (isset($data['status'])) {
$gallery->status = $data['status'];
}else{
$gallery->status = 'off';
}
if (isset($data['home'])) {
$gallery->home = $data['home'];
}else{
$gallery->home = 'off';
}
if (isset($data['title'])) {
$gallery->title = $data['title'];
}
if($gallery->update()){
return true;
}else{
return false;
}
}
public static function getGalleryCounts(){
$galleryCounts = array();
$galleryCounts['all'] = count(Gallery::all());
$galleryCounts['allActive'] = count(Gallery::where('status','=','on')->get());
$galleryCounts['allInActive'] = count(Gallery::where('status','=','off')->get());
$galleryCounts['personal'] = count(Gallery::where('type','=','1')->get());
$galleryCounts['personalActive'] = count(Gallery::where('type','=','1')->where('status','=','on')->get());
$galleryCounts['personalInActive'] = count(Gallery::where('type','=','1')->where('status','=','off')->get());
$galleryCounts['corporate'] = count(Gallery::where('type','=','2')->get());
$galleryCounts['corporateActive'] = count(Gallery::where('type','=','2')->where('status','=','on')->get());
$galleryCounts['corporateInActive'] = count(Gallery::where('type','=','2')->where('status','=','off')->get());
return $galleryCounts;
}
Admincontroller.php
public function editGalleryForm($type,$id){
$data['id'] = $id;
$data['type'] = $type;
$data['galleryCounts'] = Gallery::getGalleryCounts();
$data['image'] = Gallery::getGalleryById($id);
$data['personalTags'] = GalleryTag::getPersonalActive();
$data['corporateTags'] = GalleryTag::getCorporateActive();
return View::make('admin.editGalleryForm', $data);
}
Formcontroller.php
public function editGallery(){
$type = Input::get('type');
$editId = Input::get('Id');
$filename=Input::get('image');
$rules = array(
'order'=>'Numeric');
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
$data['type'] = $type;
$data['Id'] = $editId;
return Redirect::route('editGalleryForm',$data)->withInput()->withErrors($validation);
}
if ($validation->passes()) {
$fileName='';
if (Input::hasFile('image')) {
$name = Input::file('image')->getClientOriginalName();
$destinationPath = 'assets/img/gallery/';
$data['Id'] = $Id;
$fileName = $name;
Input::file('image')->move($destinationPath, $fileName);
//Gallery::convertImage($destinationPath,$fileName);
}
$editGallery = Gallery::editGallery(Input::all());
if ($editGallery) {
$data['success'] = 'Gallery Image Updated!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
else
{
$data['failure'] = 'Operation failed!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
}
}
this is the form
#extends('admin.layouts.master')
#section('pageHeader')
<h2>Edit Gallery Image</h2>
<ol class="breadcrumb">
<li>{{HTML::linkRoute('adminHome','Dashboard')}}</li>
<li>{{HTML::linkRoute('newGallery','Gallery',array('type'=>$type))}}</li>
<li class="active">Edit Gallery Image</li>
</ol>
#stop
#section('content')
<div class="cl-mcont">
<div class="status_bar">
<div class="butpro butstyle {{($type=='1')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'1'))}}">
<div class="sub"><h2>PERSONAL</h2><span id="total_clientes">{{$galleryCounts['personal']}} Image{{($galleryCounts['personal'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['personalActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['personalInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
<div class="butpro butstyle {{($type=='2')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'2'))}}">
<div class="sub"><h2>CORPORATE</h2><span id="total_clientes">{{$galleryCounts['corporate']}} Image{{($galleryCounts['corporate'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['corporateActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['corporateInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
</div>
<div class="row">
<div class="col-md-12">
{{Form::open(array('action'=>'editGallery','method'=>'POST','files'=>true,'class'=>'form-horizontal'))}}
<div class="form-group">
{{Form::label('forType', 'Type', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::select('type', array('1'=>'personal','2'=>'corporate'), ($image->type=='2')? '2':'1', array('class'=>'form-control','onChange'=>'tagChange(this)'))}}
<div class="color-danger">{{$errors->first('type')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTag', 'Tag', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<select class="form-control" id="tags" name="tag">
#if($type == 2)
#foreach($corporateTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#else
#foreach($personalTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#endif
</select>
<div class="color-danger">{{$errors->first('tag')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTitle', 'Title', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('title', $image->title, array('class'=>'form-control','placeholder'=>'Image Title'))}}
<div class="color-danger">{{$errors->first('title')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forImage', 'Gallery Image', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::file('forimage', array('class'=>'form-control','placeholder'=>'image'))}} (600 X 400)px
<div class="color-danger">{{$errors->first('image')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('', '', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="col-md-2 padding photo">
<img src="{{asset('assets/img/gallery/'.$image->image)}}" width="200px" height="120px">
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forOrder', 'Order', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('order', $image->position, array('class'=>'form-control','placeholder'=>'Image Order'))}}
<div class="color-danger">{{$errors->first('order')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forStatus', 'Publish Status', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="status"{{($image->status=='on')? 'checked':''}}>
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forShow', 'Show on Homepage', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="home"{{($image->home=='on')? 'checked':''}}>
</div>
</div>
</div>
{{Form::text('editId', $image->id, array('style'=>'display:none'))}}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{Form::submit('Update Gallery', array('class'=>'btn btn-primary'))}}
{{HTML::linkRoute('newGallery','Cancel',array('type'=>$type),array('class'=>'btn btn-default'))}}
</div>
</div>
{{Form::token().Form::close()}}
</div>
</div>
</div>
#stop
#section('customScripts')
<script type="text/javascript">
function tagChange(element){
console.log(element.value);
$('#tags').empty();
$.ajax({
url:'{{URL::route("getTagsAjax")}}',
type:'POST',
data:{'type':element.value},
dataType:'JSON',
success:function(data){
console.log(data);
for (var i = 0; i <= data.length; i++) {
$('#tags').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
};
}
});
}
</script>
#stop

Last input added to a form in Laravel not inserting to database

I bought a ready made Laravel Tailor application, I am trying to add an additional input to it but after doing so, I tried to submit it to the database but the last one I added wasn't inserting. The input is in array.
All other values are inserting except for service_description[] which is newly added to the form.
What exactly could I be doing wrong?
Database Structure
HTML Codes:
#extends('admin.layouts.master')
#section('content')
<style type="text/css">
</style>
#if(Session::has('success'))
<div class="alert alert-success" role= "alert">
<strong>Successful:</strong>
{!! session('success') !!}
</div>
#endif
#if (count($errors) > 0)
<div class="row">
<div class="col-md-06">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</div>
</div>
</div>
#endif
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-red-sunglo"></i>
<span class="caption-subject font-red-sunglo bold uppercase">Order Submission</span>
<span class="caption-helper">Service Details</span>
</div>
<div class="tools">
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="{{url('admin/save-order')}}" class="form-horizontal" method="POST">
<input name="order_create_by" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-body">
{{ csrf_field() }}
<h3 class="form-section">Customer Info</h3>
<!--Start Customer Area-->
<div class="row">
<div class="col-md-6">
<!-- text input -->
<div class="form-group">
<label class="control-label col-md-4">Customer Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="Enter ..." name="service_cus_name" id="service_cus_name">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Email Address:</label>
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Enter ..." name="service_cus_email" id="service_cus_email">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Order Create Date:</label>
<div class="col-md-8">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right createdpicker" name="service_crete_date" id="service_crete_date">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Cell Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="Enter ..." name="cell_number" id="cell_number">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Order Delivery Date:</label>
<div class="col-md-8">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right dpicker" name="service_delivery_date" id="service_delivery_date">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-2">Cutomer Address:</label>
<div class="col-md-10">
<textarea class="form-control" rows="3" placeholder="Enter ..." name="service_cus_address" id="service_cus_address"></textarea>
</div>
</div>
</div>
</div>
<!--End Customer Area-->
<!--Start Service Order Area-->
<div class="form-section">
<h3 class="inlineBlock">Service Details with Measurement</h3>
<button type="button" class="btn dark flot-right " id="addService" disabled="disabled"> Add Another Service </button>
</div>
<div class="row">
<div class="col-md-3">
<div class="col-md-11">
<label>Select Service</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Rate:</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Quantity:</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Amount:</label>
</div>
</div>
<div class="col-md-3">
<div class="col-md-10">
<label>Action</label>
</div>
</div>
</div>
<div class="row serviceRow redBorder" id="orderBox">
<div class="col-md-3">
<div class="form-group">
<div class="col-md-11">
<select class="form-control service_id" name="service_id[]" id="service_id">
<option selected="selected" disabled="disabled" value="0">Select Service</option>
#foreach($services as $service)
<option value="{{$service->id}}">{{$service->service_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control service_price" placeholder="Rate" name="service_price[]" id="service_price" readonly>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control service_qty" placeholder="Quantity" id="service_qty" name="service_quantity[]">
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control amount" placeholder="Total" id="amount" name="service_amount[]" readonly>
</div> </div>
</div>
<div class="col-md-3">
<div class="form-group">
<div class="col-md-10">
<button type="button" class="btn removeService red btn-block" id="removeService" disabled="disabled"> Delete</button>
</div>
</div>
</div>
<div class="row pading-margin-zero">
<div class="col-md-12 col-md-offset-1">
<div class="form-group">
<div class="col-md-5" >
<textarea type="text" class="form-control service_measer" placeholder="Enter Measurement of Service ..." name="service_measer[]"></textarea>
</div>
<div class="col-md-5" >
<textarea type="text" class="form-control description service_description" placeholder="Description(s)" name="service_description[]" id="description"></textarea>
</div>
</div>
</div>
</div>
</div>
<!--End Service Order Area-->
</div>
<!--Start Form Footer Area-->
<div class="form-action">
<div class="row">
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-success">Total Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="total" name="total_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-info">Discount Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="discount" name="discount_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-warning">Advance Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="advance_amount" name="advance_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn purple btn-block">Submit Order</button>
</div>
</div>
</div>
<!--End Form Footer Area-->
</form>
</div>
<script>
jQuery(document).ready(function() {
//Commom Script
$('.dpicker').datepicker({
autoclose: true
})
var currentDate = new Date();
$(".createdpicker").datepicker("setDate",currentDate);
$("#loader").css("display",'none');
$("#myDiv").removeAttr("style");
$("#addService").removeAttr("disabled");
//Start Order Form
$('form').submit(function() {
if ($.trim($("#service_cus_name").val()) === "") {
alert('Customer Name Field Empty');
return false;
}else if( $.trim($("#service_cus_email").val()) === ""){
alert('Email Address Field Empty');
return false;
}else if( $.trim($("#cell_number").val()) === ""){
alert('Cell Number Field Empty');
return false;
}else if( $.trim($("#service_crete_date").val()) === ""){
alert('Create Date Field Empty');
return false;
}else if( $.trim($("#service_delivery_date").val()) === ""){
alert('Delivery Date Field Empty');
return false;
}else if( $.trim($("#service_cus_address").val()) === ""){
alert('Customer Address Field Empty');
return false;
}
var flag = 0;
$(".service_qty").each(function(i){
if ($(this).val() == "")
flag++;
});
if(flag==0){
flagNew=0
$(".service_measer").each(function(i){
if ($(this).val() == "")
flagNew++;
});
if(flagNew==0){
return true;
}else{
alert("All Measurement Fileds Requried");
return false;
}
}else{
alert("All Service Quantity Fileds Requried");
return false;
}
});
$("#addService").click(function(){
//
//alert('addButton');
var serviceRowQty = $('.serviceRow').length;
//alert(serviceRowQty);
$("#orderBox:last").clone(true).insertAfter("div.serviceRow:last");
$("div.serviceRow:last input").val('');
$("div.serviceRow:last textarea").val('');
$("div.serviceRow:last select").prop('selectedIndex',0);
$("div.serviceRow:last label").text('');
$("div.serviceRow .removeService").prop('disabled', false);
return false;
})
$(document).on("click" , "#removeService" , function() {
//alert('deletebutton');
var serviceRowQty = $('.serviceRow').length;
if (serviceRowQty == 1){
$("div.serviceRow .removeService").prop('disabled', true);
return false;
$(".serviceRow").css("display", "block");
}else{
$(this).closest('.serviceRow').remove();
if(serviceRowQty==1){
//return false;
$("div.serviceRow .removeService").prop('disabled', true);
return false
}else{
$("div.serviceRow .removeService").prop('disabled', false);
}
//$(".serviceRow").remove();
return false;
}
alert();
return false;
});
$('.serviceRow').delegate('.service_id','change',function(){
;
var subdiv = $(this).parent().parent().parent().parent();
var cat_id = $(this).closest('.serviceRow').find('.service_id option:selected').attr('value');
subdiv.find('.service_price').val('');
//alert(cat_id);
//var a =
//alert(totalamount());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type : 'get',
url : 'get-orders-list-jason/'+cat_id+'',
dataType : 'json',
//date : { cat_id: cat_id},
success:function(data){
console.log(data);
subdiv.find('.service_price').val(data.service_price);
var price = subdiv.find('.service_price').val();
var qty = subdiv.find('.service_qty').val();
var total = data.service_price * qty ;
subdiv.find('.amount').val(total);
$('#total').val(totalamount());
//alert(alert(JSON.stringify(subdiv)));
},
error: function(error) {
//alert("Data retrive faield");
}
});
$(".serviceRow").delegate('.service_qty', "keyup",function(){
//alert('keyup');
var subdiv = $(this).parent().parent().parent().parent();
var price = subdiv.find('.service_price').val();
var qty = subdiv.find('.service_qty').val();
var discount = $('#discount').val();
var total = price * qty ;
subdiv.find('.amount').val(total);
$('#total').val(totalamount());
//alert('background-color');
//$("p").css("background-color", "pink");
});
$("#discount").keyup(function(){
$('#total').val(totalamount());
});
function totalamount(t){
var t=0;
$('.amount').each(function(i,e){
var amt = $(this).val()-0;
t+=amt;
});
var d = $('#discount').val();
total = t-d;
return total;
$('.total').html(t);
}
});
$('.serviceRow').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if( $('.serviceRow').find('select option[value='+$(this).val()+']:selected').length>1){
$(this).val($(this).css("border","1px red solid"));
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}else{
$(this).css("border","1px #D2D6DE solid");
}
});
});
});
</script>
#endsection
Order Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Validator;
use Illuminate\Support\Facades\Input;
use App\lib\Custom;
use App\lib\DBQuery;
use App\Order;
use DB;
use App\Orderdetail;
use App\Session;
use App\ShopInfo;
use App\Payment;
use Auth;
class OrderController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function getOrders(){
$orders = Order::All();
//return $orders;
return view('order.allorderlist',compact('orders'));
}
public function getOrderajax($cat_id)
{
$orders = Service::where('id',$cat_id)->first();
return $orders;
}
public function addOrder()
{
$services = Service::where('active_status',0)->get();
return view('order.addneworder',compact('services'));
}
public function saveOrder(Request $request)
{
if($request->discount_amount==""){
$validator = Validator::make(Input::all(), Order::$rules);
$request['discount_amount']=0;
}else{
$validator = Validator::make(Input::all(), Order::$numberrules);
}
if($validator->fails()){
$services = Service::where('active_status',0)->get();
return view('order.addneworder',compact('services'))->withErrors($validator);
}else{
$order = DBQuery::saveOrder($request);
//return $order;
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.invsaveprint',compact('order','shopinfo','total_bill_word'));
}
}
public function addOrderExCustomer($order_id)
{ $order = Order::where('id',$order_id)->first();
$services = Service::where('active_status',0)->get();
return view('order.addneworderexcus',compact('services','order'));
}
public function saveOrderExCustomer(Request $request)
{
$validator = Validator::make(Input::all(), Order::$rules);
if($validator->fails()){
$services = Service::where('active_status',0)->get();
$order = Order::where('id',$request->order_id)->first();
return view('order.addneworderexcus',compact('services','order'))->withErrors($validator);
}else{
$order = DBQuery::saveOrder($request);
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.invupdateprint',compact('order','shopinfo','total_bill_word'));
}
}
public function updateOrderById($order_id){
$order = Order::where('id',$order_id)->first();
$services = Service::All();
return view('order.editOrder',compact('services','order'));
}
public function saveUpdateOrderById(Request $request){
$validator = Validator::make(Input::all(), Order::$rules);
if($validator->fails()){
$services = Service::where('active_status',0)->get();
$order = Order::where('id', '=', $request->order_id)->first();
//return $order;
return view('order.editOrder',compact('services','order'))->withErrors($validator);
}else{
DBQuery::saveUpdateOrder($request);
$order = Order::where('id', '=', $request->order_id)->first();
//return $order ;
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.newinvoice',compact('order','shopinfo','total_bill_word'));
}
}
public function deliveryOrderById($order_id){
$order = Order::where('id',$order_id)->first();
//return $order;
$services = Service::All();
return view('order.deliveryorder',compact('services','order'));
}
public function saveDeliveryOrderById($order_id){
//$a = Auth::user()->is_permission;
//return $order_id;
//if(Auth::user()->is_permission==1){
Order::where('id',$order_id)
->update(array('service_status' => 3));
// }
$order = Order::where('id',$order_id)->first();
return view('order.deliveryorder',compact('order'));
}
}
**The order codes**
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $table = "orders";
protected $fillable = [
'service_ref',
'service_status',
'order_create_by',
'service_crete_date',
'service_delivery_date',
'service_cus_name',
'cell_number',
'service_cus_email',
'service_cus_address',
'total_amount',
'discount_amount',
];
public static $numberrules = array(
'service_cus_name' =>'required',
'service_cus_address' =>'required',
'service_cus_email' =>'required',
'service_crete_date' =>'required',
'service_delivery_date' =>'required',
'total_amount' =>'required',
'discount_amount' =>'numeric|',
'cell_number' =>'required|numeric',
'service_quantity.*' =>'required|numeric',
'service_id.*' =>'required',
'service_measer.*' =>'required',
'service_description.*' =>'required',
);
public static $rules = array(
'service_cus_name' =>'required',
'service_cus_address' =>'required',
'service_cus_email' =>'required',
'cell_number' =>'required|numeric',
'service_crete_date' =>'required',
'service_delivery_date' =>'required',
'total_amount' =>'required',
'service_quantity.*' =>'required|numeric',
'service_id.*' =>'required',
'service_measer.*' =>'required',
'service_description.*' =>'required',
);
public function orderdetails() {
//return $this->hasMany('App\OrderDetail','fid','id');
return $this->hasMany('App\Orderdetail','order_id','id');
}
public function user() {
//return $this->hasMany('App\OrderDetail','fid','id');
return $this->hasOne('App\User','id','ser_act_create_by');
}
public function payments() {
return $this->hasMany('App\Payment','order_id','id');
//return $this->>belongsTo('App\Order');
}
}
Order Details Code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Orderdetail extends Model
{
protected $table = "orderdetails";
protected $fillable = [
'order_id',
'service_id',
'service_price',
'service_quantity',
'service_amount',
'service_measer',
'service_description',
'service_id',
];
public function order() {
return $this->belongsTo('App\Order');
//return $this->>belongsTo('App\Order');
}
public function service() {
return $this->belongsTo('App\Service','service_id','id');
//return $this->>belongsTo('App\Order');
}
}

dropzone server implementation

I just started using the dropzone plugin and i'm using laravel in my project. I want to know how to get the files uploaded so i can store them in my database. this is my view :
<form action="{{route('realisation.storeimg')}}" method="POST" files="true" enctype="multipart/form-data"
data-toggle="validator" role="form" class="dropzone" id="my-awesome-dropzone">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="table table-striped" class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail/></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
<input type="hidden" name="realisation_id" value="{{$realisation->id}}">
</form>
my route for the upload:
Route::post('/storeimg',[
'as'=>'realisation.storeimg',
'uses'=>'RealisationController#storeimg'
]);
my controller:
public function storeimg (Request $request)
{
$realisation = Realisation::where('id','realisation_id')->first();
if($request->file('image')) {
foreach ($request->file('image') as $image) {
$realisation_image = Realisationimg::where('realisation_id','realisation_id')->first();
File::delete($realisation_image->image);
File::delete($realisation_image->image_thumb);
$extension = $image->getClientOriginalExtension();
$name = substr($image->getClientOriginalName(), 0, -4);
list($width, $height) = getimagesize($image);
$imgname = str_slug($name, '_');
$filename = $imgname.'.'.$extension;
if(file_exists('uploads/realisationimg/cover/' . $filename)){
do {
$newname = $imgname.'_'.str_random(3) . '.' . $extension;
}
while(file_exists('uploads/realisationimg/cover/' . $newname));
$filename = $newname;
}
$path = 'uploads/realisationimg/cover/'.$filename;
$path_thumb = 'uploads/realisationimg/thumb/'.$filename;
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path);
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path_thumb);
$realisation_image->image = $path;
$realisation_image->image_thumb = $path_thumb;
$realisation_image->realisation_id = $id;
$realisation_image->save();
}
}
Session::flash('ajouter','ok');
return redirect(route('realisation.edit',['id'=>$request->get('realisation_id')]));
}
in the dropzone.js file i changed the default options to the following:
uploadMultiple: true,
paramName: "image",
when i submit the dropzone form nothing gets executed (no files are stored and nothing in my database). can someone point to me my mistake? thanks.
Here is s sample code that might help.
Route:
Route::post('/storeimg', 'GalleryController#storeimg')
->name('realisation.storeimg');
Controller:
public function storeimg(Request $request)
{
$path = $request->file('file')->store('public/photo');
if (!$path)
return url('storage');
$dirs = explode('/', $path);
if ($dirs[0] === 'public')
$dirs[0] = 'storage';
$data['image'] = url(implode('/', $dirs));
Photo::create($data);
session()->flash('success', 'Photos uploaded successfully');
return response()->json(['success'=>$data['image']]);
}
View: Just open file to send files to controller.
{!! Form::open([ 'route' => [ 'realisation.storeimg'], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{!! Form::close() !!}
<link rel="stylesheet" href="../dropzone.min.css">
<script src="../dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize : 1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
//Remove Photo
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
console.log(id);
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
});
});
</script>
This is result in a dropzone box where you can add multiple photos at a time

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

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,

Resources