Was wondering if it is possible. My attempt is to have a dark mode checker within the PHP controller and send it back to the body as an if statement checking if the boolean is true or not.
Here's my current work:
Sender URL
Switch modes
Controller
public function switchModes()
{
//doesnt work since $isDark's value is not initialized
$isDark = !$isDark;
dd($isDark);
return $isDark;
}
Target result:
<body background="#if($isDark) #505050 #else #ffffff #endif">
The short answer is yes. But you should really try to make your question clearer.
If you want user to click a button or link to switch between light/dark modes, you should use Session.
In your current controller method, you commented that $isDark isn't initialized. You didn't provide a way to initialize that value anywhere, and your controller has no way to figure out what you are doing.
By using session variables, you can have values that persist between pages.
Learn more about sessions here: PHP Session Introduction
Session in Laravel works a little different, but the idea is the same. You want to fetch a session variable in your controller method, and check the value to determine if the user is under light or dark mode, then you would switch his mode by setting the session variable to the other value. In your view, you can check related session variable to determine the mode.
In your controller, you may want to do something like:
public function switchModes()
{
if (session()->has('isDark')) {
session()->put('isDark', !session('isDark'));
}
else {
//provide an initial value of isDark
session()->put('isDark', true);
}
return redirect()->route('your-route-name');
}
And in your view, you can check the session variable like this:
<body class="#if (session('isDark')) dark-mode #else light-mode">
Related
I have a website where the front page contains a search form with several fields.
When the user performs a search, I make an ajax call to a function in a controller.
Basically, when the user clicks on the submit button, I send an ajax call via post to:
Route::post('/search', 'SearchController#general');
Then, in the SearchController class, in the function general, I store the values received in a session variable which is an object:
Session::get("search")->language = Input::get("language");
Session::get("search")->category = Input::get("category");
//I'm using examples, not the real variables names
After updating the session variable, in fact, right after the code snippet shown above, I create (or override) a cookie storing the session values:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
And after that operation, I perform the search query and send the results, etc.
All that work fine, but I'm not getting back the values in the cookie. Let me explain myself.
As soon as the front page of my website is opened, I perform an action like this:
if (!Session::has("search")) {
//check for a cookie
$search = Cookie::get('mysite_search');
if($search) Session::put("search", json_decode($search));
else {
$search = new stdClass();
$search->language = "any";
$search->category = "any";
Session::put("search", $search);
}
}
That seems to be always failing if($search) is always returning false, and as a result, my session variable search has always its properties language and category populated with the value any. (Again: I'm using examples, not the real variables names).
So, I would like to know what is happening here and how I could achieve what I'm intending to do.
I tried to put Session::put("search", json_decode($search)); right after $search = Cookie::get('mysite_search'); removing all the if else block, and that throws an error (the ajax call returns an error) so the whole thing is failling at some point, when storing the object in the cookie or when retieving it.
Or could also be something else. I don't know. That's why I'm here. Thanks for reading such a long question.
Ok. This is what was going on.
The problem was this:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
Before having it that way I had this:
Cookie::forever("mysite_search", json_encode(Session::get("search")));
But for some reason, that approach with forever wasn't creating any cookie, so I swichted to queue (this is Laravel 4.2). But queue needs a third parameter with the expiration time. So, what was really going on is that the cookie was being deleted after closing the browser (I also have the session.php in app/config folder set to 'lifetime' => 0 and 'expire_on_close' => true which is exactly what I want).
In simple words, I set the expiration time to forever (5 years) this way:
Cookie::queue("mysite_search", json_encode(Session::get("search")), 2592000);
And now it seems to be working fine after testing it.
For example:
If anyone fails at the login function (for example: enters wrong password) on my webpage, i want to show an error-message at the webpage. My idea was like that:
if(doLogin()) {
//....
}else {
$GLOBAL['errorLogin'] = "Wrong Userdata";
}
and then echo the global-variable in the .html.
But i searched also for this topic and found only this method, but everyone had used the $_SESSION variable for this instead of $GLOBAL.
Is my variant with the $GLOBAL varible wrong or bad practise?
And why use $_SESSION for a error-message, if i only echo the message one time and don't need it in the next request?
I think you mean $GLOBALS (notice the s) which is a suber global variable and therefore can be accessed from anywhere in the PHP script (also from within functions or methods).
There is nothing wrong about that.
I don't think that you should use the $_SESSION variable for that, because the user needs to see the error message only one time. In your case, and in most cases, that's why it might make no sense to store it in a session.
Personally, I just would use a custom errorMessage-Array, like that:
//store all Error Messages in one array.
$errorMessages = array();
if(doLogin()) {
//....
}else {
$errorMessages["Login"] = "Wrong Userdata";
}
//...
foreach($errorMessages as $key=>$message){
echo $key.": ".$message."<br>";
}
I have created a web app that has 2 control panels. One for the admin and one for the users. I want the users to be able to perform one specific action from their panel only if the admin sets this action "on" (from his panel) and not being able when he sets it "off".
My app also uses a MySql database.
How can I implement it? Is an extra table with only one field a viable solution? Can I do it by reading a file (maybe JSON)?
EDIT: I want the admin to be able to toggle the "on/off" status with a click of a button, so constants are not a solution.
A database query could be used every time the action is used but if it is more general and you are going to be using this a lot, I would look into PHP constants. You could set it in a configuration file like:
Config.php
define('USER_CAN_MODIFY', true);
Other.php
if ((defined('USER_CAN_MODIFY') and USER_CAN_MODIFY === true) { }
Constants have a global scope and cannot be changed once set.
Since you want to store a single value you don't need to use DB. You may simply store this flag in a file as serialized value.
Below is simplified example.
define('PERM_FLAG_FILE', 'perm_flag.dat');
$PERM_FLAG = false;
function loadFlag() {
global $PERM_FLAG;
return file_exists(PERM_FLAG_FILE)? unserialize(file_get_contents($PERM_FLAG)) : false;
}
function saveFlag() {
global $PERM_FLAG;
file_put_contents(PERM_FLAG_FILE, serialize($PERM_FLAG));
}
function setFlag($v) {
global $PERM_FLAG;
$PERM_FLAG = (bool)$v;
}
I am trying to do a variable_set() when clicking 'Reset default values' on my module's admin page form. This runs through system_settings_form_submit(). The #default_value inside my form is reset, but my module relies on this stored variable to display some data. Clicking reset fills in the form with the default, but does not 'Save' it to recreate the variable in the database, so my module's function breaks. It appears that nothing happens after clicking Reset, other than it deleting the variable from the database. Thanks in advance.
My submit function looks like this:
function faculty_submit(&$form, &$form_state){
if($form_state['values']['op'] == 'Reset to defaults') {
global $faculty_detail_template_default;
variable_set('faculty_detail_template', $faculty_detail_template_default);
}
elseif ($form_state['values']['op'] == 'Save configuration') {
// Clear caches for list and detail pages.
cache_clear_all('faculty_list', 'cache', TRUE);
cache_clear_all('faculty_detail_load', 'cache', TRUE);
}
}
First of all that's what system_settings_form_submit does when you press the Reset to defaults button. It calls variable_del which will delete all your defined variables in the form from the variables table.
Now your form's #default value is probably filled because you do something like this:
global $faculty_detail_template_default;
$form = array (
'#default_value' => variable_get('faculty_detail_template', $faculty_detail_template_default),
);
I don't see why you insist of adding a default value in the variables table. This entire approach is flawed. Just use variable_get($name, $default) wherever your code depends on faculty_detail_template. That's precisely what the second parameter of this function is used for: $default The default value to use if this variable has never been set. So for Drupal, the absence of a variable from the variable table means it's up to the coder how to handle this case (provide a default for example). Default value which is specified using variable_get.
Second, if you used system_settings_form then you already have a submit function, the one mentioned above (system_settings_form_submit) so your faculty_submit won't be called unless you add it specifically to the array of submit callbacks to be executed. Something like this:
$form['#submit'][] = 'faculty_submit';
return system_settings_form($form);
BTW, using global variables is a bad idea (in general) and you should try to avoid using them. That's what variables are used for :) Pieces of information which can be retrieved in different parts of the code. So instead add a .install file to your module and in that file you define these global variables using variable_set. This is a lot cleaner than just magically popping some global variables in the middle of the code.
you need to use &$form_state['values']['yourVariableNameOfForm'] instead of what I have made bold below.
variable_set('faculty_detail_template', $faculty_detail_template_default);
In my project, I am using pagination and I used these statements to get the page number detail:
$page=$this->uri->segment(3);
$this->session->set_userdata('page',$page);
echo $this->session->userdata('page');
When I print this session value in that page itself, I get the value correctly and when I click on the particular link and then print that data, I am getting the value like 'images'.
Why is this happening?
However, when I write the statements like
$page=$this->uri->segment(2);
$this->session->set_userdata('page',$page);
echo $this->session->userdata('page');
it's working fine.
My URL is: http://localhost/CI/user/index/4
I have the same problem with you, the session variable always get value 'images'. Then i realize that: if we made a session variable, then we must call redirect() directly.
This is my example:
$page=$this->uri->segment(3);
$this->session->set_userdata('page',$page);
redirect('control/function2');
Then, you can get continue your code in the 'function2'.
Solved the issue by writing another function, setting the session and redirecting to above function like this:
function set_session(){
$id=$this->uri->segment(3);
$this->session->set_userdata('id',$id);
redirect('set_uri_session');
}
function set_uri_session(){
$id=$this->uri->segment(3);
$this->session->set_userdata('id',$id);
echo $this->session->userdata('id');
}