Example #1
0
 /**
  * Gets a form submitted via #ajax during an Ajax callback.
  *
  * This will load a form from the form cache used during Ajax operations. It
  * pulls the form info from the request body.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  *
  * @return array
  *   An array containing the $form and $form_state. Use the list() function
  *   to break these apart:
  *   @code
  *     list($form, $form_state, $form_id, $form_build_id) = $this->getForm();
  *   @endcode
  *
  * @throws Symfony\Component\HttpKernel\Exception\HttpExceptionInterface
  */
 protected function getForm(Request $request)
 {
     $form_state = \Drupal::formBuilder()->getFormStateDefaults();
     $form_build_id = $request->request->get('form_build_id');
     // Get the form from the cache.
     $form = form_get_cache($form_build_id, $form_state);
     if (!$form) {
         // If $form cannot be loaded from the cache, the form_build_id must be
         // invalid, which means that someone performed a POST request onto
         // system/ajax without actually viewing the concerned form in the browser.
         // This is likely a hacking attempt as it never happens under normal
         // circumstances.
         watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
         throw new BadRequestHttpException();
     }
     // Since some of the submit handlers are run, redirects need to be disabled.
     $form_state['no_redirect'] = TRUE;
     // When a form is rebuilt after Ajax processing, its #build_id and #action
     // should not change.
     // @see \Drupal\Core\Form\FormBuilderInterface::rebuildForm()
     $form_state['rebuild_info']['copy']['#build_id'] = TRUE;
     $form_state['rebuild_info']['copy']['#action'] = TRUE;
     // The form needs to be processed; prepare for that by setting a few internal
     // variables.
     $form_state['input'] = $request->request->all();
     $form_id = $form['#form_id'];
     return array($form, $form_state, $form_id, $form_build_id);
 }
 /**
  * {@inheritdoc}
  */
 public function view(OrderInterface $order, $view_mode)
 {
     if ($view_mode != 'customer') {
         // @todo Merge OrderUpdateForm into this plugin?
         return \Drupal::formBuilder()->getForm('\\Drupal\\uc_order\\Form\\OrderUpdateForm', $order);
     }
 }
Example #3
0
 /**
  * Tests form behaviour.
  */
 public function testActionUrlBehavior()
 {
     // Create a new request which has a request uri with multiple leading
     // slashes and make it the master request.
     $request_stack = \Drupal::service('request_stack');
     $original_request = $request_stack->pop();
     $request = Request::create($original_request->getSchemeAndHttpHost() . '//example.org');
     $request_stack->push($request);
     $form = \Drupal::formBuilder()->getForm($this);
     $markup = \Drupal::service('renderer')->renderRoot($form);
     $this->setRawContent($markup);
     $elements = $this->xpath('//form/@action');
     $action = (string) $elements[0];
     $this->assertEqual($original_request->getSchemeAndHttpHost() . '//example.org', $action);
     // Create a new request which has a request uri with a single leading slash
     // and make it the master request.
     $request_stack = \Drupal::service('request_stack');
     $original_request = $request_stack->pop();
     $request = Request::create($original_request->getSchemeAndHttpHost() . '/example.org');
     $request_stack->push($request);
     $form = \Drupal::formBuilder()->getForm($this);
     $markup = \Drupal::service('renderer')->renderRoot($form);
     $this->setRawContent($markup);
     $elements = $this->xpath('//form/@action');
     $action = (string) $elements[0];
     $this->assertEqual('/example.org', $action);
 }
 /**
  * Returns the form builder.
  *
  * @return \Drupal\Core\Form\FormBuilderInterface
  *   The form builder.
  */
 protected function formBuilder()
 {
     if (!$this->formBuilder) {
         $this->formBuilder = \Drupal::formBuilder();
     }
     return $this->formBuilder;
 }
Example #5
0
 /**
  * Form validation handler for widget elements.
  *
  * @param array $element
  *   The form element.
  * @param array $form_state
  *   The form state.
  */
 public static function validateElement(array $element, array &$form_state)
 {
     if ($element['#required'] && $element['#value'] == '_none') {
         \Drupal::formBuilder()->setError($element, $form_state, t('!name field is required.', array('!name' => $element['#title'])));
     }
     // Massage submitted form values.
     // Drupal\Core\Field\WidgetBase::submit() expects values as
     // an array of values keyed by delta first, then by column, while our
     // widgets return the opposite.
     if (is_array($element['#value'])) {
         $values = array_values($element['#value']);
     } else {
         $values = array($element['#value']);
     }
     // Filter out the 'none' option. Use a strict comparison, because
     // 0 == 'any string'.
     $index = array_search('_none', $values, TRUE);
     if ($index !== FALSE) {
         unset($values[$index]);
     }
     // Transpose selections from field => delta to delta => field.
     $items = array();
     foreach ($values as $value) {
         $items[] = array($element['#key_column'] => $value);
     }
     form_set_value($element, $items, $form_state);
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     // Return form inside block
     return $form = \Drupal::formBuilder()->getForm('Drupal\\krishna\\Form\\KrishnaForm');
     // Return simple text inside block
     return array('#type' => 'markup', '#markup' => $form);
 }
 /**
  * Page that triggers a programmatic form submission.
  *
  * Returns the validation errors triggered by the form submission as json.
  */
 public function submitFormPage()
 {
     $form_state = new FormState();
     $values = ['name' => 'robo-user', 'mail' => '*****@*****.**', 'op' => t('Submit')];
     $form_state->setValues($values);
     \Drupal::formBuilder()->submitForm('\\Drupal\\user\\Form\\UserPasswordForm', $form_state);
     return new JsonResponse($form_state->getErrors());
 }
 /**
  * {@inheritDocs}
  *
  * Validate callback for the focal point field.
  */
 public static function validateFocalPoint($element, FormStateInterface $form_state)
 {
     $field_name = array_pop($element['#parents']);
     $focal_point_value = $form_state->getValue($field_name);
     if (!is_null($focal_point_value) && !FocalPoint::validate($focal_point_value)) {
         \Drupal::formBuilder()->setError($element, $form_state, t('The !title field should be in the form "leftoffset,topoffset" where offsets are in percents. Ex: 25,75.', array('!title' => $element['#title'])));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function overview(RouteMatchInterface $route_match, $entity_type_id = NULL)
 {
     $build = parent::overview($route_match, $entity_type_id);
     if (\Drupal::entityManager()->getAccessControlHandler('tmgmt_job')->createAccess()) {
         $build = \Drupal::formBuilder()->getForm('Drupal\\tmgmt_content\\Form\\ContentTranslateForm', $build);
     }
     return $build;
 }
Example #10
0
/**
 * Renders a form with a list of available database updates.
 */
function update_selection_page()
{
    // Make sure there is no stale theme registry.
    \Drupal::cache()->deleteAll();
    $build = \Drupal::formBuilder()->getForm('Drupal\\Core\\Update\\Form\\UpdateScriptSelectionForm');
    $build['#title'] = 'Drupal database update';
    return $build;
}
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $build = [];
     $builder = \Drupal::formBuilder();
     $form = $builder->getForm('\\Drupal\\dday2015\\Form\\NodeGeneratorForm');
     $build['form'] = $form;
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function itemPage(Request $request, RouteMatchInterface $route_match, $plugin_id)
 {
     $build = parent::itemPage($request, $route_match, $plugin_id);
     if (\Drupal::entityManager()->getAccessControlHandler('tmgmt_job')->createAccess()) {
         $build = \Drupal::formBuilder()->getForm('Drupal\\tmgmt_config\\Form\\ConfigTranslateForm', $build, $plugin_id);
     }
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $build = [];
     $build['default_block_my_text_area']['#markup'] = '<p>' . $this->configuration['my_text_area'] . '</p>';
     // Add a form to block.
     $build['default_block_new_form'] = \Drupal::formBuilder()->getForm('Drupal\\add_block\\Form\\NewForm');
     return $build;
 }
Example #14
0
 /**
  * Returns an administrative overview of Imce Profiles.
  */
 public function adminOverview(Request $request)
 {
     // Build the settings form first.(may redirect)
     $output['settings_form'] = \Drupal::formBuilder()->getForm('Drupal\\imce\\Form\\ImceSettingsForm') + array('#weight' => 10);
     // Buld profile list.
     $output['profile_list'] = array('#type' => 'container', '#attributes' => array('class' => array('imce-profile-list')), 'title' => array('#markup' => '<h2>' . $this->t('Configuration Profiles') . '</h2>'), 'list' => $this->entityManager()->getListBuilder('imce_profile')->render());
     return $output;
 }
Example #15
0
 function testFormCheckbox()
 {
     // Ensure that the checked state is determined and rendered correctly for
     // tricky combinations of default and return values.
     foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
         // Only values that can be used for array indices are supported for
         // #return_value, with the exception of integer 0, which is not supported.
         // @see \Drupal\Core\Render\Element\Checkbox::processCheckbox().
         foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
             $form_array = \Drupal::formBuilder()->getForm('\\Drupal\\form_test\\Form\\FormTestCheckboxTypeJugglingForm', $default_value, $return_value);
             $form = \Drupal::service('renderer')->renderRoot($form_array);
             if ($default_value === TRUE) {
                 $checked = TRUE;
             } elseif ($return_value === '0') {
                 $checked = $default_value === '0';
             } elseif ($return_value === '') {
                 $checked = $default_value === '';
             } elseif ($return_value === 1 || $return_value === '1') {
                 $checked = $default_value === 1 || $default_value === '1';
             } elseif ($return_value === 'foobar') {
                 $checked = $default_value === 'foobar';
             } elseif ($return_value === '1foobar') {
                 $checked = $default_value === '1foobar';
             }
             $checked_in_html = strpos($form, 'checked') !== FALSE;
             $message = format_string('#default_value is %default_value #return_value is %return_value.', array('%default_value' => var_export($default_value, TRUE), '%return_value' => var_export($return_value, TRUE)));
             $this->assertIdentical($checked, $checked_in_html, $message);
         }
     }
     // Ensure that $form_state->getValues() is populated correctly for a
     // checkboxes group that includes a 0-indexed array of options.
     $results = json_decode($this->drupalPostForm('form-test/checkboxes-zero/1', array(), 'Save'));
     $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
     $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
     $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
     $edit = array('checkbox_off[0]' => '0');
     $results = json_decode($this->drupalPostForm('form-test/checkboxes-zero/1', $edit, 'Save'));
     $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
     // Ensure that each checkbox is rendered correctly for a checkboxes group
     // that includes a 0-indexed array of options.
     $this->drupalPostForm('form-test/checkboxes-zero/0', array(), 'Save');
     $checkboxes = $this->xpath('//input[@type="checkbox"]');
     $this->assertIdentical(count($checkboxes), 9, 'Correct number of checkboxes found.');
     foreach ($checkboxes as $checkbox) {
         $checked = isset($checkbox['checked']);
         $name = (string) $checkbox['name'];
         $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
     }
     $edit = array('checkbox_off[0]' => '0');
     $this->drupalPostForm('form-test/checkboxes-zero/0', $edit, 'Save');
     $checkboxes = $this->xpath('//input[@type="checkbox"]');
     $this->assertIdentical(count($checkboxes), 9, 'Correct number of checkboxes found.');
     foreach ($checkboxes as $checkbox) {
         $checked = isset($checkbox['checked']);
         $name = (string) $checkbox['name'];
         $this->assertIdentical($checked, $name == 'checkbox_off[0]' || $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
     }
 }
Example #16
0
 /**
  * Custom ajax form submission handler.
  *
  * @param array $form
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  */
 public function add(array &$form, FormStateInterface $form_state)
 {
     $context = $form_state->getValue('contexts');
     $content = \Drupal::formBuilder()->getForm($this->getContextClass(), $context, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }
Example #17
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $nid = $this->getValue($values);
     $node = node_load($nid);
     if (uc_product_is_product($node)) {
         $form = \Drupal::formBuilder()->getForm('\\Drupal\\uc_product\\Form\\AddToCartForm', $node);
         return drupal_render($form);
     }
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $nid = $this->getValue($values);
     $node = node_load($nid);
     if (uc_product_is_product($node)) {
         $form_object = new \Drupal\uc_product\Form\BuyItNowForm($node->id());
         $form = \Drupal::formBuilder()->getForm($form_object, $node);
         return drupal_render($form);
     }
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function fulfillOrder(OrderInterface $order, array $package_ids)
 {
     $shipment = new \stdClass();
     $shipment->order_id = $order->id();
     $shipment->packages = array();
     foreach ($package_ids as $id) {
         $package = Package::load($id);
         $shipment->packages[$id] = $package;
     }
     return \Drupal::formBuilder()->getForm('\\Drupal\\uc_fulfillment\\Form\\ShipmentEditForm', $order, $shipment);
 }
 /**
  * View a MailChimp signup form as a page.
  *
  * @param string $signup_id
  *   The ID of the MailchimpSignup entity to view.
  *
  * @return array
  *   Renderable array of page content.
  */
 public function page($signup_id)
 {
     $content = array();
     $signup = mailchimp_signup_load($signup_id);
     $form = new \Drupal\mailchimp_signup\Form\MailchimpSignupPageForm();
     $form_id = 'mailchimp_signup_subscribe_page_' . $signup->id . '_form';
     $form->setFormID($form_id);
     $form->setSignup($signup);
     $content = \Drupal::formBuilder()->getForm($form);
     return $content;
 }
Example #21
0
 /**
  * Tests the form cache without a logged-in user.
  */
 function testNoCacheToken()
 {
     $this->container->set('current_user', new UserSession(array('uid' => 0)));
     $this->form_state->set('example', $this->randomMachineName());
     \Drupal::formBuilder()->setCache($this->form_build_id, $this->form, $this->form_state);
     $cached_form_state = new FormState();
     $cached_form = \Drupal::formBuilder()->getCache($this->form_build_id, $cached_form_state);
     $this->assertEqual($this->form['#property'], $cached_form['#property']);
     $this->assertTrue(empty($cached_form['#cache_token']), 'Form has no cache token');
     $this->assertEqual($this->form_state->get('example'), $cached_form_state->get('example'));
 }
 public function add(array &$form, FormStateInterface $form_state)
 {
     $condition = $form_state->getValue('conditions');
     $content = \Drupal::formBuilder()->getForm($this->getConditionClass(), $condition, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     list(, $route_parameters) = $this->getOperationsRouteInfo($this->machine_name, $form_state->getValue('conditions'));
     $content['submit']['#attached']['drupalSettings']['ajax'][$content['submit']['#id']]['url'] = $this->url($this->getAddRoute(), $route_parameters, ['query' => [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]]);
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }
 public function photos_access_page(\Drupal\node\NodeInterface $node) {
   if ($node) {
     $pass_form = \Drupal::formBuilder()->getForm('\Drupal\photos_access\Form\PhotosAccessPasswordForm', $node);
     $output = drupal_render($pass_form);
     return array(
       '#markup' => $output
     );
   }
   else {
     throw new NotFoundHttpException();
   }
 }
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $form = \Drupal::formBuilder()->getForm('\\Drupal\\page_example\\Form\\PageExampleForm');
     //var_dump($form);
     //exit();
     return $form;
     /*
         return [
           '#type' => 'markup',
           '#markup' => $form,
         ];*/
 }
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $signup_id = $this->getDerivativeId();
     /* @var $signup \Drupal\mailchimp_signup\Entity\MailchimpSignup */
     $signup = mailchimp_signup_load($signup_id);
     $form = new \Drupal\mailchimp_signup\Form\MailchimpSignupPageForm();
     $form_id = 'mailchimp_signup_subscribe_block_' . $signup->id . '_form';
     $form->setFormID($form_id);
     $form->setSignup($signup);
     $content = \Drupal::formBuilder()->getForm($form);
     return $content;
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     // Get the current node.
     $node = \Drupal::routeMatch()->getParameter('node');
     // Build the field quiz answer form
     $form_object = new FieldQuizAnswerForm($node, $items);
     $form = \Drupal::formBuilder()->getForm($form_object);
     $elements = array();
     // Add the output to the node.
     $elements[] = $build['field_quiz'] = ['#theme' => 'field_quiz_question_view', '#form' => $form];
     return $elements;
 }
 function er_browser_widget_search_content(array &$form, FormStateInterface $form_state)
 {
     $form = \Drupal::formBuilder()->getForm('Drupal\\er_browser_widget\\Form\\EntityReferenceBrowserWidgetForm');
     $response = new AjaxResponse();
     $title = $this->t('Entity Search and Reference.');
     $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response->setAttachments($form['#attached']);
     $content = views_embed_view('entity_reference_browser_widget');
     $options = array('dialogClass' => 'test-dialog', 'width' => '75%');
     $modal = new OpenModalDialogCommand($title, $form, $options);
     $response->addCommand($modal);
     return $response;
 }
 /**
  * @todo Remove ajax_test_dialog().
  */
 public function dialog()
 {
     // Add two wrapper elements for testing non-modal dialogs. Modal dialogs use
     // the global drupal-modal wrapper by default.
     $build['dialog_wrappers'] = array('#markup' => '<div id="ajax-test-dialog-wrapper-1"></div><div id="ajax-test-dialog-wrapper-2"></div>');
     // Dialog behavior applied to a button.
     $build['form'] = \Drupal::formBuilder()->getForm('Drupal\\ajax_test\\Form\\AjaxTestDialogForm');
     // Dialog behavior applied to a #type => 'link'.
     $build['link'] = array('#type' => 'link', '#title' => 'Link 1 (modal)', '#href' => 'ajax-test/dialog-contents', '#attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-modal'));
     // Dialog behavior applied to links rendered by links.html.twig.
     $build['links'] = array('#theme' => 'links', '#links' => array('link2' => array('title' => 'Link 2 (modal)', 'href' => 'ajax-test/dialog-contents', 'attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-modal', 'data-dialog-options' => json_encode(array('width' => 400)))), 'link3' => array('title' => 'Link 3 (non-modal)', 'href' => 'ajax-test/dialog-contents', 'attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-dialog', 'data-dialog-options' => json_encode(array('target' => 'ajax-test-dialog-wrapper-1', 'width' => 800)))), 'link4' => array('title' => 'Link 4 (close non-modal if open)', 'href' => 'ajax-test/dialog-close', 'attributes' => array('class' => array('use-ajax'))), 'link5' => array('title' => 'Link 5 (form)', 'href' => 'ajax-test/dialog-form', 'attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-modal')), 'link6' => array('title' => 'Link 6 (entity form)', 'href' => 'admin/structure/contact/add', 'attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-modal', 'data-dialog-options' => json_encode(array('width' => 800, 'height' => 500)))), 'link7' => array('title' => 'Link 7 (non-modal, no target)', 'href' => 'ajax-test/dialog-contents', 'attributes' => array('class' => array('use-ajax'), 'data-accepts' => 'application/vnd.drupal-dialog', 'data-dialog-options' => json_encode(array('width' => 800))))));
     return $build;
 }
Example #29
0
 /**
  * Retrieves, populates, and processes a form.
  *
  * @param string $class
  *   Defines a class.
  *
  * @param array $params
  *  HTTP request parameters.
  *
  * @return mixed
  *   Form values or errors | undefined
  */
 public function submitForm($class, $params)
 {
     // Create FormState instance, set values, and submit.
     $form_state = (new FormState())->setValues($params);
     \Drupal::formBuilder()->submitForm($class, $form_state);
     if ($form_state->hasAnyErrors()) {
         // Returns an associative array of error messages.
         return array('error' => $form_state->getErrors());
     } else {
         // Returns the submitted and sanitized form values.
         return array('data' => $form_state->getValues());
     }
 }
 /**
  * Tests altering of the configuration translation forms.
  */
 public function testConfigTranslationFormAlter()
 {
     $form_builder = \Drupal::formBuilder();
     $add_form = $form_builder->getForm('Drupal\\config_translation\\Form\\ConfigTranslationAddForm', \Drupal::request(), $this->pluginId, $this->langcode);
     $edit_form = $form_builder->getForm('Drupal\\config_translation\\Form\\ConfigTranslationEditForm', \Drupal::request(), $this->pluginId, $this->langcode);
     // Test that hook_form_BASE_FORM_ID_alter() was called for the base form ID
     // 'config_translation_form'.
     $this->assertTrue($add_form['#base_altered']);
     $this->assertTrue($edit_form['#base_altered']);
     // Test that hook_form_FORM_ID_alter() was called for the form IDs
     // 'config_translation_add_form' and 'config_translation_edit_form'.
     $this->assertTrue($add_form['#altered']);
     $this->assertTrue($edit_form['#altered']);
 }