codeigniter how to store real time data - codeigniter

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

Related

how to create new session to replace old session 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);

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

Magento Invoice sendEmail() with PDF attachment

I use the following code to load an invoice and send email programatically:
<?php
$invoice = Mage::getModel('sales/order_invoice')
->loadByIncrementId($invoice_queue['increment_id']);
if (null !== $invoice->getId()){
$invoice->sendEmail();
echo "- Done Invoice #". $invoice_queue['increment_id'] ."\r\n";
}
$invoice = null;
?>
This appears to be sending the invoice email correctly. However, the PDF attachment of the invoice isn't there in the email.
If I were to send the email via magento, it works.
Any idea how to get the PDF to be attached, when calling sendEmail() function?
For sending invoice email you need to overwrite
In mage/core/model/email/template.php add this method at the end of the file:
public function addAttachment(Zend_Pdf $pdf){
$file = $pdf->render();
$attachment = $this->getMail()->createAttachment($file);
$attachment->type = 'application/pdf';
$attachment->filename = 'test.pdf';
}
2 In sales/model/order/Invoice.php add the code between comments(2 lines of code) to the function sendEmail like this:
<?php
public function sendEmail($notifyCustomer=true, $comment='')
{
if (!Mage::helper('sales')->canSendNewInvoiceEmail($this->getOrder()->getStore()->getId())) {
return $this;
}
$currentDesign = Mage::getDesign()->setAllGetOld(array(
'package' => Mage::getStoreConfig('design/package/name', $this->getStoreId()),
'store' => $this->getStoreId()
));
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
$order = $this->getOrder();
$copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
$copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $this->getStoreId());
if (!$notifyCustomer && !$copyTo) {
return $this;
}
$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
->setIsSecureMode(true);
$mailTemplate = Mage::getModel('core/email_template');
if ($order->getCustomerIsGuest()) {
$template = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $order->getStoreId());
$customerName = $order->getBillingAddress()->getName();
} else {
$template = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $order->getStoreId());
$customerName = $order->getCustomerName();
}
// attachment here
$pdf = Mage::getModel('sales/order_pdf_invoice')->getPdf(array($this));
$mailTemplate->addAttachment($pdf);
if ($notifyCustomer) {
$sendTo[] = array(
'name' => $customerName,
'email' => $order->getCustomerEmail()
);
if ($copyTo && $copyMethod == 'bcc') {
foreach ($copyTo as $email) {
$mailTemplate->addBcc($email);
}
}
// enter code here
}
if ($copyTo && ($copyMethod == 'copy' || !$notifyCustomer)) {
foreach ($copyTo as $email) {
$sendTo[] = array(
'name' => null,
'email' => $email
);
}
}
foreach ($sendTo as $recipient) {
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$order->getStoreId()))
->sendTransactional(
$template,
Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $order->getStoreId()),
$recipient['email'],
$recipient['name'],
array(
'order' => $order,
'invoice' => $this,
'comment' => $comment,
'billing' => $order->getBillingAddress(),
'payment_html'=> $paymentBlock->toHtml(),
)
);
}
$translate->setTranslateInline(true);
Mage::getDesign()->setAllGetOld($currentDesign);
return $this;
} ?>
Now when you create an invoice from the back office and you select to notify customer a pdf attachment should be sent as well.

codeigniter get last insert id from model to use as redirect parameter

I need to get the insert ID to be used in my controller, the problem is my model function has several data arrays, and I need the insert ID of the 1st array. therefor if I try to get the insert ID on my controller obviously its grabbing the 2nd insert ID and not the 1st.
I'm not sure this makes sense but here is an example:
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
}
This is working fine...However after this runs, on my controller the redirect is getting the data2 last insert which makes my redirect wrong.
Controller
public function add() {
if (isset($_POST["add"]))
{
$this->Company_model->add();
$id = $this->db->insert_id();
redirect('company/view/'.$cid);
}
$data['states'] = $this->Company_model->
}
Any help would be greatful!
You were very close. Instead of repeating $id = $this->db->insert_id(); in your controller, you can return the $cid from your models method.
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
// This returns your first inserts id
return $cid;
}
Controller
public function add() {
if (isset($_POST["add"]))
{
$id = $this->Company_model->add();
redirect('company/view/'.$id);
}
...

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