Use image from taxonomy term as exposed filter option I created a view which has an exposed filter for taxonomy terms. Now the next step is to theme the options. I tried the module "Better exposed Filters" but I wasn't satisfied. I would like to have images to click on instead the standard filter. I already have stored the images in the taxonomy fields, so every term has it own image.

I tried to create a template file for the filter, but I don't have any access to the fields, where the image is stored. I could do some hardcoded stuff, but I want it as generic as possible.

Has anyone an idea how to achieve it?

Use "Better exposed Filters" and choose its Display setting as Checkbox
Now you have to do form alter like this

function THEMENAME_form_views_exposed_form_alter(&$form, &$form_state) {
  foreach ($form['TAXONOMY_ELEMENT']['#options'] as $tid => &$name) {
      $term = taxonomy_term_load($tid);
      $name = '<img src="' . file_create_url($term->IMAGE_FIELD_NAME['und'][0]['uri']) . '" />';
  }
}

In my case ::
TAXONOMY_ELEMENT = field_type_tid
IMAGE_FIELD_NAME = field_term_image


Queue doesn't enter on worker function with Elysia cron I'm trying to use queue api with cron, everything seems work but drupal does not enter on the "worker" function.
The problem there is only if I enable Elysia Cron (and I've to enable it..)

<?php

/**
 * Implements hook_cron_queue_info().
 */
function monitor_import_cron_queue_info() {
  $queue['monitor_import_queue'] = array(
    'worker callback' => 'monitor_import_queue_worker',
    'time' => 10,
  );
  return $queue;
}

/**
 * Implements hook_cron().
 */
function monitor_import_cron() {

  $call = new MyWS();
  $params = new getSoggettoView();
  $params->limit = '10'; //$limit;
  $params->offset = '0';
  $results = $call->getSoggettoView($params);
  $items = $results->return;
  $queue = DrupalQueue::get('monitor_import_queue'); // grab queue
  $queue->createQueue(); // initialize
  foreach ($items as $item) {
    $queue->createItem($item);
  }
}

/**
 * Worker callback
 *
 * @see mymodule_cron_queue_info().
 */
function monitor_import_queue_worker($item) {
  $a = 1;
}

Below code perfectly works for me...

/**
 * Implements hook_cron_queue_info().
*/
function drup_custom_cron_queue_info() {
  $queue['drup_custom_queue'] = array(
      'worker callback' => 'drup_custom_queue_worker',
      'time' => 10,
  );
  return $queue;
}

/**
 * Implements hook_cron().
 */
function drup_custom_cron() {
  $items = array('1', '2', '3', '4', '5', '6', '7');
  $queue = DrupalQueue::get('drup_custom_queue'); // grab queue
  foreach ($items as $i) {
    $item = new stdClass();
    $item->created = time();
    $item->sequence = $i;
    $queue->createItem($item);
  }
}

/**
 * Worker callback
 *
 * @see mymodule_cron_queue_info().
 */
function drup_custom_queue_worker($item) {
  watchdog('drup_custom', 'Queue worker processed item with @sequence created at @time',
    array(
      '@sequence' => $item->sequence,
      '@time' => date_iso8601($item->created),
    )
  );
}

Check your custom callback which returns results as mentioned by David in comment..


How do I write a config file manually? I need to find out how to manually create a configuration file, one which will be included with a custom theme as optional/required upon installation.

I know I need to create a file in themes/mytheme/config/optional for a block, but how do I know the exact filename and what to put in it?

Creating configuration files manually is tedious and like @Berdir mentioned in the comments it is better to export them.

First install your theme, so you can place the blocks for your new theme.

Create the blocks in the UI.
Make sure you have installed the module: Configuration Manager (already installed if you use Standard profile)
Export the configuration using the UI (/admin/config/development/configuration/full/export) or using Drush: drush cex
Depending on how you exported the configuration:

If you used UI, you have a .zip that you must extract.
If you used Drush, the files are exported to sites/default/config_longname/sync

The blocks file names are block.block.BLOCK_MACHINE_NAME.yml
Copy those block files that you created and put them config/optional in your theme folder.
Now open these files and remove the first line, looking something like: uuid: f95127a4-7947-48e3-a0f1-1dae6c61940d

That's it, if you move the theme to a new site and install the theme, the blocks will be installed and placed where you originally put them.


Add an action to user register form On registration I want to get the value of the user's email and forward them to a page that has an option to resend their activation email.
I have the page with the form they're forwarded to, but I need some place to add the user's email address to a $session variable when user_register is being submitted. Apparently there is no submit_hook for that form without overriding it entirely (which I would rather not do).

This is the code I have so far:

function mymodule_form_alter(&$form, &$form_state, $form_id){
    global $user;

    if($form_id=='user_register_form' && $user->uid != 1 && !in_array('manager', array_values($user->roles)))
    {
        $form['actions']['submit']['#value'] = 'Create Account';
        $form['account']['mail']['#description'] = "Please use a valid email address as you will need to verify it.";
        $form['account']['mail']['#attributes'] = array('placeholder' => 'email@address.com');
        $form['account']['mail']['#title'] = 'Email Address';
        $form['account']['name']['#description'] = "";

        $form['#action'] .= '?destination=node/'.variable_get('checkemailpage', 6);

    }
}

You can add additional submit callback function to the registration form, then assign user's email to a session so you can call it on the destination page.

Add the following line after $form['#action']

$form['#submit'][] = 'custom_user_register_submit';

Then add this function to your custom module

function custom_user_register_submit(&$form, &$form_state) {

  $_SESSION['custom_user_mail'] = $form_state['values']['mail'];
}

Then call $_SESSION['custom_user_mail'] on any page you want.


Node Gallery not using administration theme for its custom tabs I'm using a very minimal custom theme for the website, but Bartik for administration.

Node Gallery plugin adds tabs to the Edit Node page (e.g. node/46/edit): "Manage Items", "Sort items" and "Upload new items". When I click on them, the custom theme is used instead of Bartik. I suspect this is because these pages weren't properly flagged as admin pages, or something like that.

How can I make Node Gallery use administration theme for its custom tabs?

Generally, to declare a path as an admin path (and thus one that would open in the overlay/use the admin theme, etc.) you need to declare them using hook_admin_paths.

If this is the issue (I don't know Node Gallery, so I can't be more precise) the best would be to implement hook_admin_paths in the Node Gallery module and submit the patch on the Node Gallery issue queue.


How to transform data from the Google Analytics Reports module into charts? I'm using Google Analytics Reports to bring in Google Analytics data into Views, this works fine, but I'd like to display this data as a chart.

I've tried with two different charts modules: Charts and Google Chart Tools. Both require you to use Aggregation in views to group the data, but this isn't something the Google Analytics Reports module supports.

Can anyone recommend a way around this or a different approach?

You can use the API sub-module within the Google Analytics Reports module and use

DataViz module for the visual representation.

You could use http://blog.amazeelabs.com/en/comment/257249 for reference.


Migrating to XAMPP local install - Configure the temporary directory I have copied a site I have on a VPS down to run from XAMPP on my local machine. When I restore the site using Backup and Migrate I get the error message on all pages of the site:

  The specified file temporary://filemy1oSK could not be copied, because the destination directory is not properly configured.

I have clean installs of drupal running fine on XAMPP. On the File System configuration page (admin/config/media/file-system) they use '/Applications/XAMPP/xamppfiles/temp/' so I have tried using this and '/Applications/XAMPP/xamppfiles/private/' but this doesn't fix the error.

There is a similar Drupal Answers Question, about moving a site from local up to a VPS I have tried to work through the suggestions there to no effect. The top answer recommends advice from this site. Following this to avoid starting the file paths with a forward slash I tried using 'sites/default/files/private/' and 'sites/default/files/temp/'but this doesn't fix the error either.

As this is a local install, security is less of an issue. I have been setting the above directories to 777 to ensure that there are enough permissions. I have also made 'sites', 'sites/default' and 'sites/default/files/' 777.

Possibly incidentally, clean URLS weren't working on the the local install, even though they work fine on the fresh installs of Drupal. This stopped the links on the site working. I disabled them by going to http://localhost/sitename/?q=admin/config/search/clean-urls and the site links now work without clean URLS

Also possibly incidentally, I got an error message when I used the site files I downloaded to install with a clean database. I did this so I could install the backup migrate module and restore the site properly. At the end of the install I got the error:

  Deprecated function: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in _acquia_profile_create_node() (line 158 of /Applications/XAMPP/xamppfiles/htdocs/sitename/profiles/acquia/acquia.profile).

I don't have any admin menu and the overlay admin screens aren't working. I am assuming this is a result of the temporary files error.

Any advice?

This issue has nothing to do with Drupal config. Its related the your tmp folder permission. You got to update the tmp folder permission, so that apache user have proper write permission.

chmod -R 0700 chmod -R 0700 /tmp


Why doesn't the view show every node? I have created a view as a page that I want to only show my blog posts. I filter the Content: Has taxonomy term (= blog) to limit to my blog posts. Now I want to add a search box that can search the title and body. I've tried using Search: Search Terms and Global: Combine fields filter, but neither seems to work properly. They don't bring up any posts that match the search, even if the text is in the title, body, or the exact name of a linked taxonomy.

How can I make a search box for my view that will search the title and body?

I have just learned that in order to use Global: Combine fields filter, you must set "Show" (under the "Format" section) to "Fields". My issue was I had it set to "Content" and couldn't select the fields in the settings for the filter.


Views related content based same term names in different vocabulary I'm trying to create a view for a taxonomy term and show a related content based on term name.

For example, i have term name Manchester United in vocabulary teams and i want to show all news nodes that have term Manchester United. The problem is that terms in news are in different vocabulary.

For now i create a View with Contextual filters Content: Has taxonomy term ID which get me ID for term Manchester United from vocabulary teams.

My questions is, how i can use this term name and show related nodes from news which have same term name but in different vocabulary and different ID.

EDIT: it's important to know that i'm getting first term by his ID in url.

First option (doesn't work as expected though):

You should be able to do that, by doing the following in your contextual filter:

Check the "Specify validation criteria" option.
Select "Taxonomy term" as "Validator".
Select "Term name" as "Filter value type".

I just tried this however and it returns only one result, which is not what you need.

Alternative (this one was tested and works):

You can create a View of Taxonomy Terms, and then use a "Taxonomy term: Name" contextual filter.
Afterwards, you can add a relationship to your tagged nodes, using the "Taxonomy term: Content with term" relationship.

That way, you can get all the content tagged with a specific term name, even if the term name belongs to different taxonomies.

Here is a sample View configuration:

and a sample result-set with "ManU" used as a contextual filter:

Good luck!


How to print text (formatted, long) in twig without raw filter? We have a text (formatted, long) field that is used to insert embed code such as the Youtube embed code for videos.

When printing the field in twig we are finding that rather than rendering the embed code, it is displaying the embed code as string. To get around this, we currently apply Twig's Raw filter, but wanted to see if there was a way to not use the raw filter and render the field as is.

Content type (basic page):

body (text, formatted long) field
title

Current results (inserted into Body field using Full HTML text format, displayed as string):

Desired results (output of body field shows the video)

With the excellent Twig Tweak module you can do this:

{{ node.FIELD_NAME.value | check_markup(node.FIELD_NAME.format) }}

This feature (and more) is well documented on the module's cheat sheet.


How to alter single custom field value in views? I have a view with field Global: Custom Text, which is modified as a link.
I want to change replacement tokens for generating this link, dependent on a value of other field.

Tried to modify this in hook_views_pre_render but I can't find a way to do this.

In hook_views_post_render there are two arrays:

$view->style_plugin->render_tokens
$view->style_plugin->row_tokens

which contains generated links for every row, but they are not present in pre_render, and changing them in post_render doesn't work.

I've also tried to do that in template_preprocess_views_view_fields but for that specific view this function does not firing (for other views it does), and I don't know why.

function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

Check the link for more details
How to insert values into Global custom text field of views programmatically?

add nid as field in view and use that field for condition
you can add condition as follows: if ($nid == '124') {  $view->field['nothing']->options['alter']['text'] = $nid}

Simple way is to create a new field field_waga which will have field_waga_1 as new name if you check in the view and then you can change the label and override that field with your custom value

if($view->result[0]->field_waga[0]['raw']['value'] == '10') {
//here you can create the field to act as custom text field and enter the custom //value
$view->result[0]->field_waga_1[0]['#markup'] = 'alter';
}


How to send mail from drupal 7 efficently and avoid 'Too many concurrent SMTP connections' error? I'm using the smtp module to send mail from a drupal 7 installation throught gmail. In

 /admin/config/system/smtp

I set

 smtp server 'smtp.gmail.com'
 smtp port '587'
 use encryption 'use tls'

and i set my valid mail 'something@gmail.com'.

Now, it's working, but some days ago a lot of mail, on the account something@gmail.com, began to arrive containing an error message:

 Delivery to the following recipient has been delayed:
 someBadGuy@somemail.com
 Message will be retried for 2 more day(s)
 Technical details of temporary failure:
 The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720
 [(10) somemail.com. [someip]:25: 421 Too many concurrent SMTP connections; please try again later. ]

There were and there will always be on my drupal site people registering with fake unreachable mail, so assuming i can't solve this problem, what this message means? It began some days ago, out of the blue, so i think something is changed, but i do not know precisely what. And do not know precisely where. (gmail, my provider, my server...)

Anyway, what is the best way to send mail from drupal, excluding the idea of setting up my own mail server and excluding gmail, as it implies this problem?

Have you tried using the Mandrill module? https://www.drupal.org/project/mandrill


Form textfield AJAX validation "deletes" injected services to form I'm trying to create a form that has two services injected (for access to an API) and a textfield with an AJAX callback. Here it is:
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['vat_number'] = [
        '#title' => $this->t('VAT Number'),
        '#type' => 'textfield',
        '#default_value' => isset($address['vat_number']) ? $address['vat_number'] : '',
        '#states' => [
          'visible' => [
            ':input[name="is_business"]' => ['checked' => TRUE],
          ],
          'required' => [
            ':input[name="is_business"]' => ['checked' => TRUE],
          ],
        ],
        '#ajax' => [
          'callback' => '::validateVatAjax',
          'event' => 'change',
          'url' => Url::fromRoute('shop_product.digital_river_payment_form'),
          'options' => [
            'query' => [
              FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
            ],
          ],
        ],
        '#suffix' => '
',
      ];
    }
.....
}
public function validateVatAjax(array &$form, FormStateInterface $form_state) {$response = new AjaxResponse();
    $message = '
';

    if (!$this->customerService->validateCustomerTaxFormat($form_state->getValue('vat_number'))) {
      $message .= $this->customerService->$schema['properties']['value']['description'];
      $message .= '
';
    }
    else {
      $message = '

';
    }
    $response->addCommand(new ReplaceCommand('#errors', $message));
    $form_state->setRebuild(FALSE);
    return $response;
  }

public function validateForm(array &$form, FormStateInterface $form_state) {
if ($form_state->getValue('is_business') == 1) {
        $vat_number = $form_state->getValue('vat_number');
        if (empty($vat_number)) {
          $form_state->setErrorByName('vat_number', $this->t('Please enter your tax number.'));
        }
        elseif (!$this->customerService->validateCustomerTaxFormat($form_state->getValue('vat_number'))) {
          $schema = $this->customerService->getSchema();
            $form_state->setErrorByName('vat_number', $schema['properties']['value']['description']);
          }
          else {
            $form_state->setErrorByName('vat_number', $this->t('Please enter your VAT number including the two letter country code.'));
          }
        }
      }
}

I omitted some of the code but my problem is that on the second AJAX call to the callback, it fails because the customerService is null. Aside from that, I don't understand why validateForm() is called on the textfield input change. Is this normal for Drupal?
Thanks in advance.

For anyone running into this problem or AJAX call that fails on the second call intermittently, check the properties used on your AJAX form class for the right access. It seems a trivial thing but change the properties of DInjected services to protected. Refrain from using private as the dependency serialization from Drupal won't be able to get those for caching purposes.
Check this link for more information.


Get the before and after values of a node field I need to compare the before save/update value with the after save/update value of a node field.

Example: There is an already existing node with the title of "Hello". I then edit the node and change the title to "World".

I need to get the before value of "Hello".

function mymodule_node_presave($node){

    $before = $node->title;
    drupal_set_message($before, 'error');

}

function mymodule_node_update($node){

    $after = $node->title;
    drupal_set_message($after, 'warning');

}

But I always keep getting the same value...

Did I just discover a drupal bug? or what? Because I've used this method in the past with user hooks and it works as expected:

function mymodule_user_presave(&$edit, $account, $category) {

     $before = $account->field_custom['und'][0]['value'];
     drupal_set_message($before, 'error');

}

function mymodule_user_update(&$edit, $account, $category) {

     $after = $account->field_custom['und'][0]['value'];
     drupal_set_message($after, 'warning');

}

For new created nodes in hook_node_update you will never get any old values for any $node fields. Use node_load($node->nid) to load the previous instance of the $node and do any comparisons with it. You can also use $node->original to view the commited values to the database.


Ubercart- free shipping through pay per click Can anyone think of a way to offer free shipping for people who arrive at the site through Pay-per-click advertising (without a coupon code).

drupal 7.

thanks!

You need to use Commerce Free Shipping module.

  This module provide a solution to add Free shipping rate on top of
  commerce_shipping services.

  This module change the price of the service to 0 and can display a
  message to the user saying the free shipping are applyed or the amount
  left to obtain free shipping.

  You can use this module to have a free shipping rate by:

  Shipping service
  Total amount of the line items in the cart (don't take in account the shipping line items)

How to setup free shipping


Getting content type data from twig view template I have a custom content type, view and block all setup and working properly. When I attempt to use kint to access node or anything else from my block template file: views-view--testimonials--block_1.html.twig i keep getting NULL values returned.

Prior to attempting to customize my block template, in my content-types folder, i had a file to directly access my content type: node--testimonials.html.twig which could access the values like so: {{ node.field_testimonial_author.value }}

My question is, how can I get access to node.field_testimonial_author from my block template file? (which is views-view--testimonials--block_1.html.twig)

I may be approaching this entirely wrong. If so, please feel free to offer any educational resources that will help me out. Coming from Drupal 7 the learning curve here for me is essentially a brick wall.

Thanks in advance.

Blocks don't have the same variables as other entity types do. They will vary in their theme hook implementations. That is why there is no {{ node.field }} concept for blocks, the information does not exist. The same principle applies to Views, Media, Paragraphs and other entities. For example, to reference fields on the paragraph in its template, you wouldn't call {{ node.field_foo }} you would call {{ paragraph.field_foo }}.

Just because a view block is rendering on a node detail page doesn't mean that the same twig template automatically sees a node object.

If the View is building this block display, I would say add the field to the View that you want to output (Author).

If you want to blow your own mind, if the view you have is returning fields on a node, change the display to use the rendered content mode, and choose a display mode (start with Teaser). This approach will allow you to use node--node-type twig templates, as Views is rendering the entity instead of printing fields into the View. The View output is then driven by the display mode on the node type itself and is a much more manageable result in most cases.


How does importing a content type work? I have used featured to create  a yml file for views and other configurations.  When I import my yml file all that is created is a content type that has a title.  Is there a way to import the fields with the content type?

uuid: 1bd0f08e-cf80-4fc3-8707-7a9d19c404da
langcode: en
status: true
dependencies:
  module:
    - menu_ui
third_party_settings:
  menu_ui:
    available_menus:
      - main
    parent: 'main:'
name: Podcast
type: podcast
description: 'Allows Drupal to play an audio file.  The Embed Podcast field should contain the name of the Podcast exactly as it is uploaded to Drupal.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

this is my file and there is nothing about the fields in a content type

To add a field to custom content type you need

field.field.node.content-type.field-name.yml
field.storage.node.field-name.yml

The easiest way for you is create the content type and fields via UI and then just simply export it in admin/config/development/configuration/single/export (you have to install the config core module). Then remove  uuid and you are done.

While exporting, export following configuration types..

Content Type
Entity form display
Entity view display
Field
Field Storage

Hope this will help you.


Using a different view mode with a node I understand using Views you can use a different view mode, e.g. teaser or full content.

Is it possible to view a node using a view mode other than the full content view mode?
What I want to achieve is being able to display different fields depending on the user's role.

You can override the page callback used on a node page to use your own function that will select the view mode based on the current user role.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
   $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_page_view($node) {
  global $user;
  // If there is a menu link to this node, the link becomes the last part
  // of the active trail, and the link name becomes the page title.
  // Thus, we must explicitly set the page title to be the node title.
  drupal_set_title($node->title);
  $uri = entity_uri('node', $node);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  return MODULE_node_show($node);
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_show($node, $message = FALSE) {
  if ($message) {
    drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  }

  $view_mode = MODULE_user_node_view_mode($node, $user);

  // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  $nodes = node_view_multiple(array($node->nid => $node), $view_mode);

  // Update the history table, stating that this user viewed this node.
  node_tag_new($node);

  return $nodes;
}

/**
 * Determines the view mode to use for the node page of the given node
 * when viewed by the given user.
 * @param $node
 *  The viewed node object
 * @param $account
 *  The viewing user object
 */
function MODULE_user_node_view_mode($node, $account) {
  // ... Implement your custom view mode selection logic here
}

Note: There is probably something that need to be done to ensure the page using a given view mode is not cached and re-used for different user.


How does a module tell Drupal which mail plugin should be used? How does a module tell Drupal which mail plugin should be used? The SMTP Authentication Support module uses the following code in the submission handler of its settings form.

$values = $form_state->getValues();
$config = $this->configFactory->getEditable('smtp.settings');
$mail_config = $this->configFactory->getEditable('system.mail');
$mail_system = $mail_config->get('interface');

// Updating config vars.
if (isset($values['smtp_password'])) {
  $config->set('smtp_password', $values['smtp_password']);
}
$config->set('smtp_on', $values['smtp_on'])
  ->set('smtp_host', $values['smtp_host'])
  ->set('smtp_hostbackup', $values['smtp_hostbackup'])
  ->set('smtp_port', $values['smtp_port'])
  ->set('smtp_protocol', $values['smtp_protocol'])
  ->set('smtp_username', $values['smtp_username'])
  ->set('smtp_from', $values['smtp_from'])
  ->set('smtp_fromname', $values['smtp_fromname'])
  ->set('smtp_allowhtml', $values['smtp_allowhtml'])
  ->set('smtp_debugging', $values['smtp_debugging'])
  ->save();

// If an address was given, send a test e-mail message.
if ($test_address = $values['smtp_test_address']) {
  $params['subject'] = t('Drupal SMTP test e-mail');
  $params['body'] = array(t('If you receive this message it means your site is capable of using SMTP to send e-mail.'));
  $account = \Drupal::currentUser();
  // If module is off, send the test message with SMTP by temporarily overriding.
  if (!$config->get('smtp_on')) {
    $original = $mail_config->get('interface');
    $mail_system['default'] = 'SMTPMailSystem';
    $mail_config->set('interface', $mail_system)->save();
  }
  \Drupal::service('plugin.manager.mail')->mail('smtp', 'smtp-test', $test_address, $account->getPreferredLangcode(), $params);
  if (!$config->get('smtp_on')) {
    $mail_config->set('interface', $original)->save();
  }
  drupal_set_message(t('A test e-mail has been sent to @email via SMTP. You may want to check the log for any error messages.', ['@email' => $test_address]));
}

This code is not working, since in the log set with the mail.log directive I see the following, where it is evident that Drupal is still using the mail plugin definined in PhpMail.php.

  [11-Mar-2016 06:36:14 UTC] mail() on [/home/domain/public_html/core/lib/Drupal/Core/Mail/Plugin/Mail/PhpMail.php:101]: To: edited@email.org -- Headers: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: 8Bit X-Mailer: Drupal Sender: edited@email.org From: Edited <edited@email.org>

I cleared the log before sending the test email from the administrative page of the SMTP Authentication Support module; so, I am sure the log is caused from sending the test email.

Since the method used from this module doesn't seem to work, what is the correct way to set the plugin Drupal uses to send emails?

Update

To make my question clearer, there are two things that are not clear to me in the code being used.

The code is setting the mail plugin Drupal should use, just for the test email, but as I can see that method doesn't work, since Drupal still uses the default plugin.
Apart from setting the mail plugin for the test email, the module doesn't change the mail plugin set by Drupal. How can Drupal know to use the mail plugin implemented by the module, then?

Basing on Mail backends are now annotated plugins, drupal_mail_service() has been removed and the documentation for the MailManagerInterface interface, a module implementing a mail plugin should not set its own plugin as default plugin because MailManagerInterface interface doesn't document any configuration key the classes implementing it should use; only the site maintainer eventually know which mail manager is being used, and which configuration keys that mail manager is using. This is similar to setting the cache handlers, which is done in the settings.php file.

The SMTP Authentication module is doing the correct thing when it doesn't set its plugin as default plugin for sending emails.

As for the code to send a test email, the correct one should not directly set the configuration keys, if it wants to be independent from the current implementation of the mail manager. Eventually, code similar to the following should be used.

$mailer = \Drupal::service('plugin.manager.mail')->createInstance($plugin_id);
$bool = $mailer->send($mailer->format($message));


Bundle field validation with Feature in Drupal 8 How can I have the field validation settings (via the field validation module) bundle with the content type using Features module?

eg: I have a content type Post and a field validation that says post's title must match a certain regex. I need to bundle this logic up with Features.

Thank you!

It looks like the field validation module has it's own configuration entity type.  This means that in the feature editor there should be a section labeled something like Field Validation Rule Sets.

Select the appropriate configuration under this section to include it with your content type feature.

I assume that you know that to include the content definition you need a minimum of the content type, the individual fields (storage and field settings), the entity form display, and entity view display.

There may be other specialty items like language settings here.  Enter the machine name of the content type in the feature editor search field (after checking include conflicts) to find them.  NOTE: Red indicates they are part of another feature and you may not need to include them.


Render a custom menu in a custom block I want to create a block that contains somes links of a menu, without using the interface.
So I created a custom module. Inside, there are somes files.

a mymodule/test.links.menu.yml :

test.menu.listown:
  title: list
  route_name: test.listown

test.menu.addnew:
  title: Add new
  route_name: test.addnew
  weight: 0
  parent: test.menu.listown

and a mymodule/src/Plugin/Block/test_block_main.php

class test_block_main extends BlockBase {
  public function build(){

    $mp = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters("test.menu.listown");
    $test = \Drupal::menuTree()->load("test.menu.listown", $mp);
    $render = \Drupal::menuTree()->build($test);

    return array('#markup' => \Drupal::service('renderer')->render($render));
  }

}

I cleared caches (drush cache-rebuild). When I go to my homepage, the "test_block_main" is displayed, but it is empty. Why is my custom block empty? Is the "test.menu.listown" parameter passed to the methods not correct?

You also need to provide the actual menu config entity as default configuration in config/install. Note that test.menu.listown is not a valid menu name, they can't contain dots only alphanumeric characters and dashes.

I'd recommend to prefix all default configuration with your module name, so that they're unique. Something like mymodule-something.

And, try to follow coding standards and conventions. For example, always use camelCase for class names, like TestBlockMain in TestBlockMain.php.

And last, avoid calling render() yourself whenever possible. You can just return a render array from a block.


How to Create and Retrive a product programmatically in Drupal commerce 2.x I have created the store in Drupal commerce 2.x. I have added a product for the product type from the dashboard. Now i want to create Product grammatically  in  my custom module. how  this can be done Drupal 8 for Drupal commerce 2.x

To create a product is similar to how you'd create a node:

use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

$variation1 = ProductVariation::create([
  'type' => 'default',
   'sku' => '123',
   'price' => new Price('14.50', 'USD'),
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
   'sku' => '1234',
   'price' => new Price('10.00', 'USD'),
]);
$variation2->save();

$product = Product::create([
   'type' => 'default',
   'title' => t('Product Title'),
    'variations' => [$variation1, $variation2],
]);
$product->save();


How to hide blocks based on content type or for specific nodes? In some of my nodes I need to show only "body" part of node. I don't want to show blocks etc. in those nodes. How can I do this ?

Create a new "content type" and put the data from existing nodes to that type of node. And excluding that "content type" from each of the blocks.
By using javascript/jquery like: $('div'.block).remove()

Any more elegant answers?

The answer very much depends on how the nodes you want to show only bodies of are different from all other nodes of same content type.

I see two possible solutions:

Create a new content type and convert all the nodes you want to it. Then you can specify in blocks visibility settings not to show blocks on the nodes of that content type and create a new template for this content type in which only body is printed.
Another way is to give the context module a try. The context module provides a much more flexible way to control blocks visibility so you can specify different contexts for your normal nodes (and assign blocks to this context) and your no-blocks nodes with no blocks assigned.

I'm sure there must be other ways to accomplish this, but these two are the first things I thought of :)


Display a field from a content type which is not displayed in the current node I can add new variables to the node (like day, month, year) based on current node->created. The problem is I need to display the date field from another content type which is not displayed on the page. How do I fetch it from there?

Here is my code so far:

  function mytheme_preprocess_node(&$vars) {
        $node = $vars['node'];
        $vars['year'] = format_date($node->created, 'custom', 'Y' );
        $vars['month'] = format_date($node->created, 'custom', 'm' );
        $vars['day'] = format_date($node->created, 'custom', 'd' );
      }

and I display them in node.tpl.php simply printing them as $day, $month, $year. I am interested in finding an answer. Thanks.

I think you're looking for the node_load function.
Example:

function mytheme_preprocess_node(&$vars) {
  // Load node with ID 123.
  $another_node = $node_load(123);
  // Format a date.
  $vars['another_node_created'] = format_date($another_node->created, 'custom', 'Y, m, d' );
}

Beware that node_load returns raw data from the database. While $another_node->created is a safe value to use, user entered data (eg. the title or body text) needs to be checked before you print it (eg. <?php print check_plain($another_node->title); ?>). Not checking raw data is a security risk for your site. See Handle text in a secure fashion for more info.


Reuse file uploaded via (File|Image|Whatever)Field in another node I noticed the existence of this file_usage table in D7's database and I was wondering if it's possible to link in a new node the same file I uploaded using a file field in a previously created node. This seems logical to me, yet I can't seem to find a way to do it.

The FileField Sources module expands the file field widget and allows the user to select new or existing files through additional means, including  re-use files by an auto-complete textfield, attach server-side files uploaded via FTP, transfer files from a remote server (cURL required) and select existing files through the IMCE file browser.

The Media module (2.x) provides and additional file field widget which use its media browser to upload or select a (media) file.


How to make a field readonly using hook_form_alter I am trying to make some of the Drupal profile form fields as read-only in edit mode. I am using the following code
in hook_alter

$form[field_organisation_company_name][und][0]['#after_build'][]='_build_element_readonly';

function _build_element_readonly($element, &$form_state) {
    $element['value']['#attributes']['readonly'] = 'readonly';
    return $element;
}

In the UI filed is showing as read-only, but still, I can change the value using firebug and save. Is there any way to prevent this behavior?

It sounds like you could accomplish what you need to with Field Permissions. On a field-by-field basis you can set permissions to:

  Create own value for the field
  Edit own value for the field
  Edit anyone's value for the field
  View own value for the field
  View anyone's value for the field

So you would easily be able to allow your users to create the value for the field initially, but as soon as they have it only becomes editable by an admin.


How to theme markers bubble with Gmap module? I've installed Gmap and location modules. I have a view with gmap display and i'd like to be able to display more than one field in the marker bubble, but the module doesn't allow more than one field in the bubble. How do i achieve that ? Is there a template or a theme function that'll allow me to do that?

Thanks.

There's a actually a way to do this in Views UI.

Add all your fields in Views as per usual
On the bottom most field (ideally the one that's the bubble), edit it and click on "Rewrite results".  (Note you can drag / reorder fields to get the right one at the bottom.)
Check the box, "Rewrite the output of this field"
Below that once expanded, you will see "Replacement patterns"
Now add in all the tokens into the rewrite text box. e.g. [title] == Content: Title, [some_other-field] == Content: Some other field, etc...
Click apply.
Now go in and edit the other fields that you added in to the bottom field and check the box "Exclude from display"
Now go to "Format" probably something like "Gmap" and click on "settings". You will see a "grouping setting
select to group on that bottom most field that you added in all the tokens to.
Save this and now all those fields should be in the bubble.

Obviously without seeing your view, I was guessing at some of this so you will have to try to make sense of it as it in terms of your view.


Search by product with punctuation I'm starting to configure frontend search for user search, and I can't find a product if it has a puctuation sign. For example, a product called

The world today: a new adventure

In search box, if I enter world today:, the search doesn't find the product.

Anybody could help me with that?

Drupal Core Search is designed to deal with many punctuations, but not all. Take a look at either of these modules:

Punctuation Preprocessor:

  This module implements a punctuation pre-processor that provides
  special handling for punctuation characters when they are encountered
  within word strings during searching and indexing.

Fuzzy Search:

  This module provides drupal sites with a fuzzy search engine to allow
  for broader keyword matches including partial or misspelled keywords.

or any of the other core search alternatives - they may pick up the punctuation better.


How to add "new" icon on node view page for predefined time frame I would like to add "new" icon on node view page of some content type for a predefined time frame after the node content is created or updated. For example, I would like to display "new" icon on the top of node view page for 2 weeks after the node content was saved. I found this for Views but need it for node page. Is there anyway to achieve this?

You can do this at least two ways:

1)  Edit your theme's node.tpl.php to include some PHP code that compares the current date and the node creation or modification date, and, if it's within the predefined timeframe, prints that "new" icon wherever you want it, or,

2)  Create a preprocess_node() hook in either a custom module or in your theme that sets a variable that can be used in your node.tpl.php file for the same purpose.

SNIPPET ADDITION:

A quick (but verbose for self-commenting purposes) preprocess() hook in your template.php file could look something like this:

function phptemplate_preprocess_node(&$vars) {

  $node=$vars['node'];

  $two_weeks_ago = time() - (14 * 24 * 60 * 60);

  $node_creation_time=$node->created;
  $node_changed_time=$node->changed;

  if ($node_creation_time >= $two_weeks_ago || $node_changed_time >= $two_weeks_ago) {
    $this_node_is_new="THIS NODE IS NEW!";
  }

  $vars['this_node_is_new']=$this_node_is_new;

}

This would provide a $this_node_is_new variable in your node.tpl.php template file(s) when the node was created or modified within the last two weeks.


DS and theme hook suggestion in my site I have update DS to the last versione 7.x-2.7 and now theme-hook_suggestions does not works. Drupal is update to the last version, too.

I, via mytheme_preprocess_node() function, insert some hook_suggestions for my node, based on node type and a field value.

Via devel themer I can see this:

Candidate template files:
ds-1col--node-article-full.tpl.php < ds-1col--node-article.tpl.php < ds-1col--node-full.tpl.php < ds-1col--node.tpl.php < ds-1col.tpl.php

theme_hook_suggestions (Array, 9 elements)
0 (String, 13 characters ) node__article
1 (String, 11 characters ) node__59325
2 (String, 31 characters ) ds_1col__node_article_cartoline
3 (String, 31 characters ) ds_1col__node_article_cartoline
4 (String, 7 characters ) ds_1col
5 (String, 13 characters ) ds_1col__node
6 (String, 18 characters ) ds_1col__node_full
7 (String, 21 characters ) ds_1col__node_article
8 (String, 26 characters ) ds_1col__node_article_full

Note that element nr 2 is my suggestion, so my function is correct.
(items 2 and 3 are identical because I have tried to insert the same template function code in a module function code to see if there was some type of problem with my templates).

Why my file (ds_1col__node_article_cartoline -> ds-1col--node-article-cartoline.tpl.php) in my "templates" directory in my theme is not used ? If I write a simple ds-1col.tpl.php in my "templates" directory file this file is used.

I have tried to change one of my module "weight" from 0 to 2 or from 0 to -1 (ds weight is 1) but without luck.

Where is the problem ?

Thanks.

I have 3 suggestions:

Might just be a typo on your behalf but the tpl file should be ds-1col--node-article-cartoline.tpl.php rather than ds-1col--node-article-immagini.tpl.php
Could it be that because you've specified ds_1col it's being affected by display suite's naming convention, try using your theme name instead.
There is some sort of inheritance that can be hard to spot, for example to override node--article.tpl.php you need node.tpl.php present in your theme


How to alter node body content through Views pre render hook? I have build the view to display node title and node body also I have applied combined fields filter which searches the keyword in title and body and returns the results.

While rendering the contents I have to render the title and body with the highlighted keywords that  are been searched.

Currently I am using hook_views_pre_render to alter the same.But unable to replace the body text with my generated results.

How can I alter the body contents?

What variable are you modifying? When I modify Views results I usually use hook_views_post_execute. I then modify the appropriate element in $view->result. You may be able to do the same from hook_views_pre_render (I don't use that one often especially in this type of case).


Changing language in drupal So my problem is i dont know how to make my custom menu item change language in drupal. I know there is a language switcher in drupal, but i want to make a new custom menu in drupal, theme it, and i want the links to trigger changing the language, like the link "french" changes the site to french. How can this custom trigger of events be created in drupal and how do i know which functions to call/variables to change to allow me to achieve this?

I really appreciate any help!

May be you are looking for language_negotiation_get_switch_links

  Return the language switch links for the given language.

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$links = language_negotiation_get_switch_links($type, $path);


How to redirect to referenced entity form with Rules I use drupal commerce. I have several entityform type. Each product has entity reference to one of these forms. How to page redirect to referenced form url when a product added to cart.

Thanks

You want to use Rules for this. It should already be installed since Drupal Commerce requires it.

Create a new rule by going to Admin > Config > Workflow > Rules, and click Add rule.

A rule consists of 3 parts.

The event, the action that triggers the rule.

The event that initiates the rule would be After adding a product to the cart.

The conditions, the checks to make sure the rule applies.

Use this to find your reference field;

Add a rule entity had field and check if the commerce_line_item (I suppose you get that by default) has a field commerce_product. Then add a second check to see if commerce_line_item:commerce_product has a field entity_reference.

Depending on where you created the field you might require several layers.

The actions, what to do if the rule is valid.

You want to use the Page redirect action in the system group. Make sure to click the data selector button, then you can search the redirect path. It suppose should look something like commerce_line_item:commerce_product:field_reference:url.


Permissions checkboxes have disappeared on the Admin page for administrator users All of the checkboxes on the Permissions page (/admin/people/permissions) have disappeared.

I see the permissions for a split second as the page loads before they disappear, so I think this is a Javascript or CSS issue.

Also, if I edit a single role's permissions (i.e., /admin/people/permissions/3), the checkboxes are there. This only happens when using the main permissions page.

Example of the disappearing checkboxes:

What I've done

I've switched my theme and admin theme to Stark to make sure my theme wasn't hiding the permissions.
I was using the jQuery Multi module to upgrade jQueryUI for some custom scripts, so I disabled that.
I've searched if anyone else has had this issue, and the only thing I've found is https://drupal.org/node/1649186. I'm not familiar with Organic Groups, and I haven't renamed any machine names, so that post didn't get me very far.

Oh my, I just discovered what it is and I feel really ridiculous... I'm using the admin menu module, and in the configuration, under "System tweaks", there is an option "Collapse module groups on the Permissions page". It is checked. The checkboxes weren't hidden after all. The groups were just collapsed... Maybe I just need a break and another cup of tea.


How does the service module work? i am using drupal 6 and services 6.3x module but i am unable to use this module completely.
I have enabled rest server module also.
I added a new service and added resources to it.
I added node resource to it and i am able to fetch all the nodes in json format

what i am not able to understand is :-

The exact uri or may be the procedure to call getTree method in taxonomy_vocabulary resource
How to acccess all the methods (CRUD) functions under every resource enabled
The url -> mydomain.com/service/rest/node.json works for me but how can i access the getTree method ??

I am stuck on this like forever i have even posted jobs on the drupal site but i guess there are very rare people who have knowledge about this.

Edit :-

Live link is http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy_vocabulary

The following is the java code i am using :-

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = null;
    HttpPost postMethod = new HttpPost("http://delvelogic.com/merchant/drupal-6.22/rest/taxonomy_vocabulary/getTree.json");
    postMethod.addHeader("Content-type", "application/x-www-form-urlencoded");
    postMethod.addHeader("Accept","application/json");
  //  postMethod.addHeader("Authorization", "basic " + Base64.encodeBytes(("admin"+":"+"admin123").getBytes()));
 //   httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT));

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("vid", ""+1));
     nameValuePairs.add(new BasicNameValuePair("parent", ""+1));
     nameValuePairs.add(new BasicNameValuePair("maxdepth",""+1));
    // nameValuePairs.add(new BasicNameValuePair())
    try{
     postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     response = httpClient.execute(postMethod);

     InputStream input = response.getEntity().getContent();
      BufferedReader rd = new BufferedReader(new InputStreamReader(input),input.toString().length());
     String line;
     StringBuilder sb =  new StringBuilder();
     while ((line = rd.readLine()) != null) {
            sb.append(line);
     }
     rd.close();
     uploadresponse = sb.toString();

     Log.d("Response", ""+uploadresponse);
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

Also if there is any firefox add on so that i can actually see the method working ??

Edit Again :-

I have found this add on restclient to work on firefox

i choose the method as post
in the url i typed http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy_vocabulary/getTree

added header :-

Content-type : application/x-www-form-urlencoded

Accept : application/json

request body :-

&vid=1&parent=1&maxdepth=1

it gives me 404 not found with no vocabulary with id 1 found
Thanks in advance

According to the documentation the URLs shouldn't necessarily have .json at the end, but I guess this is a setting you've changed if it's working for the node functions. I know you're not going to like this answer (I'm fairly certain you've tried it before) but the URL is: mydomain.com/service/rest/taxonomy_vocabulary/getTree. I've even been through the service and rest_server modules' respective code and that is definitely what it should be.

For further proof look at the (valid, passed) test module for services taxonomy_vocabulary:

ServicesResourceTaxonomyTests::testVocabularyGetTree.

You'll see that the URLs accessed by this successfully passed test are: $path . '/taxonomy_vocabulary/getTree', where $path is the path to the endpoint (i.e. mymodule.com/service/rest/).

It really would help if you could provide a live link though so we can test to see if the problem is in your Java code or with Drupal (although the latter seems very unlikely).

EDIT

p.s. do comment on this answer as I have a lot of experience with the services module and I'm sure I can point you in the right direction with a bit more info. It pains me to see someone struggling with something that I've had nothing but joy with in the past!

ANOTHER EDIT

This is the response I get from http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy_vocabulary:

<?xml version="1.0" encoding="utf-8"?>
  <result>
    <nodes/>
    <module>taxonomy</module>
    <name></name>
    <help></help>
    <relations>0</relations>
    <hierarchy>0</hierarchy>
    <multiple>0</multiple>
    <required>0</required>
    <tags>0</tags>
    <weight>0</weight>
    <vid>4</vid>
  </result>

Notice the <vid>4</vid> bit...I'm pretty sure the vid you should be looking for is 4, not 1!


Display contact information for each car owner I am trying to view contact information for each user who will be the car owner in this case. so in each car in car content type I want to display user info with each car he post

best

How do you gather the contact information? Is it profile fields or a node connected to the user account?

Regardless of the method you can create a view that will use the author of the node as the argument of the view (D6) or contextual filter (D7) to bring the contact information for the user. One thing to consider is that you might have to create a relationship to the entity or method you used to collect the information.

After the view is created the next thing will be to decide how to present it, maybe you want to create a block, or attach it at the end of the car content type or make it a tab, all those options are available in views as well.


Custom CKEditor buttons or wrong way? I need to setup a textarea field which will provide game cheats. So I have small gifs of each and every button of Xbox, PLaystation and so on. So when someone wants to publish a cheat for Xbox he needs to insert this small gifs into the text area field. How could I go about this?
I thought it would be possible to setup a custom button for each gif in the ckeditor but I can not find out how to do it. Or is there a better way?
Thanks

One Option might be BUEditor if you're not tied to CKEditor. BUEditor buttons are easily and highly customizable.


Is it safe to use $_SESSION to store temporarily a user provided value under multi-step form processing I have a form which contains an AJAX button press callback. Upon pressing this AJAX button, I want to store temporarily a form element's value before fully processing all the data upon pressing main form submimission button. On the meanwhile, how do I store that particular field value? Is it fine to achieve this using $_SESSION? Is this secure? Does it work flawlessly under Drupal 7, or is there a better alternative?

Drupal has an Ajax framework for this use case. Use $form_state to store values. The API page about the Ajax framework contains a use of $form_state.


Custom nested element and its child sub-elements callbacks I'm trying to create a custom element that consist of a few other elements, namely some select box and one timeperiod element.

I've set up custom #process, #value_callback, and #element_validate and everything works well with one exception. The #element_validate` of timeperiod element is run after my own elemen's callback is which means I can't effectively use the results of that field for either validation or creation some structured output.

As far as I know it's a normal drupal7 behaviour, callbacks on forms are supposed to be run top->down. That said, however, I still need some after-submit callback on higher-level element that can access already final results of all of its children elements.

I'd also love to know why has top-down approach been chosen. Because no matter how much I think about it it's just completely non-sensical.

Specific example:

function TST_element_info() {
  return array(
    'station_channel' => array(
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => array('TST_element_process'),
      '#value_callback' => 'TST_value_callback',
      '#element_validate' => array('TST_element_validate'),
    ),
  );
}

function TST_element_process($element, &$form_state, $form) {
  global $user;
  $opts = array(/* magic */);
  $element['Sel'] = array(
    '#type' => 'select',
    '#options' => $opts,
    '#empty_option' => t('Tsss'),
    '#empty_value' => 'default',
  );

  ...

  $element['Per'] = array(
    '#type' => 'timeperiod_select',
    '#title' => t('Tsss:'),
    '#required' => true,
     '#units' => array(
       '86400' => array('max' => 365, 'step size' => 1),
       '3600' => array('max' => 23, 'step size' => 1),
       '60' => array('max' => 55, 'step size' => 5),
     ),
  );
  return $element;
}

function station_channel_value_callback($element, $input = FALSE, &$form_state) {

  if (empty($input) || $input == 'default') {

    if(isset($element['#default_value'])) {

     /*magic*/

    } else {

      return false;

    }

  } else {

    $Sel =  $input['Sel'];
    $Per = $input['Per'];

  }

  return array(
    //I'd need need to return something like (or I could do it in validate):
    //But can't do it here because $input['Per'] contains raw input from its three textfields instead of computed timestamp (and even if I altered the module to do the computation in its #value_callback it would still not help because their callback is run after mine).

    'path' => "weirdStuff/$Sel/period/$Per/json"

     //Therefore I have to return:
    'Per' => $Per,
    'Sel' => $Sel,

  );
}

function TST_element_validate(&$element, &$form_state) {

  // Magic validation

  $Sel = $element['#value']['Sel'];
  $Per = $element['#value']['Per'];

  $validated_input_array = array(
     //Again, I'd need to do this but can't because timeperiod's element_validate is run after mine which means their $element['#value']['Per'] still contains raw data.
     'path' => "weirdStuff/$Sel/period/$Per/json"
  );
  form_set_value($element, $validated_input_array, $form_state);

}

//It's perfectly ok in form_submit, the form_state['#values'] contains computed (timestamp) data for the period field. But that is kinda too late for my own element.

PS: Consider this example but with one of the sub-elements that are used for connection string connection being a bit more complex one that computes its true value in #element_validate.

The whole workflow of form API is shown here  (source: https://www.drupal.org/node/165104).

You can notice that #process is top-bottom whereas #after_build is bottom-top, and #element_validate is a whole another step and bottom-top. You can also see that #value_callback is called quite early (even before #process).

Thus, and by experience, your #value_callback should not be more than 15 lines long, and in the case of a nested element, always take form_type_checkboxes_value or form_type_radios_value as examples: they only care about edge cases and rarely modify values.

This said, another input to take into consideration is the timeperiod module, because your way of handling will depend entirely of this module. (source: http://cgit.drupalcode.org/timeperiod/tree/timeperiod.module)

/**
 * Implements hook_element_info().
 */
function timeperiod_element_info() {
  // A duration form element which represents the duration in seconds.
  $types['timeperiod_select'] = array(
    '#input' => TRUE,
    '#tree' => TRUE,
    '#default_value' => 0,
    '#value_callback' => 'timeperiod_element_value',
    '#process' => array('timeperiod_element_process', 'ajax_process_form'),
    '#after_build' => array('timeperiod_element_after_build'),
    '#pre_render' => array('form_pre_render_conditional_form_element'),
    // Controls the available units. Array keys are the units, see
    // timeperiod_element_units(). The values control the number of available
    // values per unit, taking steps in the configured size starting from 0.
    '#units' => array(
      '3600' => array('max' => 23, 'step size' => 1),
      '60' => array('max' => 55, 'step size' => 5),
    ),
  );
  return $types;
}

timeperiod_element_value() does literally nothing (see its comment)
timeperiod_element_process() breaks down into units and sets up sub-elements
timeperiod_element_after_build() actually sets the
value

So based on these informations, you also need to implement #after_build, which is bottom-up, so it will run after timeperiod, and set the value using form_set_value()

Remember that validation is only for validation, and will always have processed values as input.


Drush can not connect to mysql when run a Drupal in a Docker/Azure I have a website that it's running ok in Docker/Azure.

I have this configuration in my settings.php

$databases ['default'] ['default'] = array (
    'database' => getenv ( 'MYSQL_DATABASE' ),
    'username' => getenv ( 'MYSQL_USER' ),
    'password' => getenv ( 'MYSQL_PASSWORD' ),
    'prefix' => '',
    'host' => getenv ( 'MYSQL_HOSTNAME' ),
    'port' => getenv ( 'MYSQL_PORT' ),
    'driver' => 'mysql'
);

When I make drush status

I get this.

 Drupal version   : 8.7.3
 Site URI         : http://default
 DB driver        :
 DB hostname      :
 DB port          :
 DB username      :
 DB name          :

Any idea how to make that Drush get the mysql configuration options?

Thanks

It looks like the environment variables are defined only for HTTP requests. In other words, they seem to be set in FPM, NGINX, or Apache, but not in your shell.

Try typing echo $MYSQL_DATABASE in your shell. If that outputs nothing, you'll have to export the environment variables first, so Drush can see them.


Social Field Module: Icons not showing up in options Trying to use Social Field Module for general user Profile. Followed through module text but no icons appear to show up for the module in either the Field itself or from an End-user logged in perspective. Installed Font Icon Module also.

Anyone any ideas why this is? Module seems quite simple, but maybe I'm missing something or it's lost in translation somewhere.

Just copy "font" and "Css" folder in your activated theme and if it ask to merge just allow them to merge and check further.

Hope this helps you.

Thanks!


Create node upon form submit rendered by block plugin I'm attempting to create a block plugin that displays a form that allows users to enter information and create a node with that information.
I understand I can easily create a form plugin that accomplishes this task but I'd like this to be inside a block plugin so that I can place it on existing pages instead of it being on it's own dedicated page. I'm building the form like so

<?php

/**
 * @file
 * Contains \Drupal\my_plugin\Plugin\Block\EquipmentEntry.
 */

namespace Drupal\my_plugin\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @Block(
 * id = "equipmententry",
 * admin_label = @Translation("Equipment Entry"),
 *  )
 */

class EquipmentEntry extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        return $form;
    }
    public function blockSubmit($form, FormStateInterface $form_state) {

    }
    public function build(){
                $content = [
            'container'    => [
                '#type'       => 'container',
                '#attributes' => [
                    'class'      => ['equipment-entry'],
                ],
                'form'         => [
                    '#type'       => 'form',
                    '#attributes' => [
                        'name'       => 'equipment-entry',
                        'id'         => 'test',
                    ],
                    'title'   => [
                        '#type'  => 'html_tag',
                        '#tag'   => 'h1',
                        '#value' => $title,
                    ],
                    'contact'      => [
                        '#type'       => 'textfield',
                        '#title'      => t('Contact Person'),
                        '#attributes' => [
                            'name'       => 'contact',
                        ],
                    ],
                    'Telephone'    => [
                        '#type'       => 'textfield',
                        '#title'      => t('Telephone'),
                        '#attributes' => [
                            'name'       => 'phone',
                        ],
                    ],
                ],
             ];
          return $content;
    }
}

However I'm not sure how to perform any action upon submitting the form. I understand there's a blockSubmit() function but I believe that's only when you save a block.

I tried intercepting the form with a form_alter hook like so

function my_plugin_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
        die($form_id);
}

but the function never fired. Is there a way to programmatically create a node when someone submits a form that was created to be displayed inside a block plugin? Or is there a way to create a form plugin and embed it inside a block?

You are right, the blockSubmit() method is used when you configure the block. The config form is in blockForm(), not in build().

If you put form elements in build() they get rendered like any other render element, but they are not part of the form api and can't be submitted.

If you want to build a form, use a form class. Then you can put the form class in build() by using the formBuilder():

public function build() {

  $content = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

  return $content;
}

Better solution:

Instead of building your own form use the entity form for nodes, which you can place in a block with this module: https://www.drupal.org/project/entityform_block


What's the best file permission to drupal's files and directories? Possible Duplicate:
  What are the recommended directory permissions?

I want to know what's the best file permission under a linux system to my drupal's files and directories including the files directory and the core either.
Thank you very much

Drupal has already a well documented page with all informations you are looking for.


How to run PHPUnit tests? Drupal 8 is supplementing the testing framework based on Simpletest with PHPUnit, and Simpletest could be removed in Drupal 9.

I'm not upgrading yet to Drupal 8, but I was wondering how I can write existing tests in PHPUnit (to follow-up with the trend) for Drupal 7, instead in Simpletest?

Is there any method or module for integrating PHPUnit with Drupal 7?

There are few like phpunit or drunit, but they're not for Drupal 7.

You can get PHPUnit tests to run by bootstrapping Drupal within each of your test files. It's not ideal, but it does work.

define('DRUPAL_ROOT', 'your/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

// Bootstrap Drupal.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Proceed with PHPUnit tests as usual from here.
class MyTest extends \PHPUnit_Framework_TestCase {
  ...


Using Webform as an Application for membership/user roles I'd like to implement the following on a Drupal site:

Anonymous site visitor (Joe) submits a membership application with various custom fields
Admin (Jane) reviews membership application
Jane approves Joe's application and creates new user account
Joe gets notice of approval and login information

Possible solutions:

A Webform (But how can the data from the webform be easily transferred into a user account?)
Profile2 with Admin approval necessary. (The problem with this one is we don't want it to feel to the user like they are creating an account on the site, but applying for the membership.)
Create a Membership content type that an anonymous user can fill out (?)

I feel like I'm overlooking something obvious.

I can't use the core user registration with additional fields because there are 3 different types of memberships. And users should be able to change from 1 membership to another (upon approval).

Based on some other questions you've asked on this site I wonder if you are using CiviCRM for tracking the memberships? If so I might suggest this workflow:

Setup a webform with CiviCRM integration. Add your membership and other custom fields to the form.
Set the membership status to be "Approval Needed" (you can create that status in CiviCRM if it isn't there already).
Have it send an email to your staff whenever that form is filled out.
You can optionally restrict access to that form so that only non-members can use it.  This would require you to enable the module 'CiviMember Roles Sync' which is bundled with CiviCRM and enabled syncing between Drupal roles and Civi memberships.


Display a field of a node that is referenced on another node via a relationship I have two content types, "Stores" and "Offers." In the "Offers" content type, there is a CCK node reference field type that references the "Stores" nodes.  So essentially, I create a store and if the store has an offer, I create the "Offer" node and select the store with which it is associated.

I have a view (a default glossary view) that displays a list of stores. I would like to display the node titles of any offers that are associated with it but I can't figure out how to do it.

I have tried to add a relationship on the node reference field then add a field that uses the relationship but the result just appears blank.

In your view style template you can access the node reference value, load the related node and then do whatever you need with that. You don't need a relationship for this approach.


How to prevent caching of field element data in custom field formatter? I have a custom field formatter that performs dynamic calculations to determine the output. However, for anonymous user's the previous data is always stored until a cache clear is performed.

in the field formatter viewElements() function I have the $elements #cache max-age set to 0. I thought this would resolve the issue but it does not. Am I missing something?

 public function viewElements(FieldItemListInterface $items, $langcode) {

    $elements = [];

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
      // Check if gate cookie is set

      if (isset($_COOKIE['Drupal_visitor_resource_gate'])){

        //$tags = $file->getCacheTags();
        //Cache::invalidateTags($tags);
        $item = $file->_referringItem;

        $elements[$delta] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
          '#cache' => [
            'max-age' => 0,
          ],
        ];

        // Pass field item attributes to the theme function.
        if (isset($item->_attributes)) {
          $elements[$delta] += ['#attributes' => []];
          $elements[$delta]['#attributes'] += $item->_attributes;
          // Unset field item attributes since they have been included in the
          // formatter output and should not be rendered in the field template.
          unset($item->_attributes);
        }
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }else{
...
}

For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.

If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:

  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';


How to get the current active DB in Drupal 6? You can easily print out the current db_name, by printing out $db_url. But there is no clear way in the API that allows you to print out the "key" for the active db. So I have two dbs, namely "testing" and "default". What php code can I run to find out whether I am currently using the "testing" db, or the "default" db?

I'm bascially looking for the inverse of "db_set_active". So If I do this:

db_set_active("default");

What can I call directly after it to find out which is the current active db (i.e. "default")?

Doesn't look like drupal allows it inherently, so I'm posting my hack in the meantime. I'm open to any suggestions on improving this:

global $db_url;
$activeDBName = db_result(db_query('select database()'));
$mode = '';
foreach ($db_url as $key => $url) {
    if(strpos($url, $activeDBName) !== FALSE) {
        $mode = $key;
    }
}

$mode will then be whatever the active db is.


Theme a link with l - redirect to translated version I'd like to insert a link in my node templates that displays when viewing nodes of a particular type (news). That link should lead to the news archive (node/26). Node 26 is a normal drupal page made in swedish (with a menu item and so on). On that page a block is displayed with a viewed list of news items.

There is a translated version of node/26 - translated with normal multi language modules.

What I'd lite for the system is to redirect from node/26 to the english translated version (node/27) if the current users language is english.

I have the module Translation Redirect activated - but it does not redirect.

If a redirect can't be achieved - is there any way that the link function can create the link depending on what the current language is (preferably without if-cases for each language).

Version is Drupal 7.

Thank you very much for any replies!

I ended up doing it this way:

$nodepath = "node/26";
$languagepaths = translation_path_get_translations($nodepath);
$currentlanguage = i18n_language()->language;
$path = $languagepaths[$currentlanguage];

if (preg_match('/^node/',$path)) {
    $path = "". drupal_get_path_alias($path, $currentlanguage);
} else {
   $path = $nodepath;
}


Displaying only what's entered on the page I have created a new field within one of the content types that can be entered on the content pages and placed the block into the layout, but it seems to add all the pages content that was entered in on all the pages within that field. How can I filter it, so it only shows what has been entered on that specific page.

On the far right, Under Advanced, for Contextual Filters click add

Add Content ID, select provide default value, select content ID from URL.


Why can't I disable or enable the block cache? In the admin/settings/performance page, I (the administrator) cannot enable or disable the block cache. Why?

I know you asked "why?" not "can i get around that problem"... but you can get around that problem without removing modules that use hook_node_grants(). Try out the Block Cache Alter module. It allows, among other things, the ability to use block caching even if modules implement hook_node_grants().


My New Site admin approval I'm planning to build a website with Drupal (having very little experience in building sites and none with Drupal). Through my webhost I managed to install Drupal on my site and I tried to create a drupal account immediately. I got an email "Account details....(Pending Admin Approval)", but then nothing. Maybe I'm just too eager and should just wait longer :-), but it could also be that I did something wrong.
So my question: is it normal for an account to take more than 3 days getting My New Site admin approval? And can I do something to speed up the process?

I'm following some tutorials and wish I could play around a little while learning.
THanks for the info!
Hetty

When you installed Drupal you should have had to setup a main account:

That is the login you should be using, if you don't know that password go to /user and click Forgot Password and you can retrieve your login if you remember username or email you used. Since you got (Pending Admin Approval) it should be that email that is registered as main account.

(Pending Admin Approval) emails are sent when someone else tries to register an account on your site.


Using GraphQL webform add-on I started to use GraphQL for my drupal8 application to expose some data.  Now I want to use it to return a webform that I created.

I installed an add-on for webform graphl https://github.com/duartegarin/graphql_webform but am not sure how to use it.  I thought it will add a new query type called WebformQueryById but it is not showing up when I navigated to the GraphQL explorer.

I have been stuck for days on this.  Is there some configuration / setting steps I might be missing?  Thanks

You can use the fields defined on the graphql_json module in order to retrieve the webform structure.

{
  webformById(webform_id: "contact") {
    webform {
      elements {
        name: path(steps: "#name") {
          ... on JsonLeaf {
            value
          }
        }
        type: path(steps: "#type") {
          ... on JsonLeaf {
            value
          }
        }
        title: path(steps: "#title") {
          ... on JsonLeaf {
            value
          }
        }
      }
    }
  }
}

Result:

{
  "data": {
    "webformById": {
      "webform": {
        "elements": [
          {
            "name": {
              "value": "name"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Your Name"
            }
          },
          {
            "name": {
              "value": "email"
            },
            "type": {
              "value": "email"
            },
            "title": {
              "value": "Your Email"
            }
          },
          {
            "name": {
              "value": "subject"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Subject"
            }
          },
          {
            "name": {
              "value": "message"
            },
            "type": {
              "value": "textarea"
            },
            "title": {
              "value": "Message"
            }
          },
          {
            "name": null,
            "type": {
              "value": "captcha"
            },
            "title": null
          },
          {
            "name": null,
            "type": {
              "value": "webform_actions"
            },
            "title": {
              "value": "Submit button(s)"
            }
          }
        ]
      }
    }
  }
}

You can find the available steps with keys field.

{
  webformById(webform_id: "contact") {
    webform {
      elements {
        keys
      }
    }
  }
}


How can I categorize nodes by countries? I have a created a content type "person", added to it custom field "country". I have downloaded the "countries" module and installed it.

I would like to categorize "person" nodes by countries, i.e. by clicking on the person's country, I could see all persons who live in the same country.

I don't think taxonomy could do the trick since I will have to add around 140 vocabulary terms also, node reference seems not to work properly...

Any help?

Thanks
Sam

You can achieve this by using views:

Create a new view that displays persons.
Under "Advanced" add a contextual filter for your country
As path use: "my_path/%"
All users for country "Belgium" Will be available on "my_path/BE"


RDFa output and Panels I need to get RDFa working with Panels.  As it currently stands, fields output with panels or panelizer will have their property fields set correctly.  You can see an example of this at http://schema.org/Product when you look at the bottom and view RDFa output.

The part that isn't working is getting all of the properties to be wrapped by their proper type, in this case Drug.  So at some point, all of the output fields need to be contained within a wrapper that has the attribute typeof="Product".

Panels has no support for this, but you can see an example of what it would look like if you looked at some sample node output.  The node container wrapper would look something like this.

<div id="node-121" class="node node--product node--full node--product--full clearfix" about="/products/sample-product" typeof="schema:Product sioc:Item foaf:Document" role="article" itemscope="" itemtype="http://schema.org/Product">

That's your typical RDFa output when rendering output with node.tpl.php.  Panels doesn't use this though, so it never gets rendered.

I'm hoping someone out there has dealt with this situation.  Structured data is pretty common to see these days, and so is the use of Drupal with Panels.  Someone has to have tackled this problem before, and I'm just looking for the best solution possible at this time.  Thanks.

TL;DR: What is the best way to get RDFa working with Panels?  Specifically, getting the typeof property added to some wrapper element which contains all of the other properties.

This is a known issue, and something I'm hoping to tackle at some point in the next couple of months: https://drupal.org/node/1485074 (see in particular comments #5 and #8). Feel free to subscribe to that issue as well.


Is necessary any sanitization functions if I use the database layer correctly In Writing secure code said:

  Use the database abstraction layer to avoid SQL injection attacks

Then, my question:

When I get value for a user form is necessary pass to check_plain() or others sanitization functions, before I use the database layer correctly.

The db abstraction layer, as you noted, should prevent SQL injection attacks.

Check_plain is actually used to make sure text is html safe. If your printing out user submitted data to the screen, it should (at some point) be run through check plain to guard against cross site scripting attacks.


How do I show a progressive number such as "Item 1 of termName", "Item 2 of termName"? I have a vocabulary with 4 taxonomy terms. There is a content type with a taxonomy reference field for that vocabulary.
I have a view that is pulling a list of all these nodes on a page. My design calls for the list to display to which taxonomy term the nodes belong, along with a progressive number.

Each node shows Issue #, where the progressive number shows which node was created first for that taxonomy term.
I thought being able to use tokens in view fields would help, but it seems it isn't currently possible, reading Provide Field item that supports Text Filters.
Does anyone know of a way to accomplish this without writing custom code?
I saw Node count for taxonomy terms, but that's about showing a node count, while I want to show a progressive number.

I know that you can set the format to html ordered list and group by the tag, but that will number the items automatically as in a standard ordered list with no control of the placement or prefixing with "Issue #". See Number items in a grouped view, resetting counter with each group, for example.
I think the views_php module with some custom coding could possibly work. I'll admit I have difficulties in getting parameters to reset effectively at times, but perhaps your mileage will vary.


Create Drupal User when creating commerce customer I am using drupal commerce. What I've found out so far is, that when you create a commerce customer, no drupal user is generated. But without a drupal user attached to the customer, you can't use that data in an order. Am I just missing something, or is this the most useless user-management I've ever seen? What do I have from customers if I can't use them.

Do I have to generate a drupal user first, then change to commerce and generate a customer there and attach the drupal user? Any chance for a one-step-solution?

It is not a usual workflow to create customer profiles "by hand" even if the UI allows for this, the normal workflow would be when the user performs an action, the profile is generated, normally when they progress through the checkout process. At the end of the checkout, order, profiles and user are linked together in case of an anonymous purchase.

The same way you can't create a node and assign the author to an unexistant user, you can't create a customer profile and expect that the references appear magically.

Of course you can build a workflow that makes more sense to you and build a useful solution for your use case, one thing you could do is use Rules to generate a user every time you create an anonymous customer profile, but this will probably conflict with the normal checkout process as customer profiles are assigned to anonymous users when there's an anonymous purchase.

I'd create a boolean field attached to the customer profile that reads "Create a user for this profile" or similar and on the Entity creation event in rules, you can add an action that creates the user. You've got a very similar example in the default commerce Checkout rule "Create a new account for an anonymous order" for how to create an user.


How can i fetch the value from database in a simple module? I'm working in drupal 7 and I have tried all help but not able to fetch the value from database.

    function myModule_load($node){

    $result = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => 258,));
$record = $result->fetch();

    // print the fields/values of $record
print('<pre>'); print_r($record); print('</pre>');

and also

    function myModule_block_view($delta) {
       if (($node = menu_get_object()) && ($node->type === 'product')) {
        $results = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => $node->nid));
        $records = $results->fetchAllAssoc('bid');

        $content = ... // Format records here...

        return array(
          'subject' => t('Bids'),
          'content' => $content
        );   } }

I want to fetch the value in module and in the page, but not at the top of the drupal header

Something like this should work:

/**
 * Implements hook_block_view
 */
function MY_MODULE_block_view($delta = '') {

  if (($node = menu_get_object()) && ($node->type == 'product')) {
    $query = db_select('uc_auction_bids', 'bids');
    $query->fields('bids');
    $query->condition('nid', $node->nid);
    $result = $query->execute()->fetchAllAssoc('bid');

    // Debug
    drupal_set_message('<pre>'.print_r($result,1).'</pre>');

    $content = ''; // Format records here...

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );
  }

}


trouble with hook_menu I am trying to set up a new menu item in Drupal 7 and not having any luck. I've tried several examples and have been successful at this in the past, but this is just not working.

The following code is in a module called directory, I keep getting a "page not found" error.

function directory_menu() {
  $items=array();

  $items['directory'] = array(
    'title' => 'Employee Directory',
    'page callback' => 'directory_content',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function directory_content() {
  $content = array();

  $content['raw_markup'] = array(
    '#type' => 'markup',
    '#markup' => 'Testing',
  );

  return $content;
}

Your code is working perfectly ok. I installed it you can check the screenshot below.


Linking to My Blog on Menu I am creating a new Drupal website.  I want to create a menu tab that links to the My Blog section.  What URL link do I use for this?

Should be just (whatever your drupal directory)/blog, if it's installed in root directory, then it would look like http://www.example.com/blog, if the blog you created is different from the system default one, it would be http://www.example.com/your_blog_machine_name


How to pass argument into markup (renderable array)? I'm doing a Drupal 7 module course. We're building a function in an include file that takes and argument from the URL. It then prints the value to the page. Seems simple enough, but then he does this in the example:

function good_morning_extra($wildcard) {
$content = array(
'#type' => 'markup',
'#markup' => '
' . t('The wildcard contains the value "%wildcard".', array('%wildcard' => $wildcard)) . '
',
);

return $content;
}

It's this part that has me confused, and the instructor glossed over it: 'The wildcard contains the value "%wildcard".', array('%wildcard' => $wildcard) Why not just 'The wildcard contains the value "' . $wildcard .'"
'?

It prints out the same, but I'm wondering if there's something to learn here.
I'm still learning the whole "renderable array" syntax and exactly what that means. I have a feeling understanding this may be key to me understand how Drupal passes data around.

The docs for format_string() should clear up the confusion:

  @variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
  %variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
  !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

So in the specific case you've provided, %wildcard is used to ensure that the value is :

  Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.

The different placeholder types are simply used in different situations, depending on what you need to do with the value, and whether or not you trust its source.

The docs for t() are also worth a read for extra context.


After each View Item I made a block using the Views module, that displays 3 blog posts. It only displays the title and the teaser, and I want to add a "Read More" after each blog post teaser. I can only see how to add a footer to the end of the whole block, not after each listed item. Is this possible? thanks

Sure, add a Node: Link field, turn off the label, and set the Text To Display to "Read More" and you should be set.


How to force login before submitting webform? Drupal 7.17, Webform 7.x-3.18 : I'm presenting a webform that anyone can fill out, but upon submit, if the user is anonymous, or not logged in/authenticated, I want to force a redirect to the login page (with a callback to the redirect of the webform). In other words, they must register or login in prior to submitting data in that webform.

So far, I've tried Rules to no avail. If (content type is Webform), and Site User Role is Anonymous, then Page Redirect to [site-url: login].

I suspect a webform relies on the Form API, but maybe forcing login at the submit handler might work (webform api?), but how do I get a callback to the form redirect within that submit handler?

I noticed Confirm Form - http://api.drupal.org/api/drupal/modules%21system%21system.module/function/confirm_form/7, but we're not confirming, it's more of a validation?

Keep in mind, I want the anonymous user to see the form, so using content access or limit visibility of form by role won't necessarily work. Thanks in advance for any advice!

Here is a simple example, you would place this in a custom module:

function hook_webform_submission_presave($node, $submission) {
  //test is user is anon
  if (user_is_anonymous()) {
    //tell user what is going on
    drupal_set_message("Please register before submitting form");
    //redirect to registration page, with path to send back to form when done
    drupal_goto('user/register', array('query'=>drupal_get_destination()) );
  }
}

Here are docs for hook_webform_submission_presave(), and webform.api.php within the webform module is also a great resource.

It seems to preserve form data with select components, but not 100% on that.


I want the view to show no results when the filter doesn't containing anything I am trying to use the Views module for an auto-submit field, to get the names from my taxonomies. How can I get the field to show the results after the users type something into the input box, instead of showing all the results when nothing has been entered as value for the filter?

I have tried a number of contextual filters but no luck.

This what the current search looks like, if I type in one of the terms or the field name it matches up to what I type which is how i wanted it to work, the problem is the the results are showing by default before I type anything.

This is built into views 3:

Edit your view
Set Advanced | Exposed Form | Exposed Form Style to input required


No hooks are called on webform submit I have created a registration form via webform 7.x-3.18. In my custome module I wrote following hooks

  MYMODULE_node_submit($node, $form, &$form_state)

  MYMODULE_node_insert($info)

But on form submission none of the hooks are triggered.
I tried submission with normal article page content form and at that time my custom module hooks are triggered.
Could someone tell the problem with my code??

Please check on the Webform's hooks list Webform Module Hooks here. These hooks are associated with each webform activities.


Drupal Commerce "product type" vs kickstart "variation type" I am new to online shops creation, and I am looking at Drupal Commerce and its popular distribution package, Drupal Kickstart.

I understand more or less the concept behind "product type" in Drupal Commerce, but Kickstart uses different terminology - "product variation type". Is it the same thing? Is there difference?

Product variations types within Drupal Commerce Kickstart are the same as product types referenced by vanilla Drupal Commerce.

I think the label changed within Kickstart so that it is a little less ambigious.


Unsupported operand types error when creating new Webform handler Following the example here: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-programmatically-add-a-handler-to-a-new-webform

I've created my handler manager sucessfully, however, when I go to create the handler, I get the error

  Error: Unsupported operand types in Drupal\webform\Plugin\WebformHandlerBase->setConfiguration() (line 363 of /var/www/sitename/web/modules/contrib/webform/src/Plugin/WebformHandlerBase.php

Here's a sample of the code I'm using to get this error

$webform_machine_name = 'form_id';
$webform = \Drupal\webform\Entity\Webform::load($webform_machine_name);

$handler_manager = \Drupal::service('plugin.manager.webform.handler');

// Create webform handler.
$handler_configuration = [
  'id' => 'my_form_handler',
  'label' => 'My form handler',
  'handler_id' => 'my_form_handler',
  'status' => 1,
  'weight' => 0,
  'settings' => [],
];

$handler = $handler_manager->createInstance('my_form_handler', $handler_configuration );

When I look at line 263 in \Drupal\webform\Plugin\WebformHandlerBase there is the below code...

$this->configuration = $configuration['settings'] + $this->defaultConfiguration();

Your Unsupported operand types error message indicates that one of those variables/properties is not an array.

My best guess is that \Drupal\webform\Plugin\WebformHandlerBase::defaultConfiguration is not returning an array() because your $configuration['settings'] is set to an empty array.


How to set an existing database field to auto increment I have an existing database that has an id field that is an unsigned integer with a length of ten (and is set as the primary key). I would like to write an update to change this field so that it auto increments. How would I go about doing that? I am familiar with writing updates, just haven't done one like this before. I am doing this with Drupal 7.

I found the solution I was looking for here. Below is the relevent part.

For example, suppose you have:

$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is:

db_drop_primary_key('foo');
db_change_field('foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));