I have never used sessions before and I am trying to figure out the best way to handle this. I basically am trying to do:
1 step selecting a service
2 step selecting a time
3 step review and book
I can get it to work with no problems using mysql. What I would usually do is save the information into the database after each step and by the time I get to the review part I would have all the information saved and was OK.
However I don't think this is the best way to approach this and might cause problems down the road (what if they stopped at step 2 blah blah)
I decided to try the Laravel 4 sessions and it was super easy to save the session and move on to the next step. However, when I get to the final step I need to join mysql tables to fully show the information about their booking. Can I use the session information to join the information? Can I use the Sessions Database to save this information? Or use different tables?
My controller that POST after reviewing the information:
public function getReview() {
//sets id of user
$user = User::find(Auth::user()->id);
//gets the time and date that they booked from #getSchedule
$scheduler = Session::get('schedule');
//formats time to put in db
$date = strtotime($scheduler['date']);
//same thing as the line above
$dateFormat = date('Y-m-d',$date);
//model to save the schedule
$schedule = new Schedule();
$schedule->userID = $user->id;
$schedule->date = $dateFormat;
$schedule->block = $scheduler['timeslot'];
$schedule->status = "1";
$schedule->save();
//gets the services the user picked from #getServices
$service = Session::get('service');
//saves the services as individual rows in db table
foreach($service as $services)
{
if(!empty($services)) {
$service = new Service();
$service->userID = $user->id;
$service->services = $services;
$service->save();
}
}
return Redirect::to('dashboard');
}
This is the GET review page (where I am having the issues with all the JOINS)
public function showReview() {
$user = User::find(Auth::user()->id);
//show the information and confirm that they want all this crap...if they do..save it and return them to their dashboard
$time = DB::table('bk_schedule')
->leftJoin('bk_timeslot', 'bk_schedule.block', '=', 'bk_timeslot.id')
->where('bk_schedule.id', Auth::user()->id)->first();
$date = strtotime($time->date);
$dateFormat = date('D: F d, Y',$date);
$service = Session::get('service');
$serviceSummary = DB::table('bk_service')
->leftJoin('pr_service', 'pr_service.id', '=', 'bk_service.services')
->where('bk_service.userID', Auth::user()->id)
->get();
$total = DB::table('bk_service')
->leftJoin('pr_service', 'pr_service.id', '=', 'bk_service.services')
->where('bk_service.userID', Auth::user()->id)
->sum('pr_service.price');
return View::make('book.review', array('pageTitle' => 'Booking Appointment Review and Finalize', 'service' => $service, 'date' => $dateFormat,
'time' => $time, 'email' => $user->email, 'serviceSummary' => $serviceSummary, 'total' => $total));
}
Is it possible to save the information at the GET and delete it if they don't submit to POST? Could I maybe use my session data to and use the MySQL queries I have?
You don't understand what the session is, with you approach users will not be able to fill several forms (open in several tabs) simultaneously.
So, general way to do this is:
First page shows just HTML code with some fields
User selects them and POST data back to server
Server validates data and open ANOTHER HTML page with new fields AND adds several "hidden" field with values selected in step 1 (of course server can present page1 with error messages)
Users posts this form, server can open THIRD form where new visible fields and ALL previous fields are stored in hidden inputs
Finally user posts form to last page, where you have all data from all previous pages.
Just to notice: another approach is to store "temporary" data in session, for this you will need to obtain some generated ID on 2nd step and pass it through pages as described before
Related
I have a problem with my Laravel crud application for Registrations.
There are these tables: Registration, ExtraRegistration (with a registration_id, extra_id and extraoptions_id),
Extra and ExtraOptions (with the Extra_id).
In the RegistrationController when i add a Registration it makes a new record in the ExtraRegistration with the extraoptions_id and the extra_id. the extra_id is the name of the option and the extraoptions_id is the id of the option you selected.
But now, when you click on edit a record, it shows all the information. the problem is that when you change the extraoption, it makes another record, and not change the select.
And when you have edited something and you look at it again, it still shows the option before you edited it.
RegistrationController
$options = Extra::where("exa_form_id", $distance->asd_form_id)->get();
foreach($options as $option){
$input_name = "option_" . $option->exa_id;
$input_option = $request->$input_name;
if(!is_null($input_option)){
$input_name_extra = "extraoptions_" . $option->exa_id;
$input_option_extra = $request->$input_name_extra;
$registrationextra = new ExtraRegistration();
$registrationextra->iea_registration_id = $registration->isg_id;
$registrationextra->iea_extra_id = $input_option;
$registrationextra->iea_extraoption_id = $input_option_extra;
$registrationextra->iea_price = $option->exa_price;
$registrationextra->save();
}
}
$registration->isg_options = $input_option;
$registration->isg_option_extra_id = $input_option_extra;
I want a check before it makes a new ExtraRegistration. that it only makes a new registration if the registration_id with that extra_id doesn't already exists. (Not 100% sure though).
Thanks in advance!
you make a new object of ExtraRegistration so its always make a new entry for update first get object of those id after that update
check the below link
https://laravel.com/docs/5.8/eloquent#updates
This happens because you're creating a new ExtraRegistration record:
$registrationextra = new ExtraRegistration();
If you want to update it, you need to find the related $registrationextra for your $options, and then update them (assuming you have relations set up):
$registrationextra = ExtraRegistration::where('options_id', $option->id);
$registrationextra->update([
'your_fields' => value
// etc...
]);
If you want to check if ExtraRegistration exists, and depending on that, create or update it, you can do something like this:
$registrationextra = App\ExtraRegistration::updateOrCreate(
['your_fields' => 'value'],
);
You can read more on official documentation.
I am currently working on a site that has users submit through a form created with Contact Form 7. I am trying to expand this to recording that activity (date/time, logged in user, grabbing information from the fields filled), and I have tried a number of times and ways to use both the hooks wpcf7_before_send_mail and wpcf7_submit but neither seem to be working. The form submits, but the code the code below does not run. I have even attempted manually entering the infomation (table name, user id, customer, etc) manually to see if it would submit and it still does not.
Below is the current code that I am using to save some information to the data base I want the activity stored in:
add_action('wpcf7_before_send_mail', 'save_in_database');
function save_in_database($data) {
global $wpdb;
$account_number = get_account_number();
$department = get_user_role();
if ($data->title == 'Social_Media_Tool_Form'){
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$cf7_data = $submission->get_posted_data();
$name = $cf7_data['customer-name'];
}
}
$activity_table_name = $wpdb->prefix .'_'. $account_number . '_activity_log';
//Creates activity log
$wpdb->insert($activity_table_name, array(
'date' => current_time('Y-m-d H:i:s'),
'user_id' => get_current_user_id(),
'customer_name' => $name,
'activity_type' => 'social',
'department' => $department
));
}
I've used this same code to record other activities prior, so in theory, it should be working here.
I'm currently on Wordpress 5.1 and using Contact Form 7 5.1.1
I figured out the issue. On the forms, you must add "subscribers_only: true" to additional settings. Because this was not set, it was not allowing me to pull information from the current user, which was the reason it was not submitting to the database.
This is one of my first applications out of tutorials so I don't know how to express my issue well.
Well I have these 2 tables:
User ( id, code )
Hours ( id, user_id, created)
I want to know how I can add an entry to the Hours table using the user_code.
I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.
I don't have a whole lot of information to work with, but I'll give it a go.
I want to know how I can add an entry to the Hours table using the
user_code
You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.
However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}
I'm currently busy with a project that needs users to go to a specific page to create a profile when they log in for the first time (and haven't created one yet). Honestly, I don't know where to start. I would like to do it in a good way.
So in short:
User signs up -> logs in -> needs to fill in form before anything else is allowed -> continue to rest of application
Question: What is a neat way to do this? A solution that isn't going to give me problems in the future development of the application.
I suggest you to use filters. In every controller where the completed profile is neeeded add this code:
public function filters() {
return array(
'completedProfile + method1, method2, method3', // Replace your actions here
);
}
In your base controller (if you don't use base controller, in any controllers) you need to create the filter named completedProfile with the simular code:
public function filterCompletedProfile($filterChain) {
$criteria = new CDBCriteria(array(
'condition' => 'id = :id AND firstname IS NOT NULL AND lastname IS NOT NULL',
'params' => array(':id' => Yii::app()->user->getId())
));
$count = User::model()->count($criteria);
if ($count == 1) {
$filterChain->run();
} else {
$this->redirect(array('user/profile'));
}
}
Possibly add a field to the user profile database table which denotes if they have filled out their profile information. Something like profile_complete. Then you can do a test on pages to see if profile_complete is true and display the page if so, and display the profile page if not.
Understanding about Question:
When any user logged into website , there is one page shows records
coming from mysql database table. What I want is to show records
randomly when user first time shows that page. Then after the
records must have same sequence of display as user shows first time
when logged into account.
The sequence of records remain persist until logout.
But the sequence will again change randomly when user logged in
again.
Create cache with results when user first login and then just read from cache, not from DB.
For cache you can use function serialize and save data to file (unique name for each user). Then just unserialize form file.
Example:
Lanch login() to simulate user login to site, and then replace it with notLogin() to simulate user already login on site. Notice that users points change when user is login, but not when he is already on site.
//when user is login
function login(){
//1. here you log in user;
$userID = '345353';
//2. And you get some data drom DB
$randomRowsFromDb = getRandomDataFromDB();
//3. Save it to cache
saveToCache($userID, $randomRowsFromDb);
//4. Display it (optional)
display($randomRowsFromDb);
}
//when user is already on site
function notLogin(){
$userID = '345353';
$data = loadFromCache($userID);//load from cache
display($data);//display cached data instead of taking it from DB
}
//function geting random data form DB
function getRandomDataFromDB(){
return
array(
array('id'=>'43534','login' => 'John', 'points' => rand(0,100)),
array('id'=>'27725','login' => 'Anna', 'points' => rand(0,100)),
array('id'=>'23664','login' => 'Jerremy', 'points' => rand(0,100)),
array('id'=>'87855','login' => 'Kate', 'points' => rand(0,100)));
}
function display($dataToDisplay){
var_dump($dataToDisplay);
}
function saveToCache($userID, $data){
file_put_contents($userID.'.cache', serialize($data));
}
function loadFromCache($userID){
if (file_exists($userID.'.cache')){
$file = file_get_contents($userID.'.cache');
return unserialize($file);
}else{
//in case cache is missing
$data = getRandomDataFromDB();
saveToCache($userID, $data);
return $data;
}
}
I get one good solution:
>> After login use rand function.
>> When you fetch the records, stores them in SESSION var for future use.
>> Next time when page loads, use session vars to show data.
OR
You can store data in Session when user lo-gin && remove it when log out.
Like:
<?php
session_start();
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$query = "SELECT children, name FROM tree ORDER BY RAND()";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$_SESSION['tree'][] = $row['children'];
}
header("Location: blank.php");
?>
Thanks
Get records into array
and use shuffle command
http://php.net/manual/en/function.shuffle.php
RAND() function in SQL returns Random records from table.
Select * from table_name order by RAND() Limit 10
If you want to persist record in the same order that it first showed, and show it in multiple pages, save the array on fetching in Session variable