Example #1
0
  /**
   * Test the basic settings.
   */
  public function testBasicSettings() {
    $manage_display = '/admin/structure/types/manage/article/display';
    $this->drupalGet($manage_display);
    $this->drupalPostAjaxForm(NULL, [], 'body_settings_edit');

    $this->drupalPostAjaxForm(NULL, [
      'fields[body][label]' => 'above',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_field_tag]' => 'article',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_field_classes]' => 'my-field-class',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_field_item_tag]' => 'code',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_field_item_classes]' => 'my-field-item-class',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_label_tag]' => 'h2',
      'fields[body][settings_edit_form][third_party_settings][fences][fences_label_classes]' => 'my-label-class',
    ], ['body_plugin_settings_update' => 'Update']);
    $this->drupalPostForm(NULL, [], 'Save');

    $expected_field_markup = <<<EOD
      <article class="my-field-class clearfix text-formatted field field--name-body field--type-text-with-summary field--label-above field__items">
        <h2 class="my-label-class field__label">Body</h2>
        <code class="my-field-item-class field__item">
          <p>Body field value.</p>
        </code>
      </article>
EOD;

    $page = $this->drupalGet('/node/' . $this->node->id());
    $this->assertTrue(strpos($this->stripWhitespace($page), $this->stripWhitespace($expected_field_markup)) !== FALSE, 'Found the correct field markup on the page.');
  }
 /**
  * {@inheritdoc}
  */
 public function access(Route $route, AccountInterface $account, NodeInterface $node = NULL)
 {
     if ($node->bundle() && \Drupal::config('webform.settings')->get('node_' . $node->bundle())) {
         return AccessResult::allowed();
     }
     return AccessResult::forbidden();
 }
 /**
  * Tests ConfigurableEventHandlerEntityBundle.
  *
  * Test that rules are triggered correctly based upon the fully qualified
  * event name as well as the base event name.
  *
  * @todo Add integrity check that node.field_integer is detected by Rules.
  */
 public function testConfigurableEventHandler()
 {
     // Create rule1 with the 'rules_entity_presave:node--page' event.
     $rule1 = $this->expressionManager->createRule();
     $rule1->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.0.value'));
     $config_entity1 = $this->storage->create(['id' => 'test_rule1']);
     $config_entity1->set('events', [['event_name' => 'rules_entity_presave:node--page']]);
     $config_entity1->set('expression', $rule1->getConfiguration());
     $config_entity1->save();
     // Create rule2 with the 'rules_entity_presave:node' event.
     $rule2 = $this->expressionManager->createRule();
     $rule2->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.1.value'));
     $config_entity2 = $this->storage->create(['id' => 'test_rule2']);
     $config_entity2->set('events', [['event_name' => 'rules_entity_presave:node']]);
     $config_entity2->set('expression', $rule2->getConfiguration());
     $config_entity2->save();
     // The logger instance has changed, refresh it.
     $this->logger = $this->container->get('logger.channel.rules');
     // Add node.field_integer.0.value to rules log message, read result.
     $this->node->field_integer->setValue(['0' => 11, '1' => 22]);
     // Trigger node save.
     $entity_type_id = $this->node->getEntityTypeId();
     $event = new EntityEvent($this->node, [$entity_type_id => $this->node]);
     $event_dispatcher = \Drupal::service('event_dispatcher');
     $event_dispatcher->dispatch("rules_entity_presave:{$entity_type_id}", $event);
     // Test that the action in the rule1 logged node value.
     $this->assertRulesLogEntryExists(11, 1);
     // Test that the action in the rule2 logged node value.
     $this->assertRulesLogEntryExists(22, 0);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL)
 {
     $form['#title'] = $node->label();
     $form['#node'] = $node;
     $this->bookAdminTable($node, $form);
     $form['save'] = array('#type' => 'submit', '#value' => $this->t('Save book pages'));
     return $form;
 }
 /**
  * Generates HTML for export when invoked by book_export().
  *
  * The given node is embedded to its absolute depth in a top level section. For
  * example, a child node with depth 2 in the hierarchy is contained in
  * (otherwise empty) <div> elements corresponding to depth 0 and depth 1.
  * This is intended to support WYSIWYG output - e.g., level 3 sections always
  * look like level 3 sections, no matter their depth relative to the node
  * selected to be exported as printer-friendly HTML.
  *
  * @param \Drupal\node\NodeInterface $node
  *   The node to export.
  *
  * @throws \Exception
  *   Thrown when the node was not attached to a book.
  *
  * @return array
  *   A render array representing the HTML for a node and its children in the
  *   book hierarchy.
  */
 public function bookExportHtml(NodeInterface $node)
 {
     if (!isset($node->book)) {
         throw new \Exception();
     }
     $tree = $this->bookManager->bookSubtreeData($node->book);
     $contents = $this->exportTraverse($tree, array($this, 'bookNodeExport'));
     return array('#theme' => 'book_export_html', '#title' => $node->label(), '#contents' => $contents, '#depth' => $node->book['depth'], '#cache' => ['tags' => $node->getEntityType()->getListCacheTags()]);
 }
 /**
  * Checks access to the node preview page.
  *
  * @param \Drupal\Core\Session\AccountInterface $account
  *   The currently logged in account.
  * @param \Drupal\node\NodeInterface $node_preview
  *   The node that is being previewed.
  *
  * @return string
  *   A \Drupal\Core\Access\AccessInterface constant value.
  */
 public function access(AccountInterface $account, NodeInterface $node_preview)
 {
     if ($node_preview->isNew()) {
         $access_controller = $this->entityManager->getAccessControlHandler('node');
         return $access_controller->createAccess($node_preview->bundle(), $account, [], TRUE);
     } else {
         return $node_preview->access('update', $account, TRUE);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL)
 {
     $this->attributeTable = 'uc_product_attributes';
     $this->optionTable = 'uc_product_options';
     $this->idField = 'nid';
     $this->idValue = $node->id();
     $attributes = uc_product_get_attributes($node->id());
     return parent::buildForm($form, $form_state, $attributes);
 }
Example #8
0
 /**
  * Marks a node as read by the current user right now.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request of the page.
  * @param \Drupal\node\NodeInterface $node
  *   The node whose "last read" timestamp should be updated.
  */
 public function readNode(Request $request, NodeInterface $node)
 {
     if ($this->currentUser()->isAnonymous()) {
         throw new AccessDeniedHttpException();
     }
     // Update the history table, stating that this user viewed this node.
     history_write($node->id());
     return new JsonResponse((int) history_read($node->id()));
 }
 /**
  * Creates a new revision for a given node.
  *
  * @param \Drupal\node\NodeInterface $node
  *   A node object.
  *
  * @return \Drupal\node\NodeInterface
  *   A node object with up to date revision information.
  */
 protected function createNodeRevision(NodeInterface $node)
 {
     // Create revision with a random title and body and update variables.
     $node->title = $this->randomMachineName();
     $node->body = array('value' => $this->randomMachineName(32), 'format' => filter_default_format());
     $node->setNewRevision();
     $node->save();
     return $node;
 }
 /**
  * {@inheritdoc}
  */
 public function build(RouteMatchInterface $route_match)
 {
     $breadcrumb = new Breadcrumb();
     $links[] = Link::createFromRoute(t('Home'), '<front>');
     // Articles page is a view.
     $links[] = Link::createFromRoute(t('Articles'), 'view.articles.page_1');
     $links[] = Link::createFromRoute($this->node->label(), '<none>');
     $breadcrumb->setLinks($links);
     return $breadcrumb;
 }
 /**
  * Determine if a user can view a given registration node.
  *
  * The user may view the node if they are the creator of it, or if they are
  * an admin.
  *
  * @param \Drupal\node\NodeInterface $node
  * @param \Drupal\Core\Session\AccountInterface $account
  * @return \Drupal\Core\Access\AccessResult
  */
 public function canViewRegistration(\Drupal\node\NodeInterface $node, \Drupal\Core\Session\AccountInterface $account)
 {
     if ($account->hasPermission('administer content')) {
         return \Drupal\Core\Access\AccessResult::allowed();
     }
     if ($node->getOwner()->getAccountName() === $account->getAccountName()) {
         return \Drupal\Core\Access\AccessResult::allowed();
     }
     return \Drupal\Core\Access\AccessResult::forbidden();
 }
Example #12
0
 public function nodeGreeting(NodeInterface $node)
 {
     if ($node->isPublished()) {
         $formatted = $node->body->processed;
         foreach ($node->field_tags as $tag) {
             $terms[] = $tag->entity->label();
         }
         return ['#theme' => 'greeting_node', '#title' => $node->label() . ' (' . $node->bundle() . ')', '#body' => $formatted, '#name' => $node->getOwner()->label(), '#terms' => $terms];
     }
     return ['#markup' => $this->t('Not published')];
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL)
 {
     $query = \Drupal::request()->query->all();
     $form['#action'] = Url::fromRoute('<current>')->setOptions(['query' => $query])->toString();
     $form['nid'] = array('#type' => 'value', '#value' => $node->id());
     $form['qty'] = array('#type' => 'value', '#value' => 1);
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Add to cart'), '#id' => 'edit-submit-' . $node->id());
     uc_form_alter($form, $form_state, $this->getFormId());
     return $form;
 }
 /**
  * Simulates the scheduled (un)publication of a node.
  *
  * @param \Drupal\node\NodeInterface $node
  *   The node to schedule.
  * @param string $action
  *   The action to perform: either 'publish' or 'unpublish'. Defaults to
  *   'publish'.
  *
  * @return \Drupal\node\NodeInterface
  *   The updated node, after scheduled (un)publication via a cron run.
  */
 protected function schedule(NodeInterface $node, $action = 'publish')
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     // Simulate scheduling by setting the (un)publication date in the past and
     // running cron.
     $node->{$action . '_on'} = strtotime('-1 day');
     $node->save();
     scheduler_cron();
     $node_storage->resetCache(array($node->id()));
     return $node_storage->load($node->id());
 }
Example #15
0
 protected function setUp()
 {
     parent::setUp();
     ViewTestData::createTestViews(get_class($this), array('tracker_test_views'));
     $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
     // Add a comment field.
     $this->addDefaultCommentField('node', 'page');
     $permissions = array('access comments', 'create page content', 'post comments', 'skip comment approval');
     $account = $this->drupalCreateUser($permissions);
     $this->drupalLogin($account);
     $this->node = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $account->id(), 'status' => 1));
     $this->comment = Comment::create(array('entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'subject' => $this->randomMachineName(), 'comment_body[' . LanguageInterface::LANGCODE_NOT_SPECIFIED . '][0][value]' => $this->randomMachineName(20)));
 }
Example #16
0
 /**
  * Text, if the user answered wrong.
  *
  * @param \Drupal\node\NodeInterface $node
  *   The node the client form belongs to.
  * @return array
  */
 public function sorry(NodeInterface $node)
 {
     $config = $this->config('field_quiz.settings');
     $text = $config->get('field_quiz.test_answer_wrong');
     $elements[] = array('#type' => 'html_tag', '#tag' => 'p', '#attributes' => array('style' => 'color: red'), '#value' => $this->t($text));
     $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()));
     $project_link = Link::fromTextAndUrl(t('Please try again.'), $url);
     $project_link = $project_link->toRenderable();
     // If you need some attributes.
     $project_link['#attributes'] = array('class' => array('button', 'button-action', 'button--primary', 'button--small'));
     $elements[] = array('#type' => 'html_tag', '#tag' => 'p', '#attributes' => array(), '#value' => render($project_link));
     return $elements;
 }
 /**
  * Displays the product features tab on a product node edit form.
  */
 public function featuresOverview(NodeInterface $node)
 {
     $header = array($this->t('Type'), $this->t('Description'), $this->t('Operations'));
     $rows = [];
     $features = uc_product_feature_load_multiple($node->id());
     foreach ($features as $feature) {
         $operations = array('edit' => array('title' => $this->t('Edit'), 'url' => Url::fromRoute('uc_product.feature_edit', ['node' => $node->id(), 'fid' => $feature->fid, 'pfid' => $feature->pfid])), 'delete' => array('title' => $this->t('Delete'), 'url' => Url::fromRoute('uc_product.feature_delete', ['node' => $node->id(), 'fid' => $feature->fid, 'pfid' => $feature->pfid])));
         $rows[] = array(array('data' => uc_product_feature_data($feature->fid, 'title')), array('data' => array('#markup' => $feature->description)), array('data' => array('#type' => 'operations', '#links' => $operations)));
     }
     $build['features'] = array('#theme' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => array('class' => array('uc-product-features')), '#empty' => $this->t('No features found for this product.'));
     $build['add_form'] = $this->formBuilder()->getForm('Drupal\\uc_product\\Form\\ProductFeatureAddForm', $node);
     return $build;
 }
Example #18
0
 /**
  * Helper function to setup the faq question.
  *
  * @param array &$data
  *   Array reference to store display data in.
  * @param \Drupal\node\NodeInterface $node
  *   The node object.
  * @param string $path
  *   The path/url which the question should link to if links are disabled.
  * @param string $anchor
  *   Link anchor to use in question links.
  */
 public static function viewQuestion(&$data, \Drupal\node\NodeInterface $node, $path = NULL, $anchor = NULL)
 {
     $faq_settings = \Drupal::config('faq.settings');
     $disable_node_links = $faq_settings->get('disable_node_links');
     $question = '';
     // Don't link to faq node, instead provide no link, or link to current page.
     if ($disable_node_links) {
         if (empty($path) && empty($anchor)) {
             $question = $node->getTitle();
         } elseif (empty($path)) {
             // Can't seem to use l() function with empty string as screen-readers
             // don't like it, so create anchor name manually.
             $question = '<a id="' . $anchor . '"></a>' . $node->getTitle();
         } else {
             $options = array();
             if ($anchor) {
                 $options['attributes'] = array('id' => $anchor);
             }
             $question = l($node->getTitle(), $path, $options);
         }
     } else {
         $node_id = $node->id();
         if (empty($anchor)) {
             $question = l($node->getTitle(), "node/{$node_id})");
         } else {
             $question = l($node->getTitle(), "node/{$node_id}", array("attributes" => array("id" => "{$anchor}")));
         }
     }
     $question = '<span datatype="" property="dc:title">' . $question . '</span>';
     $detailed_question = $node->get('field_detailed_question')->value;
     if ($faq_settings->get('display') != 'hide_answer' && !empty($detailed_question) && $faq_settings->get('question_length') == 'both') {
         $question .= '<div class="faq-detailed-question">' . $detailed_question . '</div>';
     }
     $data['question'] = SafeMarkup::set($question);
 }
Example #19
0
 /**
  * Tests that cron clears day counts and expired access logs.
  */
 function testExpiredLogs()
 {
     $this->config('statistics.settings')->set('count_content_views', 1)->save();
     \Drupal::state()->set('statistics.day_timestamp', 8640000);
     $this->drupalGet('node/' . $this->testNode->id());
     // Manually calling statistics.php, simulating ajax behavior.
     $nid = $this->testNode->id();
     $post = array('nid' => $nid);
     global $base_url;
     $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
     $this->client->post($stats_path, array('body' => $post));
     $this->drupalGet('node/' . $this->testNode->id());
     $this->client->post($stats_path, array('body' => $post));
     $this->assertText('1 view', 'Node is viewed once.');
     // statistics_cron() will subtract
     // statistics.settings:accesslog.max_lifetime config from REQUEST_TIME in
     // the delete query, so wait two secs here to make sure the access log will
     // be flushed for the node just hit.
     sleep(2);
     $this->cronRun();
     $this->drupalGet('admin/reports/pages');
     $this->assertNoText('node/' . $this->testNode->id(), 'No hit URL found.');
     $result = db_select('node_counter', 'nc')->fields('nc', array('daycount'))->condition('nid', $this->testNode->id(), '=')->execute()->fetchField();
     $this->assertFalse($result, 'Daycounter is zero.');
 }
Example #20
0
 /**
  * Tests retaining of node form submissions containing profanity.
  */
 function testRetain()
 {
     $this->drupalLogin($this->adminUser);
     $this->setProtectionUI('node_article_form', FormInterface::MOLLOM_MODE_ANALYSIS, NULL, ['checks[profanity]' => TRUE, 'discard' => 0]);
     $this->drupalLogout();
     // Login and submit a node.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('node/add/article');
     $edit = ['title[0][value]' => 'profanity', 'body[0][value]' => 'ham profanity'];
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
     debug($this->node, 'node');
     $this->assertFalse($this->node->isPublished(), t('Node containing profanity was retained as unpublished.'));
     $this->assertUrl('node/' . $this->node->id());
     $this->assertMollomData('node', $this->node->id());
 }
 /**
  * Takes the user to the node creation page for the type of a given node.
  */
 public function addAnotherAccess(NodeInterface $node)
 {
     if (!$node->access('create')) {
         return AccessResult::forbidden();
     }
     $config = \Drupal::config('addanother.settings');
     $account = \Drupal::currentUser();
     $type = $node->getType();
     if (\Drupal::routeMatch()->getRouteName() == 'entity.node.edit_form' && !$config->get('tab_edit.' . $type)) {
         return AccessResult::forbidden();
     }
     if ($config->get('tab.' . $type) && $account->hasPermission('use add another')) {
         return AccessResult::allowed();
     }
     return AccessResult::forbidden();
 }
 /**
  * Tests if file fields in teasers have correct resources.
  *
  * Ensure that file fields have the correct resource as the object in RDFa
  * when displayed as a teaser.
  */
 function testNodeTeaser()
 {
     // Render the teaser.
     $node_render_array = entity_view_multiple(array($this->node), 'teaser');
     $html = \Drupal::service('renderer')->renderRoot($node_render_array);
     // Parses front page where the node is displayed in its teaser form.
     $parser = new \EasyRdf_Parser_Rdfa();
     $graph = new \EasyRdf_Graph();
     $base_uri = \Drupal::url('<front>', [], ['absolute' => TRUE]);
     $parser->parse($graph, $html, 'rdfa', $base_uri);
     $node_uri = $this->node->url('canonical', ['absolute' => TRUE]);
     $file_uri = file_create_url($this->file->getFileUri());
     // Node relation to attached file.
     $expected_value = array('type' => 'uri', 'value' => $file_uri);
     $this->assertTrue($graph->hasProperty($node_uri, 'http://www.w3.org/2000/01/rdf-schema#seeAlso', $expected_value), 'Node to file relation found in RDF output (rdfs:seeAlso).');
     $this->drupalGet('node');
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     if ($this->bookManager->checkNodeIsRemovable($this->node)) {
         $this->bookManager->deleteFromBook($this->node->id());
         drupal_set_message($this->t('The post has been removed from the book.'));
     }
     $form_state->setRedirectUrl($this->getCancelUrl());
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     if ($this->bookManager->checkNodeIsRemovable($this->node)) {
         $this->bookManager->deleteFromBook($this->node->id());
         drupal_set_message($this->t('The post has been removed from the book.'));
     }
     $form_state['redirect_route'] = $this->getCancelRoute();
 }
Example #25
0
 protected function setUp()
 {
     parent::setUp();
     ViewTestData::createTestViews(get_class($this), array('comment_test_views'));
     // Add two users, create a node with the user1 as author and another node
     // with user2 as author. For the second node add a comment from user1.
     $this->account = $this->drupalCreateUser(array('skip comment approval'));
     $this->account2 = $this->drupalCreateUser();
     $this->drupalLogin($this->account);
     $this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page')));
     $this->addDefaultCommentField('node', 'page');
     $this->nodeUserPosted = $this->drupalCreateNode();
     $this->nodeUserCommented = $this->drupalCreateNode(array('uid' => $this->account2->id()));
     $comment = array('uid' => $this->loggedInUser->id(), 'entity_id' => $this->nodeUserCommented->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'subject' => 'How much wood would a woodchuck chuck', 'cid' => '', 'pid' => '', 'mail' => '*****@*****.**');
     $this->comment = Comment::create($comment);
     $this->comment->save();
 }
  /**
   * Test an AJAX flag link.
   */
  public function doUseAjaxFlag() {
    // Create and login as an authenticated user.
    $auth_user = $this->drupalCreateUser();
    $this->drupalLogin($auth_user);

    $node_url = $this->node->toUrl();

    // Navigate to the node page.
    $this->drupalGet($node_url);

    // Confirm the flag link exists.
    $this->assertLink($this->flag->getFlagShortText());

    // Click the flag link. This ensures that the non-JS fallback works we are
    // redirected to back to the page and the node is flagged.
    $this->clickLink($this->flag->getFlagShortText());
    $this->assertUrl($node_url);
    $this->assertLink($this->flag->getUnflagShortText());

    // Click the unflag link, repeat the check.
    $this->clickLink($this->flag->getUnflagShortText());
    $this->assertUrl($node_url);
    $this->assertLink($this->flag->getFlagShortText());

    // Now also test with an ajax request and that the correct response is
    // returned. Use the same logic as clickLink() to find the link.
    $urls = $this->xpath('//a[normalize-space()=:label]', array(':label' => $this->flag->getFlagShortText()));
    $url_target = $this->getAbsoluteUrl($urls[0]['href']);
    $ajax_response = $this->drupalGetAjax($url_target);

    // Assert that the replace selector is correct.
    $this->assertEqual($ajax_response[0]['selector'], '#' .$urls[0]['id']);

    // Request the returned URL to ensure that link is valid and has a valid
    // CSRF token.
    $xml_data = new \SimpleXMLElement($ajax_response[0]['data']);
    $this->assertEqual($this->flag->getUnflagShortText(), (string) $xml_data);

    $ajax_response = $this->drupalGetAjax($this->getAbsoluteUrl($xml_data['href']));
    // Assert that the replace selector is correct.
    $this->assertEqual($ajax_response[0]['selector'], '#' . $xml_data['id']);

    $xml_data_unflag = new \SimpleXMLElement($ajax_response[0]['data']);
    $this->assertEqual($this->flag->getFlagShortText(), (string) $xml_data_unflag);

  }
 public function webform_paymethod_select_continue(\Drupal\node\NodeInterface $node, $submission, $page_num)
 {
     // We can't use a simple drupal_get_form() because we wan't to enter the form
     // at a specific $page_num.
     $form_state = [];
     $args = [$node, $submission, TRUE, TRUE];
     $form_state['build_info']['args'] = $args;
     $form_state['storage']['component_tree'] = [];
     $form_state['storage']['page_count'] = 1;
     $form_state['storage']['preview'] = !empty($node->webform['preview']);
     _webform_components_tree_build($node->webform['components'], $form_state['storage']['component_tree'], 0, $form_state['storage']['page_count']);
     $form_state['storage']['page_num'] = $page_num;
     if (\Drupal::moduleHandler()->moduleExists('webform_steps')) {
         $form_state['steps_finished'] = $page_num - 1;
     }
     return \Drupal::formBuilder()->buildForm('webform_client_form_' . $node->id(), $form_state);
 }
Example #28
0
 public function nodeHug(NodeInterface $node)
 {
     if ($node->isPublished()) {
         // These are the same!
         $body = $node->body->value;
         $body = $node->body[0]->value;
         // But we really want...
         $formatted = $node->body->processed;
         $terms = [];
         foreach ($node->field_tags as $tag) {
             $terms[] = $tag->entity->label();
         }
         $message = $this->t('Everyone hug @name because @reasons!', ['@name' => $node->getOwner()->label(), '@reasons' => implode(', ', $terms)]);
         return ['#title' => $node->label() . ' (' . $node->bundle() . ')', '#markup' => $message . $formatted];
     }
     return $this->t('Not published');
 }
 /**
  * Tests Quick Edit autocomplete term behavior.
  */
 public function testAutocompleteQuickEdit()
 {
     $this->drupalLogin($this->editor_user);
     $quickedit_uri = 'quickedit/form/node/' . $this->node->id() . '/' . $this->field_name . '/und/full';
     $post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
     $response = $this->drupalPost($quickedit_uri, 'application/vnd.drupal-ajax', $post);
     $ajax_commands = Json::decode($response);
     // Prepare form values for submission. drupalPostAJAX() is not suitable for
     // handling pages with JSON responses, so we need our own solution here.
     $form_tokens_found = preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
     $this->assertTrue($form_tokens_found, 'Form tokens found in output.');
     if ($form_tokens_found) {
         $post = array('form_id' => 'quickedit_field_form', 'form_token' => $token_match[1], 'form_build_id' => $build_id_match[1], $this->field_name => implode(', ', array($this->term1->getName(), 'new term', $this->term2->getName())), 'op' => t('Save'));
         // Submit field form and check response. Should render back all the terms.
         $response = $this->drupalPost($quickedit_uri, 'application/vnd.drupal-ajax', $post);
         $this->assertResponse(200);
         $ajax_commands = Json::decode($response);
         $this->drupalSetContent($ajax_commands[0]['data']);
         $this->assertLink($this->term1->getName());
         $this->assertLink($this->term2->getName());
         $this->assertText('new term');
         $this->assertNoLink('new term');
         // Load the form again, which should now get it back from TempStore.
         $quickedit_uri = 'quickedit/form/node/' . $this->node->id() . '/' . $this->field_name . '/und/full';
         $post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
         $response = $this->drupalPost($quickedit_uri, 'application/vnd.drupal-ajax', $post);
         $ajax_commands = Json::decode($response);
         // The AjaxResponse's first command is an InsertCommand which contains
         // the form to edit the taxonomy term field, it should contain all three
         // taxonomy terms, including the one that has just been newly created and
         // which is not yet stored.
         $this->drupalSetContent($ajax_commands[0]['data']);
         $this->assertFieldByName($this->field_name, implode(', ', array($this->term1->getName(), 'new term', $this->term2->label())));
         // Save the entity.
         $post = array('nocssjs' => 'true');
         $response = $this->drupalPost('quickedit/entity/node/' . $this->node->id(), 'application/json', $post);
         $this->assertResponse(200);
         // The full node display should now link to all entities, with the new
         // one created in the database as well.
         $this->drupalGet('node/' . $this->node->id());
         $this->assertLink($this->term1->getName());
         $this->assertLink($this->term2->getName());
         $this->assertLink('new term');
     }
 }
 /**
  * Verifies that you can disable individual search plugins.
  */
 function testSearchModuleDisabling()
 {
     // Array of search plugins to test: 'keys' are the keywords to search for,
     // and 'text' is the text to assert is on the results page.
     $plugin_info = array('node_search' => array('keys' => 'pizza', 'text' => $this->searchNode->label()), 'user_search' => array('keys' => $this->searchUser->getUsername(), 'text' => $this->searchUser->getEmail()), 'dummy_search_type' => array('keys' => 'foo', 'text' => 'Dummy search snippet to display'));
     $plugins = array_keys($plugin_info);
     /** @var $entities \Drupal\search\SearchPageInterface[] */
     $entities = entity_load_multiple('search_page');
     // Disable all of the search pages.
     foreach ($entities as $entity) {
         $entity->disable()->save();
     }
     // Test each plugin if it's enabled as the only search plugin.
     foreach ($entities as $entity_id => $entity) {
         // Set this as default.
         $this->drupalGet("admin/config/search/pages/manage/{$entity_id}/set-default");
         // Run a search from the correct search URL.
         $info = $plugin_info[$entity_id];
         $this->drupalGet('search/' . $entity->getPath(), array('query' => array('keys' => $info['keys'])));
         $this->assertResponse(200);
         $this->assertNoText('no results', $entity->label() . ' search found results');
         $this->assertText($info['text'], 'Correct search text found');
         // Verify that other plugin search tab labels are not visible.
         foreach ($plugins as $other) {
             if ($other != $entity_id) {
                 $label = $entities[$other]->label();
                 $this->assertNoText($label, $label . ' search tab is not shown');
             }
         }
         // Run a search from the search block on the node page. Verify you get
         // to this plugin's search results page.
         $terms = array('keys' => $info['keys']);
         $this->submitGetForm('node', $terms, t('Search'));
         $current = $this->getURL();
         $expected = \Drupal::url('search.view_' . $entity->id(), array(), array('query' => array('keys' => $info['keys']), 'absolute' => TRUE));
         $this->assertEqual($current, $expected, 'Block redirected to right search page');
         // Try an invalid search path, which should 404.
         $this->drupalGet('search/not_a_plugin_path');
         $this->assertResponse(404);
         $entity->disable()->save();
     }
     // Test with all search plugins enabled. When you go to the search
     // page or run search, all plugins should be shown.
     foreach ($entities as $entity) {
         $entity->enable()->save();
     }
     // Set the node search as default.
     $this->drupalGet('admin/config/search/pages/manage/node_search/set-default');
     $paths = array(array('path' => 'search/node', 'options' => array('query' => array('keys' => 'pizza'))), array('path' => 'search/node', 'options' => array()));
     foreach ($paths as $item) {
         $this->drupalGet($item['path'], $item['options']);
         foreach ($plugins as $entity_id) {
             $label = $entities[$entity_id]->label();
             $this->assertText($label, format_string('%label search tab is shown', array('%label' => $label)));
         }
     }
 }