Using Hook_form_alter on webform submitted values - php

Drupal 7. Webforms 3.x.
I am trying to modify a webform component value on submit. I made a custom module called 'mos' and added this code to it.
function mos_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'webform_client_form_43') {
dsm($form['#node']->{'webform'}['components']['1']);
$form['#submit'][] = 'mos_contact_us_submit';
}
}
function mos_contact_us_submit($form, &$form_state) {
$form['#node']->{'webform'}['components']['1'] = 'working#mos.com';
}
However when I look at the results in the database the regular, non-overridden value is stored. Can you help let me know what I am doing wrong?
Eventually I want to take the input value and output an email address based on what was provided (for example. 24 turns into bob#somewhere.com) But I think I can figure this part out myself.

You should to place your submit first.
array_unshift(
$form['actions']['submit']['#submit'],
'mos_contact_us_submit'
);
However, if you want to change some variables in form_state, you should to using custom _valadate function.

I got it! BIG Thanks to #dobeerman for pointing me in the right direction. Here is the code that ended up working:
function mos_form_alter(&$form, &$form_state, $form_id) {
if ('webform_client_form_43' == $form_id) {
//dsm($form);
$form['#validate'][] = 'mos_check_email';
}
}
function mos_check_email(&$form, &$form_state, $form_id) {
$emailVal = $form_state['values']['submitted']['to'];
switch($emailVal) {
case 1: $emailVal = 'email#test.com'; break;
case 2: $emailVal = 'email2#test.com'; break;
case 3: $emailVal = 'email3#test.com'; break;
......
}
$form_state['values']['submitted']['to']=$emailVal;
//dpm($form_state);
}
This way I can keep email address private, but still pass variables to the form with _GET. Kind of a weird situation... but we are trying to keep some existing code intact, so it seemed like the best route.
I accidentally messed up my account creation, so I can't give you the credit dobeerman but I emailed the admins and hopefully I will get it straightened out to get you some rep!

Related

Drupal global variables between module hook functions

Can anyone advice how best to set a temporary variable with scope to be used between hooks?
I have a custom module with the purpose of checking and warning if an attempted file upload matches an existing file on the system.
I am using hook_form_alter to identify the specific upload form and hook_file_validate to check if the file was previously uploaded.
My problem is those two hooks don't share a common parameter - I need to pass information from hook_form_alter back to hook_validate.
The information I want the functions to share is a simple boolean which should be destroyed immediately the file upload is done/dismissed, so using variable_set to persist it to the database is overkill. I don't believe a session or cookie approach is best either.
UPDATES:
Globals approach:
function duplicate_uploads_warning_init(){
$GLOBALS['processed'] = 'testing';
}
function duplicate_uploads_warning_file_validate($file){
drupal_set_message("PROCESSED[file-validate]: {$GLOBALS['processed']}", 'warning');
}
function duplicate_uploads_warning_form_alter(&$form, &$form_state, $form_id){
if( $form_id == 'file_entity_add_upload' ){
drupal_set_message("PROCESSED[form-alter]: {$GLOBALS['processed']}", 'error');
$GLOBALS['processed'] = 'tested';
$form['#validate'][] = 'duplication_validate';
}
}
The code above sets GLOBALS[processed] in the init hook and that value in immediately confirmed in the hook_form_alter.
However the attempt to reassign the value to tested fails. The reassigned value is what I hoped to see in hook_file_validate but I still get the initial value of testing.
Hook_form_alter validation approach:
I tried adding a custom validation function but the upload of the image still took place where I intend to stop it. My code is as follows:
function duplication_validate($form, &$form_state) {
$data = duplicates($form_state['complete form']['upload']['#file']->filename);
if( sizeof($data) > 0 ){
form_set_error('test', 'testing validation');
return false;
}
}
I can confirm my $data variable has content and the sizeof test returns greater than 0.
using variable_set to persist it to the database is overkill
I don't agree they are overkill (you can easily delete variables), and as #2pha have mentioned globals are not recommended. I think you could use variable_set($name, $value), variable_get($name), and variable_del($name) without worrying unless you need to super-optimise your sites database queries. If you really don't want to use the variable_* functions, then maybe cache_set() and cache_get() might work because you can give it a temporary status.
Edit, variables approach:
function duplicate_uploads_warning_init(){
$account = \Drupal::currentUser();
variable_set($account->id() . '_processed', 'testing');
}
function duplicate_uploads_warning_file_validate($file){
$account = \Drupal::currentUser();
$processed_var = variable_get($account->id() . '_processed');
drupal_set_message("PROCESSED[file-validate]: {$processed_var}", 'warning');
}
function duplicate_uploads_warning_form_alter(&$form, &$form_state, $form_id){
if( $form_id == 'file_entity_add_upload' ){
$account = \Drupal::currentUser();
$processed_var = variable_get($account->id() . '_processed');
drupal_set_message("PROCESSED[form-alter]: {$processed_var}", 'error');
variable_set($account->id() . '_processed', 'tested');
$form['#validate'][] = 'duplication_validate';
}
}
… and in a success or #submit callback function run variable_del($account->id() . '_processed') to delete the variable.
maybe $GLOBALS['processed'] was initialized with the static keyword elsewhere....?

Drupal form redirect to fragment

I have a poll block in the bottom of my front page, and I'd like to redirect the poll form to the block after submit. I use Drupal 6.x.
As usual, I use form_alter for this.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'poll_view_voting':
// not worked also
//$form['#redirect'] = url('', array('fragment' => 'poll-block'));
$form['#redirect'] = '#poll-block';
break;
}
}
After submit, I'm redirected to /%2523poll_block (this is a 404 page).
In a preprocess_page function I wrote the $_REQUEST['q'] using drupal_set_message(), and it shows the good redirect (#poll-block), but the URL in browser is encoded.
Can anybody help me?
Thanks in advance.
As per FAPI reference, you can enter an array to be passed to drupal_goto(). Ultimately this goes through url() so use your url() function's ninja tricks here.
Basically you can have 3 types of data here.
a string, Boolean FALSE, or an array.
If it's a string, it will redirect to the correct location after a url encode (what happens in your case). FALSE will disable redirects, and if you enter an array, it will be passed to drupal_goto().
So for your case, it would be:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'poll_view_voting':
// not worked also
//$form['#redirect'] = url('', array('fragment' => 'poll-block'));
//$form['#redirect'] = array('node/54', array('page' => '2'), 'poll-block'); // No "#" in fragment. This will work.
$form['#redirect'] = array('', array(), 'poll-block');
break;
}
}
However, drupal_goto() usually happens with absolute URL so probably your effort would be useless unless you use javascript.

Drupal - CCK field - make required

I've installed the following module - http://drupal.org/project/og_reg_keys This module adds an additional field to your Organic Group Node types, to allow auser to specify a registration key for users to use to join the group.
The problem is that field is not required to be entered by the user.How can one make this field a required field ?
I found the below code, which makes the CCK field mandatory for users of a specific role, but being a non PHP person I have no idea how to change this to:
Make the Group registration key a required field (not sure what the $form element would be called or where to find this)
To remove the section on the code where it applies to users of a specific role, so that it always applies.
Code:
function mymodule_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'profile_node_form':
global $user;
if(in_array('targetrole', $user->roles)) {
$form['field_profile_pic'][0]['#required'] = 'TRUE';
$form['#field_info']['field_profile_pic']['required'] = '1';
break
Any help would be greatly appreciated. Sorry for the code being so messy, I couldn't seem to paster it correctly, it kept getting cut off.
This should make it required for all users:
function mymodule_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'profile_node_form':
$form['field_profile_pic'][0]['#required'] = 'TRUE';
$form['#field_info']['field_profile_pic']['required'] = '1';
break ;
}
}

Additional submit event handler for webform in Drupal 6

Im using Drupal 6.19 and the webform module on my site.On a particular form,i want to do some additional processing with the values entered,so i created a module and implemented hook_form_alter, and added my own function called mymodule_webform_submit to the list of submit event handlers.
Suppose i have two fields in the form having field key values name and address respectively. How to print the values of those fields in mymodule_webform_submit function ?. Some example would be really appreciated. Below is my code so far.
<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'webform_client_form_8') {
$form['#submit'][] = 'mymodule_webform_submit';
}
}
function mymodule_webform_submit(&$form,&$form_state) {
drupal_set_message($form_state['values']['name']);
}
?>
Please help
Thank You
You're missing the arguments to your submit function. Once those are added, your values should be in $form_state['values']. It should be something like:
function mymodule_webform_submit($form, &$form_state) {
print $form_state['values']['name'];
print $form_state['values']['address'];
}
But do whatever you want with the values in there. Just make sure you have the correct element keys. You could see what's available by putting var_export($form_state['values']); exit(); inside the function and submitting the form.

need some tips on Drupal $form value

I got dpm($form) working. Nice! This is much better way to view data. I am still trying to figure out where stuff is coming from eg: location longitude & latitude. The word 'longitude' is referenced in 20 different places. I thought this was a likely place to isolate text box for this input field. dpm($form['#field_info']['field_store_latitude']['location_settings']['form']['fields']);
Any tips on how to track down individual input elements?
** this is not an answer, but a supplement to my first question **
hi googletorp -
I am trying to modify existing forms using hook_form_alter.
After several hours of poking around, I can now turn off location (longitude/latitude) section of a form like this:
unset($form['field_store_latitude']);
However, turning off just the latitude like this, does not work:
unset($form['field_store_latitude']['0']['#location_settings']['form']['fields']['locpick']);
I cannot find a easy way to link id and names in html source with arrays produced by Krumo.
In this case id is called "edit-field-store-latitude-0-locpick-user-latitude".
I need a recipe or guidelines for identifying form elemets in Drupal form.
I think I nailed down a solution
<?php
// allows you to alter locations fields, which are tricky to access.
// this will require a patch in location module described here:
// http://drupal.org/node/381458#comment-1287362
/**
* Implementation of custom _element_alert() hook.
*/
function form_overrides_location_element_alter(&$element){
// change some location descriptions
$element['locpick']['user_latitude']['#description'] = ' ' . t('Use decimal notation.');
$element['locpick']['user_longitude']['#description'] = ' ' . t('See <a href=!url target=_blank>our help page</a> for more information.', array('!url' => url('latlon_help')));
// or make them disappear entirely
unset($element['locpick']['user_longitude']);
unset($element['locpick']['user_latitude']);
}
/**
* Implementation of form_alter hook.
*/
function form_overrides_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'user_profile_form':
// change titles in user profile form
$form['account']['name']['#title'] = t('Login Name');
$form['account']['mail']['#title'] = t('Email');
break;
case 'retailer_node_form':
// let's check what is supposed to be here...
print '<pre>';
//print_r($form);
dsm($form);
print '</pre>';
// this works to remove the city
unset($form['field_myvar_latitude']['0']['#location_settings']['form']['fields']['city']);
// let's try #after_build property
$form['#after_build'][]='mymodule_after_build_mynode';
break;
}
}
function mymodule_after_build_mynode($form, $form_values) {
// This will not work for locations fields
return $form;
}`enter code here`
So there is sneaky way to alter the location field, what you need to do is to use the #after_built callback:
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'x_node_form') {
// alter the location field
if (isset($form['locations'])) {
$form['locations']['#after_build'][] = 'mymodule_alter_location_field';
}
}
}
/**
* Remove the delete checkbox from location element.
*/
function mymodule_alter_location_field($form_element, &$form_state) {
$location = $form_element[0]; // The location field which you can alter
return $form_element;
}

Categories