How can I get the title of a form element in Drupal? - 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']));
}
}
?>

Related

Drupal 7 Views custom view template fields

I've successfully created a custom view template for my Drupal 7 site but am having issues adding attributes to the content which is outputted. I've searched high and low for the answer to this but to no avail.
I have a view called: views-view-fields--homepage-articles.tpl.php
I am printing content like :
$fields['title']->content
This is fine and expected, and outputs:
Title
But I want to add classes to it - how? I'm thinking I need to write a hook, but I cannot find this documented anywhere. At the moment my solution is a string replace:
<?php print str_replace('<a ', '<a class="brand-blue uppercase nodecoration"', $fields['title']->content); ?>
As you can imagine, this is not a satisfactory or long-term solution.
Many thanks!
You should be able to add the classes to the field using template_preprocess_views_view_fields().
Edit: Couldn't do it the way I thought, but you can overwrite the output of the field like so:
function MY_THEME_preprocess_views_view_fields(&$vars) {
$view = $vars['view'];
if ($view->name == 'node_listing') {
foreach ($vars['fields'] as $id => $field) {
if ($id == 'title') {
$field_output = l($view->result[$view->row_index]->node_title, 'node/'. $view->result[$view->row_index]->nid, array('attributes' => array('class' => 'brand-blue uppercase nodecoration')));
$vars['fields'][$id]->content = $field_output;
}
}
}
}
Have you tried using Semantic Views? https://drupal.org/project/semanticviews - that way you can override the classes within the UI instead of template files, may suit your needs better.

Change form data after submit in drupal

in some content type form I added a checkbox. When this checkbox is checked I want to remove some of the submitted data.
To do so I created a custom module (my_module.module):
function my_module_form_alter(&$form, &$form_state) {
// ...
$form['#submit'][] = 'my_module_form_alter_submit';
}
function my_module_form_alter_submit($form_id, $form_values) {
drupal_set_message(t('Submit Function Executed!'));
}
How can I tell this module to refer only to the form of a certain containt type? And how can I remove data when it is submitted?
Assuming you are altering a node edit form, you can either conditionally add the submit callback such as (in your hook_form_alter):
if(isset($form['#node']) && $form['type']['#value'] == 'page') {
$form['#submit'][] = 'my_module_form_alter_submit';
}
or, you could check the $form argument in the submit callback in a similar fashion.
You are missing the third argument to the hook_form_alter which should be $form_id, and your submit callback should take the arguments such as:
function my_module_form_alter_submit($form, &$form_state) { ... }
See also:
http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_form_alter/6
http://api.drupal.org/api/drupal/developer%21topics%21forms_api.html/6
To remove data after the submit, in your form_alter function, just use unset() on the form field. unset($form['my-field']);

Get $node variable in html.tpl.php - Drupal 7

I'm trying to allow users to update head titles and meta descriptions for each page. I thought that an easy way to achieve this would be to add a field to the 'Basic page' content type for the page title, then check if that field is not empty in html.tpl.php and if it is not, override $head_title with this user-defined value.
However, it appears that the $node variable is not available in html.tpl.php. Can anyone suggest a way for me to make this data available in this template file, or alternatively, alter $head_title before it is sent to html.tpl.php? Thanks for reading.
Taken in part from this thread that I found: http://drupal.org/node/1041768...
In your template.php, you can do the following:
function yourtheme_preprocess_html(&$variables) {
// If on an individual node page, add the node type to body classes.
if ($node = menu_get_object()) {
$variables['head_title'] = $node-> // find your cck field here
}
}
Bit messy, but would work:
if(arg(0) == 'node' && !empty(arg(1))) {
$node = node_load(arg(1));
}
However, you might prefer http://drupal.org/project/metatags_quick (an interrim module until the full http://drupal.org/project/metatags is finished).

Drupal hook_form_alter for Taxonomy admin

I created a module to do all my form altering called "form_mods". It's working for most situations but not for the Taxonomy page.
I'm targeting the form id of "taxonomy_overview_vocabularies". I'm trying to hide the link "edit vocabulary" for roles of "webmaster" and "dj".
My code is unsetting the $form array correctly, but Drupal is still displaying the "edit vocabulary" link.
function form_mods_form_alter($form, $form_state, $form_id) {
if($form_id == 'taxonomy_overview_vocabularies'){
global $user;
$hide=0;
$hideArray = array('webmaster', 'dj');
foreach($user->roles AS $key => $value){
if(in_array($value, $hideArray)){
$hide++;
}
}
if($hide){
foreach($form AS $vocab){
//print_r($vocab);
if(isset($vocab['edit']['#value'])){
unset($vocab['edit']['#value']);
}
}
}
}
}
Very small PHP mistake,
when you want to change array members in a for each statement you have to pass them by reference & foreach($form AS &$vocab) otherwise the $vocab would be just a copy of the array
foreach($form AS &$vocab){
//print_r($vocab);
if(isset($vocab['edit']['#value'])){
unset($vocab['edit']['#value']);
}
}
In addition to Amjad's answer, if you don't like using references, I would suggest another alternative:
foreach ($form as $key => $vocab) {
unset($form[$key]['edit']['#value']);
}
This way you avoid using references, and potential issues they may lead to.
Also note I removed the if statement, which is not useful (PHP can figure it out).
An array_map could also be considered.

populate a form programmatically in 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

Resources