I am trying to create a plugin that will take the value of a listbox TV and set the document's createdby field to match that TV's setting onDocFormSave. The TV populates itself automatically with all active users and output's their ID.
I have the following code for the plugin, but when I try to save any resource it simply hangs and never saves. setCreatedBy is the name of the listbox TV:
switch ($modx->event->name) {
case 'onDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy')
if ($resource->get('createdby') != $created_by) {
$modx->resource->set('createdby', $created_by));
}
break;
}
Untested.
It looks like setting also has to be done on the resource, not via the Modx-class.
$resource->set('createdby', $created_by); // You also have a ) too much in your code.
Inspected the docs.
If you omit the $resource->set... and run the plugin, will it pass? I'm wondering if you might be causing a loop, i.e $resource->set triggers another onDocFormSave. Do you have access to the server error.log? It probably contains whatever is crashing.
Those on the Modx forums were able to give me a leg up.
switch ($modx->event->name) {
case 'OnDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy');
if (!empty($created_by) && $resource->get('createdby') != $created_by) {
$resource->set('createdby', $created_by);
$resource->save();
}
break;}
For reference, the way I handled gathering the names and user id's of Modx users and placing them in a selectbox TV was to use the Peoples snippet in an #EVAL binding:
#EVAL return $modx->runSnippet('Peoples',array('tpl'=>'peoplesTpl','outputSeparator'=>'||','active'=>'1'));
This is a petty dirty and slow way of doing things, but a request to have this be a standard field on Modx resources has been submitted to GitHub
Related
I am building my wedding website and want to integrate an RSVP form using Gravity Forms. The issue I am running into is how to set certain guest that have +1's. I would like to show an additional guest entry (First Name, Last Name, Meal Option) when the initial First Name and Last Name has been populated. How would I go about doing this? Any help would be great! Thanks in advance!
Here is how I'd solve this problem:
First, you need to put everything in the DB, the easiest way would be to either do it manually or somehow loop through an array/CSV calling add_option($key, $value) Again, I would recommend a mobile/phone number as they'll be unique so you don't pull the wrong "John Smith". I'll assume you'll keep it basic with $key as the unique identifier and $value as boolean as to whether to show additional info. Interestingly, by default, if not found get_option($key) will return false and therefore not show your additional data, which I would assume you'd want anyway. If you'd rather it return true just pass true as the second argument.
Now for your answer:
Your URL is something like https://somesite.com/rsvp?id=1234.
function allowed_plus_one() {
$id = $_GET["id"];
$allowed = get_option($id);
return $allowed;
}
Then assumedly it'll be something like
if (allowed_plus_one()) {
// show form with plus one
} else {
// show form without
}
EDIT:
Keeping separate incase this has already been viewed.
You should also be checking for the existence of $_GET["id"] and behaving accordingly. eg:
if (isset($_GET["id"] && !empty($_GET["id"]) {
//do logic above
} else {
//here by mistake so don't show any form?
}
I have a personal search site project I'm building, at the moment the only data that is being displayed on the website is data that is retrieved using SELECT queries and the GET method using the super global $_GET['example']. Now I don't know if I'm doing this wrong but some parts of my page are only displayed if certain GET variables in the URL are set or not empty. Below shows how my URL looks
EXAMPLE: index.php?search_category=guitar&main_category=9&postcode_val1=NP22&distance_default=100&submit=search
I have a lot of these if(isset($_GET['search_category']) type conditions in my website which are replied upon and show particular parts of content depending whether or not these are either true or false.
I have been on a lot of other websites that have similar URL's, I have tried to alter and manipulate these and the content does not break, alter or change in any way yet when i try this with my url it breaks my page and only certain parts of content gets displayed by being based on what is set. Is there some other layer of protection I should add, would using something like a rewrite rule help? The code below shows how I have wrote a drop down box based on what has been set In the URL but if a user edits the URL this is easily broken.
if(isset($_GET['search_category']) && isset($_GET['main_category']) &&
isset($_GET['postcode_val1']) && isset($_GET['distance_default']))
{
$stmt = $getFromUi->dispCategories();
echo "<option value='0'>All</option>";
echo "<option value='#'>-------------</option>";
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$selected = '';
if(!empty($_GET['main_category']) && $_GET['main_category'] == $row->cat_id)
{
$selected = ' selected="selected"';
}
echo '<option value="'.htmlentities($row->cat_id).'"'.$selected.'>'.htmlentities($row->cat_title).'</option>';
}
}
It will break because the strict nature of logic you use on your code. The && mark with isset mean any parameter you define not set will not evaluate to true. If the parameter is quite flexible why not ||.
If you need it to still evaluate all parameter try to do limit first if condition to main determiner. like $_GET['search_category'] and use the remaining $_GET['other_parameter'] as needed inside the block code of main if.
You would need to use a post method, so that this goes through as a request instead. In my experiance, get will only fetch the url you open - not actually pass anything through unless its in the URL.
Not sure if that made any sense, but check post out.
https://www.w3schools.com/tags/ref_httpmethods.asp is a good place to start to see the difference of get vs post.
OK, here's my dilemma:
I've read all over about how many guys want to be able to display a set of images from Flickr using PHPFlickr, but lament on how the API for PhotoSets does not put individual photo descriptions. Some have tried to set up their PHP so it will pull the description on each photo as the script assembles the gallery on the page. However, the method has shown how slow and inefficient it can be.
I caught an idea elsewhere of creating a string of comma separated values with the photo ID and the description. I'd store it on the MySQL database and then call upon it when I have my script assemble the gallery on the page. I'd use explode to create an array of the photo ID and its description, then call on that to fill in the gaps...thus less API calls and a faster page.
So in the back-end admin, I have a form where I set up the information for the gallery, and I hand a Set ID. The script would then go through and make this string of separated values ("|~|" as a separation). Here's what I came up with:
include("phpFlickr.php");
$f = new phpFlickr("< api >");
$descArray = "";
// This will create an Array of Photo ID from the Set ID.
// $setFeed is the set ID brought in from the form.
$photos = $f->photosets_getPhotos($setFeed);
foreach ($photos['photoset']['photo'] as $photo) {
$returnDesc = array();
$photoID = $photo['id'];
$rsp = $f->photos_getInfo($photoID);
foreach ($rsp as $pic) {
$returnDesc[] = htmlspecialchars($pic['description'], ENT_QUOTES);
}
$descArray .= $photoID."|~|".$returnDesc[0]."|~|";
}
The string $descArray would then be placed in the MySQL string that puts it into the database with other information brought in from the form.
My first question is was I correct in using a second foreach loop to get those descriptions? I tried following other examples all over the net that didn't use that, but they never worked. When I brought on the second foreach, then it worked. Should I have done something else?
I noticed the data returned would be two entries. One being the description, and the other just an "o"...hence the array $returnDesc so I could just get the one string I wanted and not the other.
Second question is if I made this too complicated or not. I like to try to learn to write cleaner/leaner code, and was looking for opinions.
Suggestions on improvement are welcome. Thank you in advance.
I'm not 100% sure as I've just browsed the source for phpFlickr, and looked the the Flickr API for the getInfo() call. But let me have a go anyway :)
First off, it looks like you shouldn't need that loop, like you mention. What does the output of print_r($rsp); look like? It could be that $rsp is an array with 1 element, in which case you could ditch the inner loop and replace it with something like $pic = $rsp[0]; $desc = $pic['description'];
Also, I'd create a new "description" column in your database table (that has the photo id as the primary key), and store the description in their on its own. Parsing db fields like that is a bit of a nightmare. Lastly, you might want to force htmlspecialchars to work in UTF8 mode, cause I don't think it does by default. From memory, the third parameter is the content encoding.
edit: doesn't phpFlickr have its own caching system? Why not use that and make the cache size massive? Seems like you might be re-inventing the wheel here... maybe all you need to do is increase the cache size, and make a getDescription function:
function getDescription ($id)
{
$rsp = $phpFlickr->photos_getInfo ($id);
$pic = $rsp[0];
return $pic['description'];
}
I have a Drupal website and I want to show different welcome pages, depending on what my users enter as profile fields. I can't use the global $user variable, because users are not automatically logged in (They have to very their email address before they can log in).
Where can I add code to set the redirect?
I've tried with $form['#redirect'] and $form_state['redirect'] in the form validator, but that didn't work.
You can use logintobogan for inspiration:
#implementation of hook_user
mymodule_user($op) {
if ($op == 'login') {
$_REQUEST['destination'] = '/user/will/be/redirected/here'
}
}
The important part is to make sure, that by the time the final drupal_goto() is called in user.module, you have set your $_REQUEST['destination'].
A few things to note:
Logintoboggan has a lot of code to deal with all sorts of edge-cases, such as redirecting out/to https. You can ignore these, if your case is simple.
Your module must be called after user.module and probably after other modules implementing hook_user, for they might change this global too. Very ugly, but the way this works in Drupal.
Do not -ever- issue drupal_goto() in any hook. Especially not hook_user, or hook_form_alter. drupal_goto will prohibit other hooks from being called; breaking functionality at the least, but often corrupting your database.
Do not issue drupal_goto() in form_alter callbacks such as "_submit", this might break many other modules and might even corrupt your database.
Similar to Berke's answer, but it seems like you just want this to be a one time thing. For that, you can check for the $account->access property to check their last login. If it is 0, then they are logging in for the first time.
This should work fine for email or no email validation.
<?php
/**
* Implements hook_user().
*/
function mymodule_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
// execute this if they have never accessed the site before
if ($account->access == 0) {
// run conditional logic based on profile fields
// to set destination here
$_REQUEST['destination'] = 'path/to/welcome-page';
}
break;
}
}
?>
I suggest you use the Login Destionation module or you can use the Rules module redirect action which is maybe to robust for your purpose.
Just in case you don't want to write your own custom module :-)
I'm working on a patch to submit to the Registration Code module for Drupal. In short, is there a more efficient way to write the code below?
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', array('regform' => 'regform'));
if (empty($cnfg['regform'])) {
return;
}
}
It seems like I should be able to reduce it to one if statement with && combining two conditions, but I haven't found the syntax or the necessary php array function that would allow me to do that.
In case some context helps, the regcode_voucher sub-module allows users to enter their registration code on the user edit page. On our sites, after a "beta" period, we want to simplify the registration form by removing the registration code field; but we'd like users to still be able to enter the code on their account edit page. The code above is part of a patch that allows the regcode's hook_user changes to be bypassed.
Code looks like good, what efficient do you want? Little changes may be:
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', null);
if ($cnfg) {
// do your actions
}
}
And I don't recommend to merge if..., code should be clear and simpler to understand. If you merge these for optimizing, you win "tiny" milliseconds for real-live processors, but lost your clean code.
Why are you returning an array from variable_get if the variable is not found? variable_get will always return a string or a serialized array (that needs to be unserialized). If I'm missing something, you can use array_key_exists('regcode', variable_get(...)) to check for the array key.
This should work... note returning "false" from variable_get as a default if the variable is not found, which will cause the if conditions to not match. I personally find this more readable than nested if statements (for 3+ conditions I'd nest, though).
if( module_exists('regcode_voucher') && variable_get('regcode_voucher_display', false) ) {
// stuff
}