how to create new session to replace old session CodeIgniter - codeigniter

Im set session when user login
user model
function cek(){
$username=$this->input->post('username');
$password=md5($this->input->post('password'));
$query=$this->db->query("select akun.*,profile.kelas, profile.jurusan FROM profile right JOIN akun ON profile.id_akun = akun.id_akun WHERE akun.username = '$username' AND akun.password = '$password'");
if ($query->num_rows() > 0)
foreach ($query->result() as $data) {
$data=array('LOGIN'=>TRUE,'LEVEL'=>$data->level,'KELAS'=>$data->kelas,'JURUSAN'=>$data->jurusan,'ID_AKUN'=>$data->id_akun,'USERNAME'=>$data->username);
$this->session->set_userdata($data);
echo json_encode(array("status" => TRUE));
} else {
echo json_encode(array("status" => FALSE));
}
}
I want replace just session KELAS and JURUSAN
profile Controller
public function tambahprofile()
{
if($this->session->userdata('LOGIN')=='TRUE' and $this->session->userdata('LEVEL')==1 )
{
$id_akun=$this->session->userdata('ID_AKUN');
$kelas='12';
$jurusan='multimedia';
$this->validasi();
$data = array(
'nis' =>$this->input->post('nis'),
'id_akun' =>$id_akun,
'nama' =>$this->input->post('nama'),
'telpon' =>$this->input->post('telpon'),
'alamat' =>$this->input->post('alamat'),
'tgllahir' =>$this->input->post('tgllahir'),
'tmptlahir' =>$this->input->post('tmptlahir'),
'jurusan' =>$this->input->post('jurusan'),
'kelas' =>$this->input->post('kelas'),
'jk' =>$this->input->post('jk'),
);
if ($this->input->post('id')=='') {
$this->profile_model->tambah($data);
/**
TODO:
- First todo item
- Second todo item
*/
echo json_encode(array("status" => TRUE));
}else{
$this->profile_model->update(array('id' => $this->input->post('id')),$data);
$this->profile_model->update($data);
echo json_encode(array("status" => TRUE));
}
}else {
redirect('beranda/loginPage');
}
}
View
<?php echo $this->session->userdata('KELAS').$this->session->userdata('JURUSAN');?>
I'm create new session to replace old session KELAS and jurusan
no error but in my view is old session

Try this.
$data = array(
'kelas' => "test1",
'jurusan' => "Test2"
);
$this->session->set_userdata($data);
var_dump($this->session->userdata() );
$this->session->unset_userdata('kelas');
$data = array( 'kelas' => "newTest" );
$this->session->set_userdata($data);
var_dump($this->session->userdata() );
Using $this->session->unset_userdata( 'kelas' ); will unset only that entry.
$data = array( 'kelas' => "newTest" ); $this->session->set_userdata($data); will replace only that entry.
On a side note $password=md5( $this->input->post( 'password' ) ); this is not advised mate. If you read around that speed in which md5() can be broken make it a bad option for storing passwords.
PHP has a built in hashing function password_hash()
http://php.net/manual/en/function.password-hash.php
Would be worth a read.

when you need to replace old data just unset previous data and then set again your new data
//remove old data
$perticular_data = array('KELAS'=>$kelas,'JURUSAN'=>$jurusan);
$this->session->unset_userdata($perticular_data);
//set new data
$perticular_data = array('KELAS'=>$new_kelas,'JURUSAN'=>$new_jurusan);
$this->session->set_userdata($perticular_data);

Related

How to add months dynamically which is stored in database as a header in excel file while exporting using laravel?

Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}

codeigniter how to store real time data

public function insert_employee($fldCompanyStringID) {
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$data2 = array(
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert('tblUser', $data)&& $this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
The tblUser table auto generates a userID. I want to take that userID and store it into the tblWorkHistory table **
Here CodeIgniter transactions will help you.
https://www.codeigniter.com/user_guide/database/transactions.html
Please use this code --
<?php
public function insert_employee($fldCompanyStringID) {
$this->db->trans_start();
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
/* Insert User */
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$this->db->insert('tblUser', $data)
$insert_id = $this->db->insert_id();
/* Insert Work History */
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
$this->db->insert('tblWorkHistory', $data2)
/* Manage Transaction */
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->session->set_flashdata('error_msg', 'Failed, please try again');
}else{
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
?>
$this->db->insert_id() is used to get the last insert auto increment id data.
$this->db->insert('tblUser', $data);
$insert_id = $this->db->insert_id();
if($insert_id) {
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
} else {
$this->session->set_flashdata('error_msg', 'Something went wrong');
}

Drupal 8 Form alter the ajax callback is not working

I am getting my ajax callback in normal custom form, but on form alter its not working.
function sample_ajax_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form_id === 'node_sampleajax_form' || $form_id === 'node_sampleajax_edit_form') {
$form['field_nametrain']= array(
'#title' => t('training name'),
'#type' => 'select',
'#options' => _load_training(),
'#required' => FALSE,
'#ajax' => [
'callback' => [$this, 'changeOptionsAjax'],
// 'callback' => '::changeOptionsAjax',
'wrapper' => 'second_field_wrapper',
],
);
$form['field_namedomain'] = [
'#type' => 'select',
'#title' => t('Domain program'),
'#options' => $this->getOptions($form_state),
'#prefix' => '<div id="second_field_wrapper">',
'#suffix' => '</div>',
];
return $form;
}
}
function _load_training() {
$training = array('- Select domain training -');
$query = db_select("node__field_trainingname", "a");
$query->fields("a", array('field_trainingname_value', 'entity_id'));
$query->orderBy("a.field_trainingname_value");
$result = $query->execute();
while($row = $result->fetchObject()){
$training[$row->entity_id] = $row->field_trainingname_value;
}
return $training;
}
function changeOptionsAjax(array &$form, FormStateInterface $form_state) {
return $form['field_namedomain'];
}
function getOptions(array &$form, FormStateInterface $form_state) {
$cvvv = $form_state->getValue('field_nametrain');
<!-- return ["shgsh", $form_state->get(['field_nametrain'])]; -->
$options = array('- Select subdomain category -');
$query = db_select("node__field_trainingname", "a");
$query->fields("a", array('field_trainingname_value', 'entity_id'));
$query = db_select("node__field_cms", "b");
$query->fields("b", array('field_cms_value', 'entity_id'));
$query->join("node__field_trainingname", "b", "b.entity_id=a.entity_id");
$query->condition("a.entity_id", $cvvv);
$result = $query->execute();
while($row = $result->fetchObject()){
$options[$row->entity_id] = $row->field_cms_value;
}
return $options;
}
On using $this->getOptions($form_state) it represent the error log it is not an object and throws website encounter error in front end. But on custom form no error came only in formalter it throws error.
Kindly suggest me ideas to apply in form_alter of Drupal 8
The .module file, where your form alter hook is located, is not a class, therefore there is no $this. Your custom form however is a class (usually in your_module/src/Form/YourForm.php), that's why it works there but not in the .module file.
Further reading: http://www.php.net/manual/en/language.oop5.basic.php
and What does the variable $this mean in PHP?
In your case you should be able to just call
'#options' => getOptions($form, $form_state),
And more on a side note: I would strongly recommend to do some code refactoring.
In your custom submit handler, firt get the form object from the form state.
$formObj = $formState->getFormObject();
then call submitForm() on the form object and pass the form and form state variables.
$formObj->submitForm($form, $formState);
and finally, you just need to simply trigger the save() function on the object.
$formObj->save($form, $formState);
So the whole solution is something like
function YOR_CUSTOM_SUBMIT_HANLDLER(array $form, FormStateInterface $form_state) {
/** #var Drupal\user\RegisterForm $entity */
$formObj = $form_state->getFormObject();
$formObj->submitForm($form, $form_state);
$formObj->save($form, $form_state);
}

Filter admin grid with custom render values Magento

i have created a custom grid in which one of the columns i have render
my custom date.On the basis of data i am returning
yes or no
like below
public function render(Varien_Object $row)
{
$currentruleid = $this->getRequest()->getParam('id');
$value = (int)$row->getData($this->getColumn()->getIndex());
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "SELECT exclusive_coupon_id FROM mutually_exclusive
WHERE rule_id ='$currentruleid' AND exclusive_coupon_id ='$value' ";
$result = $read->query($query);
$affected_rows = $result->rowCount();
if($affected_rows > 0){
return 'Yes';
}
else{
return 'No';
}
}
and in grid my column code is
$this->addColumn('', array(
'header' => Mage::helper('salesrule')->__('Exclusive'),
'index' => 'coupon_id',
'width' => '100',
'type' => 'options',
'options' => array(
Mage::helper('adminhtml')->__('No'),
Mage::helper('adminhtml')->__('Yes')
),
'renderer' => 'adminhtml/promo_quote_edit_tab_exclusivecoupons_grid_column_renderer_used',
));
my renderer is returning accurate data
and its showing in columns
i need to filter also with yes or no. But filtering is not working.
Can you please suggest me how can i do this.
thanks
i have check that but my renderer is not any direct field , its a custom data like below is my renderer function
public function render(Varien_Object $row)
{
$currentruleid = $this->getRequest()->getParam('id');
$value = (int)$row->getData($this->getColumn()->getIndex());
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "SELECT exclusive_coupon_id FROM mutually_exclusive
WHERE rule_id ='$currentruleid' AND exclusive_coupon_id ='$value' ";
$result = $read->query($query);
$affected_rows = $result->rowCount();
if($affected_rows > 0){
return 'Yes';
}
else{
return 'No';
}
}

CodeIgniter: Passing fields to user_profiles database with Tank_auth

I'm wracking my brain on what is probably a simple issue. Relatively new to MVC and codeigniter. I'm using tank_auth for user registration, and it comes with a db table user_profiles which I've altered slightly to add things like 'firstname', 'lastname', 'homephone', etc.
I've added the appropriate fields to my register_form.php view and following advice from this question: Tank Auth Adding Fields and others, tried to update all necessary stuff. Unfortunately, while the users table gets populated properly, the user_profiles table does not. I've double checked with firebug that the view is posting properly, but the model is not picking up the data, and I keep getting the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: firstname
Filename: tank_auth/users.php
Line Number: 382
Using var_dump, I can see that the controller function is not receiving 'firstname' or anything else and they are NULL, but the data going into users is being sent properly.
Here's the relevant code:
Model:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Controller:
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname', 'trim|xss_clean');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($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();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('homephone'),
$this->form_validation->set_value('cellphone'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
View:
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 40,
'size' => 30,
);
...
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
I have been working on this far too long, am hoping that a fresh (and knowledgeable) pair of eyes can see what I cannot.
The data to be recorded in user_profile is passed along the folllowing chain:
view -> controller -> library/tank_auth/create_user() -> model/users/users/create_user() -> model/create_profile
Therefore you need to make sure that the variable is passed along every time.
Here is my working solution, building up on the modifications that you mentioned in the question:
VIEW + CONTROLER:
Your solution is good
LIBRARY
function create_user($username, $email, $password, $firstname, $lastname, $company='', $email_activation)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
} elseif (!$this->ci->users->is_email_available($email)) {
$this->error = array('email' => 'auth_email_in_use');
} else {
// Hash password using phpass
$hasher = new PasswordHash(
$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
$hashed_password = $hasher->HashPassword($password);
$data = array(
'username' => $username,
'password' => $hashed_password,
'email' => $email,
'last_ip' => $this->ci->input->ip_address(),
);
$data_profile = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => $company,
);
if ($email_activation) {
$data['new_email_key'] = md5(rand().microtime());
}
if (!is_null($res = $this->ci->users->create_user($data, $data_profile, !$email_activation))) {
$data['user_id'] = $res['user_id'];
$data['password'] = $password;
unset($data['last_ip']);
return $data;
}
}
return NULL;
}
MODEL:
function create_user($data, $data_profile, $activated = TRUE)
{
$data['created'] = date('Y-m-d H:i:s');
$data['activated'] = $activated ? 1 : 0;
var_dump($data);
if ($this->AuthDb->insert($this->table_name, $data)) {
$user_id = $this->AuthDb->insert_id();
$this->create_profile($user_id, $data_profile);
return array('user_id' => $user_id);
}
return NULL;
}
[...]
private function create_profile($user_id, $data_profile)
{
$this->AuthDb->set('user_id', $user_id);
$this->AuthDb->set('firstname', $data_profile['firstname']);
$this->AuthDb->set('lastname', $data_profile['lastname']);
$this->AuthDb->set('company', $data_profile['company']);
return $this->AuthDb->insert($this->profile_table_name);
}
You need to pass $firstname as a parameter to the function...
private function create_profile($user_id, $firstname)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Ok so I figured it out, in case anyone googles this answer down the line. I'm not sure if this is the 'proper' or most elegant solution, but does fine for my purposes. I edited the create_profile function like so:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$data = array(
'firstname' => $this->input->post('firstname'),
);
$this->db->insert($this->profile_table_name, $data);
}

Resources