I have been struggling on this issue for a very long time and I still do not have any idea how to get this working.
Currently I need to show my new generated username from Model to Controller. But I can't seem to call it. Below is my code:
Model formval_callbacks.php :
public function _username_check( $user_name )
{
$this->db->select('user_name');
$this->db->like('user_name', $user_name);
$this->db->order_by('user_date', 'desc');
$this->db->limit(1);
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
$row = $query->row();
$db_username = $row->user_name;
$username_counter = preg_match("/".$user_name."(\d+)/", $db_username, $matches) ? (int)$matches[1] : NULL;
$username_counter++;
return $user_name.$username_counter;
}else{
$username_counter = 1;
return $user_name.$username_counter;
}
}
Model user_model.php :
public function create_user( $role, $insert_array = array() )
{
// The form validation class doesn't allow for multiple config files, so we do it the old fashion way
$this->config->load( 'form_validation/administration/create_user/create_' . $role );
$this->validation_rules = config_item( $role . '_creation_rules' );
// If the data is already validated, there's no reason to do it again
if( ! empty( $insert_array ) OR $this->validate() === TRUE )
{
// Prepare user_data array for insert into user table
$user_data = array(
'user_name' => ( isset( $insert_array['user_name'] ) ) ? $insert_array['user_name'] : set_value('user_name'),
'user_pass' => ( isset( $insert_array['user_pass'] ) ) ? $insert_array['user_pass'] : set_value('user_pass'),
'user_email' => ( isset( $insert_array['user_email'] ) ) ? $insert_array['user_email'] : set_value('user_email')
);
// User level derived directly from the role argument
$user_data['user_level'] = $this->authentication->levels[$role];
// If we are using form validation for the user creation
if( empty( $insert_array ) )
{
// Remove some user_data elements from _field_data array as prep for insert into profile table
$this->form_validation->unset_field_data( array(
'user_name',
'user_pass',
'user_email'
));
// Create array of profile data
foreach( $this->form_validation->get_field_data() as $k => $v )
{
$profile_data[$k] = $v['postdata'];
}
// Unset all data for set_value(), so we can create another user
$this->kill_set_value();
}
// If we are not using form validation for the user creation
else
{
// Remove some insert_array elements as prep for insert into profile table
unset( $insert_array['user_name'] );
unset( $insert_array['user_pass'] );
unset( $insert_array['user_email'] );
// Profile data is insert array
$profile_data = $insert_array;
}
// Encrypt any sensitive data
if( isset( $profile_data['license_number'] ) )
{
$this->load->library('encrypt');
$profile_data['license_number'] = $this->encrypt->encode( $profile_data['license_number'] );
}
// Create a random user id if not already set
$random_unique_int = $this->get_unused_id();
// Generate random user salt
$user_salt = $this->authentication->random_salt();
// Perform transaction
$this->db->trans_start();
$user_data['user_id'] = $random_unique_int;
$user_data['user_pass'] = $this->authentication->hash_passwd( $user_data['user_pass'], $user_salt );
$user_data['user_salt'] = $user_salt;
$user_data['user_date'] = time();
$user_data['user_modified'] = time();
// Insert data in user table
$this->db->set($user_data)
->insert( config_item('user_table'));
$profile_data['user_id'] = $random_unique_int;
// Insert data in profile table
$this->db->set($profile_data)
->insert( config_item( $role . '_profiles_table'));
// Complete transaction
$this->db->trans_complete();
// Verify transaction was successful
if( $this->db->trans_status() !== FALSE )
{
// Load var to confirm user inserted into database
$this->load->vars( array( 'user_created' => 1 ) );
}
return TRUE;
}
return FALSE;
}
Controller register.php :
public function index()
{
// Load resources
$this->load->library('csrf');
$this->load->model('registration_model');
$reg_mode = $this->registration_model->get_reg_mode();
// Check to see if there was a registration submission
if( $this->csrf->token_match )
{
// If mode #1, registration allows for instant user creation without verification or approval.
if( $reg_mode == 1 )
{
$_POST['user_level'] = 1;
$this->load->model('user_model');
$this->user_model->create_user( 'customer', array() );
$this->load->model('formval_callbacks');
$view_data['new_username'] = $this->formval_callbacks->_username_check();
}
}
// If for some reason the user is already logged in
$this->is_logged_in();
// Send registration mode to view
$view_data['reg_mode'] = $reg_mode;
// Ouput alert-bar message if cookies not enabled
$this->check_cookies_enabled();
$data = array(
'title' => WEBSITE_NAME . ' - Account Registration',
'content' => $this->load->view( 'public/register/registration_form', $view_data, TRUE ),
// Load the show password script
'javascripts' => array(
'js/jquery.passwordToggle-1.1.js',
'js/jquery.char-limiter-3.0.0.js',
'js/default-char-limiters.js'
),
// Use the show password script
'extra_head' => '
<script>
$(document).ready(function(){
$("#show-password").passwordToggle({target:"#user_pass"});
});
</script>
'
);
$this->load->view( $this->template, $data );
}
There is an error for this line because I never put in any parameters :
$view_data['new_username'] = $this->formval_callbacks->_username_check();
What should I do if I just want to get the new generated username without putting in the parameter?
Also, is it better to get the new generated username from formval_callback.php or user_model.php in this function :
if( $this->db->trans_status() !== FALSE )
Hope you guys can help me out here.
Related
I am trying to implement the Paypal payment gateway once the contact form is submitted.
For that I am storing the form data in db and retrieving data from the saved id once payment is completed. Saving that db id in hidden field for sending to paypal url.
I have tried and values are returned. But when I getting form data in wpcf7mailsent it is empty.
function action_wpcf7_submit( $array ) {
global $wpdb;
$wpcf7 = WPCF7_ContactForm::get_current();
$form_id = $wpcf7->id;
$submission = WPCF7_Submission::get_instance();
$invalid_fields = $submission->get_invalid_fields();
$posted_data = $submission->get_posted_data();
if ($form_id ==123 && empty($invalid_fields))
{
$first_name = $posted_data['first-name'];
$last_name = $posted_data['last-name'];
$parent_email = $posted_data['parent-email'];
$parent_phone = $posted_data['parent-phone'];
$duration = $posted_data['Duration'][0];
$total_price = $posted_data['total_price'];
$notes_requests = $posted_data['notes-requests'];
$studentcount = $posted_data['studentcount'];
$table_name = "store_subscription";
$result_check = $wpdb->insert($table_name, array('parent_guardian_firstname' => $first_name, 'parent_guardian_lastname' => $last_name, 'parent_guardian_email' => $parent_email,'parent_guardian_phone' => $parent_phone, 'subscription_duration' => $duration, 'total_price' => $total_price, 'notes_special_request' => $notes_requests) );
$lastid = $wpdb->insert_id;
if($result_check){
for($i=1;$i<=$studentcount;$i++){
$add_student_name = $posted_data['student_name_'.$i];
$add_current_grade_level = $posted_data['current_grade_level_'.$i];
$additional_student_table = "store_subscription_student";
if(!empty($add_student_name)){
$wpdb->insert($additional_student_table, array('store_subscription_id'=> $lastid, 'student_name' => $add_student_name, 'grade_level' => $add_current_grade_level));
}
}
//setting the store_subscriptin_id to retrieve the data from the paypal.
$posted_data['store_subscription_id'] = $lastid;
$posted_data['paypal_pg_redirect_url'] = "https://www.example.com/redirect-paypal/?id=$lastid&amt=$total_price";
return $posted_data;
}
}
}
add_filter( 'wpcf7_submit', 'action_wpcf7_submit');
add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( e ) {
console.log(e.detail);
if ( '123' == e.detail.contactFormId ) {
var paypal_pg_redirect_url = document.getElementById('paypal_pg_redirect_url').value;
console.log(paypal_pg_redirect_url);
///window.location.href = paypal_pg_redirect_url;
}
}, false );
</script>
<?php
}
The hidden field value is not set. Can someone help me to set the hidden field value and retrieve in wpcf7mailsent
Note: I have tried hook before_send_mail, later came to know that we cant change the value in before_send_mail. So then I tried posted_data hook also the value not set to hidden field. store_subscription_id is the hidden field I am trying to set value. Pls help.
Maybe try adding if(isset()) before setting the value:
if(isset($lastid)){
$posted_data['store_subscription_id'] = $lastid;
}
So I'm having a bit of troubles with this query as it is the first time in which instead of checking for a value in a row, I'm checking if a row itself exists on database.
This is the problem that I'm facing:
UPDATE:
public function individualDiscountVerification($id){
// Get postID
$data['item'] = $this->PublicStore_model->readPostID($id);
$data['relationship'] = $this->PublicStore_model->getPostRelationship($id);
// Get Last Post ID
$postID = $id;
$activityTitle = $data['item']->title;
// Verify Data
$itemInCart = $this->PublicCart_model->verifyUserCartItem($postID);
// Redirect if row does not exist -- HERE IS WHERE I NEED HELP
if(!$itemInCart){
// Set message
$this->session->set_flashdata('error', 'You first need to add it to you cart');
// Redirect
redirect('store/read/'.$id);
// Redirect if seller is the same as the current userID
} elseif($this->session->userdata('user_id') == $data['relationship']->user_id) {
// Set message
$this->session->set_flashdata('error', 'You can not add discounts to your own products');
// Redirect
redirect('store/read/'.$id);
} else {
// Verify discount exists
$discount = $this->input->post('discount_code');
$discountCode = $this->PublicCart_model->verifySingleDiscount($discount);
if(!$discountCode){
// Set message
$this->session->set_flashdata('error', 'The discount has expired or is invalid');
// Redirect
redirect('store/read/'.$id);
} else {
// Get Last ID Data
$discountID = $discountCode->discount_id;
// Get Discount Type
$discountType = $this->PublicCart_model->getIndividualDiscountID($discountID);
// Verify data
$verifyItemDiscount = $this->PublicCart_model->verifySingleItemDiscountCode($postID, $discountID);
if($discountType->type == 'percent' && $verifyItemDiscount != NULL?:'' && $discountID == $data['relationship']->discount_id){
// Update Post Array
$postData = array(
'price' => round($data['relationship']->price * ((100 - $discountCode->amount) / 100), 2),
'discount_id' => $discountID,
);
// Update Post Array
$this->PublicCart_model->updateUserCartItem($postID, $postData);
// Set message
$this->session->set_flashdata('success', 'A percent discount type has been applied to your final price');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountID != $data['relationship']->discount_id){
// Set message
$this->session->set_flashdata('error', 'Percent discount is not attached to this product');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountType->type == 'float' && $verifyItemDiscount != NULL?:'' && $discountID == $data['relationship']->discount_id){
// Update Post Array
$originalprice = $data['relationship']->price;
$amount = $discountCode->amount;
$postData = array(
'price' => $originalprice - $amount,
'discount_id' => $discountID,
);
// Update Post Array
$this->PublicCart_model->updateUserCartItem($postID, $postData);
// Set message
$this->session->set_flashdata('success', 'A float discount type has been applied to your final price');
// Redirect
redirect('store/read/'.$data['item']->post_id);
} elseif($discountID != $data['relationship']->discount_id){
// Set message
$this->session->set_flashdata('error', 'Float discount is not attached to this product');
// Redirect
redirect('store/read/'.$data['item']->post_id);
}
// Activity Array
$activityData = array();
// Insert Activity
$this->Activity_model->add($activityData);
}
}
}
and here is the method in the model:
UPDATE:
/*
*
* IS IN USER'S CART? -- FROM HERE AND BELOW IS FOR THE INDIVIDUAL ITEMS DISCOUNT
*
*/
public function verifyUserCartItem($postID){
$query = $this->db->get($this->relationship, array(
'post_id' => $postID,
'friend_id' => $this->session->userdata('user_id'),
'type' => $this->cartType,
));
if($query->num_rows() > 0){
return $query->row_array();
} else {
return null;
}
}
/*
*
* DOES THE DISCOUNT EXISTS?; IF YES, WHAT TYPE OF DISCOUNT IT IS?
*
*/
public function verifySingleDiscount($discount){
$query = $this->db->get_where($this->discounts, array(
'code' => $discount,
));
return $query->row();
}
public function getIndividualDiscountID($discountID){
$query = $this->db->get_where($this->relationship, array(
'discount_id' => $discountID,
'status' => $this->published,
));
return $query->row();
}
/*
*
* IS THE DISCOUNT ATTACHED TO THE POST?; IF YES, UPDATE IT
*
*/
public function verifySingleItemDiscountCode($postID, $discountID){
$query = $this->db->get_where($this->relationship, array(
'post_id' => $postID,
'discount_id' => $discountID,
'status' => $this->published,
));
return $query->row();
}
public function updateUserCartItem($postID, $postData){
$this->db->select('*');
$this->db->where('friend_id', $this->session->userdata('user_id'));
$this->db->where('post_id', $postID);
$this->db->where('type', $this->cartType);
$this->db->update($this->relationship, $postData);
}
Note: As you can see I'm already using isset but that messes up the following blocks of code(I'll put the whole function if requested) which are not posted here; I already used if empty or if var === false but I'm still getting the same error.
try below in verifyUserCartItem function :
if($query->num_rows() > 0){
return $query->row_array();
} else {
return null;
}
and if(!$itemInCart){ instead of if(isset($itemInCart)){
For example:
var_dump($this->db->where('id', $id)->get('TABLE_NAME')->num_rows());
ManagementController.php
public function getDuplicate(Request $request)
{
$data = \App\Chalet::find( \Crypt::decrypt($request->input('cid')) );
if ( $data->group_id == Auth::user()->group->group_id ) {
$cid = \Crypt::decrypt($request->input('cid'));
$mid = Extras::getMeta( 'chalet_details', '\App\ChaletMeta', $cid, 'chalet_id', true );
$sid = Extras::getMeta( 'chalet_status', '\App\ChaletMeta', $cid, 'chalet_id', true );
$ciid = Extras::getMeta( 'chalet_images', '\App\ChaletMeta', $cid, 'chalet_id', true );
$arid = Extras::getMeta( 'auto_release_excemption', '\App\ChaletMeta', $cid, 'chalet_id', true );
$rchalet = \App\Chalet::find($cid);
$dup_chalet = $rchalet->replicate();
$dup_chalet->unit_no = '';
$dup_chalet->status = 0;
$dup_chalet->visibility = 1;
$dup_chalet->save();
$nCID = $dup_chalet->chalet_id;
$rmchalet = \App\ChaletMeta::find($mid);
$dupM_chalet = $rmchalet->replicate();
$dupM_chalet->chalet_id = $dup_chalet->chalet_id;
$dupM_chalet->save();
$archalet = \App\ChaletMeta::find($arid);
if ( $archalet ) {
$dupA_chalet = $archalet->replicate();
$dupA_chalet->chalet_id = $dup_chalet->chalet_id;
$dupA_chalet->save();
}
$schalet = \App\ChaletMeta::find($sid);
$dupSChalet = $schalet->replicate();
$dupSChalet->chalet_id = $dup_chalet->chalet_id;
$dupSChalet->save();
$cichalet = \App\ChaletMeta::find($ciid);
$dupCIChalet = $cichalet->replicate();
$dupCIChalet->chalet_id = $dup_chalet->chalet_id;
$dupCIChalet->save();
return Redirect::to(Auth::user()->group->alias.'/app/echalet/view/?cid=' . \Crypt::encrypt($nCID) .'&action=view')->with('message', Extras::alert('success', 'Successful Duplicated Chalet! Please enter Unit #.'))->with('duplicate', true);
} else {
return Redirect::to( Auth::user()->group->alias.'/app/echalet' )->with('message', Extras::alert( 'error', "Something went wrong, Didn't managed to duplicate chalet" ));
}
}
This "get" function creates a duplicate of an item after clicking the button that says "duplicate". I wish you guys can help me point out which part of the code should I remove so I can make a separate "post" function.
This code replicates the ChatletMeta model and returns a message. If you want to modify the method(GET/POST) this function can be called, you need to modify the route belonging to this Controller/action.
Also, you can remove the Model replications.
I have an issue with the form. For some reason it does not populate the table I named About
Table info (About):
user_id,
aboutme_id,
about,
Table info (Users):
user_id,
...,
...,
...,
etc.
Form:
$this->addElement('textarea', 'description', array(
'label' => 'Body Content',
'required' => true,
'allowEmpty' => false,
));
Verification
public function onProcess()
{
// In this case, the step was placed before the account step.
// Register a hook to this method for onUserCreateAfter
if( !$this->_registry->user ) {
// Register temporary hook
Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array(
'callback' => array($this, 'onProcess'),
));
return;
}
$user = $this->_registry->user;
$data = $this->getSession()->data;
$form = $this->getForm();
if( !$this->_skip && !$this->getSession()->skip ) {
if( $form->isValid($data) ) {
$values = $form->getValues();
$table = Engine_Api::_()->getDbtable('about', 'user');
$rName = $table->info('name');
$userTable = Engine_Api::_()->getDbtable('users', 'user')->info('name');
$select = $select
->setIntegrityCheck(false)
->from($userTable)
->joinLeft($userTable, "$userTable.user_id = $rName.user_id")
->where($userTable, "$userTable.user_id = $rName.user_id");
}
}
}
Any idea what is going on with this picture?
Try to test database table operations in a sample empty action of some controller using echo "<pre>"; print_r(); echo "</pre>"; die(); to debug results. You can also use $select->__toString() to get raw sql of constructed query.
Also take a look at /temporary/log/main.log for some notices/errors.
I've created several new child groups under registered users and when I create a new user from the backend, everything works fine. When trying to create an account on the frontend the system is giving them the gid of the parent group (registered users). I would like to know if you can pass the gid to joomla. Here's the script I'm using that's not working. Many thanks!
// Begin create user
global $mainframe;
JFactory::getLanguage()->load('com_user');
$this->execPieceByName('ff_InitLib');
$user = clone(JFactory::getUser());
$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
$authorize =& JFactory::getACL();
$document =& JFactory::getDocument();
// If user registration is not allowed, show 403 not authorized.
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0') {
echo '<script>alert("Access forbidden");history.go(-1);</script>';
return;
} else {
// Initialize new usertype setting
$newUsertype = $usersConfig->get( 'new_usertype' );
if (!$newUsertype) {
$newUsertype = 'Free User';
}
// Bind the post array to the user object
$post = array(
'name' => ff_getSubmit('ownerName'),
'username' => ff_getSubmit('ownerEmail'),
'email' => ff_getSubmit('ownerEmail'),
'password' => ff_getSubmit('password'),
'password2' => ff_getSubmit('password'),
'task' => 'register_save',
'id' => '0',
'gid' => ff_getSubmit('101'),
);
if (!$user->bind( $post, 'usertype' )) {
echo '<script>alert("'.addslashes($user- >getError()).'");history.go(-1);</script>';
return;
} else {
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', 'Free User');
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
echo '<script>alert("'.addslashes(JText::_( $user->getError())).'");history.go(-1);</script>';
return;
} else {
$db =& JFactory::getDBO();
$name = $user->get('name');
$email = $user->get('email');
$username = $user->get('username');
JFactory::getDBO()->setQuery("Update #__facileforms_records Set user_id = '".$user->get('id')."',
username = ".JFactory::getDBO()->Quote($username).", user_full_name = ".JFactory::getDBO()->Quote($name)." Where id = '".$this->record_id."'");
JFactory::getDBO()->query();
}
}
}
[SOLVED] Assigning gid to new user in joomla 1.5
I figured it out. If anyone else looking for an answer to this questions, just replace this line of code:
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
with
$user->set('gid', 'your gid#);