Drupal AHAH, Dynamic form expansion - drupal

Form
$form['animal'] = array(
'#type' => 'select',
'#title' => t('Animal'),
'#options' => load_animals(),
'#ahah' => array(
'event' => 'change',
'path' => 'path/to/ajax/service',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'breed-wrapper',
),
);
...
$form['breed'] = array(
'#type' => 'select',
'#title' => t('Breeds'),
'#options' => array('Select animal to load breed'),
'#prefix' => '<div id="breed-wrapper">',
'#suffix' => '</div>',
);
And following is the AHAH callback processing
$post = $_POST;
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $post['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form['#redirect'] = FALSE;
$form['#post'] = $post;
$form['#programmed'] = FALSE;
$form_state['post'] = $post;
drupal_process_form($form_id, $form, $form_state);
// New form elements
$breed_form = $form['breed'];
$options = load_breeds((int)$post['animal']);
$breed_form['#options'] = $options;
$form['breed'] = $breed_form;
form_set_cache($form_build_id, $form, $form_state);
$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
unset($breed_form['#prefix'], $breed_form['#suffix']);
// Render the new output.
$output .= drupal_render($breed_form);
drupal_json(array('status' => TRUE, 'data' => $output));
Default form submit handler
function default_form_submit(&$form, $form_state){
$clicked_button = $form_state['clicked_button']['#value'];
$values = $form_state['values'];
if($clicked_button == $values['submit']){
unset($values['op'], $values['submit'], $values['form_build_id'],
$values['form_token'], $values['form_id']);
....
drupal_goto($_REQUEST['q'], $query);
}
}
When I finally submit the form in normal post way, a validation error is reported as An illegal choice has been detected. Am I properly using form_set_cache()?
On AHAH post, the default form submission handler is also invoked. As this handler contains a redirection logic so AHAH request is collapsed. How to bypass it even-though I am doing click_button validation?

i think for your last question, use need to set $form_state['ahah_submission'] = TRUE.

Related

Drupal 8 form builder error webform custom module

can anyone guide me , I'm continuously facing this error , webform custom module Drupal 8
InvalidArgumentException: The form argument sun_webforms_usage_settings_page_form is not a valid form. in Drupal\Core\Form\FormBuilder->getFormId() (line 197 of F:\wamp\www\neo9\web\core\lib\Drupal\Core\Form\FormBuilder.php).
function neo_webforms_usage_settings_page_form($form, \Drupal\Core\Form\FormStateInterface $form_state)
{
$form = array();
$form['neo_webforms_usage_inactivity_time'] = array(
'#title' => t('Inactivity Time (seconds)'),
'#type' => 'textfield',
'#default_value' => \Drupal::state()->get('neo_webforms_usage_inactivity_time', 86400),
);
$form['neo_webforms_usage_alert_email'] = array(
'#title' => t('Alert receiver email (one per line).'),
'#type' => 'textarea',
'#default_value' => \Drupal::state()->get('neo_webforms_usage_alert_email', ""),
);
return system_settings_form($form);
}
and Controller
public function neo_webforms_usage_settings_page() {
$header = [
'#type' => 'markup',
'#markup' => t('<h4>Webform Usage Settings</h4>'),
];
$form = \Drupal::formBuilder()->getForm('neo_webforms_usage_settings_page_form');
$page = [
'header' => $header,
'form' => $form,
];
return $page;
}
}
Please anyone help me with that?
As per the official documentation of the FormBuilder getForm function, the parameter of getForm should be the Class/Instance name of the Form.
Parameters
\Drupal\Core\Form\FormInterface|string $form_arg: The value must be one of the following: The name of a class that implements \Drupal\Core\Form\FormInterface.
An instance of a class that implements \Drupal\Core\Form\FormInterface.
Try passing something like this:
$form = \Drupal::formBuilder()->getForm('\Drupal\module_name\Form\FormClassName');

Drupal 7: Insert into content type from custom module function

I created a form inside a custom module, in a drupal 7 project, and I need to insert the values into a custom content type called 'players'
Here is what I have for a form:
function custom_module_reg_form($form, $form_state){
$form['first_name'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('First Name')),
);
$form['last_name'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Last Name')),
);
$form['email_address'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Email Address')),
);
$form['state'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('State')),
);
$form['zip_code'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Zip Code')),
);
$form['phone_number'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Phone Number')),
);
$form['password'] = array(
'#type' => 'password',
'#attributes' => array('placeholder' => t('Password')),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Register',
);
return $form;
}
Here is the submit function but I am getting an error:
function custom_module_reg_form_submit($form, $form_state){
$first_name = $form_state['values']['first_name'];
$last_name = $form_state['values']['last_name'];
$email_address = $form_state['values']['email_address'];
$state = $form_state['values']['state'];
$zip_code = $form_state['values']['zip_code'];
$phone_number = $form_state['values']['phone_number'];
$password = encrypt($form_state['values']['password']);
$nid = db_insert('players')->fields(array(
'first_name' => $first_name,
'last_name' => $last_name,
'email_address' => $email_address,
'state' => $state,
'zip_code' => $zip_code,
'phone_number' => $phone_number,
'password' => $password,
'created' => REQUEST_TIME
))->execute();
// Save new node
$node = new stdClass();
// Set node title
$node->title = $email_address;
// set node type ex: article etc
$node->type = "players";
// set node language
$node->language = LANGUAGE_NONE;
//(1 or 0): published or not
$node->status = 0;
//(1 or 0): promoted to front page
$node->promote = 0;
node_object_prepare($node);
node_save($node);
}
I was following an example and I see in my logs that the table is not correct but I can't find anywhere else that gives an example. What am I doing wrong? Is it better to create a custom table for programmatically inserting from forms? Thanks and please let me know.
There are two common ways of programmatically creating nodes in Drupal 7: without or with the Entity API contributed module.
Without Entity API
$node = new stdClass();
$node->type = "players";
$node->uid = $user->uid; // makes sense to have the global $user the owner of the node
$node->language = LANGUAGE_NONE;
$node->status = 0;
$node->promote = 0;
$node->title = $email_address;
// NB: if you created the field in Drupal's UI -- it will be named "field_first_name", not "first_name"
$node->field_first_name[$node->language][]['value'] = $first_name;
// ...
$node = node_submit($node);
node_save($node);
With Entity API (more common nowadays)
// Use the Entity API to create a new object
$values = array(
'type' => 'players',
'uid' => $user->uid,
'status' => 1,
'promote' => 0,
);
$entity = entity_create('node', $values);
// Then create an entity_metadata_wrapper around the new entity.
$wrapper = entity_metadata_wrapper('node', $entity);
// Now assign values through the wrapper.
$wrapper->title->set($email_address);
$wrapper->field_first_name->set($first_name);
// ...
// Finally save the node.
$wrapper->save();
Whichever way you choose, you do not need db_insert('players'). It actually won't work, because Drupal 7 does not store the entity in a single database table.
More information about creating nodes in code can be found here.

Drupal 7 adding custom menus to pages

I have been developing with Drupal 7 for the past 4 months now, and I can't seem to find a straight answer as to how to add more menus on my pages. I understand the whole system_main_menu and system_secondary_menu, but how in the world can I add more menus to my page if I make a custom menu, let's say I have a footer_social_menu? I just love dynamic menus.
Here's what I am working with right now
function cornmaze_links($variables){
$html = '<ul>';
foreach($variables['links'] as $link){
$html .= '<li>'. l($link['title'], $link['href'], $link).'</li>';
}
$html .= '</ul>';
return $html;
}
I tried using the THEME_links($vars) function, but that affects ALL of the menus, what if I wanted to add a certain ID to a custom menu? or change the custom menu to use all divs? That's what I don't get. I can't necessarily loop through the menus using the THEME_links() function?
I don't want to put them in a block either, if I don't have to, just to avoid any extra markup that I don't need. I just want to be able to control menus, whether they be system or custom.
Any help, or light shed would be awesome! Thank you in advance!
Try menu block module. It creates your menus as blocks and highly configurable.
Here's the documentation link.
Please Check , this may be help ful for you,
function formuserentry_menu() {
$items = array();
$items['formuserentry'] = array( //this creates a URL that will call this form at "examples/form-example"
'title' => 'Entry Page',
'page callback' => array('formuserentry_view'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM
);
$items['formuserentry/application'] = array( //this creates a URL that will call this form at "examples/form-example"
'title' => 'Entry Application Forms', //page title
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed. for a form, use drupal_get_form
'page arguments' => array('formuserentry_application' , 2), //put the name of the form here
'access arguments' => array('administer your module'),
);
return $items;
}
/********** front page view ***********/
function formuserentry_view() {
$result = 'My Sub Menu URL was hit';
$header = array('Entry Id','Name', 'DOB', 'Year', 'Image' );
$rows = array();
$no_yes = array('No', 'Yes');
$results = db_query("SELECT * FROM userentryform ORDER BY userentryId DESC");
foreach ($results as $node) {
$rows[] = array(
l($node->firstname, 'formuserentry/application/'. $node->userentryId ),
array('data' => $node->firstname, 'class' => 'title'),
array('data' => $node->lastname, 'class' => 'type'),
array('data' => $node->birthyear, 'class' => 'type'),
array('data' => '<img src="sample.jpg">dff', 'class' => 'image'),
);
}
return theme('table', array('header' => $header, 'rows' => $rows));
}
/********************** add form ***************************/
function formuserentry_application($form, &$form_state, $candidateId) {
$firstname = '';
$lastname = '';
$birthyear = '';
/****** query fetch ******/
if(isset($candidateId)){
$fetchquery = db_select('userentryform', 'n')
->fields('n', array('firstname','lastname', 'birthyear'))
->fields('n')
->condition('userentryId',$candidateId)
->execute()
->fetchAll();
$firstname = $fetchquery[0]->firstname;
$lastname = $fetchquery[0]->lastname;
$birthyear = $fetchquery[0]->birthyear;
}
/**************************/
//print($fetchquery);
//drupal_set_message('<pre>'. print_r($fetchquery[0]->firstname, TRUE) .'</pre>');
$form['name'] = array(
'#type' => 'fieldset',
'#title' => t('Name'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['name']['first'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
'#required' => TRUE,
'#default_value' => $firstname,
'#description' => "Please enter your first name.",
'#size' => 20,
'#maxlength' => 20,
);
$form['name']['canid'] = array(
'#type' => 'hidden',
'#required' => FALSE,
'#default_value' => $candidateId,
'#description' => "Please enter your first name.",
'#size' => 20,
'#maxlength' => 20,
);
$form['name']['last'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#value' => $lastname,
'#required' => TRUE,
);
$form['name']['year_of_birth'] = array(
'#type' => 'textfield',
'#title' => "Year of birth",
'#description' => 'Format is "YYYY"',
'#value' => $birthyear,
'#required' => TRUE,
);
// Image upload field.
$form['name']['image'] = array(
'#type' => 'managed_file',
'#title' => 'File',
'#upload_location' => 'public://my-files/',
'#process' => array('formuserentry_my_file_element_process'),
"#upload_validators" => array('file_validate_is_image' => array())
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
/********* for validation ************/
> function formuserentry_my_file_element_process($element, &$form_state,
> $form) { $element = file_managed_file_process($element, $form_state,
> $form); $element['upload_button']['#access'] = FALSE; return
> $element; }
>
> function formuserentry_application_validate($form, &$form_state) {
> $year_of_birth = $form_state['values']['year_of_birth'];
> if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
> form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
> } }
/********** form submission ***************/
function formuserentry_application_submit($form, &$form_state) {
$first_name = $form_state['values']['first'];
$last_name = $form_state['values']['last'];
$year_of_birth = $form_state['values']['year_of_birth'];
$profileimage = $form_state['values']['image'];
$canid = $form_state['values']['canid'];
if($canid == '') {
$nid = db_insert('userentryform')
->fields(array(
'firstname' => $form_state['values']['first'],
'lastname' => $form_state['values']['last'],
'birthyear' => $form_state['values']['year_of_birth'],
'profileimage' => $form_state['values']['profileimage'],
))
->execute();
drupal_set_message(t('The form has been Added your last insert ID is => '.$nid));
} else {
$nid = db_update('userentryform')
->fields(array(
'firstname' => $form_state['values']['first'],
'lastname' => $form_state['values']['last'],
'birthyear' => $form_state['values']['year_of_birth']
))
->condition('userentryId',$canid)
->execute();
drupal_set_message(t('The form has been Updated your last insert ID is => '.$nid));
}
drupal_goto("/formuserentry/");
}

drupal field widget not saving submitted data

I'm trying to create a custom widget but when I submit, Drupal doesn't seem to save any data. When using hook_field_attach_submit() to display what data I've pasted, it is listed as null.
Strangely, if i change the #type to be a single textfield instead of a fieldset it will save only the first character of the string that has been entered.
This seems like a validation issue, but I'm not sure how to hook into it or to debug the problem. Where can I go from here?
<?php
function guide_field_widget_info(){
dpm("guide_field_widget_info");
return array(
'guide_text_textfield' => array(
'label' => t('test Text field'),
'field types' => array('text'),
'settings' => array('size' => 60),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
'default value' => FIELD_BEHAVIOR_DEFAULT,
),
)
);
}
function guide_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$field_name = $instance['field_name'];
$required = $element['#required'];
$item =& $items[$delta];
$element += array(
'#type' => 'fieldset',
'#title' => t('helloooooooo'),
);
$required = $element['#required'];
$item =& $items[$delta];
$element['nametest'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => $required,
// use #default_value to prepopulate the element
// with the current saved value
'#default_value' => isset($item['nametest']) ? $item['nametest'] : '',
);
$element['checkme'] = array(
'#title' => t('Check this box or dont'),
'#type' => 'checkbox',
'#default_value' => isset($item['checkme']) ? $item['checkme'] : '',
);
//When changing the above code to have a single field, $value is no longer null but will display the first character of the string. I've pasted the code I used to test beloe
/*
$element+= array(
'#title' => t('Name'),
'#type' => 'textfield',
'#default_value' => isset($item['nametest']) ? $item['nametest'] : '',
);
*/
return $element;
}
//hooking this here is required given that after submit, the value is a multidimensional array, whereas the expected value of text is, well, text :-)
function guide_field_attach_submit($entity_type, $entity, $form, &$form_state){
dpm($form,"guide_field_attach_submit data"); //shows $form[field_test_field][und][0] [value] as being null
}
hook_field_is_empty is mandatory and has to be implement like following:
/**
* Implements hook_field_is_empty().
*/
function MODULENAME_field_is_empty($item, $field) {
if ($field['type'] == 'FIELDTYPE') {
if (empty($item[$field['type']]['YourField']) ) {
return (TRUE);
}
}
return (FALSE);
}

Drupal - add form element on successful submission

In a Drupal custom module, I want to make $form['link_wrapper'] conditional on a successful submission of the form but this is not a very successful way of doing this. Can anyone suggest better approach.
function my_function_my_form($form_state){
//echo "-" . $form_state['post']['op'] ."-";
//die();
global $base_root;
$form = array();
$form ['query_type'] =array (
'#type' => 'radios',
'#title' => t('Select from available Queries'),
'#options' => array(
"e_commerce_orders" => t("Query1"),
"new_orders" => t("Query2"),
"cancelled_orders" => t("Query3")),
'#required' => TRUE,
);
// only show link when submitted
if($form_state['post']['op'] == 'Submit')
{
$form['link_wrapper'] = array(
'#prefix' => '<div>',
'#value' => l("Click to View file"),
'#suffix' => '</div><br><br>',
);
}
// add submit button
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'));
return $form;
}
Have you tried setting your condition in the validate hook?
Something like:
function my_function_my_form_validate($form_state){
//some condition is true
$form_state['something'] = TRUE;
}
http://api.drupal.org/api/function/hook_validate/6
This is rough. I can't remember the args for hook_validate

Resources