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);
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.
I have a custom behavior, specified in AppModel.php, that automatically creates a field based on the selected language. Thus, depending on the chosen language, name_eng -> name or name_fra -> name.
...
$virtualField = sprintf($model->name.'.'.$name.'_%s', Configure::read('Config.language'));
$virtualFields[$name] = $virtualField;
$model->virtualFields = $virtualFields;
...
This part works.
The issue arises when I submit the edit form, get a validation error and the field isn't available when the edit view is displayed with error prompts. I believe this is due to either my behavior not being called in this process or $this->request->data being created using form data?
I figured that I would initialize the values using beforeValidate. However, it's not working out: the field still doesn't exist once I've submitted the form which gives me this error:
In AppModel.php:
function beforeValidate(array $options = array()){
//hard coded for test purposes
$this->data['CertificateType']['name'] = $this->data['CertificateType']['name_'.Configure::read('Config.language')]
return true;
}
In the view (edit.ctp):
echo $this->request->data['CertificateType']['name'];
Essentially, how can I replicate the functionality of my custom behavior and initialize my field after a form has been submitted but doesn't validate?
The needed logic was eventually put in AppController.php. Everything works fine now.
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'm trying to make the following form's GET function to be part of a predefined variable.
Any ideas? Thanks in advance!
Let me explain a little more of what I'm really trying to do. I currently run a website concentrating on the U.S. stock market. I've created an HTML form with a method=GET. This form is used like a search box to look up stock ticker symbols. With the GET method, it places the ticker symbol at the end of the URL, and I created a quotes.php page that captures this information and displays a stock chart based on what ticker symbol is keyed into the box. For the company names, I've created a page called company.php that declares all of the variables for the company names (which happens to be a $ followed by the ticker symbol). The file, company.php, is the only file included in quotes.php.
This is where this came in: ' . $$_GET["symbol"] . '
The above code changes the GET into the variable based on what was typed into the form. I've used "die" to display an error message if someone types something into the box that doesn't match a variable in the company.php page.
I've also added into the company.php page variables for each company that will display which stock exchange each stock is listed on. These variables begin with "$ex_". So, what I was trying to do was have the symbol keyed into the box appended to "$ex_" so that it would display the corresponding stock exchange.
My questions are:
Is there a way to have what is typed into the form added to "$ex_"?
Is this an insecure way to code something like this (can it be hacked)?
Thank you all!
Rather than prefixing your variables and using variable variables (that are potentially insecure especially with user input), try this:
$ex = array(
"foo" => "bar",
...
);
if( !isset($ex[$_GET['symbol']])) die("Error: That symbol doesn't exist!");
$chosen = $ex[$_GET['symbol']];
Here's another approach:
extract($_GET, EXTR_PREFIX_ALL, "ex");
Although it's better to use it like this just to make sure there is no security issues.
extract($_GET, EXTR_SKIP);
PHP's extract() does what exactly what you want, and you should specify "ex_" as the prefix you want.
However, there are security issues and unintended consequences to using such a function blindly, so read up on the additional paragraphs following the function parameters.
Will the below achieve what you need?
$myGetVariable = $_GET['symbol'];
$ex_{$myGetVariable} = "Something";
$_GET['symbol'] = 'APPL';
if (!empty($_GET)) {
foreach ($_GET as $k => $v) {
$var = 'ex_'.$k ;
$$var=$v;
}
}
var_dump($ex_symbol);
APPL
On my website, I have user accounts that are configurable with forms that allow users to update everything from first and last names to privacy settings. I use the following function to update the database with that input. (Note that the following code uses WordPress-specific features.)
function update_account() {
global $current_user; get_currentuserinfo();
require_once( ABSPATH . WPINC . '/registration.php' );
$uid = $current_user->ID;
// First Name
if(isset($_POST['first_name']) && $_POST['first_name'] <> $current_user->first_name) {
wp_update_user( array(
'ID' => $uid, 'first_name' => esc_attr($_POST['first_name'])
));
}
// ...and so on 43 more times...
}
This feels like the wrong way to process forms. This also looks like it will negatively impact server performance when there are multiple users and frequent updates, given that the if-then-else conditions for every field, even fields not on a particular page, force checking each field for input.
Moreover, since form data can be expected to remain relatively constant, I added the <> operator to prevent the function from updating fields where there has not been any change, but I suspect this also means that every field is still evaluated for change. To make matters worse, adding new fields -- there are already 44 fields in total -- is an unwieldy process.
What's a better way to process form data?
Keep an array of the fields you will be processing with this code, and iterate over it. This works if all your attributes are strings, for example. If you have different data types such as boolean flags to handle differently from the strings, you may wish to group them into their own array.
// All the fields you wish to process are in this array
$fields = array('first_name', 'last_name', 'others',...'others99');
// Loop over the array and process each field with the same block
foreach ($fields as $field) {
if(isset($_POST[$field]) && $_POST[$field] != $current_user->{$field}) {
wp_update_user( array(
'ID' => $uid, $field => esc_attr($_POST[$field])
));
}
}
There's a lot of things missing with your implementation. I don't know what kinds of data you're allowing the user to manipulate but most usually have some kind of requirements to be acceptable. Like not having certain characters, not being blank, etc. I don't see any validation occurring, so how do you handle values that might be undesirable? And what happens when you receive bad data? How do you inform the user of the bad data and prompt them to correct it?
If we abstract the situation a bit we can come up with generalizations and implement an appropriate solution.
Basically form fields [can] have a default value, a user specified value [on form review], validation requirements and validation errors [with messages]. A form is a collection of fields that upon form submit needs to be validated and if invalid, re-displayed to the user with instructive corrective prompts.
If we create a form class that encapsulates the above logic we can instantiate and use it to pass around our controller/views. Oops, I was just assuming you were using an Model/View/Controller type framework, and I'm not really familiar with wordPress so I don't know if that is exactly applicable. But the principle still applies. On the page where you both display or process the form, here's some pseudo logic how how it might look.
function update_account()
{
// initialize a new form class
$form = new UserAccountInfoForm();
// give the form to your view for rendering
$this->view->form = $form;
// check if form was posted [however your framework provides this check]
if(!Is_Post())
return $this->render('accountform.phtml');
// check if posted form data validates
if(!$form->isValid($_POST))
{
// if the form didn't validate re-display the form
// the view takes care of displaying errors, with the help of its
// copy of the $form object
return $this->render('accountform.phtml');
}
// form validated, so we can use the supplied values and update the db
$values = $form->getValues(); // returns an array of ['fieldname'=>'value']
// escape the values of the array
EscapeArrayValues($values);
// update db
wp_update_user($values);
// inform the user of successful update via flash message
$this->flashMessage('Successfully updated profile');
// go back to main profile page
$this->redirect('/profile');
That makes your controller relatively clean an easy to work with. The view gets some love and care to, utilizing the $form value to display the form correctly. Technically, you can implement a method in the form class to give you the form html, but for simplicity I'm just going to assume your form html is manually coded in accountform.phtml and it just uses $form to get field info
<form action='post'>
<label>first name</label> <input class='<?=$this->form->getElement('first_name')->hasError() ? "invalid":""?>' type='text' name='first_name' value="<?=$this->form->getElement('first_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('first_name')->getError()?></span><br/>
<label>last name</label> <input class='<?=$this->form->getElement('last_name')->hasError() ? "invalid":""?>' type='text' name='last_name' value="<?=$this->form->getElement('last_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('last_name')->getError()?></span><br/>
<label>other</label> <input class='<?=$this->form->getElement('other')->hasError() ? "invalid":""?>' type='text' name='other' value="<?=$this->form->getElement('other')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('other')->getError()?></span><br/>
<input type='submit' value='submit'/>
</form>
Here the pseudo code relies on the form class method "getElement" which returns the field class instance for the specified field name (which would be created an initialized in the constructor of your form class). Then on the field class methods "hasError" and "getError" to check if the field validated correctly. If the form has not be submitted yet, then these return false and blank, but if the form was posted and invalid, then they will have been set appropriately in the validate method when it was called. Also "getValue" would return either the value supplied by the user when the form was submitted, or if the form has not been submitted, the default value as specified when the field class was instantiated and initialized.
Obviously this pseudo code is relying on a lot of magic that you'd have to implement if you roll your own solution--and it's certainly doable. However, at this point I'll direct you to the Zend Framework Zend_Form components. You can use zend framework components by themselves without having to utilize the entire framework and application structure too. You might also find similar form component solutions from other frameworks but I wouldn't know about those (we are a Zend Framework shop at my work place).
Hopefully this hasn't been too complicated, and you know where to go from here. Of course just ask if you need any clarification.