/** * Processes an Ajax form submission. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return mixed * Whatever is returned by the triggering element's #ajax['callback'] * function. One of: * - A render array containing the new or updated content to return to the * browser. This is commonly an element within the rebuilt form. * - A \Drupal\Core\Ajax\AjaxResponse object containing commands for the * browser to process. * * @throws \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface */ public function content(Request $request) { /** @var $ajaxForm \Drupal\system\FileAjaxForm */ $ajaxForm = $this->getForm($request); $form = $ajaxForm->getForm(); $form_state = $ajaxForm->getFormState(); $commands = $ajaxForm->getCommands(); drupal_process_form($form['#form_id'], $form, $form_state); // We need to return the part of the form (or some other content) that needs // to be re-rendered so the browser can update the page with changed content. // Since this is the generic menu callback used by many Ajax elements, it is // up to the #ajax['callback'] function of the element (may or may not be a // button) that triggered the Ajax request to determine what needs to be // rendered. $callback = NULL; /** @var $form_state \Drupal\Core\Form\FormStateInterface */ if ($triggering_element = $form_state->getTriggeringElement()) { $callback = $triggering_element['#ajax']['callback']; } $callback = $form_state->prepareCallback($callback); if (empty($callback) || !is_callable($callback)) { throw new HttpException(500, t('Internal Server Error')); } /** @var \Drupal\Core\Ajax\AjaxResponse $response */ $response = call_user_func_array($callback, [&$form, &$form_state]); foreach ($commands as $command) { $response->addCommand($command, TRUE); } return $response; }
/** * Function to create a user in Drupal. * * @param array $params associated array * @param string $mail email id for cms user * * @return uid if user exists, false otherwise * * @access public * */ function createUser(&$params, $mail) { $form_state = array(); $form_state['input'] = array('name' => $params['cms_name'], 'mail' => $params[$mail], 'op' => 'Create new account'); $admin = user_access('administer users'); if (!variable_get('user_email_verification', TRUE) || $admin) { $form_state['input']['pass'] = array('pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']); } $form_state['rebuild'] = FALSE; $form_state['programmed'] = TRUE; $form_state['method'] = 'post'; $form_state['build_info']['args'] = array(); $config = CRM_Core_Config::singleton(); // we also need to redirect b $config->inCiviCRM = TRUE; $form = drupal_retrieve_form('user_register_form', $form_state); $form_state['process_input'] = 1; $form_state['submitted'] = 1; drupal_process_form('user_register_form', $form, $form_state); $config->inCiviCRM = FALSE; if (form_get_errors()) { return FALSE; } else { return $form_state['user']->uid; } }
/** * Processes AJAX file uploads and deletions. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Drupal\Core\Ajax\AjaxResponse * An AjaxResponse object. */ public function upload(Request $request) { $form_parents = explode('/', $request->query->get('element_parents')); $form_build_id = $request->query->get('form_build_id'); $request_form_build_id = $request->request->get('form_build_id'); if (empty($request_form_build_id) || $form_build_id !== $request_form_build_id) { // Invalid request. drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error'); $response = new AjaxResponse(); $status_messages = array('#theme' => 'status_messages'); return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages))); } try { /** @var $ajaxForm \Drupal\system\FileAjaxForm */ $ajaxForm = $this->getForm($request); $form = $ajaxForm->getForm(); $form_state = $ajaxForm->getFormState(); $commands = $ajaxForm->getCommands(); } catch (HttpExceptionInterface $e) { // Invalid form_build_id. drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error'); $response = new AjaxResponse(); $status_messages = array('#theme' => 'status_messages'); return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages))); } // Get the current element and count the number of files. $current_element = NestedArray::getValue($form, $form_parents); $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0; // Process user input. $form and $form_state are modified in the process. drupal_process_form($form['#form_id'], $form, $form_state); // Retrieve the element to be rendered. $form = NestedArray::getValue($form, $form_parents); // Add the special Ajax class if a new file was added. if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) { $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content'; } else { $form['#suffix'] .= '<span class="ajax-new-content"></span>'; } $status_messages = array('#theme' => 'status_messages'); $form['#prefix'] .= drupal_render($status_messages); $output = drupal_render($form); drupal_process_attached($form); $js = _drupal_add_js(); $settings = drupal_merge_js_settings($js['settings']['data']); $response = new AjaxResponse(); foreach ($commands as $command) { $response->addCommand($command, TRUE); } return $response->addCommand(new ReplaceCommand(NULL, $output, $settings)); }
/** * Processes an Ajax form submission. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return mixed * Whatever is returned by the triggering element's #ajax['callback'] * function. One of: * - A render array containing the new or updated content to return to the * browser. This is commonly an element within the rebuilt form. * - A \Drupal\Core\Ajax\AjaxResponse object containing commands for the * browser to process. * * @throws \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface */ public function content(Request $request) { list($form, $form_state) = $this->getForm($request); drupal_process_form($form['#form_id'], $form, $form_state); // We need to return the part of the form (or some other content) that needs // to be re-rendered so the browser can update the page with changed content. // Since this is the generic menu callback used by many Ajax elements, it is // up to the #ajax['callback'] function of the element (may or may not be a // button) that triggered the Ajax request to determine what needs to be // rendered. if (!empty($form_state['triggering_element'])) { $callback = $form_state['triggering_element']['#ajax']['callback']; } if (empty($callback) || !is_callable($callback)) { throw new HttpException(500, t('Internal Server Error')); } return call_user_func_array($callback, array(&$form, &$form_state)); }
/** * Function to create a user in Drupal. * * @param array $params associated array * @param string $mail email id for cms user * * @return uid if user exists, false otherwise * * @access public * */ function createUser(&$params, $mail) { $form_state = form_state_defaults(); $form_state['input'] = array('name' => $params['cms_name'], 'mail' => $params[$mail], 'op' => 'Create new account'); $admin = user_access('administer users'); if (!variable_get('user_email_verification', TRUE) || $admin) { $form_state['input']['pass'] = array('pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']); } if (!empty($params['notify'])) { $form_state['input']['notify'] = $params['notify']; } $form_state['rebuild'] = FALSE; $form_state['programmed'] = TRUE; $form_state['complete form'] = FALSE; $form_state['method'] = 'post'; $form_state['build_info']['args'] = array(); /* * if we want to submit this form more than once in a process (e.g. create more than one user) * we must force it to validate each time for this form. Otherwise it will not validate * subsequent submissions and the manner in which the password is passed in will be invalid * */ $form_state['must_validate'] = TRUE; $config = CRM_Core_Config::singleton(); // we also need to redirect b $config->inCiviCRM = TRUE; $form = drupal_retrieve_form('user_register_form', $form_state); $form_state['process_input'] = 1; $form_state['submitted'] = 1; $form['#array_parents'] = array(); $form['#tree'] = FALSE; drupal_process_form('user_register_form', $form, $form_state); $config->inCiviCRM = FALSE; if (form_get_errors()) { return FALSE; } return $form_state['user']->uid; }
/** * Function to create a user in Drupal. * * @param array $params associated array * @param string $mail email id for cms user * * @return uid if user exists, false otherwise * * @access public */ function createUser(&$params, $mail) { $form_state = array(); $form_state['values'] = array('name' => $params['cms_name'], 'mail' => $params[$mail], 'op' => 'Create new account'); if (!variable_get('user_email_verification', TRUE)) { $form_state['values']['pass']['pass1'] = $params['cms_pass']; $form_state['values']['pass']['pass2'] = $params['cms_pass']; } $config = CRM_Core_Config::singleton(); // we also need to redirect b $config->inCiviCRM = TRUE; $form = drupal_retrieve_form('user_register', $form_state); $form['#post'] = $form_state['values']; drupal_prepare_form('user_register', $form, $form_state); // remove the captcha element from the form prior to processing unset($form['captcha']); drupal_process_form('user_register', $form, $form_state); $config->inCiviCRM = FALSE; if (form_get_errors() || !isset($form_state['user'])) { return FALSE; } return $form_state['user']->uid; }
/** * Check several empty values for required forms elements. * * Carriage returns, tabs, spaces, and unchecked checkbox elements are not * valid content for a required field. * * If the form field is found in form_get_errors() then the test pass. */ function testRequiredFields() { // Originates from http://drupal.org/node/117748 // Sets of empty strings and arrays. $empty_strings = array('""' => "", '"\\n"' => "\n", '" "' => " ", '"\\t"' => "\t", '" \\n\\t "' => " \n\t ", '"\\n\\n\\n\\n\\n"' => "\n\n\n\n\n"); $empty_arrays = array('array()' => array()); $empty_checkbox = array(NULL); $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield'); $elements['textfield']['empty_values'] = $empty_strings; $elements['telephone']['element'] = array('#title' => $this->randomName(), '#type' => 'tel'); $elements['telephone']['empty_values'] = $empty_strings; $elements['url']['element'] = array('#title' => $this->randomName(), '#type' => 'url'); $elements['url']['empty_values'] = $empty_strings; $elements['search']['element'] = array('#title' => $this->randomName(), '#type' => 'search'); $elements['search']['empty_values'] = $empty_strings; $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password'); $elements['password']['empty_values'] = $empty_strings; $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm'); // Provide empty values for both password fields. foreach ($empty_strings as $key => $value) { $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value); } $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea'); $elements['textarea']['empty_values'] = $empty_strings; $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName())); $elements['radios']['empty_values'] = $empty_arrays; $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE); $elements['checkbox']['empty_values'] = $empty_checkbox; $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName())); $elements['checkboxes']['empty_values'] = $empty_arrays; $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName())); $elements['select']['empty_values'] = $empty_strings; $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file'); $elements['file']['empty_values'] = $empty_strings; // Regular expression to find the expected marker on required elements. $required_marker_preg = '@<.*?class=".*?form-required.*?">@'; // Go through all the elements and all the empty values for them. foreach ($elements as $type => $data) { foreach ($data['empty_values'] as $key => $empty) { foreach (array(TRUE, FALSE) as $required) { $form_id = $this->randomName(); $form = array(); $form_state = \Drupal::formBuilder()->getFormStateDefaults(); $form['op'] = array('#type' => 'submit', '#value' => t('Submit')); $element = $data['element']['#title']; $form[$element] = $data['element']; $form[$element]['#required'] = $required; $form_state['input'][$element] = $empty; $form_state['input']['form_id'] = $form_id; $form_state['build_info']['callback_object'] = new StubForm($form_id, $form); $form_state['method'] = 'post'; // The form token CSRF protection should not interfere with this test, // so we bypass it by setting the token to FALSE. $form['#token'] = FALSE; \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state); drupal_process_form($form_id, $form, $form_state); $errors = form_get_errors($form_state); // Form elements of type 'radios' throw all sorts of PHP notices // when you try to render them like this, so we ignore those for // testing the required marker. // @todo Fix this work-around (http://drupal.org/node/588438). $form_output = $type == 'radios' ? '' : drupal_render($form); if ($required) { // Make sure we have a form error for this element. $this->assertTrue(isset($errors[$element]), "Check empty({$key}) '{$type}' field '{$element}'"); if (!empty($form_output)) { // Make sure the form element is marked as required. $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '{$type}' field is marked as required"); } } else { if (!empty($form_output)) { // Make sure the form element is *not* marked as required. $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '{$type}' field is not marked as required"); } if ($type == 'select') { // Select elements are going to have validation errors with empty // input, since those are illegal choices. Just make sure the // error is not "field is required". $this->assertTrue(empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE, "Optional '{$type}' field '{$element}' is not treated as a required element"); } else { // Make sure there is *no* form error for this element. $this->assertTrue(empty($errors[$element]), "Optional '{$type}' field '{$element}' has no errors with empty input"); } } } } } // Clear the expected form error messages so they don't appear as exceptions. drupal_get_messages(); }
/** * Tests \Drupal\Core\Entity\Display\EntityFormDisplayInterface::extractFormValues(). */ function testEntityFormDisplayExtractFormValues() { $this->createFieldWithStorage('_2'); $entity_type = 'entity_test'; $entity_init = entity_create($entity_type, array('id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->bundle)); // Build the form for all fields. $display = entity_get_form_display($entity_type, $this->fieldTestData->field->bundle, 'default'); $form = array(); $form_state = new FormState(); $display->buildForm($entity_init, $form, $form_state); // Simulate incoming values. // First field. $values = array(); $weights = array(); for ($delta = 0; $delta < $this->fieldTestData->field_storage->getCardinality(); $delta++) { $values[$delta]['value'] = mt_rand(1, 127); // Assign random weight. do { $weight = mt_rand(0, $this->fieldTestData->field_storage->getCardinality()); } while (in_array($weight, $weights)); $weights[$delta] = $weight; $values[$delta]['_weight'] = $weight; } // Leave an empty value. 'field_test' fields are empty if empty(). $values[1]['value'] = 0; // Second field. $values_2 = array(); $weights_2 = array(); for ($delta = 0; $delta < $this->fieldTestData->field_storage_2->getCardinality(); $delta++) { $values_2[$delta]['value'] = mt_rand(1, 127); // Assign random weight. do { $weight = mt_rand(0, $this->fieldTestData->field_storage_2->getCardinality()); } while (in_array($weight, $weights_2)); $weights_2[$delta] = $weight; $values_2[$delta]['_weight'] = $weight; } // Leave an empty value. 'field_test' fields are empty if empty(). $values_2[1]['value'] = 0; // Pretend the form has been built. $form_state->setFormObject(\Drupal::entityManager()->getFormObject($entity_type, 'default')); \Drupal::formBuilder()->prepareForm('field_test_entity_form', $form, $form_state); drupal_process_form('field_test_entity_form', $form, $form_state); $form_state->setValue($this->fieldTestData->field_name, $values); $form_state->setValue($this->fieldTestData->field_name_2, $values_2); // Extract values for all fields. $entity = clone $entity_init; $display->extractFormValues($entity, $form, $form_state); asort($weights); asort($weights_2); $expected_values = array(); $expected_values_2 = array(); foreach ($weights as $key => $value) { if ($key != 1) { $expected_values[] = array('value' => $values[$key]['value']); } } $this->assertIdentical($entity->{$this->fieldTestData->field_name}->getValue(), $expected_values, 'Submit filters empty values'); foreach ($weights_2 as $key => $value) { if ($key != 1) { $expected_values_2[] = array('value' => $values_2[$key]['value']); } } $this->assertIdentical($entity->{$this->fieldTestData->field_name_2}->getValue(), $expected_values_2, 'Submit filters empty values'); // Call EntityFormDisplayInterface::extractFormValues() for a single field (the second field). foreach ($display->getComponents() as $name => $options) { if ($name != $this->fieldTestData->field_name_2) { $display->removeComponent($name); } } $entity = clone $entity_init; $display->extractFormValues($entity, $form, $form_state); $expected_values_2 = array(); foreach ($weights_2 as $key => $value) { if ($key != 1) { $expected_values_2[] = array('value' => $values_2[$key]['value']); } } $this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'The first field is empty in the entity object'); $this->assertIdentical($entity->{$this->fieldTestData->field_name_2}->getValue(), $expected_values_2, 'Submit filters empty values'); }
/** * All this is required so drupal will call dw_campaigns_user_login_submit() */ $form_id = 'dw_campaigns_user_login_form'; $form = dw_campaigns_user_login_form(); $form_build_id = 'form-'. md5(uniqid(mt_rand(), true)); $form['#build_id'] = $form_build_id; if(count($_POST) > 0) { $form['#post'] = $_POST; } $form_state = array('storage' => NULL, 'submitted' => FALSE); drupal_prepare_form($form_id, $form, $form_state); drupal_process_form($form_id, $form, $form_state); //remove labels unset($form['name']['#title']); unset($form['pass']['#title']); ?> <h2><?php echo t('Fundraiser Login'); ?></h2> <?php if(isset($_REQUEST['create'])) { echo '<p>' . t('You must have an account to create a fundraising page.') . '</p>'; echo '<p>' . t('Please login below or create an account now '); echo l(t('Sign Up'), 'dw/user/register'); echo '</p>'; } ?>
/** * Helper function for the option check test to submit a form while collecting errors. * * @param $form_element * A form element to test. * @param $edit * An array containing post data. * * @return * An array containing the processed form, the form_state and any errors. */ private function formSubmitHelper($form, $edit) { $form_id = $this->randomMachineName(); $form_state = new FormState(); $form['op'] = array('#type' => 'submit', '#value' => t('Submit')); // The form token CSRF protection should not interfere with this test, so we // bypass it by setting the token to FALSE. $form['#token'] = FALSE; $form_state['input'] = $edit; $form_state['input']['form_id'] = $form_id; $form_state['build_info']['callback_object'] = new StubForm($form_id, $form); \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state); drupal_process_form($form_id, $form, $form_state); $errors = form_get_errors($form_state); // Clear errors and messages. drupal_get_messages(); $form_state['errors'] = array(); // Return the processed form together with form_state and errors // to allow the caller lowlevel access to the form. return array($form, $form_state, $errors); }
<h2 class="support-the-cause"><?php echo t('Donate to a Walker'); ?></h2> <p><?php echo t('Support a participant in this walk.'); ?></p> <form action="<?php echo $search_url; ?>" method="post"> <?php $formId = 'dw_campaigns_user_search_dummy_form'; $form = dw_campaigns_user_search_dummy_form($campaign_id); $form['#build_id'] = 'form-'. md5(uniqid(mt_rand(), true)); if(count($_POST) > 0) { $form['#post'] = $_POST; } $formState = array('storage' => NULL, 'submitted' => FALSE); drupal_prepare_form($formId, $form, $formState); drupal_process_form($formId, $form, $formState); echo drupal_render($form['query']); echo drupal_render($form['form_id']); echo drupal_render($form['form_build_id']); echo drupal_render($form['submit']); ?> </form> </li> <li class="city"> <!-- <h2 class="raise-money-host"></h2> --> <span><?php echo t('Don\'t see your city in the list? !urlstart Click here to host a Walk !urlend in Your City', array('!urlstart' => '<a href="/dw/walking/host" class="">', '!urlend' => '</a>')); ?></span> </li> <li class="contest"> <a href="/content/oss-contest-rules"><?php echo t('Join Our May Awareness Campaign'); ?></a> <span class="content-words"><?php echo t('Find out how you can win an iPAD 2!'); ?></span>
/** * Add domain * * URL: http://guifi.net/guifi/js/add-domain */ function guifi_ahah_add_domain() { $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_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); $textfields = $form['domain_type_form']; $output = drupal_render($textfields); // Final rendering callback. print drupal_json(array('status' => TRUE, 'data' => $output)); exit; }
/** * This is a re-implementation of drupal_get_form, which returns the form_build_id along with the rendred form */ function _nodereferrer_create_get_form($form_id) { $form_state = array('storage' => NULL, 'submitted' => FALSE); $args = func_get_args(); $cacheable = FALSE; if (isset($_SESSION['batch_form_state'])) { // We've been redirected here after a batch processing : the form has // already been processed, so we grab the post-process $form_state value // and move on to form display. See _batch_finished() function. $form_state = $_SESSION['batch_form_state']; unset($_SESSION['batch_form_state']); } else { // If the incoming $_POST contains a form_build_id, we'll check the // cache for a copy of the form in question. If it's there, we don't // have to rebuild the form to proceed. In addition, if there is stored // form_state data from a previous step, we'll retrieve it so it can // be passed on to the form processing code. if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) { $form = form_get_cache($_POST['form_build_id'], $form_state); } // If the previous bit of code didn't result in a populated $form // object, we're hitting the form for the first time and we need // to build it from scratch. if (!isset($form)) { $form_state['post'] = $_POST; // Use a copy of the function's arguments for manipulation $args_temp = $args; $args_temp[0] =& $form_state; array_unshift($args_temp, $form_id); $form = call_user_func_array('drupal_retrieve_form', $args_temp); $form_build_id = 'form-' . md5(mt_rand()); $form['#build_id'] = $form_build_id; drupal_prepare_form($form_id, $form, $form_state); // Store a copy of the unprocessed form for caching and indicate that it // is cacheable if #cache will be set. $original_form = $form; $cacheable = TRUE; unset($form_state['post']); } $form['#post'] = $_POST; // Now that we know we have a form, we'll process it (validating, // submitting, and handling the results returned by its submission // handlers. Submit handlers accumulate data in the form_state by // altering the $form_state variable, which is passed into them by // reference. drupal_process_form($form_id, $form, $form_state); if ($cacheable && !empty($form['#cache'])) { // Caching is done past drupal_process_form so #process callbacks can // set #cache. By not sending the form state, we avoid storing // $form_state['storage']. form_set_cache($form_build_id, $original_form, NULL); } } // Most simple, single-step forms will be finished by this point -- // drupal_process_form() usually redirects to another page (or to // a 'fresh' copy of the form) once processing is complete. If one // of the form's handlers has set $form_state['redirect'] to FALSE, // the form will simply be re-rendered with the values still in its // fields. // // If $form_state['storage'] or $form_state['rebuild'] have been // set by any submit or validate handlers, however, we know that // we're in a complex multi-part process of some sort and the form's // workflow is NOT complete. We need to construct a fresh copy of // the form, passing in the latest $form_state in addition to any // other variables passed into drupal_get_form(). if (!empty($form_state['rebuild']) || !empty($form_state['storage'])) { $form = drupal_rebuild_form($form_id, $form_state, $args); } // If we haven't redirected to a new location by now, we want to // render whatever form array is currently in hand. return array('form_build_id' => $form['#build_id'], 'form' => drupal_render_form($form_id, $form)); }