populate a form programmatically in drupal - drupal

I need to populate the form fields programmatically in drupal. I understand that there are 2 approaches:
using drupal_execute($form_item,value,$form_state)
using form_set_value($form_id,$form_state)
Any working examples would be helpful
I tried the following code which gives the drupal white screen of death
function form_validate($form, &$form_state){
$form_id ='myform';
$form_state['values'] = array(
'name' => 'Test',
);
drupal_execute($form_id, $form_state); // this statement leads to white screen of death
}

I assume you are trying to fill out a field in the form during validation, after the user submits it? I assume this because you are using a validate function.
If so, there is no need for the drupal_execute() function, as the form will be submitted after it passes validation no matter what. I think what you want might be more like this:
function form_validate($form, &$form_state) {
$form_state['values']['name'] = 'test';
}

You should use:
<?php
$form_id = 'mymodule_form_id';
$rendered_form = drupal_get_form($form_id);
print $rendered_form;
?>
See:
http://api.drupal.org/api/drupal/includes--form.inc/function/drupal_get_form/6

Related

Woocommerce - Remove fields from woocommerce_form_field including validation

I am trying to customise the Woocommerce myaccount page, in particular the edit address page.
I want to display both the shipping + billing address forms on a single page. Ideally, in a single form with a one save button. I also need to remove a lot of the fields, so that it's a much simpler form of just an address (no name, company, etc).
I have implemented the code found on This Answer. It works nicely in that it shows both forms. However, I cannot remove the fields from the forms. If I try code like this:
add_filter( 'woocommerce_billing_fields' , 'custom_override_billing_fields' );
add_filter( 'woocommerce_shipping_fields' , 'custom_override_shipping_fields' );
function custom_override_billing_fields( $fields ) {
unset($fields['billing_country']);
unset($fields['billing_company']);
unset($fields['billing_first_name']);
unset($fields['billing_last_name']);
unset($fields['billing_phone']);
unset($fields['billing_email']);
return $fields;
}
function custom_override_shipping_fields( $fields ) {
unset($fields['shipping_country']);
unset($fields['shipping_company']);
unset($fields['shipping_first_name']);
unset($fields['shipping_last_name']);
return $fields;
}
It doesn't work, the fields are no longer shown but the form does not save on click... it just redirects to /my-account/edit-address/billing/ - and doesn't save. (the same form shown on this page doesn't save either).
I've also tried:
foreach ( $billing_fields as $key => $field ) :
if($key != 'billing_first_name' && $key != 'billing_last_name') :
woocommerce_form_field( $key, $field, $userMeta[$key][0] );
endif;
endforeach;
This removes the field from displaying, BUT the validation still exists - and any filter code I add to functions using
woocommerce_checkout_fields to remove the validation doesn't seem to affect this form at all.
Is there a way to either:
Remove fields from this form generated by woocommerce_form_field including the validation?
Create a custom form that allows me to set the input fields manually in the code, and update any fields that are there, ignoring the validation from Woocommerce completely?
This should work 100%. You need to state whether the fields you are removing is from billing or shipping and this is done by adding the ['billing'] or ['shipping'], whichever it is.
After this, adding the function directly to woocommerce_checkout_fields will apply both for billing and shipping.
For phone and company fields you can disable it in admin panel itself, do it.
Edit: And yes, all validation that was involved with the fields in the past will be removed. You can then apply any validation you need.
add_filter( 'woocommerce_checkout_fields' , 'brandimagemarketer_remove_billing_fields_checkout' );
function brandimagemarketer_remove_billing_fields_checkout( $fields ) {
unset($fields['billing']['billing_country']);
unset($fields['billing']['billing_first_name']);
unset($fields['billing']['billing_last_name']);
unset($fields['billing']['billing_email']);
unset($fields['shipping']['shipping_country']);
unset($fields['shipping']['shipping_first_name']);
unset($fields['shipping']['shipping_last_name']);
unset($fields['shipping']['shipping_email']);
return $fields;
}

How to add warning text in Drupal comment form

I want a warning message displayed in the comment form when people try to add comments:
"Please write comments in correct
grammatical English, otherwise they
will not published"
How can I do it?
Here is how you can do it by using hook_form_alter in your own module:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case "comment_form":
$form['#prefix'] .= "<div><p>Show some text before the comment form.</p></div>";
break;
}
}
You can alter the comment form so that your guidelines are added to it. There are a handful of ways to alter forms in Drupal. You can do it in your theme's template.php file (which I prefer for simple changes) or in a custom module. This article describes both methods, in Drupal 5 and 6, however not for the form you're interested in. However, the method used is the same that leads to the solution below. This is how you can make the change via template.php:
The following PHP code can be added to your theme's template.php file:
function YOURTHEME_theme() {
return array(
'comment_form' => array(
'arguments' => array('form' => NULL),
),
);
}
function YOURTHEME_comment_form($form) {
$output = '';
$output .= '<div class="comment-help">' . t('Please write comments in correct grammatical English, otherwise they will not published.') . '</div>';
$output .= drupal_render($form);
return $output;
}
Replace YOURTHEME with the name of your theme. If you already have a YOURTHEME_theme function you will need to add the 'comment_form' key to the array it is already returning. I doubt you do, but it's worth mentioning just in case.
A note: you should not be editing any of the themes in /themes, but you should have made a new theme or copied and renamed any of those themes into /sites/default/themes or /sites/all/themes.
The above code is based on code from this page.
Once you are inside a hook_form_alter function you can use the Development module (http://drupal.org/project/devel) dpm() function in place of var_dump to help view and isolate which properties to change in the big form arrays. I find this is a must-have when trying to figure out changes to an existing form. It puts all the elements of the form array into clickable rows.
In Drupal 7 go to
admin/structure/types/manage/mycontenttype/comment/fields/comment_body
There you can add your text. It will be shown below the field as usual. If you want the warning displayed above the field, you'd have to go the form_alter way.

Drupal 6 editing the submit function on a content type

I have a content type and I wish to edit the submit function. I thought the way you would do this would be as follows:
function moduleName_contentType_node_form_submit($form, &$form_state){
drupal_set_message(t('Test'));
}
I cleared the cached but the message is not being displayed on the screen. Am I doing this correctly or do I need to use form_alter? If so how would I do that?
In this case too you can use form alter, and add
$form['#submit'][] = 'your_sumbmit_callback';
or if you want to completely change the submit and do your own thing:
$form['#submit'] = array('your_submit_callback');
And obviously the callback function needs to be defined;
function your_submit_callback( $form, &$form_state) {
drupal_set_message('hello');
}

How can I get the title of a form element in Drupal?

For example, in the registration form, there is "Username" and the text field for it which has the input type="text" name="name" ....
I need to know how can I get the title from the input field's name.
I'm expecting a function like:
$title = get_title_for_element('name');
Result:
assert($title == 'Username'); // is true
Is there something like this in Drupal?
Thanks.
You have the form and the form state variables available to your validation function. You should use form_set_error() to set the error.
There is no function that I am aware of which will map from the values array to the form array. But it is not dificult to work it out. Understanding the form data structure is one of the key skills you need when building drupal.
In this case the form in question is generated (in a roundabout way) by user_edit_form, you can see the data structure in there.
$form['account']['name'] is the username field. and the array key for the title is '#title' as it will be in most cases for form elements.
You can do it in two different ways as I see it. Let's create a module called mycustomvalidation.module (remember to create the mycustomvalidation.info file also).
Note: The code below has not been tested, so you might have to do some minor adjustments. This is Drupal 6.x code by the way.
1) Using hook_user()
What you need is a custom module containing your own implementation of hook_user() http://api.drupal.org/api/function/hook_user/6.
<?php
function mycustomvalidation_user($op, &$edit, &$account, $category = NULL) {
if ($op == 'validate') {
// Checking for an empty 'profile_fullname' field here, but you should adjust it to your needs.
if ($edit['profile_fullname'] != '') {
form_set_error('profile_fullname', t("Field 'Fullname' must not be empty."));
}
}
}
?>
2) Using form_alter() and a custom validation function
Personally, I would go for this option because I find it cleaner and more "correct". We're adding a custom validation function to our profile field here.
<?php
function mycustomvalidation_form_alter(&$form, $form_state, $form_id) {
// Check if we are loading 'user_register' or 'user_edit' forms.
if ($form_id == 'user_register' || $form_id == 'user_edit') {
// Add a custom validation function to the element.
$form['User information']['profile_fullname']['#element_validate'] = array('mycustomvalidation_profile_fullname_validate');
}
}
function mycustomvalidation_profile_fullname_validate($field) {
// Checking for an empty 'profile_fullname' field here, but you should adjust it to your needs.
if ($field['#value'] != '') {
form_set_error('profile_fullname', t("Field %title must not be empty.", array('%title' => $field['#title']));
}
}
?>

Drupal Views2 Exposed Form how to change

I have a View with an exposed form . I am trying to a few things on it. Ideally I would like to have a dropdown that fires the form with no button. If that is not possible then I would like to have the button text something different than apply.
I hacked it for now and change views_form in views.module but that does not seem like the right way to do it. I only have one exposed form right now, but what if I add more?
Please see http://www.wiredvillage.ca/News for my example.
I am poking around drupal.org and seeing others with the same problem but no solutions so far. Not sure where the best place to get Drupal help is.
Here is the change I made so far:
function views_exposed_form(&$form_state) {
// Make sure that we validate because this form might be submitted
// multiple times per page.
$form_state['must_validate'] = TRUE;
$view = &$form_state['view'];
$display = &$form_state['display'];
$form_state['input'] = $view->get_exposed_input();
// Let form plugins know this is for exposed widgets.
$form_state['exposed'] = TRUE;
$form['#info'] = array();
if (!variable_get('clean_url', FALSE)) {
$form['q'] = array(
'#type' => 'hidden',
'#value' => $view->get_url(),
);
}
// Go through each filter and let it generate its info.
foreach ($view->filter as $id => $filter) {
$view->filter[$id]->exposed_form($form, $form_state);
if ($info = $view->filter[$id]->exposed_info()) {
$form['#info']['filter-' . $id] = $info;
}
}
// I CHANGED The VALUE OF THIS SUBMIT BUTTON TO GO
$form['submit'] = array(
'#name' => '', // prevent from showing up in $_GET.
'#type' => 'submit',
'#value' => t('go'),
);
$form['#action'] = url($view->get_url());
$form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
$form['#id'] = views_css_safe('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
// $form['#attributes']['class'] = array('views-exposed-form');
// If using AJAX, we need the form plugin.
if ($view->use_ajax) {
drupal_add_js('misc/jquery.form.js');
}
views_add_js('dependent');
return $form;
}
Or, you could use a preprocess function to alter the form even before it is build. I wanted to change the text on the button, so I did this:
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
// only alter the jobs search exposed filter form
if ($vars['form']['#id'] == 'views-exposed-form-jobs-search-page-1') {
// Change the text on the submit button
$vars['form']['submit']['#value'] = t('Search');
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['button'] = drupal_render($vars['form']['submit']);
}
}
If you want the drop-down to fire, I'd use JavaScript instead of hacking the module as Eaton suggests.
Basically, you can modify the text with hook_form_alter as Eaton suggests, then use in the same hook_form_alter, add a call to drupal_add_js with your custom JS which hides the button and submits the form on the onChange handler of the select drop-down. You want that submit button there for those 10% of users for whom the JS fails.
Both of the above are fine but I found out that altering the form might not always lead to desirable results, mainly because exposed filters are themed using a specifc theme template. The proper way of changing the theme would be to override the views-exposed-form.tpl file in your theme's folder. Bear in mind that this will apply to all exposed filter forms, to theme a specific one, you will need to use a different name for that filename, like:
views-exposed-form--TITLE--DISPLAY.tpl.php
views-exposed-form--TITLE.tpl.php
and some others, you can check the Theme: Information section of your views for template naming conventions.
This module provides an auto-submit among other things http://drupal.org/project/views_hacks
This module is great to improving exposed filters http://drupal.org/project/better_exposed_filters
You should be able to use hook_form_alter() (http://api.drupal.org/api/function/hook_form_alter) to change the form as it's built, modifying the fields in question when that particular view is being displayed. You can nuke the submit button, add a #theme function that calls the drupal_add_js() function, and so on.
As long as the GET params come in the way views expect them, everything will work fine -- it was designed that way to allow bookmarking of pages with exposed filter settings, etc. The important part is to make sure you're doing the form mangling in your own module's hook_form_alter() function, so that it won't make other views driven stuff choke.

Resources