Unset sessions after form success not working - codeigniter

When I deselect my check box in my modify & access permissions it does not unset it from sessions if form is submitted success full.
What I am trying to achieve is on my edit function if any check box is not checked then it will unset from sessions when form is submitted success full. Because the reason need it unset from sessions is because when user logs in the permissions modify and access are set into sessions.
How can I make this work what I am after I have tried it in my edit but not unset when check box is empty
If i use this $this->session->unset_userdata('modify'); it unset all the modify array in sessions I just need it to unset the one that matches the unchecked check box.
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
if ($this->session->userdata('user_id') == TRUE) {
if (isset($_POST['permission[access]'])) {
$this->session->unset_userdata('permission[access]');
}
if (isset($_POST['permission[modify]'])) {
$this->session->unset_userdata('permission[modify]');
}
}
redirect('admin/users_group');
}
$this->getForm();
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->uri->segment(4) == FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
if ($this->uri->segment(4) == FALSE) {
$data['user_group_id'] = $this->input->post('user_group_id');
} else {
$data['user_group_id'] = $user_group_info['user_group_id'];
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif (!empty($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}
$permission_modify = $this->input->post('permission');
if (isset($permission_modify)) {
if (isset($permission_modify['modify'])) {
$data['modify'] = $permission_modify['modify'];
} elseif (!empty($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
}
$this->load->view('template/user/users_group_form.tpl', $data);
}

I have found away to get it working I have got sessions from database then re set the sessions in form, without using unset_sessions();
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$user_group_query = $this->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$this->session->userdata('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
redirect('admin/users_group');
}
$this->getForm();
}

Related

Prestashop shipping costs cleared after order confirmation

I'm on Prestashop 1.7.6. I made a simple test module for adding a custom carrier and manage it programmatically.
Everything works well during checkout: I see new carrier with the correct cost, if I select it the total of cart is correct! (the shipping cost is added).
After choosing the payment method and confirming the order (and I'm redirected to order confirmation page), the shipping costs disappear: is always free shipping!
I do not understand why..
I report the code of this test:
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class TxShipping extends CarrierModule
{
const PREFIX = 'tx_';
public $id_carrier;
private $loopCount = 0;
private $shipCost = 0;
protected $_hooks = array(
'actionCarrierUpdate',
'displayOrderConfirmation',
);
protected $_carriers = array(
//"Public carrier name" => "technical name",
'My new carrier' => 'txshipping',
);
public function __construct()
{
$this->name = 'txshipping';
$this->tab = 'shipping_logistics';
$this->version = '1.0.0';
$this->author = 'Gerry';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.7.1.0',
'max' => _PS_VERSION_
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Tx Shipping');
$this->description = $this->l('manage shipping costs');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TXSHIPPING_NAME')) {
$this->warning = $this->l('No name provided');
}
}
public function getTemplate($area, $file)
{
return 'views/templates/' . $area . '/' . $file;
}
//-------------------------------------------------
// Hooks
//-------------------------------------------------
public function hookActionCarrierUpdate($params)
{
if ($params['carrier']->id_reference == Configuration::get(self::PREFIX . 'fcd_reference')) {
Configuration::updateValue(self::PREFIX . 'fcd', $params['carrier']->id);
}
}
public function getOrderShippingCost($params = null, $shipping_cost = 0) {
$curPage = $this->context->controller->php_self;
/* using test on which page is running cause the following code is always executed (even if is loading home page!?)
I don't understand why */
if ($curPage == "order") {
$this->loopCount++; // attempt for not to run the same code over and over.. but it doesn't work very well
if ($this->loopCount == 1) {
$this->shipCost = 77;
/*
$address = new Address($params->id_address_delivery);
$cap = $address->postcode;
$curID = $this->id_carrier; */
}
return floatval($this->shipCost);
} elseif ($curPage == "order-confirmation") {
$test = 76; // for simple test
return floatval($test);
} else {
if ($curPage != "pagenotfound") {
$this->loopCount = 0;
$this->shipCost = 0;
}
}
}
public function getOrderShippingCostExternal($params){
//return 999; costi spedizione
return $this->getOrderShippingCost($params, 0);
}
//-------------------------------------------------
// Setup
//-------------------------------------------------
public function install()
{
if (parent::install()) {
foreach ($this->_hooks as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
if (!$this->createCarriers()) {
return false;
}
return true;
}
return false;
}
public function uninstall()
{
if (parent::uninstall()) {
foreach ($this->_hooks as $hook) {
if (!$this->unregisterHook($hook)) {
return false;
}
}
if (!$this->deleteCarriers()) {
return false;
}
return true;
}
return false;
}
//-------------------------------------------------
// Funzioni private
//-------------------------------------------------
protected function createCarriers()
{
foreach ($this->_carriers as $key => $value) {
//Create own carrier
$carrier = new Carrier();
$carrier->name = $key;
$carrier->id_tax_rules_group = 0;
$carrier->active = 1;
$carrier->deleted = 0;
foreach (Language::getLanguages(true) as $language)
$carrier->delay[(int)$language['id_lang']] = 'Delay [1-2 days]';
$carrier->shipping_handling = false;
$carrier->range_behavior = 0;
$carrier->is_module = true;
$carrier->shipping_external = true;
$carrier->external_module_name = $this->name;
$carrier->need_range = true;
if ($carrier->add()) {
$groups = Group::getGroups(true);
foreach ($groups as $group) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_group', array(
'id_carrier' => (int) $carrier->id,
'id_group' => (int) $group['id_group']
), 'INSERT');
}
$rangePrice = new RangePrice();
$rangePrice->id_carrier = $carrier->id;
$rangePrice->delimiter1 = '0';
$rangePrice->delimiter2 = '1000000';
$rangePrice->add();
$rangeWeight = new RangeWeight();
$rangeWeight->id_carrier = $carrier->id;
$rangeWeight->delimiter1 = '0';
$rangeWeight->delimiter2 = '1000000';
$rangeWeight->add();
$zones = Zone::getZones(true);
foreach ($zones as $z) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_zone',
array('id_carrier' => (int) $carrier->id, 'id_zone' => (int) $z['id_zone']), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => (int) $rangePrice->id, 'id_range_weight' => NULL, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => NULL, 'id_range_weight' => (int) $rangeWeight->id, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
}
copy(dirname(__FILE__) . '/views/img/carrier.jpg', _PS_SHIP_IMG_DIR_ . '/' . (int) $carrier->id . '.jpg');
Configuration::updateValue(self::PREFIX . $value, $carrier->id);
Configuration::updateValue(self::PREFIX . $value . '_reference', $carrier->id);
}
}
return true;
}
protected function deleteCarriers()
{
foreach ($this->_carriers as $value) {
$tmp_carrier_id = Configuration::get(self::PREFIX . $value);
$carrier = new Carrier($tmp_carrier_id);
$carrier->delete();
}
return true;
}
}
Im my opinion it has something to do with your $curPage
I'd go for this if instead:
if ($this->context->controller instanceof CartController || $this->context->controller instanceof OrderController) {
I don't understand this part of code:
} elseif ($curPage == "order-confirmation") {
why would you do something different on real order-confirmation page where order is already placed?

How to redirect to another page in codeigniter from one page?

I have written a code in the controller which is given below. This code is for login page. In this code, the if statement notification is properly working but the else part is not working. It is not redirect to the url given in the redirect() instead it is showing a blank page. Can anyone tell y it is like that and correct it for me ? I have used header() function but also it is not working.I have placed all the code inside the 'kw' folder. This code is properly working in the localhost but when uploaded the same code to the live server, its not working.Is it due to version of the CI ?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('validation');
$this->load->model('studentsmodel');
}
public function index() {
if (isset($_POST['submit']))
{
$post_data = array('stud_cin' => $this->input->post('stud_cin'),'stud_password' => $this->input->post('stud_password'),
);
$this->validation->set_data($post_data);
$this->validation->set_rules('stud_cin','Cin','required|trim');
$this->validation->set_rules('stud_password','Password','required|trim');
if ($this->validation->run() === FALSE)
{
}
else
{
$this->load->model("studentsmodel");
$this->load->helper('url');
$result = $this->studentsmodel->loginCheck($post_data);
if (!$result){
$this->notifications->notify('Wrong username/password; Login Failed','error');
}
else{
$this->session->set_userdata('student_id', $result['id']);
$this->session->set_userdata('stud_cin', $result['stud_cin']);
$this->session->set_userdata('stud_photopath', $result['stud_photopath']);
redirect('student/profile/edit/id/'.$this->session->userdata('student_id'),'refresh');
//header('location:http://www.website.com/kw/application/controller/student/profile/edit/id/$this->session->userdata("student_id")');
}
}
} $this->load->view("login");
}
}
profile controller edit function
public function index()
{
$student_id=$this->session->userdata('student_id');
$data['profile_data'] =$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profileDetails.php", $data);
}
public function edit()
{
$uri = $this->uri->uri_to_assoc(4);
$student_id=$uri['id'];
if(isset($_POST['btn_submit']))
{
//echo "<pre>";print_r($_FILES);exit;
$img_val = $this->studentsmodel->getStudent_photo($student_id);
$photo_val = $img_val['stud_photopath'];
$photo_unlink = "";
if ($_FILES['stud_photopath']['name'] != "")
{
/*echo "in";exit;*/
$photo_chk = explode("photo/", $photo_val);
$photo_unlink = $photo_chk[1];
$photo_path = "";
$flag = "";
$f_type_chk = $_FILES['stud_photopath']['type'];
if ($f_type_chk != "image/gif" && $f_type_chk != "image/jpg" && $f_type_chk != "image/jpeg"
&& $f_type_chk != "image/bmp" && $f_type_chk != "image/png" && $f_type_chk != "")
{
$flag = "Select allowed file type and size for photo";
}
if ($_FILES['stud_photopath']['size'] >= 5242880) { $flag = "Select allowed file type and size for photo"; }
$target_path = getcwd() . "/public/photo/";
$db_path = "photo/";
if ($_FILES['stud_photopath']['name'] != '')
{
$file_name = $_FILES["stud_photopath"]["name"];
$file_size = $_FILES["stud_photopath"]["size"] / 1024;
$file_type = $_FILES["stud_photopath"]["type"];
$file_tmp_name = $_FILES["stud_photopath"]["tmp_name"];
$random = rand(111, 999);
$new_file_name = $random . $file_name;
$newfile_name=$cin."_". $file_name;
$upload_path = $target_path . $newfile_name;;
if (move_uploaded_file($file_tmp_name, $upload_path)) { $photo_path = addslashes($db_path . $newfile_name); } /*end if*/
else { $this->notifications->notify('Photo cannot upload', 'error'); }/*end else var_dump($this->validation->show_errors());*/
}/*end if $_FILES['photo']['name']*/
} /*END OF if ($_FILES['photo']['name'] != "") */
else { $photo_path = $photo_val; } /*END OF ELSE ($_FILES['photo']['name'] != "") */
$this->session->unset_userdata('stud_photopath');
$this->session->set_userdata('stud_photopath', $photo_path);
$data['photo_unlink'] = $photo_unlink;
/* echo $dob_dd = $this->input->post('dob_dd');exit;
$dob_mm = $this->input->post('dob_mm');
$dob_yy = $this->input->post('dob_yy');
$dob = $dob_dd . "-" . $dob_mm . "-" . $dob_yy;*/
$stud_age_dob =$this->input->post('stud_age_dob');
$timestamp = strtotime($stud_age_dob);
$dob = date('Y-m-d', $timestamp);
$validation_data = array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' =>$this->input->post('stud_age_dob'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
);
//echo "<pre>";print_r($validation_data); exit;
$this->validation->set_data($validation_data);
$this->validation->set_rules('stud_name', 'Student Name', 'trim|alpha_space|required');
$this->validation->set_rules('stud_gender', 'Gender', 'required');
$this->validation->set_rules('stud_age_dob', 'DOB', 'required');
$this->validation->set_rules('stud_mobile', 'Mobile number', 'numeric|required');
$this->validation->set_rules('stud_email', 'Email Id', 'trim|required|valid_email|xss_clean');
if ($this->validation->run() === FALSE)
{ /* var_dump($this->validation->show_errors()); */ $this->notifications->notify('Please make all entries', 'error');}
else
{
$updation_data=array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' => $this->input->post('stud_age_dob'),
'stud_gaurdian' =>$this->input->post('stud_gaurdian'),
'stud_mother' =>$this->input->post('stud_mother'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
'stud_tel' => $this->input->post('stud_tel'),
'stud_guardian_address' => $this->input->post('stud_guardian_address'),
'stud_pin' => $this->input->post('stud_pin'),
'stud_photopath' => $photo_path,
'stud_age_dob' => $dob
);
/*echo "<pre>";print_r($updation_data); exit; */
$update_status=$this->studentsmodel->update_profile($updation_data, $student_id);
if($update_status==1)
{
//$this->session->set_userdata('profile_status', 'Yes');
/*$this->session->userdata('profile_status');*/
redirect('student/profile/index/', 'refresh');
}
else
{
$this->notifications->notify('profile updted failed', 'error');
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profile_edit.php",$data);
}
Check if you already load this helper
$this->load->helper('url');
This is the information about the redirect function
redirect($uri = '', $method = 'auto', $code = NULL);
Parameters:
$uri (string) URI string $method (string)
Redirect method (‘auto’,
‘location’ or ‘refresh’)
$code (string) HTTP Response code (usually 302 or 303)
Note:
Don't forget add in the config file the value for base_uri
https://www.codeigniter.com/user_guide/helpers/url_helper.html
https://www.codeigniter.com/userguide3/libraries/config.html
remove /id/ from your redirect()
redirect('student/profile/edit/'.$this->session->userdata('student_id'));

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

Why does this webform uploaded file via ajax throw an error in Drupal 7?

I have a webform and mymodule which alters it. The webform has a field stelle which gets populated based on the url query. For instance, if ?stelle=10 the field gets populated by the title of node with nid 10. If the query ?stelle is non-existant or followed by a nid which does not exist (is not of a certain content type) or does not contain a certain string the form will be redirecting to mynode?stelle=initiativ. The form has 2 fields to upload files via ajax, works good so far. Here is my code:
<?php
/**
* Altering the form! this will add class to the file upload/ remove buttons
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$conf = mymodule_defaults();
if ($form_id == 'webform_client_form_' . $conf['nid']) {
if (isset($form['submitted']['field1'])) {
$form['submitted']['field1']['#process'] = array('mymodule_my_file_element_process');
}
if (isset($form['submitted']['field2'])) {
$form['submitted']['field2']['#process'] = array('mymodule_my_file_element_process');
}
$nid = $form['#node']->nid;
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_webform_js_submit',
'wrapper' => 'webform-client-form-' . $nid,
'method' => 'replace',
'effect' => 'fade',
);
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
$hide_components = array(
'einleitung_standard',
'einleitung_initiativ',
);
$unhide_components = array();
if ($form['submitted']['stelle']['#default_value'] == '') {
$redirect_form = true;
}
elseif (is_numeric($form['submitted']['stelle']['#default_value'])) {
$nid = $form['submitted']['stelle']['#default_value'];
$node = node_load($nid);
if ($node === false || (isset($node->type) && $node->type !== 'job')) {
$redirect_form = true;
}
else {
$type = $node->type;
if ($type == 'job') {
$form['submitted']['stelle']['#default_value'] = $node->title;
$form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
$form['submitted']['related']['#value'] = $nid;
$unhide_components = array(
'einleitung_standard'
);
}
}
}
elseif ($form['submitted']['stelle']['#default_value'] == 'initiativ') {
// unset($form['submitted']['stelle']);
$form['submitted']['related']['#value'] = 'initiativ';
$unhide_components = array(
'einleitung_initiativ'
);
}
}
else {
// $redirect_form = true;
// this causes an error
}
This is the weird part:
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
...
else {
// $redirect_form = true;
// this causes an error
}
When I active the line to redirect the form when the if condition is false, the button to upload a file via ajax throws an error alert on click (see bottom for error). To me, this looks like the form alter hook is being called again when the file upload button is clicked without having my field stelle available - is that right? How to fix this?
And now the rest of the module, basically just alterings:
else {
// $redirect_form = true;
// this causes an error
}
foreach ($unhide_components as $key => $component) {
if (is_array($component)) {
foreach ($component as $_key => $_component) {
$index = array_search($_component, $hide_components[$key]);
if ($index !== false) {
unset($hide_components[$key][$index]);
}
}
}
else {
$index = array_search($component, $hide_components);
if ($index !== false) {
unset($hide_components[$index]);
}
}
}
// hide
foreach ($hide_components as $k=>$hc1){
if (is_array($hc1)) {
foreach ($hc1 as $hc2) unset($form['submitted'][$k][$hc2]);
} else {
unset($form['submitted'][$hc1]);
}
}
if ($redirect_form) drupal_goto('node/'.$conf['nid'], array('query'=>array('stelle'=>'initiativ')), 301);
}
}
function mymodule_my_file_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#attributes'] = array('class' => array('button'));
$prefix = '<label class="browse-slave">';
$prefix .= '<span class="button">' . t('Choose a file') . '</span>';
$element['upload']['#prefix'] = $prefix;
$element['upload_button']['#prefix'] = '</label>';
$element['remove_button']['#attributes'] = array('class' => array('button'));
$element['remove_button']['#prefix'] = '</label>';
return $element;
}
function mymodule_webform_js_submit($form, $form_state) {
// define the $sid variable (submission id from webform)
$sid = $form_state['values']['details']['sid'];
// if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
if ($sid) {
// first we have to load up the webform node object
$node = node_load($form_state['values']['details']['nid']);
// create an array up with the confirmation message, retreived from the webform node
$confirmation = array(
'#type' => 'markup',
'#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
);
// return the confirmation message
return $confirmation;
}
else {
// return the form
return $form;
}
}
The AJAX error is something like described here. Changing server/php settings didnt help it.
Thanks!
The form builder (and any hook alters) will be run when a form is validated, which happens on #ajax actions.
I like to throw static custom data in $form['#someProperty'] so that it's available in the build, validate, and submit functions. Something like this should help you:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// ...
if (isset($_GET['stelle'])) {
$form['#stelle'] = $_GET['stelle']; // This will always be there.
}
// ...
}
Another option would be to throw the $node that you load in the form, like $form['#stelle_node'] = node_load(...) and obviously only do that when the nid is actually available to you, so that you don't overwrite it with empty data when the form builder runs again in the future.
When i was working with ajax in drupal 6 the hash symbol in url or request caused an error everytime..... so i replaced url with this
data.url.replace(/%2523/, '%23');

$this->form_validation->run() not executing

I have an issue in codeignitor form handling it does not execute $this->form_validation->run() on local server. But it does work very fine on live server. I can't find out what is the reason. Here is my controller.
class Login extends CI_Controller
{
function __construct(){
parent::__construct();
}
function removeUser($record_id){
$a = new Alumni();
$a->removeConnections($record_id);
}
function index(){
$redir = isset($_GET['redir'])?$_GET['redir']:'admin';
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('admin');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/login/send_again/');
} else {
//
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
//var_dump($login);
} else {
$login = '';
}
//var_dump($this->input->post("remember"));
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
if ($this->form_validation->run() === false) {
}else{
echo " logged in";// validation ok
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
//echo $loginID;
if ($this->tank_auth->login(
$loginID,
$pass,
$remember,
$data['login_by_username'],
$data['login_by_email'])) { // success
echo "success";
redirect($redir);
} else {
$errors = $this->tank_auth->get_error_message();
//echo "error";
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
.....
Sorry for long code please help me.
I don't see the library getting loaded in your constructor
public function __construct()
{
parent :: __construct();
$this->load->helper('url');
$this->load->helper('cookie');
//load the validation library
$this->load->library('form_validation');
$this->load->library("pagination");
}

Resources