Drupal save global variables - forms

I make a form in drupal to store data (for annonymous user) so when the form is validate i would like to save it to access it from all page but that does not work outside this function the variable is NULL
can you help me or have you another method to proceed ?
function myform_form_submit($form, &$form_state) {
....
$GLOBALS ['info'] = $info;
}

When a Drupal form is evaluated, it executes any code, including database changes. But then it redirects the user to a new page, which discards the PHP session, including $GLOBALS, among other things.
The more Drupally way is to use persistent variables, which are stored in the "variables" database table.
The variable_set function can be used here. So replace
### $GLOBALS['info'] = $info ### replace with:
variable_set('mymodule_info', $info);
and then when you access it, instead of using $GLOBALS, just use
$info = variable_get('mymodule_info', NULL);
You can use any name to specify the variable. I add NULL as a second parameter to variable_get in case the value isn't present in the database.
If the data is associated with a particular user, you might need to do something like
global $user;
variable_set('mymodule_info_uid_' . $user->uid, $info);
and then to retrieve the data use
global $user;
$info = variable_get('mymodule_info_uid_' . $user->uid, NULL);
EDIT: Ah, now I see you're dealing with anonymous users. In that case, PHP can identify anonymous users for you by giving a session id that can be used in the same way:
variable_set('mymodule_info_session_' . session_id(), $info);
variable_get('mymodule_info_session_' . session_id(), NULL);
This should be persistent for an anonymous user's browsing session.
The issue with this approach is that you'll need to come up with some way of clearing these out. You'll probably need to store a timestamp in the $info variable and have a cron job to delete expired entries from the variable table.

Related

Handle POST data sent as array

I have an html form which sends a hidden field and a radio button with the same name.
This allows people to submit the form without picking from the list (but records a zero answer).
When the user does select a radio button, the form posts BOTH the hidden value and the selected value.
I'd like to write a perl function to convert the POST data to a hash. The following works for standard text boxes etc.
#!/usr/bin/perl
use CGI qw(:standard);
sub GetForm{
%form;
foreach my $p (param()) {
$form{$p} = param($p);
}
return %form;
}
However when faced with two form inputs with the same name it just returns the first one (ie the hidden one)
I can see that the inputs are included in the POST header as an array but I don't know how to process them.
I'm working with legacy code so I can't change the form unfortunately!
Is there a way to do this?
I have an html form which sends a hidden field and a radio button with
the same name.
This allows people to submit the form without picking from the list
(but records a zero answer).
That's an odd approach. It would be easier to leave the hidden input out and treat the absence of the data as a zero answer.
However, if you want to stick to your approach, read the documentation for the CGI module.
Specifically, the documentation for param:
When calling param() If the parameter is multivalued (e.g. from multiple selections in a scrolling list), you can ask to receive an array. Otherwise the method will return the first value.
Thus:
$form{$p} = [ param($p) ];
However, you do seem to be reinventing the wheel. There is a built-in method to get a hash of all paramaters:
$form = $CGI->new->Vars
That said, the documentation also says:
CGI.pm is no longer considered good practice for developing web applications, including quick prototyping and small web scripts. There are far better, cleaner, quicker, easier, safer, more scalable, more extensible, more modern alternatives available at this point in time. These will be documented with CGI::Alternatives.
So you should migrate away from this anyway.
Replace
$form{$p} = param($p); # Value of first field named $p
with
$form{$p} = ( multi_param($p) )[-1]; # Value of last field named $p
or
$form{$p} = ( grep length, multi_param($p) )[-1]; # Value of last field named $p
# that has a non-blank value

Moodle: Access global variables on theme settings pages

Is it possible to access a global variable from either $OUTPUT or $PAGE in /admin/settings.php?
I've tried var_dump on them but I get something along the lines of:
object(bootstrap_renderer)#3 (5) { ["initialising":protected]=> bool(false) ["opencontainers":protected]=>
The variables you want to access, if I understand, are fields of the $PAGE object. You cannot access directly these fields, because they are protected (you can see it in the class defining the $PAGE in /lib/pagelib.php). However, you can access their value by using a slightly different syntax: if the variable is named $_myvariable, you can access it with $PAGE->myvariable, (leaving out the underscore).
Example: you want to access $_pagetype, $_url, and $_navigation, use:
$test = $PAGE->pagetype;
$test1 = $PAGE->url;
$test2 = $PAGE->navigation;
Variables (fields) of the $OUTPUT object are also protected, and I did not find a way to access them, though. Here you can probably change the renderer bound to your $OUTPUT variable, and implement public functions returning your fields.

shopping cart implementation using perl

I need to design a shopping cart using perl such that the user gets clear idea of the goods he choose to buy. I thought of saving data of those items in a cookie. But i wonder how to update an already existing cookie each time an item is added. Is there any better way to design a cart/checkout page. Is there any perl module which makes my work easier?
Here is the snippet i tried out for updating cookie of cart
$cooki = $q->cookie('CART'); #retrieve cookie CART if already exists into var $cooki
$val2 = $cooki;
$val1 = $picid;
$cooki=$q->cookie(-name=>'CART',
-value =>["$val1"," $val2"],
-expires=>'+5m',
-path=>'/');
print $q->header(-cookie=>$cooki);
retrieval:
$cooki = $q->cookie('CART');
But it stores only the current id of the pic selected like for ex '45%20' i.e. 45 with a space and not multiple values like '45 12 16' . Where could i go wrong?
Do not use Cookies, instead use CGI::Session. For all the reasons why, you can read CGI::Session::Tutorial.
I created a working examples of using sessions to transfer information from one form to another in this question: How to access variable of other perl program in my perl program
Try this, because the return is an array:
#cooki = $q->cookie('CART');
Use CGI::Cookie and set cookies in anonymous array
my $c = CGI::Cookie->new(-name => 'CART',
-value => ['45','12','16'],
then fetch existing cookies by:
%cookies = CGI::Cookie->fetch;
$cart = $cookies{'CART'}->value;

How can I store more information in a session in Zend?

So I created a user system, and I want to grab the a few other fields from my database after authenticate()ing them. How can I do this?
If you want to store extra information in the identity beyond the typical, you can do something like this upon successful authentication.
This is in my login controller, processAction() upon successful authentication:
$identity = new stdClass;
$identity->username = strtolower( $auth->getIdentity() );
$identity->miscParam1 = 'Miscellaneous parameter1';
$identity->miscParam2 = 'Miscellaneous parameter2';
# ... etc ...
$storage = $auth->getStorage();
$storage->write($identity);
It's important to note that if you use this approach, then every time you want to get the username or the other parameters, you will need to retrieve it like so:
$identity = Zend_Auth::getInstance()->getStorage()->read();
echo $identity->username; # echo is just for example
echo $identity->miscParam1;
echo $identity->miscParam2;
Note that you would use getStorage()->read() instead of getIdentity() (which might also work but I am not sure).
Now, the only thing left to do is populate $identity->miscParam1 (etc) with information from your database using Zend_Db_Select. (Looking back at your question... I hope you weren't asking how to query. I probably didn't even answer your question.)

CGI::Application and SQLite

I've been messing around with CGI::application the past couple of days and decided to create a really basic forum: the first page displays all posts (only first level, no replies or anything) and a form which can be used to create a new post.
The issue I'm running into is that the data that gets entered into the form never gets inserted into the SQLite database.
Here's the sub procedure I'm having trouble with:
sub newpost {
my $self = shift;
if ( $self->param() ){
my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file","","");
my $sth = $dbh->prepare("INSERT INTO posts (author, time, text) VALUES('testuser', '2011-10-23', 'This is a test!')");
$sth->execute();
$self->header_type('redirect');
$self->header_props(-url=> '?rm=viewall');
}
else {
my $tmpl_obj = $self->load_tmpl('newpost.html');
return $tmpl_obj->output();
}
What happens correctly is that when the newpost run mode is first called, the code within the else statement is run (the template with the form is loaded). The action for the form calls this same run mode, but now that parameters are being provided, the code in the if statement is run. I've checked the SQL code itself and it works, so there must be something else I'm over looking.
Also, is it considered best practice to go about implementing the form logic in this way?
Thanks
You're confusing $self->param() with $self->query->param. The 1st is per-request application level parameters (stuff you might set in one method and use again in another method) and the 2nd are the parameters from the GET query string or the POST body of the request. If you're expecting something from the user it will be in $self->query->param.
BTW, the $self->query object is a normal CGI object, so see it's documentation for specifics.