form validation with array not working - codeigniter

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;
}
}

Related

How add create AdditionalActionBlockHtml into massactions in category products grid in magento?

How add create AdditionalActionBlockHtml into massactions in category products grid?
like this status
I founded getAdditionalActionBlockHtml in app/design/adminhtml/default/default/template/widget/grid/massaction.phtml
But I'm dont understand how it's work.
<div class="right">
<div class="entry-edit">
<?php if ($this->getHideFormElement() !== true):?>
<form action="" id="<?php echo $this->getHtmlId() ?>-form" method="post">
<?php endif ?>
<?php echo $this->getBlockHtml('formkey')?>
<fieldset>
<span class="field-row">
<label><?php echo $this->__('Actions') ?></label>
<select id="<?php echo $this->getHtmlId() ?>-select" class="required-entry select absolute-advice local-validation">
<option value=""></option>
<?php foreach($this->getItems() as $_item): ?>
<option value="<?php echo $_item->getId() ?>"<?php echo ($_item->getSelected() ? ' selected="selected"' : '')?>><?php echo $_item->getLabel() ?></option>
<?php endforeach; ?>
</select>
</span>
<span class="outer-span" id="<?php echo $this->getHtmlId() ?>-form-hiddens"></span>
<span class="outer-span" id="<?php echo $this->getHtmlId() ?>-form-additional"></span>
<span class="field-row">
<?php echo $this->getApplyButtonHtml() ?>
</span>
</fieldset>
<?php if ($this->getHideFormElement() !== true):?>
</form>
<?php endif ?>
</div>
<div class="no-display">
<?php foreach($this->getItems() as $_item): ?>
<div id="<?php echo $this->getHtmlId() ?>-item-<?php echo $_item->getId() ?>-block">
<?php echo $_item->getAdditionalActionBlockHtml() ?>
</div>
<?php endforeach; ?>
</div>
</div>
I decided this via add methods in massactions
public function addMassAction($observer)
{
$block = $observer->getEvent()->getBlock();
if(get_class($block) =='Mage_Adminhtml_Block_Widget_Grid_Massaction' && $block->getRequest()->getControllerName() == 'catalog_product')
{
$stores = Mage::getSingleton('adminhtml/system_config_source_store')->toOptionArray();
$block->addItem('export', array(
'label' => Mage::helper("prodestransl")->__("Export"),
'url' => Mage::helper('adminhtml')->getUrl('prod/adminhtml_export/run'),
'additional' => array(
'stores' => array(
'name' => 'stores',
'type' => 'select',
'class' => 'required-entry',
'label' => Mage::helper('catalog')->__('Stores'),
'values' => $stores
)
)
));
}
}

OUTPUGet street1 and street 2 Magento

How I can get street address 1 and street address 2 value. I create an extension and I want to get street address in Magento. In the block I have this function:
public function updateFormData() {
$data = $this->getData('form_data');
if (is_null($data)) {
/** #var array $formData */
$formData = Mage::getSingleton('customer/session')->getCustomerFormData(true);
$order = $this->getOrder();
$address = $order->getShippingAddress();
$customerData = [
'email' => $order->getCustomerEmail(),
'firstname' => $order->getCustomerFirstname(),
'lastname' => $order->getCustomerLastname(),
'city' => $order->getBillingAddress()->getCity(),
'country' => $order->getBillingAddress()->getCountry(),
'telephone' => $order->getBillingAddress()->getTelephone(),
'company' => $order->getBillingAddress()->getCompany(),
];
$data = new Varien_Object();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
$data->addData($customerData);
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}
and in the phtml file I add this:
<?php $_streetValidationClass = $this->helper('customer/address')->getAttributeValidationClass('street'); ?>
<li class="wide">
<label for="street_1" class="required"><em>*</em><?php echo $this->__('Street Address') ?></label>
<div class="input-box">
<input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getFormData()->getStreet(1)) ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Street Address')) ?>" id="street_1" class="input-text <?php echo $_streetValidationClass ?>" />
</div>
</li>
<?php $_streetValidationClass = trim(str_replace('required-entry', '', $_streetValidationClass)); ?>
<?php for ($_i = 2, $_n = $this->helper('customer/address')->getStreetLines(); $_i <= $_n; $_i++): ?>
<li class="wide">
<div class="input-box">
<input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getFormData()->getStreet($_i)) ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Street Address %s', $_i)) ?>" id="street_<?php echo $_i ?>" class="input-text <?php echo $_streetValidationClass ?>" />
</div>
</li>
<?php endfor; ?>
I try to add this 'street_1' => $order->getBillingAddress()->getData('street'),
But always street_1 address value is blank. I try to get all fields in the order success page.
OUTPUT:
<li class="wide">
<label class="required" for="street_1">
<div class="input-box">
<input id="street_1" class="input-text required-entry" type="text" title="Street Address" value="address1 address2" name="street[]">
</div>
</li>
<li class="wide">
<div class="input-box">
<input id="street_2" class="input-text " type="text" title="Street Address 2" value="" name="street[]">
</div>
</li>
$order->getBillingAddress()->getData('street') will return an array.
So you can access the data with:
$billingStreet = $order->getBillingAddress()->getData('street');
$billingStreet1 = $billingStreet[0];
$billingStreet2 = $billingStreet[1];
$billingStreet3 = $billingStreet[2];
edit: the code above is to get the billing address of an order, what I think you want now is actually the new address, the data set in the form. So this should give you the information you're after, as long as you put it before the $data = new Varien_Object(); line:
$streetArray = $data['street'];
$street1 = $streetArray[0];
$street2 = $streetArray[1];
so your function will be:
public function updateFormData() {
$data = $this->getData('form_data');
if (is_null($data)) {
/** #var array $formData */
$formData = Mage::getSingleton('customer/session')->getCustomerFormData(true);
$order = $this->getOrder();
$address = $order->getShippingAddress();
$streetArray = $data['street'];
$street1 = $streetArray[0];
$street2 = $streetArray[1];
$customerData = [
'email' => $order->getCustomerEmail(),
'firstname' => $order->getCustomerFirstname(),
'lastname' => $order->getCustomerLastname(),
'city' => $order->getBillingAddress()->getCity(),
'country' => $order->getBillingAddress()->getCountry(),
'telephone' => $order->getBillingAddress()->getTelephone(),
'company' => $order->getBillingAddress()->getCompany(),
'street_1' => $street1,
'street_2' => $street2
];
$data = new Varien_Object();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
$data->addData($customerData);
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}

shopping cart in codeigniter using ajax

Hi I am new with ajax and having problem. I am trying to make a shopping cart using ajax.I don't know what is wrong with my code please help me out.
When I click the add button an alert comes 'No success' and nothing happen , I am not able add items to cart.
Thanks for helping me.
This is my view
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $(this).serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping2/add",
dataType: 'json',
//type: "POST",
data: insert_data,
success:function(response) {
//if (response){
//var res = JSON.parse(response);
var res = response;
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping2";
}else{
alert(res.msg);
}
//}
//else{
// alert('sorry');
//}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<div id="addcart">
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping2/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well" id="addcart">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping2/remove'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr></div>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
</html>
This is my controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping2 extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_view2', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
//$success = $this->cart->insert($insert_data);
$cart_check = $this->cart->contents();
if(!empty($cart_check)){
//$this->cart->contents(insert_data);
$res = array('status' => 200, 'msg' => 'success');
}else{
$res = array('status' => 500, 'msg' => 'No success');
}
echo json_encode($res);
//echo $data[0]['value'];
//redirect('shopping2');
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
$this->cart->destroy();
}else{
$data = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($data);
}
redirect('shopping2');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping2');
}
}
Please help me how to add items in the cart using ajax.
Since u managed to get a response, the problem should lie in your Model or data insertion.
Few suggestions:
It's also recommended that you use $.post() instead of $.ajax().
"<?php echo base_url(); ?>" + "index.php/shopping2/add" can be changed to "<?php echo site_url('shopping2/add"'); ?>"
Use the built in Codeignter output class to output your JSON. See here: https://www.codeigniter.com/userguide3/libraries/output.html

Display error message from Admin_Controller to any view

I would like to be able to display data message from my Admin_Controller in the core folder core/Admin_Controller.php to then show up on my login view.
I can only seem to get it working with session flash data but would not like to use flash data.
So what would be best method on getting the $data['error_warning'] message to from my Admin_Controller to be able to work on my Login controller and view.
<?php
class Admin_Controller extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('user');
Modules::run('admin/error/permission/check');
$ignore = array(
'login',
'logout'
);
if (!in_array($this->router->fetch_class(), $ignore)) {
if ($this->session->userdata('user_id') == FALSE) {
$data['error_warning'] = 'You have tried to directly access controller without logging on! Please login.';
redirect('admin');
}
}
}
}
Login Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends Admin_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$data['title'] = 'Administration';
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$username = $this->input->post('username');
if (isset($username)) {
$data['username'] = $username;
} else {
$data['username'] = '';
}
$password = $this->input->post('password');
if (isset($password)) {
$data['password'] = $password;
} else {
$data['password'] = '';
}
$this->form_validation->set_rules('username', 'Username', 'required|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/common/login.tpl', $data);
} else {
redirect('admin/dashboard'.'/'.$token);
}
}
public function validate() {
$this->load->library('user');
if ($this->user->login() == FALSE) {
$this->form_validation->set_message('validate', '<i class="fa fa-exclamation-triangle"></i> Does not match any of our database records!');
return false;
} else {
return true;
}
}
}
Login View
<?php echo Modules::run('admin/common/header/index');?>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12">
<div class="panel panel-default" style="margin-top: 12.5%;">
<div class="panel-heading"><strong><i class="fa fa-key"></i> Enter Details To Login </strong></div>
<div class="panel-body">
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php $data = array('class' => 'form-horizontal');?>
<?php echo form_open('admin', $data);?>
<?php if ($error_warning) { ?>
<div class="alert alert-danger text-center"><i class="fa fa-exclamation-triangle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<?php if ($this->session->flashdata('error')) { ?>
<div class="alert alert-danger text-center"><i class="fa fa-exclamation-triangle"></i> <?php echo $this->session->flashdata('error'); ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Username', 'username', $data);?>
<div class="col-sm-10">
<?php
$data_username = array(
'id' => 'username',
'name' => 'username',
'class' => 'form-control',
'placeholder' => 'Username',
'value' => $username
)
;?>
<?php echo form_input($data_username);?>
</div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Password', 'password', $data);?>
<div class="col-sm-10">
<?php
$data_password = array(
'id' => 'password',
'name' => 'password',
'class' => 'form-control',
'placeholder' => 'Password',
'value' => $password
)
;?>
<?php echo form_password($data_password);?>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">Login Now</button>
</div>
</div>
<div class="panel-footer text-right">
Not registered on admin ?
click here
<?php echo form_close();?>
</div>
</div>
</div>
</div>
<?php echo Modules::run('admin/common/footer/index');?>
Try defining a class properties in your Admin_Controller, like this:
<?php
class Admin_Controller extends MX_Controller {
// Change here
protected $ignore;
protected $data;
public function __construct() {
parent::__construct();
$this->load->library('user');
Modules::run('admin/error/permission/check');
$this->ignore = array(
'login',
'logout'
);
if (!in_array($this->router->fetch_class(), $ignore)) {
if ($this->session->userdata('user_id') == FALSE) {
$this->data['error_warning'] = 'You have tried to directly access controller without logging on! Please login.';
redirect('admin');
}
}
}
}
Also, as above, change each reference to either $data or $ignore to be $this->data or $this->ignore. You'll also need to do this inside your Login class too. Always, when referencing class properties (that is, variables declared outside a method within a class), you do so by $this->PROPERTY_NAME.

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