Wordpress Gravity Form Plugin [HELP] - php

I have a form at my website where the user can request for information, but there's a catch. Inside the form I have a checkbox and when the user selects it, the email must to be sent to another place. (See the screenshots)
What's happening is: Gravity form sends both emails when both rules match, but I only wanna send one email based on the priority.
How can I do that?

I don't believe the routing will take into account AND conditions for the individual rules.
You can however, use the following filter to do further modifications to the e-mail before it is being sent:
add_filter("gform_notification", "my_custom_function", 10, 3);
Or, for a specific form (i.e. id = 42):
add_filter("gform_notification_42", "my_custom_function", 10, 3);
Source: http://www.gravityhelp.com/documentation/page/Gform_notification
Update
An example of accessing the fields would look like this:
add_filter('gform_notification_42', 'updateNotificationForForm42', 10, 3);
function updateNotificationForForm42( $notification, $form, $entry ) {
$fields = $form['fields'];
foreach( $fields as $field ) {
// Here you need to provide the field with some kind of identifying mark (e.g., Admin Label).
// Below assumes the field you're interested in has an admin label of 'Test Me'
if( $field['adminLabel'] == 'Test Me' ) {
$fieldValue = rgpost("input_{$field['id']}");
}
}
}
The Gravity Forms developer docs have a lot of examples of how to customize via actions/filters.
See Also: http://www.gravityhelp.com/documentation/page/Fields

Related

Prefill CF7 data from the database using a dynamic field

I am trying to create a method through which I can retrieve the data from the database of contacts saved by contact form 7 and pre-fill the fields after the users have previously selected, from a drop-down menu, the PayPal payment method and filled out the form , without then proceeding to the actual payment.
The flow to follow is this:
If the user has chosen to pay with PayPal and filled out the entire form, the "paid" item will be 0 and without making any redirects to the PayPal page
Then, when the user returns to the event card, we will show all the fields filled in previously and the "pay with paypal" button to complete the paypal payment. So the "paid" item will be 1.
So far I have used the following plugins to save the data of the completed forms Advanced CF7 DB and Contact Form CFDB7.
The use of one of these, or someone else, is indifferent to my goal
Here is the code with which so far I am able to populate the dynamic and hidden field [dynamichidden paid ""] when the user selects PayPal but without too much success:
add_action('wpcf7_posted_data', 'course_registration_actions_paypal', 10, 1);
function course_registration_actions_paypal($stato0){
$paypal["paymentmethod"] = '0';
$stato0[“paid”] = '0';
$stato1[“paid”] = '1';
if (isset($paypal[“paymentmethod]) && $stato0[“paid”] === '0') {
return $stato0;
} else {
return $stato1;
}
};
Eventually I managed to get it to work as I wanted, but there remains a redirect problem using the "redirection for contact form 7" plugin.
Always redirect on the first case (paypal) rather than differentiate.
I think the problem is 'wpcf7_posted_data' as without redirects they work fine.
This is my code:
add_action('wpcf7_posted_data','course_registration_actions_persist_payment_status', 10, 1);
function course_registration_actions_persist_payment_status($record){
$current_user = wp_get_current_user();
$userId = get_field('id__pro', 'user_' . $current_user->ID);
$eventId = get_field('id', false);
$records = WPCF7_ContactForm::find([
'ID-Course' => $eventId, // 2
'ID-User' => $userId, // 82994
]);
if ($record['paymentmethod'][0] == 0) {
// Paypal
$record['paymentmethod'] = 0;
// No Paid
$record['paid'] = 0;
} else {
// Bank
$record['paymentmethod'] = 1;
// Paid
$record['paid'] = 1;
}
return $record;
};

Drupal 8 - Reading node fields values within a custom module

I am using Drupal 8.2.6 and I would like to create a block that would appear on a custom content type page.
It is kind of a booking block which sends an e-mail to the site admin that a visitor would like to book a product (the custom content type).
I assume I would need a form which only consists of a submit button and a block which renders the form.
But the real point would be sending the mail with the product's reference to the site admin.
As I found here, I could get the values I need using this snippet:
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$field_my_custom_value = $node->field_my_custom_value->value;
}
But I am not sure in which scope of my code I should use it. This example was for rendering the values within a custom block, where as my case would be sending a mail with the values.
And could anyone remind me as well how to send a mail from a custom module in Drupal 8?
Thanks a lot
So, after solving it myself after a day's whole worth of documentation, here are the solutions, as I am going to revert back my question to earlier revisions, in case anyone needs it.
So, given the snippet in the question above, I declared the variables in the buildForm() function
public function buildForm(array $form, FormStateInterface $form_state) {
$field_value = '';
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$field_value = $node->field_name->value;
}
$form['field_value'] = array(
'#type' => 'value',
'#value' => $field_value,
);
// And then you add the definition for other form items and submit button
}
And for sending the mail using the value, you retrieve the value using $form_state like this:
public function submitForm(array &$form, FormStateInterface $form_state) {
$module = 'your_module_name';
$key = 'any_key_you_would_like';
$to = 'receiver#email.address';
$langcode = 'en';
$params = array(
'body' => 'Node is booked',
'subject' => $form_state->getValue('field_value'),
);
$mailer = \Drupal::service('plugin.manager.mail');
$mailer->mail($module, $key, $to, $langcode, $params, NULL, TRUE);
}
Some values are quite tricky to get from the node, such as the node title which uses $node->getTitle() instead of $node->field_name->value so you would like to check your fields using Drupal 8's Devel + Kint module to know what attributes and methods to use.

using wp_authenticate() to redirect certain users when logging in

Our website is using Wordpress - WooCommerce login page for customers to login.
I am trying to use wp_authenticate() to achieve the following:
1) Customer login to our new website, enter their username and password, and hit Login button. In case you want to see WooCommerce Login file, click here.
2) Our new website goes through list see if the username matches. If the username matches, don't even look at the password, just redirect the user to other url such as google.com
3) if the username doesn't match with our list, just let them login as usual.
With JQuery, someone helped me to come up with the following code:
var names = new Array(”BILL”, ”JIM”, ”BOB”); // get all names into array, and all in uppercase
var dest_url = ”http://www.website.com”; // URL we want to send them to
jQuery(document).ready(function () {
jQuery(”input[name=’login’]”).click(function(event){
event.preventDefault(); // prevent default form action
var current_name = jQuery(”#username”).val();
current_name = current_name.trim().toUpperCase();
if ( -1 != jQuery.inArray(current_name, names) ) {
alert(”Redirecting ” + current_name + ” to ” + dest_url);
window.location = dest_url; // send to desired URL
}
else
document.getElementsByClassName(”login”)[0].submit(); // input name not on our list, so just do normal submit action
});
});
But I am not sure if wp_authenticate() can actually contain jquery script inside. Any suggestion would be greatly appreciated.
First, I would recommend doing this in PHP, not javascript.
Second, you have a couple of options, leveraging the built-in functionality of WordPress.
If all you care about is the username, and do not care if they successfully logged in with the right password, then you could leverage the filter found in wp_authenticate()
// This is the filter wp_authenticate fires
apply_filters( 'authenticate', null, $username, $password );
Knowing that, you could write a quick little plugin, or add this code to your theme's functions.php file:
// Run this filter with priority 9999 (last, or close to last), after core WP filters have run
add_filter('authenticate', 'redirect_certain_users', 9999, 3);
// Your custom filter function
function redirect_certain_users( $user, $username, $password) {
// Assumes you write a function called get_list_of_users_to_redirect that returns an array similar to that in your sample code
$redirect_users = get_list_of_users_to_redirect();
// If the user is in the array of users to redirect, then send them away
if ( in_array( $username, $redirect_users ) ) {
header("location:http://www.example.com");
die();
}
return $user;
}
Note that this code is untested, but should get you at least 90% of the way there.

Create gravity form poll based on post types

Is there a way to create/update form poll fields based on a content type? For example, I've got a post type called Candidate and I'd like like to dynamically update a poll list when a new Candidate is added, or when one is removed.
The reason I'm looking for this is because I'm creating a voting mechanism for this client and they have requested that users see an image, the name, and brief Bio of who they are voting for. My idea is to tie in the names so that I can target a hidden Gravity Form poll on page so when the voter clicks, it updates the corresponding named checkbox.
I can of course add each Candidate one by one, and then add each candidate one by one in the form, but was hoping there was a way to do that in code. So far I haven't found much other than filters in the Gravity Forms Documentation.
To reiterate, my question here is not the frontend connection, rather how to dynamically update/add an option in a poll field in a form when content is created for a Candidate post type.
Any help would be appreciated.
I believe the solution you're after is documented here:
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_pre_render/
Probably a combination of solution examples #1 and #2 on that page will fit your needs? So -
Create a category of standard Wordpress pages (category name: "Candidates"), and the pages would contain the candidate information (bio, photo, etc).
In your functions.php file for your current theme, you'd add something like the following to pull out that category's worth of posts:
// modify form output for the public page
add_filter("gform_pre_render", "populate_checkbox");
// modify form in admin
add_filter("gform_admin_pre_render", "populate_checkbox");
function populate_dropdown($form) {
// some kind of logic / code to limit what form you're editing
if ($form["id"] != 1) { return $form; }
//Reading posts for "Business" category;
$posts = get_posts("category=" . get_cat_ID("Candidates"));
foreach ($form['fields'] as &$field) {
// assuming field #1, if this is a voting form that uses checkboxes
$target_field = 1;
if ($field['id'] != $target_field) { break; }
// init the counting var for how many checkboxes we'll be outputting
// there's some kind of error with checkboxes and multiples of 10?
$input_id = 1;
foreach ($posts as $post) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if($input_id % 10 == 0) { $input_id++; }
// here's where you format your field inputs as you need
$choices[] = array('text' => $post->post_title, 'value' => $post->post_title);
$inputs[] = array("label" => $post->post_title, "id" => "{$field_id}.{$input_id}");
// increment the number of checkboxes for ID handling
$input_id++;
}
$field['choices'] = $choices;
$field['inputs'] = $inputs;
}
// return the updated form
return $form;
}

custom drupal search module's form losing all post data when submitted

I am modifying an already contributed drupal module (Inline Ajax Search) to handle searching of a specific content type with some search filters (i.e. when searching for help documentation, you filter out your search results by selecting for which product and version of the product you want help with).
I have modified the module some what to handle all the search filters.
I also added in similar functionality from the standard core search module to handle the presenting of the search form and search results on the actual search page ( not the block form ).
The problem is that when i submit the form, i discovered that I'd lose all my post data on that submit because somewhere, and i don't know where, drupal is either redirecting me or something else is happening that is causing me to lose everything in the $_POST array.
here's the hook_menu() implementation:
<?php
function inline_ajax_search_menu() {
$items = array();
$items['search/inline_ajax_search'] = array(
'title' => t('Learning Center Search'),
'description' => t(''),
'page callback' => 'inline_ajax_search_view',
'access arguments' => array('search with inline_ajax_search'),
'type' => MENU_LOCAL_TASK,
'file' => 'inline_ajax_search.pages.inc',
);
}
?>
the page callback is defined as such (very similar to the core search module's search_view function):
<?php
function inline_ajax_search_view() {
drupal_add_css(drupal_get_path('module', 'inline_ajax_search') . '/css/inline_ajax_search.css', 'module', 'all', FALSE );
if (isset($_POST['form_id'])) {
$keys = $_POST['keys'];
// Only perform search if there is non-whitespace search term:
$results = '';
if(trim($keys)) {
require_once( drupal_get_path( 'module', 'inline_ajax_search' ) . '/includes/inline_ajax_search.inc' );
// Collect the search results:
$results = _inline_ajax_search($keys, inline_ajax_search_get_filters(), "page" );
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), inline_ajax_search_help('inline_ajax_search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
$output .= $results;
return $output;
}
return drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
}
?>
from my understanding, things should work like this: A user goes to www.mysite.com/search/inline_ajax_search and drupal will process the path given in my url and provide me with a page that holds the themed form for my search module. When i submit the form, whose action is the same url (www.mysite.com/search/inline_ajax_search), then we go thru the same function calls, but we now have data in the $_POST array and one of them is indeed $_POST['form_id'] which is the name of the form "inline_ajax_search_search_form". so we should be able to enter into that if block and put out the search results.
but that's not what happens...somewhere from when i submit the form and get my results and theme it all up, i get redirected some how and lose all my post data.
if anybody can help me, it'd make me so happy lol.
drupal_get_form actually wipes out the $_POST array and so that's why I lose all my post data.
according to this: http://drupal.org/node/748830 $_POST should really be ignored when doing things in drupal. It's better to find a way around using it. One way is the way described in the link, making ur form data persist using the $_SESSION array. I'm sure there are various other and better ways to do this, but yeah, drupal_get_form was the culprit here...

Categories