How to insert values in another table in controller joomla - joomla

I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}

Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..

Related

Access the cart session - Laravel 5.8

Hi i am using sopping cart in laravel 5.8. I want to access the array to be able to store the order in the database. I was able to access the data in the session cart. But to the part of options -> marca y medida. Also I do not know how to bring the total cart.
My controller is as follows
public function transferencia(Request $request)
{
$cart = Session::get('cart');
foreach ($cart as $key => $order) {
$data = json_decode($order, true);
foreach($data as $item){
$opt = new Order;
$opt->id_cliente = $request->input('idusuario');
$opt->fecha = date('j/n/Y');
$opt->cliente = $request->input('persona');
$opt->dni = $request->input('dni');
$opt->producto = $item['name'];
$opt->medida = 'medida'; //how to access this data
$opt->marca = $item['marca']; //how to access this data
$opt->precio = $item['price'];
$opt->cantidad = $item['qty'];
$opt->total = 'total';
$opt->factura = 'factura';
$opt->idpedido = 'idpedido';
$opt->save();
}
}
//dd($item);
//print_r($cont);
}

CakePHP serializing objects

I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

links in pagination in codeigniter

in my view page,in the 1st form i have 2 select drop down...in the 1st drop down i am populating the value default from the controller...when u onchange the value in the 1st drop down,the selected value is passed to controller via javascript..in the controller,i get that 1st drop down value and load model and get value from model for the 2nd drop down and post it to view page...when u select the 2nd drop down value and click submit,the both drop down values are posted to controller after form validation and load model and get user information from the database and post it back again to view page ...this is the scenario for my view page..so,u can change the above both select drop down to get informations in the 2nd form in the same view page..now when i did pagination for my 2nd form user information,i am getting the links and data perfectly according to the limits and offsets..but,i am unable to retrieve the information when i click 2nd,3rd,4th..and rest on links while the informations are being posted from controller..so what can i do now?,,here is my code after i get both drop down values in the controller..
in my controller..
public function get_form_dept()
{
$this->load->helper(array('form', 'url'));
$this->load->library("pagination");
$this->load->library('form_validation');
$this->form_validation->set_rules('formation','Formation','required|required');
if($this->form_validation->run()== false) {
$this->viewstudent();
} else {
$config['base_url'] = base_url() . 'Incite/get_form_dept';
if($this->input->post('formation') == 1 && $this->input->post('department') == 1){
$config['total_rows'] = $this->db->get('user')->num_rows();
} else {
//$this->db->select('list_formation');
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
// echo $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
echo $get_formation ."<br>";
}
$query1 = $this->db->get_where('department',array('id' => $this->input->post('department')));
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
echo $get_dept . "<br>";
}
//$array = array('formation' => $get_formation, 'department' => $get_dept);
//$config['total_rows']=$this->db->get('user',$array)->num_rows();
$query = $this->db->query("SELECT * FROM user where formation='$get_formation' and department='$get_dept'");
echo "SELECT * FROM user where formation='$get_formation' and department='$get_dept'" . "<br>";
$config['total_rows']=$query->num_rows();
//echo $row ."<br>";
//echo $row=$this->db->get('user',$array)->num_rows();
}
$config['per_page'] = 5;
//$config['uri_segment'] = 3;
//$choice = $config['total_rows'] / $config['per_page'];
// $config['num_links'] = round($choice);
$config['num_links'] = 2;
//$config['use_page_numbers'] = TRUE;
$config['suffix']= '?' . http_build_query($_GET, '', "&");
$this->pagination->initialize($config);
if($this->input->post('formation')== 1 && $this->input->post('department') == 1) {
// $this->db->limit($limit, $start);
$query_result = $this->db->get('user',$config['per_page'], $this->uri->segment(3));
$data['result']= $query_result->result();
} else {
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
}
$this->db->where('id', $this->input->post('department'));
$query1 = $this->db->get('department');
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
//echo $get_dept;
}
$array = array('formation' => $get_formation, 'department' => $get_dept);
//$this->db->limit($limit, $start);
//$query = $this->db->get_where('user',$array);
$query_result=$this->db->get_where('user',$array,$config['per_page'], $this->uri->segment(3));
$data['result'] = $query_result->result();
}
$this->load->model('model_select_formation');
$data['formation'] = $this->model_select_formation->modelselectformation();
// query to fetch department
$data['dept']=$this->model_select_formation->get_department($data['formation_id']);
$data['formationid'] = $this->input->post('formation');
$data['departmentid'] = $this->input->post('department');
$this->load->view('viewstudent',$data);
}
}

Laravel Eloquent ORM save: update vs create

I've got a table and I'm trying to use the save() method to update/create lines. The problem is that it always create new lines. The following code gives me about 12 lines each time I run it. They don't have a unique id before inserting them but the combination of name and DateTimeCode is unique. Is there's a way to use those two in order for laravel to recognize them as exist()? Should I consider using if exist with create and update instead?
foreach ($x as $y) {
$model = new Model;
$model->name = ''.$name[$x];
$model->DateTimeCode = ''.$DateTimeCode[$x];
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
I assume this would work in laravel 4.x:
foreach ($x as $y) {
$model = Model::firstOrCreate(array('name' => name[$x], 'DateTimeCode' => DateTimeCode[$x]));
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
I think that in this case you will need to search for it before updating or creating:
foreach ($x as $y) {
$model = Model::where('name', name[$x])->where('DateTimeCode', DateTimeCode[$x])->first();
if( ! $model)
{
$model = new Model;
$model->name = ''.name[$x];
$model->DateTimeCode = ''.DateTimeCode[$x];
}
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources