CodeIgniter Session do not saving Array - arrays

i using CodeIgniter Session with database for save a array with $_FILES, but don't save. I do this (but the array never increment):
The post of form, redirects to himself.
Function to upload e load the page of upload.
public function getUpload($codtemp, $codmessage){
$this->load->library('session');
$this->layout = '';
$data = array();
$data['codmessage'] = $codmessage;
$data['codtemp'] = $codtemp;$tempfiles= $this->session->userdata('tempfiles');
if (isset($_FILES['attachment']))
{
$files = $this->fixGlobalFilesArray($_FILES['attachment']);
foreach($files as $file)
{
$tempfiles[$codtemp][] = $file;
}
$this->session->set_userdata('tempfiles', $tempfiles);
unset($files);
}
$this->parser->parse('attachment_upload', $data);
}
private static function fixGlobalFilesArray($files) {
$ret = array();
if(isset($files['tmp_name']))
{
if (is_array($files['tmp_name']))
{
foreach($files['name'] as $idx => $name)
{
$ret[$idx] = array(
'name' => $name,
'tmp_name' => $files['tmp_name'][$idx],
'size' => $files['size'][$idx],
'type' => $files['type'][$idx],
'error' => $files['error'][$idx]
);
}
}
else
{
$ret = $files;
}
}
else
{
foreach ($files as $key => $value)
{
$ret[$key] = self::fixGlobalFilesArray($value);
}
}
return $ret;
}

Before save the array, serialize the data and after get the data, unserialize. If data is empty, create a array

Related

Cant change single value in session array in Laravel

This my method update for products. And cant to change qty of product. Data saved inside foreach, but nothing change out of this. I can't understand what the problem.
if (!session()->has('products')) {
session()->put('products', []);
}
$products = session()->get('products');
foreach ($products as $item) {
if (isset($item[$product->id])) {
$item[$product->id]['qty'] = 10;
dd($products); // dd($item) - changes
$request->session()->put('products', $products);
return redirect()->back();
}
}
session()->push('products', [
$product->id => [
'product' => $product,
'qty' => 1
]
]);
return redirect()->back();
As you can see there is dd($products) - so its not change. But if dd($item) so it has qty 10.
I can solved this with next:
foreach ($products as $key => $value) {
if (isset($value[$product->id])) {
$value[$product->id]['qty'] = 10;
$products[$key] = $value;
$request->session()->put('products', $products);
return redirect()->back();
}
}
Just add a $key => $value and save it in $products[$key] = $value;

can not use pagination() for an array object in laravel

I am constructing an array in Laravel 5.7. I would like to paginate it, but it errors because of array feature. what shall I do?
In MyController.php:
$result = array();
foreach ($sameDateMatches as $key => $date) {
array_push($result, [
'date' => $key,
'day_of_week' => getDayOfWeek($key),
'matches' => $date,
]);
}
if (!empty($_GET['page'])) {
$result = $result->paginate(10);
$pagination = $result;
} else {
$result = $result;
$pagination = null;
}
return returnSuccessfulResponse(
trans('api.response.successful.show'),
[
'Scheduled Matches' => $result,
],
$pagination
);
Call to a member function paginate() on array
You can only use paginate on an instance of QueryBuilder or on an Eloquent query.
Instead, if you need to 'paginate' an array, you can use PHP array_chunk.
array_chunk($result, 10, true);
I solved my problems using make() and LengthAwarePaginator as below:
if (!empty($_GET['page'])) {
$per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
$page = $_GET['page'];
$result = $result instanceof Collection ? $result : Collection::make($result);
$result = new LengthAwarePaginator(
$result->forPage($page, $per_page)->values(),
$result->count(),
$per_page,
$page,
['path' => request()->url()]
);
$pagination = $result;
} else {
$pagination = null;
}

how to show as row_number() in codeignitier

need help what wrong with my code where this my sql command where successfull run in mysql :
SELECT func_inc_var_session() As row_number ,
vruasjalan2.*
FROM vruasjalan2 Where skid = #skid
ORDER BY kategoriruasjalanid, subkategoriruasjalanid,ruasjalanid;"
but when i want to display in my controller row_number start error say"Call to undefined method Jalan_model::num_rows()"
public function ajax_list()
{
$list = $this->Jalan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $Jalan) {
$no++;
$row = array();
$row[] = $no;
$row[] = $Jalan->row_number;
$row[] = $Jalan->ruasjalanid;
$row[] = $Jalan->skid;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Jalan->count_all(),
"recordsFiltered" => $this->Jalan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
and this is my model
public function get_list_companys()
{
$this->db->select('vruasjalan2.*');
$this->db->from($this->table);
$this->db->order_by('kategoriruasjalanid','asc');
$query = $this->db->get();
$result = $query->result();
$companys = array();
foreach ($result as $row)
{
$companys[] = $row->kategoriruasjalanid;
}
return $companys;
}
if there any expert know this problems

Writing custom rules for CakePHP model

use App\Model\Rule\CustomIsUnique;
$rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [
'errorField' => 'item_id',
'message' => 'Item Unit must be unique.'
]);
On CustomIsUnique I've copy pasted codes of IsUnique
Cake\ORM\Rule\IsUnique;
But How to extend or add more operations inside the __invoke method ?
Update ::
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
return true;
} else {
if ($options['type'] == 'item_units') {
$data = TableRegistry::get('item_units')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'production_rules') {
$data = TableRegistry::get('production_rules')->find()
->where(['input_item_id' => $entity['input_item_id'],
'output_item_id' => $entity['output_item_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'prices') {
$data = TableRegistry::get('prices')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
}
}
}
this is how I've implemented for different model and passed extra parameter along with options array. I think this is not the good way to do this.
If you want to extend a core application rule, you can do something like:
<?php
use App\Model\Rule;
class CustomIsUnique extends Cake\ORM\Rule\IsUnique
{
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
// the record is indeed unique
return true;
}
// do any other checking here
// for instance, checking if the existing record
// has a different deletion status than the one
// you are inserting
}
}
That will let you add any additional logic for your application.

translate behavior and associated model translation

I searched the web 1000000000000000 times and i can't find a clean solution for this
this is my CertificateType model translation part:
public $actsAs = array('Translate'=>array('title','description')) ;
and the Certificate model:
public $actsAs=array('Translate'=>array('filename')) ;
public $belongsTo = array(
'CertificateType' => array(
'className' => 'CertificateType',
'foreignKey' => 'certificate_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
) ,
);
But in fetch time the belonged model will not translate:
public function admin_index() {
$this->Certificate->locale = $this->Session->read('Config.language');
$this->Certificate->CertificateType->locale = $this->Session->read('Config.language');
$this->Certificate->recursive = 0;
$this->set('certificates', $this->paginate());
debug($this->Certificate->paginate()) ;
}
Why?
I used this and it is working great!
in AppModel.php I wrote these piece of code:
public function getTranslatedModelField($id = 0, $field) {
// retrieve active language
$ActiveLanguageCatalog=CakeSession::read('Config.ActiveLanguageCatalog') ;
$res = false;
$translateTable = (isset($this->translateTable))?$this->translateTable:"i18n";
$db = $this->getDataSource();
$tmp = $db->fetchAll(
"SELECT content from {$translateTable} WHERE model = ? AND locale = ? AND foreign_key = ? AND field = ? LIMIT 1",
array($this->alias, $ActiveLanguageCatalog['locale'], $id, $field)
);
if (!empty($tmp)) {
$res = $tmp[0][$translateTable]['content'];
}
return $res;
}
public function afterFind($results, $primary = false) {
if($primary == false && array_key_exists('Translate', $this->actsAs)) {
foreach ($results as $key => $val) {
if (isset($val[$this->name]) && isset($val[$this->name]['id'])) {
foreach($this->actsAs['Translate'] as $translationfield) {
$results[$key][$this->name][$translationfield] = $this->getTranslatedModelField($val[$this->name]['id'], $translationfield);
}
} else if($key == 'id' && is_numeric($val)) {
foreach($this->actsAs['Translate'] as $translationfield) {
$results[$translationfield] = $this->getTranslatedModelField($val, $translationfield);
}
}
}
}
return $results;
}
Add code below to AppModel:
public function afterFind($results, $primary = false) {
if(!empty($this->hasMany)) {
foreach($this->hasMany as $model => $settings) {
if(isset($this->{$model}->actsAs['Translate'])) {
if(!empty($results[0][$model])) {
foreach($results[0][$model] as $row => $result) {
$supplement = $this->{$model}->find('first', array(
'conditions' => array(
$model .'.id' => $result['id']),
'fields' => $this->{$model}->actsAs['Translate'],
'recursive' => -1));
if(!empty($supplement)) {
$results[0][$model][$row] = array_merge($results[0][$model][$row], array_diff($supplement[$model], $result));
}
}
}
}
}
}
if(!empty($this->belongsTo)) {
foreach($this->belongsTo as $model => $settings) {
if(isset($this->{$model}->actsAs['Translate'])) {
if(!empty($results[0][$model])) {
foreach($results[0][$model] as $row => $result) {
$supplement = $this->{$model}->find('first', array(
'conditions' => array(
$model .'.id' => $result),
'fields' => $this->{$model}->actsAs['Translate'],
'recursive' => -1));
if(!empty($supplement)) {
$results[0][$model] = array_merge($results[0][$model], $supplement[$model]);
}
}
}
}
}
}
return $results;
}
This works with relation hasMany and belongsTo
Thanks to Vahid Alimohamadi for the snipped. I had to modify it to work properly in my proJect.
public function getTranslatedModelField($id = 0, $field) {
// retrieve active language
//$ActiveLanguageCatalog=CakeSession::read('Config.ActiveLanguageCatalog') ;
$locale = Configure::read('Config.language');
$res = false;
$translateTable = (isset($this->translateTable))?$this->translateTable:"i18n";
$db = $this->getDataSource();
$tmp = $db->fetchAll(
"SELECT content from {$translateTable} WHERE model = ? AND locale = ? AND foreign_key = ? AND field = ? LIMIT 1",
array($this->alias, $locale/*$ActiveLanguageCatalog['locale']*/, $id, $field)
);
if (!empty($tmp)) {
$res = $tmp[0][$translateTable]['content'];
}
return $res;
}
public function afterFind($results, $primary = false) {
if($primary == false && array_key_exists('Translate', $this->actsAs)) {
foreach ($results as $key => $val) {
if (isset($val[$this->name]) && isset($val[$this->name]['id'])) {
//HERE ADDED $field => $translationfield AND PASS IT TO THE getTranslatedModelField
foreach($this->actsAs['Translate'] as $field => $translationfield) {
$results[$key][$this->name][$field] = $this->getTranslatedModelField($val[$this->name]['id'], $field);
}
} else if($key == 'id' && is_numeric($val)) {
//HERE ADDED $field => $translationfield AND PASS IT TO THE getTranslatedModelField
foreach($this->actsAs['Translate'] as $field => $translationfield) {
$results[$field] = $this->getTranslatedModelField($val, $field);
}
}
}
}
return $results;
}
I have some update to working in cakephp 2.5. It working for me now. Hope can help.
public function getTranslatedModelField($id = 0, $field) {
$res = false;
$translateTable = (isset($this->translateTable))?$this->translateTable:"i18n";
$db = $this->getDataSource();
$tmp = $db->fetchAll(
"SELECT content from {$translateTable} WHERE model = ? AND locale = ? AND foreign_key = ? AND field = ? LIMIT 1",
array($this->alias, $this->locale , $id, $field)
);
if (!empty($tmp)) {
$res = $tmp[0][$translateTable]['content'];
}
return $res;
}
public function afterFind($results, $primary = false) {
if($primary == false && array_key_exists('Translate', $this->actsAs)) {
foreach ($results as $key => $val) {
if (isset($val[$this->name]) && isset($val[$this->name]['id'])) {
foreach($this->actsAs['Translate'] as $k => $translationfield) {
$results[$key][$this->name][$translationfield] = $this->getTranslatedModelField($val[$this->name]['id'], $k);
}
} else if($key == 'id' && is_numeric($val)) {
foreach($this->actsAs['Translate'] as $k => $translationfield) {
$results[$translationfield] = $this->getTranslatedModelField($val, $k);
}
}
}
}
return $results;
}
I had done a change for getting current language and works perfectly with cacke 2.4.3
public function getTranslatedModelField($id = 0, $field) {
// retrieve active language
$locale = $this->locale ;// gets the current assigned locale
$res = false;
$translateTable = (isset($this->translateTable))?$this->translateTable:"i18n";
$db = $this->getDataSource();
$tmp = $db->fetchAll(
"SELECT content from {$translateTable} WHERE model = ? AND locale = ? AND foreign_key = ? AND field = ? LIMIT 1",
array($this->alias, $locale , $id, $field)
);
if (!empty($tmp)) {
$res = $tmp[0][$translateTable]['content'];
}
return $res;
}
public function afterFind($results, $primary = false) {
if($primary == false && array_key_exists('Translate', $this->actsAs)) {
foreach ($results as $key => $val) {
if (isset($val[$this->name]) && isset($val[$this->name]['id'])) {
foreach($this->actsAs['Translate'] as $translationfield) {
$results[$key][$this->name][$translationfield] = $this->getTranslatedModelField($val[$this->name]['id'], $translationfield);
}
} else if($key == 'id' && is_numeric($val)) {
foreach($this->actsAs['Translate'] as $translationfield) {
$results[$translationfield] = $this->getTranslatedModelField($val, $translationfield);
}
}
}
}
return $results;
}
The easiest solution is the following get the ids of the associated models items and make another search like the following:
$ids = array();
foreach ($wpage['Widget'] as &$widget):
$ids[] = $widget['id'];
endforeach;
$widgets = $this->Wpage->Widget->find('all', array(
'conditions' => array('Widget.id' => $ids)
));
$this->set(compact('wpage', 'widgets'));
Thanks,
Aris
Enabling Translate behavior for related models is very easy in Cake way, by using Model->SubModel->Behaviors->load(...)
$this->Certificate->CertificateType->Behaviors->load(
'Translate',
array('title','description')
);
Have a look at http://book.cakephp.org/2.0/en/models/behaviors.html

Resources