HTML mail - how to properly format message I am trying to implement html mail notifications using htmlmail module. I am not certain if message should be formatted as array in $message["body][] before the template or passed as a string in $message['body'].

The reason I am asking is that I first expected the email to be sent in as a string but then saw the HTMLMAILSystem::format function that flattens the body array:

  public function format(array $message) {
    $eol = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    // @todo Remove this when issue #209672 gets resolved.
    $default_from = variable_get('site_mail', ini_get('sendmail_from'));
    if ( !empty($message['headers']['From'])
      && $message['headers']['From'] == $default_from
      && valid_email_address($default_from)
    ) {
      $message['headers']['From'] = '"'
      . str_replace('"', '', variable_get('site_name', 'Drupal'))
      . '" <' . $default_from . '>';
    }
    // Collapse the message body array.
    if (module_exists('mailmime')) {
      $body = $this->formatMailMIME($message);
      $plain = $message['MailMIME']->getTXTBody();
    }
    else {
      if (is_array($message['body'])) {
        $message['body'] = implode("
$eol
$eol", $message['body']);
      }
      $body = theme('htmlmail', $message);
      if ($message['body'] && !$body) {
        watchdog(
          'htmlmail',
          'The %theme function did not return any text.  Please check your template file for errors.',
          array('%theme' => "theme('htmlmail', \$message)"),
          WATCHDOG_WARNING
        );
        $body = $message['body'];
      }

So if I understood correctly, message must be preformatted with correct html in $message["body"][] , but I am not 100% sure there are lots of code-bits involved for email sendouts. I also need to validate if this will allow me to send mail as plaintext?

In Drupal 7, it's the implementation of MailSystemInterface::format() that formats the message body and changes it to a string; before that, $message['body'] is supposed to be an array.
In Drupal 6, drupal_mail() receives an array for $message['body'], and changes it in a string.

// drupal_mail() in Drupal 6

// Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Concatenate and wrap the e-mail body.
  $message['body'] = is_array($message['body']) ? drupal_wrap_mail(implode("\n\n", $message['body'])) : drupal_wrap_mail($message['body']);

Compare the code you are showing with the code used by the Drupal 7 implementation (DefaultMailSystem::format()).

public function format(array $message) {
  // Join the body array into one string.
  $message['body'] = implode("\n\n", $message['body']);
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = drupal_wrap_mail($message['body']);
  return $message;
}

Drupal requiring $message['body'] to be an array of strings is made clear in hook_mail_alter(), which describes it as follows:

'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.

Since hook_mail_alter() is invoked right before the format() method, that method is supposed to get an array, not a string.

 // drupal_mail() in Drupal 7

 // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => isset($from) ? $from : $default_from,
    'language' => $language,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

  //  …

  // Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);

The only reason I could see to check if $message['body'] is a string is to protect the code against modules not correctly updated in the passage from Drupal 5 to Drupal 6. In fact, Drupal 5 passed a string for body, as evident in the example for hook_mail_alter() shown in the documentation.

function hook_mail_alter(&$mailkey, &$to, &$subject, &$body, &$from, &$headers) {
  $body .= "\n\n--\nMail sent out from " . variable_get('sitename', t('Drupal'));
}


PHP Variable in SQL LIKE I want to place a PHP variable in SQL LIKE, I tried many ways but no change.

e.g. today $adate is 2012-08-12%

$adate =  date("Y-m-d") . '%';
$tvisit = db_result(db_query("SELECT `counter_id` FROM counter_today WHERE `counter_date` LIKE '{$adate}' ORDER BY `counter_id` DESC LIMIT 1"));

How can I do that ?

The syntax would be along the lines of:

$adate =  date('Y-m-d');
$tvisit = db_result(db_query("SELECT counter_id FROM {counter_today} WHERE counter_date LIKE '%s%%' ORDER BY counter_id DESC LIMIT 1", $adate));

The changes from your original:

Put {}'s around table name so if you are on a shared database, drupal can put a prefix on automagically.
Put LIKE's % in the sql itself, not in the variable.  You need to put in %% since % itself is drupal's way of starting a variable (kinda like \\ to put in a \)
Put %s in in front of that for the variable, which is a string.  Remove the {}'s since they are for table names.  Granted, php will find $adate in there since it's all wrapped in ""'s but then you open up yourself to sql injection etc (however remote it would be in this specific example).
Put the $adate variable in the function call as an argument.
Take out the ``'s surrounding the field/column names.


Why is the AJAX replaced drop-down list value not being submitted? I have an AJAX method for when a value is selected from the source drop-down list the target drop-down gets replaced with new values. The problem is that the new replaced drop-down list selected value is not being submitted (e.g. not in $form_state['values']['target'] = 'not the val I selected'). It looks like the value submitted is from the target drop-down list that is default from when the page first loads.

Any ideas as to why this is happening?

function dashboard_node_filter_form(){
  ...
  $form['filters']['source'] = array(
      '#type' => 'select',
      '#options' => source_options(),
      '#title' => 'Source',
      '#ajax' => array(
          'callback' => 'dashboard_node_filter_target',
          'wrapper' => 'edit-target',
          'method' => 'replace',
          'effect' => 'none',
       ),
  );
  // when source is selected this gets replaced
  $form['filters']['target'] = array(
      '#type' => 'select',
      '#options' => get_,
      '#title' => 'Target',
  );
  $form['filters']['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Submit',
  );
}

function dashboard_node_filter_target($form, &$form_state) {
  return $form['filters']['target'] = array(
      '#type' => 'select',
      '#id' => 'edit-target',
      '#options' => display_options($form_state['values']['id']),
  );
}

You should make all form manipulations that are supposed to be actually submitted in dashboard_node_filter_form() and use dashboard_node_filter_target() only to tell ajax what part of a form should be updated, and to make aesthetic-only changes that does not affect data.


PHP Fatal error: Call to a member function get_option() views/includes/view.inc on line 2493 I installed the Carbide Builder Module from SooperThemes and now receive this error when trying to go to any node/add page.

Their support says one of my Views displays has a view with a missing display plugin.

I have a lot of views/displays. How can I find it easiest?

UPDATE: Looks like there are some old Views from a D6 installation uses Feeds.

Enable the Devel module and insert a ddebug_backtrace() statement before the line containing the get_option() method call. It should print out a stack trace that you can follow to some view id.


Why does Drupal have both "sid" and "ssid" field in the session? Learning more about Drupal core so I can be a better contributor, understand security better, etc.

I noticed that on creating a session Drupal uses both an "sid" and "ssid" field. The code seems to indicate they are both the same (the little code I've been able to decipher so far), 'sid' && 'ssid' = session_id(), and looking at the DB only the sid is set in my own session.

Why do both columns exist? Is it a security measure? If so what does it do? Is it a legacy field from an old system?

Looking at Drupal 7 code.

Yes it is a security measure; sid is the session id for HTTP traffic &  ssid is the session id for HTTPS traffic. The idea here is that secure parts of your website (e.g. https://www.example.com/user/*/edit ) can't be compromised by session hijacking the sid that occurs with HTTP traffic.


Pre-Populating a CCK Flexifield/Multigroup? I'm using a repeating fieldset module (Flexifield, somewhat similar to CCK3 Multigroup) to create a measurement sheet content type. In this, the user is allowed to create an unlimited number of rooms, each defined by five fields: name, level, width, length, area.

It would be really useful to pre-populate about ten of these rows (e.g. "Kitchen," "Bathroom," "Living Room").

How would one go about programmatically creating and filling CCK fields with number of values set to "Unlimited"?


How to call Ajax callback on form submit to display results I want to get results, after validating and add fields as well in result like i want to add checkbox in result

function afaf_custom_form($form, &$form_state) {
  $form = array();

  $form['d_id'] = array(
    '#type' => 'textfield',
    '#title' => t('D id'),
    '#size' => 60,
    '#maxlength' => 60,
    '#required' => TRUE,

  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#ajax' => array(
     'callback' => 'v_custom_ajax_handler',
     'wrapper' => 'display-dept-ajax',
     'method' => 'replace',
     'effect' => 'fade',
   ),
  );
$form["prefix"] = array(
    "#markup" => "

");
$form["suffix"] = array(
    "#markup" => "
");

  return $form;
}

function v_custom_ajax_handler($form, &$form_state) {

  if (!empty($form_state['input']['d_id'])) {

  $form["department name"] = array(
    "#markup" => "
Department Id : ""

");

  return  $form["department name"];
  }
}

Basic working code example for validation or submit form with ajax.

 function afaf_custom_form($form, &$form_state) {
  $form['d_id'] = array(
    '#type' => 'textfield',
    '#title' => t('D id'),
    '#size' => 60,
    '#maxlength' => 60,
    '#required' => TRUE,

  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#ajax' => array(
     'callback' => 'v_custom_ajax_handler',
     'wrapper' => 'display-dept-ajax',
   ),
  );

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  if (isset($form_state['values'])) {
    $form['output'] = array('#markup' => 'thankyou message');
  }
  return $form;
}

function afaf_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

function v_custom_ajax_handler($form, $form_state) {
  $form_errors = form_get_errors();
  if ($form_errors) {
    return $form;
  }
  else {
    $thank_you_html = drupal_render($form['output']);
    $commands[] = ajax_command_insert(NULL, $thank_you_html);
    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );
  }
}


Use url of media field in view twig I need to output the url for field_slide_media in views-view-unformatted--carousel.html.twig.
I can output the entity ID using:
{{ view.field.field_slide_media.value(view.result[i]) }}

I would like to use it in

I can also output the whole image, but I need to be able to add an img class to it in the twig, so it's too much being output. I need the uri not the whole output.
{{ view.style_plugin.getField(loop.index0, 'field_slide_media') }}

gives me:

If you are configuring the view with the fields. You can try setting the formatter of the image to 'URL to image' and then create the HTML yourself like
<img src="{{ view.field.field_slide_media }}" />

Or you can try file_url


How to add term programmatically in Paragraph field? I have a paragraph with a taxonomy reference (autocomplete) field and I want to populate it when I create programmatically a pararagraph item.
I checked the option "Create referenced entities if they do not already exist" in this field.

I use this code, but I don't know how to find more informations to do that without Term::create (if it's possible) :

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

        foreach ($field_value as $creator_type => $creator_name) {

            $paragraph = Paragraph::create(['type' => '_zotero_ref_creators']);
            //text field
            $paragraph->set('field_nom_prenom_createur', $creator_name);
            //taxo reference field
            $paragraph->set('field_type_createurs', $creator_type);

            //$paragraph->isNew();
            $paragraph->save();

            $paragraphn_field_value = array(
              'target_id' => $paragraph->id(),
              'target_revision_id' => $paragraph->getRevisionId(),
            );

            $node_reference->set('field_liste_contrib', $paragraphn_field_value);
          }

First load the node already created.
Second, create a paragraph like you did but for taxonomy term add "target_id" and for value choose a term id.
Set the paragraph value to your field of type paragraph from node. Also you need to save the node.

    $node = Node::load($nid);
     $paragraph = Paragraph::create([
            'type' => 'gallery_image',
            'field_type_createurs' => ['target_id' => $value],
          ]);
          $paragraph->save();

          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' =>$paragraph->getRevisionId(),
          ];

   $node->set('your_field', $current);
   $node->save();

Varible $value is a term id.

Hope to help you.


How to customize a link with a custom module? I installed the "Private Message" module on Drupal 8.

There is a link to send a message that I want to transform into a Bootstrap button.

How to customize a link on Drupal 8 ?

Here is the HTML code of the link :

Envoyer un message

The developer of "Private Message" gave me this code, but I do not know what to do with it.

I need to create a custom module or put it in my_theme.info.yml ?

function HOOK_node_view_alter(&$build) {
  $build['private_message_link']['#title'] = t('Click me. Click me now!');
}

The developer of the module wrote in a comment :

You can implement hook_ENTITY_TYPE_view_alter(). For example, if you are altering the link on the user profile you would implement hook_user_view_alter(). If you are altering the link on nodes, you would implement hook_node_view_alter(). If you are altering the link on comments, you would implement hook_ENTITY_TYPE_view_alter().

In this function, you can change the output of the link by altering $build['private_message_link'] as you see fit.

I created a custom module:

private_message_contact_button.module :

<?php

/**
 * @file
 * Hook implementations of private_message_contact_button module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function private_message_contact_button_node_view_alter(&$build) {
  $build['private_message_link']['class'] = array('button button--primary', 'btn');
}

The code works, but the button is not applied.

I want to add class btn btn-success

And I want to add an icon make awesome in front of the text

I have to put what as code ?

The CSS class is a sub-key of the #attributes of a render array like $build:

function private_message_contact_button_node_view_alter(&$build) {
  if (array_key_exists('private_message_link', $build)) {
    $build['private_message_link']['#attributes']['class'] = array('button button--primary', 'btn');
  }
}


Assigning User's In Taxonomy Terms Possible Duplicate:
  Views: How can I show a list of users who have a taxonomy term attached via a term reference field?

i want to assign users profile in taxonomy terms. So, i have created a vocabulary like Gender which has two terms like Male and Female. So, while registering an account in my website people need to choose his/her gender, and i wish if other people click on those terms from some one profile page, for example if they click on Male then on the taxonomy page all profiles with Male will get appear and same for other terms. But i see no result on those terms pages, to find a solution i have created a Views which successfully show users profile for each terms.Now, my question is how to integrate the Views for the terms pages? |OR| On user profiles how to link Terms pages to those Views page?

By default, the taxonomy term view lists content (nodes) and not users. If you want to use a new view on the default term page path, taxonomy/term/%, you have to disable the default view, create a new one, and give it that path. But it will also be in use for your others taxonomy terms pages !

So my advice is to disable and ignore this view, give a path to your full working new view, and set your term path pattern for this vocabulary the adress of your new view's page.

More simply :

Make a new view of users, set a "page" display and set it like this : /mypath/%
Add a taxonomy term ID argument
Add your fields
Go to your pattern url alias setting page, and for your vocabulary "gender", set terms URL to /mypath/% .

Now, all gender terms on your site will be linked to that view.


Editing a Drupal 7 sub-themes menu HTML I have a subtheme based off the Zurb Foundation Drupal Theme. The Zurb foundation theme defines the main navigation menus in it's template.php like so:

function zurb_foundation_preprocess_page(&$variables) {
    ...
    $variables['main_menu_links'] = '';
    if (isset($variables['main_menu'])) {
        $variables['main_menu_links'] = theme('links__system_main_menu', array(
            'links' => $variables['main_menu'],
            'attributes' => array(
                'id' => 'main-menu',
                'class' => array('nav-bar'),
            ),
            'heading' => array(
                'text' => t('Main menu'),
                'level' => 'h2',
                'class' => array('element-invisible'),
            ),
        ));
   }
   ...
}

and in page.tpl.php:

<?php if ($main_menu_links): ?>

    <?php print $main_menu_links; ?>

<?php endif; ?>

which works fine. I want to edit the HTML being generated (convert the links to uppercase to be precise).

I create a template.php in my sub template and add to it:

function mycustomtheme_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';
    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = drupal_strtoupper(l($element['#title'], $element['#href'], $element['#localized_options']));
    return '
' . $output . $sub_menu . "
\n";
}

But this doesn't have any effect; the normal menu is generated with out my text value attribute. The docs says that the theme function (used by the Zurb theme):

  Generates themed output. All requests for themed output must go through this function. It examines the request and routes it to the appropriate theme function or template

so I would have thought that it would have detected the current theme (my subtheme) and called the appropriate hook caketoppercompany_menu_link when rendering the links, but this doesn't seem to be the case. Any suggestions?

You just want to make the links show as uppsercase text!? Since you're not altering the HTML structure of the menu -- there is no need to modify any theme function. You just do it using CSS.

/* In ideally your last css file listed in your .info file
 * add a line such as
 */
#main-menu a { text-transformation: uppercase !important; }


Sort a View by whether content has a user reference I have a view that lists all users that have flagged a piece of content (using the Flag module). Also, for that content, I have certain user references attached (using the References module).

So:

User can flag a piece of content.
Content can reference user.

I want to be able to have the view show all users that have flagged the piece of content (I have that working correctly), but also show them in the order of:

Users that are referenced by the piece of content.
Username, alphabetically.

I think I just have a mental block from getting this done. Any pointers or advice to help me get this kind of sort working? Note: I also need to have everything done in one display, since it needs to be sortable and filterable.

I have an idea!  Use your current block to limit the list to users who are referenced in the node, and then add an ATTACHMENT to the block listing users who have flagged it who weren't referenced in the node.

That way you can separate them our and sort independently, but they'll still appear as if they're displayed in the same view.

Here are the exact steps:

Add an additional relationship that is the node user reference field, but reversed:

I added the 'Content: nid' field with the above relationship to my view just while testing, and that was helpful, so I'm including it as a step...
Add that field 'Content: nid' using the user-reference relationship to your set of contextual filters too, if you're using it, to make sure the content they're referenced in is the current node (don't want to sort them first just because they're referenced in SOME node on the site, right? ;-))

Add an attachment to your view, and set it to display directly after your existing page or block.  In this one, you'd want to do the exact same as above, however, when you're setting the contextual filter, select to 'Exclude' the matching answers (you'll find that check box in the collapsed 'More' section at the bottom.


Create a user using a single PHP file I have tried every possible ways to create a user account using only a single PHP file without writing a module. I want to create a portal in which visitors can subscribe or register themselves and do something after they logged in. I have also a mobile application (Android and iOS) in which my app users can register (subscribe) and use the app in their mobile phone. Both the web application and the mobile application use the same API to create a Drupal 8 user. Is there anyone who help me out to achieve this?

If you want a single php file you can use a drush shell script:

#!/usr/bin/env drush

use Drupal\user\Entity\User;

    $user = User::create(['name' => 'testuser', 'status' => TRUE]);
    $user->save();

For more information see https://github.com/drush-ops/drush/blob/master/docs/shellscripts.md

A better approach might be to use REST, see https://www.drupal.org/node/2754633


How do I post a node to PayPal after node insert/update? I have an option in my node to "upgrade".

If the user selects this option either when creating a new node or updating an existing node, I would like to post the node data (which includes some Paypal html elements) to Paypal so that it can process a payment.

The node should be inserted/saved regardless of the payment result. I need to specify via Paypal what the return URL is and with inserting node's I wont know that until after the node is inserted.

Is there a way to post to 2 places? I know that doesnt really make sense but im just looking for a solution.

If you want to send this information and get and nid, the best place to do this is in:

hook_node_insert() to execute this action just after inserting the node and to have a nid.
hook_node_update() to execute this action just after updating the node.


drush default site alias Is there a way of specifying a default site alias ?

couldnt find it in drushrc example nor aliases example.

motivation
i am sclerotic and lazy :) usually running drush from the dir where the site is, so no alias needed. Now working in a setup where i am logged in on a different server then the actual site, so i need to always provide a site alias for each command. So the usual workflow is:

drush wipe
oh no
drush @stage wipe

so i thought a default site alias would save me from those two lines :)

Drush automatically defines the alias @self to refer to the currently bootstrapped site.  So, if you have identified a site via cwd (that is, cd /path/to/sites/mysite, where sites/mysite is the folder that contains settings.php), then you could run:

drush sa @self

This will tell Drush to print out a site alias for the current site. You can then copy this to an alias file and give it a handy name for later use.  If you're doing this for a remote site, try adding --with-db if you'd like to include the database record inside the site alias.  You're better off leaving out the database information for local sites, though, as you can get inconsistent results if the db info in your alias does not match the db info in settings.php.

If you want to disable cwd-based site selection, then define 'root' and 'uri' in any drushrc.php file:

$options['root'] = '/path/to/drupal';
$options['uri'] = 'http://mysite.org';

There is no way to specify an alias in a Drush configuration file, but you could use the site-set command from the command line:

$ drush site-set @stage

If you wanted this command to be persistent, you could run it from your .bashrc.


Language switcher doesn't appear I have enabled the "locale" and "content translation" modules. Also I have two languages in my Drupal, Spanish and English, after that I have configured the detention method by URL.

I have finished my English page and I just need to translate the website to Spanish. When I set the language switcher to the website (the header or a columns) of my Structure I don't see anything. I can click on "translate" button of the blocks of my web, I see the "spanish" option, I click in "translate", but I get this message:

  This string uses the Full HTML text format. Strings with this format
  are not allowed for translation.

Ok, I change the format to Plain Text but I lost my HTML format, styles... I can't translate and I can't see the switcher to change to Spanish or English.

Drupal version 7.4.

To translate custom block text you need to do the following:

Download the Internationalisation module (i18n)
Enable String translation module (i18n_string)
Go to Configuration > Regional & Language > Multilingual Settings >
Strings (admin/config/regional/i18n/strings)
Enable Full HTML in Translatable text formats
Save


Separate Exposed Filter Widgets Howzit! I have a sandbox site set up, and one of my views overrides the default taxonomy term page for one of my vocabularies. The image below shows how it currently is (unstyled) - and this works just fine. The description of the manufacturer is embedded using Views Field View module, and I'm also using the Better Exposed Filters module.

Click for larger image

What I'm trying to do is separate the Sort By/Order form from the Category filter widget form as depicted in the Photoshop'd image below.

Click for larger image

My only experience with overriding tpl files has been minor theming/positioning stuff. So I overrode views-view.tpl.php and views-exposed-form.tpl.php, but the latter obviously just renders one form for exposed filters. Will sincerely appreciate your help with this.

FWIW, I'm using Devel and Theme Developer modules for the first time, and am completely lost with figuring out where the variables I'm looking for are, but I'll create another post for that if I'm still lost.

Ok, so I realise that due to the fact that the exposed filters are on one form, it will be difficult to separate the rendered elements. However, I ran some tests using jQuery to  reposition the sort elements, and so far it seems to work using the following:

jQuery(document).ready(function() {
  jQuery('div#edit-sort-by-created').appendTo('#custom-sort-block');
  jQuery('div#edit-sort-by-title').appendTo('#custom-sort-block');
});

NOTE: This breaks if Ajax is enabled in the view, but that can be circumvented using the jQuery live() function I'm sure.

It certainly isn't pretty and definitely is a hack, but it will have to do for now. I won't be marking this as the answer in the hopes that someone can suggest a more elegant and Drupaly way of accomplishing this.


Calendar with multiple content types on multiple field types I'm hoping to set up a calendar using date + calendar. I have 2 content types, one of which specifically has a date field, the other of which I want to display on the calendar using the published date. How could I go about doing this? I can get the first content to display under two different dates, one for published date and the other for its date field, but obviously this is not the desired behavior.

The following issue kind-of comes close, but not quite: How to use multiple content types in a "Calendar" View sorting by the field type of "Date"?

You're not going to get Views to add the 2nd content type (and only the 2nd content type) in this way, at least not through the Views UI. You could do this by programmatically altering the view's query or something like that, but it would be no fun.

I would recycle the "date" field from content type a into content type b and set the default value = now; that way when a new node is created it will have that value by default.


What is the basic use of the breakpoints.yml file? What's the purpose of breakpoints defined in `breakpoints.yml?

Why are the media queries defined in breakpoints.yml, and not in CSS files?

There is no way to use the breakpoints defined in a breakpoints.yml file in CSS without pre or post-processing. Since we don't use processors for styling in core, the breakpoints are still hard coded in the CSS files. In a custom theme you are however free to use tools like Gulp or Grunt and it would theoretically be possible to use the breakpoints.yml input for your CSS generation.

Currently the breakpoints.yml is mainly interesting for JavaScript (JS). Have for example a look at the Toolbar module in core. The breakpoint info is added to the 'drupalSettings' JS object in 'src/Element/Toolbar.php' like so:

$breakpoints = static::breakpointManager()->getBreakpointsByGroup('toolbar');
if (!empty($breakpoints)) {
  $media_queries =  array();
  foreach ($breakpoints as $id => $breakpoint) {
    $media_queries[$id] = $breakpoint->getMediaQuery();
  }

  $element['#attached']['drupalSettings']['toolbar']['breakpoints'] = $media_queries;
}

Then in JS the run-time settings as defined above are read in.

var options = $.extend(
  {
    breakpoints: {
      'toolbar.narrow': '',
      'toolbar.standard': '',
      'toolbar.wide': ''
    }
  },
  drupalSettings.toolbar
);

Later an event listener is added per breakpoint so that 'something' can be done when the screen size changes.

for (var label in options.breakpoints) {
  if (options.breakpoints.hasOwnProperty(label)) {
    var mq = options.breakpoints[label];
    var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq);
    mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
  }
}

In the event of a change different actions can be undertaken per breakpoint.

Drupal.toolbar = {
  mediaQueryChangeHandler: function (model, label, mql) {
    switch (label) {
      case 'toolbar.narrow':
        model.set({
          isOriented: mql.matches,
          isTrayToggleVisible: false
        });
        break;

      case 'toolbar.standard':
        // Logic
        break;

      case 'toolbar.wide':
        // Logic
        break;

      default:
        break;
    }
  }
};

Note: the code examples are taken from the Drupal Toolbar module and stripped. Use as inspiration, not as functional code.

A good explanation about using JS mediaQueries in general can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries


Count the number of users in roles In my D7 installation I'd like to have a view where all roles are listed followed by the number of users that have that particular role.

i.e. of my expected result:

role 1: 2
role 2: 5
role 3: 1
role 4: 8

In addition to this, when I can exclude a role (the admin role) from this view, it would make my day...

Thanks for your support!

Create a User View. Then add a "Contextual Filter" for the field "User: Roles". Set the "When the filter value is NOT available" option to "Display Summary" and leave all the other settings. Now you should get the list you want ...

Check the other settings for any customization of the list.


Form submit in FieldFormatter I have a custom entity type with a "yield" field. I would like to allow users to see the custom entity (full content view-mode) and change "yield" value to regenerate it with calculated values from the yield changement.

I started with a new fieldFormatter for my "yield" (number_decimal) field. The formatter extends DecimalFormatter and builds a little form object instead of displaying a simple markup.

$element = [
  '#type' => 'form',
  '#tree' => TRUE,
];
$element['yield'] = [
  '#type' => 'number',
  '#title' => $this->t('Change yield'),
  '#default_value' => floatval($this->numberFormat($item->value)),
  '#value' => floatval($this->numberFormat($item->value)),
];

$element['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Change'),
  '#submit' => ['changeYield'],
];

Form is defined in the full content view, and a click on the submit button send the form. I think this is not the correct way to add a form because #submit callback is never called. I tried different syntax, with static or non-static callback, but it doesn't work.

I would like to find an elegant solution, not hacking and adding JavaScript custom code.

Now the ideal solution is attaching #ajax callback to rebuild the data without sending the page, but I don't know if it possible and if dependencies will be not to strong, because changes done on another fieldFormatter item's values.

You can't add a form field to an entity display. You have to approach this the other way. Build a form class with the field and the submit button and add the entity content to it. Then you can respond to the posted data in the submit method of the form class and save it to the entity.

For the ideal solution you can attach ajax to the submit button to avoid a page reload.

An alternative option is an entity form using a custom form mode containing one field. This could be set up without code by using blocks for both, the entity content and entity form or only one of them and the other as page. This depends on what the end result should look like. You need a module to control the form modes Form mode control and to put an entity form in a block Entityform block. The entity content can be placed in a block with Views. For a custom entity all of this can be done in code as well.


Add non mandatory fields to user registration form I can add custom fields to the user registration form, if I add the fields to the user profile: admin/config/people/accounts/fields

There is a checkbox "Show on user registraion" which is inactive:

The checkbox only gets active if I check "Mandatory field", but some of the fields must not be mandatory. Is that a bug? Is there a workaround (without using module 'Profil2') ?

I'm using Drupal Core 7.28

I have never encountered such problem before. But since you have such problem then I think the best way is to write a hook_form_alter. And set the required field that you don't want as mandatory to false.

function mymodule_form_alter(&$form, $form_state, $form_id){
switch ($form_id)  {
    case 'registration_form_id':
                $form['field_name']['und'][0]['value']['#required'] = FALSE;
            break;
                   }
               }

Hope this helps.


Unpublish content automatically Hi I want to know if there's a way to unpublish content(nodes) automatically based on a field date previously created.

I want that task to be automatically based on the current date.

Example:

The user already has a content with that field called "Deadline" filled with 20/01/2015 so, for now that content should be passed to unpublished.

If I can do it through some hook let me know to insert in my costume module, thx so much

Edit: I can't use the Rules module because whenever I try to add some condition to one Rule one error just pop up, and I can't continue, and I'm not gonna do a CLEAN installation .....

you cane do it by Rules module

please check this article it will help if you are new in rules module


How can a controller change the url reported to browser? I have got two routes - one is for pausing mail jobs, the other one for listing them.

When I click on "pause" - the pause route:

does it's thing
internally calls the list route with a couple of extra nontrivial parameters and fetches it's render array
returns render array

However, I'd like the browser to report the url of the list-route instead of the pause-route. How can I achieve this?

You've already tagged the question with "redirect", so this is what you need to do in step 2+3. Don't return a render array, but a redirect response to the second route providing a couple of extra parameters:

return $this->redirect('second.route', ['route_parameter' => '123'], ['query' => ['foo' => 'bar']]);


Displaying Empty Option in Multiselect box This might be a really trivial question but it is driving me nuts.  I have looked at similar posts but they all address a single-select drop-down box.  What I need is to get the '-None-' to show up in a multi-select box.  For some reason, despite verifying my code a million times, it is not showing up.  Hope someone can point out what I am doing wrong.

$form['add']['add_drop_down'] = array(
  '#type' => 'select',
  '#title' => t('Select all that apply'),
  '#options' => $options,
  '#multiple' => TRUE,
  '#required' => FALSE,
  '#empty_option' => '-None-'
);

Basically, this only shows the options in $options in the select box and doesn't add the '-None-' as the first item. It works fine if I change it to a regular single-select.  The moment I turn #multiple to TRUE, the '-None-' disappears.  I have tried a number of different ways, but with no luck.  Hope someone can help.  Thanks.

That behaviour is by design; from the docs for form_process_select():

  // A non-#multiple select needs special handling to prevent user agents from// preselecting the first option without intention. #multiple select lists do// not get an empty option, as it would not make sense, user interface-wise.

(emphasis mine).

If you want to override that behaviour you can probably implement hook_element_info_alter() and provide your own process function which does things differently to the core one. e.g.

function MYMODULE_element_info_alter(&$type) {
  $type['select']['#process'] = array('MYMODULE_form_process_select', 'ajax_process_form'),
}

function MYMODULE_form_process_select($element) {
  // Duplicate code from form_process_sleect() and change what you need.
}


Frontpage with images I want to make a frontage with the Views module. On the frontpage, you can see 3 images, horizontal aligned. I don't understand the Views module very well, but I thought you can make for example a page with the Views module where you can add content that already exists on other pages.
So I don't know what to do now, as my images don't exist anywhere.

You're saying you want images from another site? I've got two pretty basic suggestions...

build them into your theme. You'll want to create a div (or three) in a template for the front page, adn then you can add them in with css pretty easily.
display them with a block. Create a new block, make sure you turn on HTML for your input and then add your images:

Enable the block for the region you want, and tell the block to only display on the front page. You'll want to do some simple css theming to that block, as well, to make them look how you want.

Both these options are just to display images. What do you want to do after that? Will clicking them take the user to another page?


Commerce Kickstart Product: URI links to admin When I try to use a Commerce Product Reference field in any view with a link to content, it links to the -admin- for the product, not the content.

This was discussed for the images here: https://www.drupal.org/node/1970482

But I'm finding that this will happen if you try to create a link wrapper to -any- Commerce Product field. (SKU, Title, etc.)

So.. can someone point me to the place in the Commerce code where that URI is generated so I can override it?

I thought it was in commerce_product_reference.module but I can't figure it out.

Please see my answer at https://www.drupal.org/node/1970482#comment-9252269 and try to avoid posting the same support request in multiple support forums.


Making File Field description required My users always skip adding the "description" to the file field because they can. I tried implementing the code posted here:

How do I make Drupal File Description Field Required?

(and thank you) -- but I have a question. My users now do see a red asterisk suggesting that the description is required ... but if they do not enter a description, they may still click save and create the node ... with no description entered in the box. Any ideas on how to get this to really force the issue and require the description?

If you like you can add to the hook_field_widget_form_alter and then add a validation callback:

  $form['#validate'][] = 'my_validate_function';

Then create a my_validate_function($form, &$form_state) which contains a check on the values and calls a form_set_error($name, $message) if a value is wrong or missing.

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $context['form']['#validate'][] = 'my_validate_function';
  }
}

/**
 * Require description to be set.
 */
function my_validate_function($form, &$form_state) {
  if ($form_state['values']['description'] == '') {
    form_set_error('description', 'Description must not be empty.');
  }
}

This may need to be changed above:

$form_state['values']['description']


How can I avoid saved configuration settings to be exported? I have a custom module and I added a form that allows the administrator to save some settings. Now, when I export the configuration (drush cex), I notice that these settings are being exported to a file (mymodule.settings.yml in the config directory).

I don't want to export these settings. How can I avoid it?

If you don't want to export configuration you should use State API.
From documentation:

  It is specific to an individual environment.
  You will never want to deploy it between environments.
  You can reset a system, losing all state. Its configuration remains.


Problems creating Drupal Commerce Product Display, list of available products not populating This is something that has happened to a site I'm maintaining. I can't create product displays for many of my products because the select list of products in the product field isn't populated with many of my products.

I have a content type called "Product Display" with product field of type product reference. When adding products the select list of products is only display 10 of about 100 products.

This only diagnostic information is that two javascript errors are reported

Uncaught TypeError: cannot read property 'behaviors' of undefind in jquery-noconflict.slicknav

And

Failed to load resource: Server responded with a status of 403 (forbidden)

This leads me to thing it's a jquery issue, but not sure how to debug this further.

So, how do I get that list of products to contain all of the products in the store?

This is a bug in Drupal Commerce 1.13. I'll be patching it today:

https://www.drupal.org/node/2697017


Let users manage certain field I'd like to give a set of users the ability to manage certain fields, such as adding items to a list. Is this in any way possible with existing modules?

Example:
Editing a node
Try to select XYZ for field FOO
XYZ isn't an option
Go to admin page and add XYZ to FOO
Can now select XYZ from FOO

I think the module Field Permissions allows you to do what you're looking for. Or at least in the documentation it write "Create own value for the field".


Custom redirect on custom page for admin user I've created a basic page with url login.

The node id is 129 and I've made a custom page--node--129.tpl.php in my theme.
On that file I've put this:

<?php print $messages; ?>
<div class="admin-login">
<?php print drupal_render(drupal_get_form('user_login')); ?>
</div>

So on this page I'm rendering the user_login form and I'm using it as a page for admin login.
How can I set redirect when admin is logging, lets say to admin/content?

Implement hook_user_login():

function MY_MODULE_user_login(&$edit, $account) {
  if(/* CONDITION, e.g.: $account->uid == 1 */) {
    $edit['redirect'] = 'admin/content';
  }
}


themes diabled after core update Every time we update Drupal core our custom themes, all previously enabled and one set to default, are no longer enabled. Has anyone else experienced this or know why this would happen?

This is a known bug in Drupal core for 6.x and 7.x


Setting up form table checkboxes I'm trying to create a form table with a column of checkboxes. The theming isn't working with the code below. All help is appreciated :)

myadmin.module

function myadmin_menu() {

  $weight=0;

  $t = get_t();

  $items = array();

  $items['myadmin_dispute'] = array(
    'title' => 'Dispute Queue',
    'access arguments' => array('view myadmin'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myadmin_dispute'),
    'file' => 'myadmin_dispute.php',
    'type' => MENU_NORMAL_ITEM,
    'expanded' => true,
    'weight' => $weight++,
    'menu_name' => 'myadmin',
    'module' => 'myadmin',
  );
}

myadmin_dispute.php

function myadmin_dispute($form_state) {
    //add output - css and javascript to include
    drupal_add_js ( drupal_get_path ( 'module', 'myadmin' ) . '/scripts/jquery.tablesorter.js' );
    drupal_add_js ( drupal_get_path ( 'module', 'myadmin' ) . '/scripts/myadmin.js' );
    drupal_add_css ( drupal_get_path ( 'module', 'myadmin' ) . '/blue/style.css' );

    $disputes = array
      (
        array('uid' => 1, 'first' => 'Joe', 'last' => 'Smith'),
        array('uid' => 2, 'first' => 'Susan', 'last' => 'Doe'),
        array('uid' => 3, 'first' => 'John', 'last' => 'Doe'),
      );

    foreach($disputes as $dispute)
      {
        $checkboxes[$dispute['uid']] = '';
        $form[$dispute['uid']]['first_name'] = array
        (
          '#value' => $dispute['first'],
        );
        $form[$dispute['uid']]['last_name'] = array
        (
          '#value' => $dispute['last'],
        );
      }

    $form['checkboxes'] = array
      (
        '#type' => 'checkboxes',
        '#options' => $checkboxes,
      );
      $form['#theme'] = 'dispute_theme';

      return $form;

}

function myadmin_dispute_theme()
{
  return array
  (
    'dispute_theme' => array
    (
      'arguments' => array('form' => NULL),
    ),
  );
}

function theme_dispute_theme($form)
{
  $rows = array();
  foreach(element_children($form['checkboxes']) as $uid)
  {
    $row = array();
    $row[] = drupal_render($form['checkboxes'][$uid]);
    $row[] = drupal_render($form[$uid]['first_name']);
    $row[] = drupal_render($form[$uid]['last_name']);
    $rows[] = $row;
  }

  if(count($rows))
  {
    $header = array(theme('table_select_header_cell') , t('First Name'), t('Last Name'));
  }
  else
  {
    $header = array(t('First Name'), t('Last Name'));
    $row = array();
    $row[] = array
    (
      'data' => t('No users were found'),
      'colspan' => 2,
      'style' => 'text-align:center',
    );
    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);
  return $output . drupal_render($form);
}

function myadmin_dispute_submit($form_id, &$form_state) {

}

Update, this is needs to work for drupal 6 instance.

Drupal has a built-in tableselect element type for situations just like this, it would be a lot easier to use that instead:

$disputes = array(
  1 => array('Joe', 'Smith'),
  2 => array('Susan', 'Doe'),
  3 => array('John', 'Doe')
);

$header = array(t('First Name'), t('Last Name'));

$form['checkboxes'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $disputes,
  '#empty' => 'No users were found.'
);

The above code produces this table:

In your form submit function you can get the selected user ids with code like this:

$selected_uids = array_filter($form_state['values']['checkboxes']);

EDIT

The above is for Drupal 7, if you're using Drupal 6 you can use the same code but you need to install the Elements module.


How can I show the drop-down lists for countries/administrative areas (from Addressfield) as exposed filters in Views? When editing the values of addresses provided by the Addressfield module, selecting certain countries (e.g., the United States) automatically populates a drop-down list of states.

I would like to do the same thing in a View using exposed filters-- when a user selects a country using the exposed filter for country, it should make available a select box for administrative area (state/province).

Adding exposed filters for the country and administrative area do not generate drop-down lists; instead, I simply get a plain text field with the standard options- is, contains, etc.

By installing the Countries module, I can get a drop-down list of the countries (but not the administrative areas).  How can I do this using only the Addressfield module?

Is there a pre-existing solution to make it work like it does on the edit page?

As of right now, there is no such views integration in the Addressfield module, although the linked issue does include a discussion of possible directions to take to tackle the problem.


How to restrict access to a non-drupal url on a site's domain? So, I've just run into this issue with a drupal 7 site that I am maintaining. Access to the mailing list URL www.XXXmysite.com/mailman/listinfo is accessible to the general public. Is there someway of restricting access to this URL through drupal's permissions? This isn't obvious how to do because the mailman program isn't a part of drupal, I'm not sure where the program actually runs from, but the url is mapped from the site's domain.

Nope. It sounds like your web server has the mailman web interface alias to that path. If that's the case, Drupal is never evoked so it wouldn't have any say on how that request is handled (i.e. index.php?q=mailmain/listinfo isn't executed for page handling).

You'll need look at configuring your web server to remove your alias, or remove it for your hostname.


Let users create versions of articles Let's say I want to make a wiki-styled knowledge base for recipes.

User A submits a recipe for "Lasagna". User B likes this recipe but would like to submit her grandmothers special recipe for others to enjoy, so she clicks "post your version" and then writes "Lasagna - Grandma B's style". The two articles now automatically have a relationship, but behave as independent pieces of content.

User C knows he wants Lasagna, and would like to try a new version of it. This is where I would like all the recipes relating to Lasagna can be listed and sorted on things like points (thumbs up/down), number of comments, visits etc.

If I had complete control over the terms this wouldn't be hard to do with views and taxonomies, but I want this to be community driven and versions of content and their relations to happen organically.

How would you approach this? I've tried References but I couldn't get it to cross reference. Relation seems to be very close, but how would I create the "post your version" (i.e relation) button?

A simple solution might be to something like Rules, and Rules Link.

Create a rule that clones the data from one node into a new node. Have it actioned to happen when a certain link/button is clicked (hence, Rules Link). The last set of actions in the rule would be to set an entity reference back to the original node (or set a common taxonomy term)

Otherwise, create a small custom module that basically does the same thing. mapping fields onto each other and creating a new node. You'll have more control on what happens with the data but its not easy if you are not a developer.


How to get contextual filter of a view from page.tpl.php? this is my page view path /news/[years]/[month]

I want to get year and month from path, how can do it ?

Thank you.

You can use the arg() function.

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

In your case:
arg(1) = [year]
arg(2) = [month]


How to add jQuery to the user profile page only? Me and Javascript/jQuery don't get along well ...

What I want to do is show the first 200 or so characters of a user's "about me" text and then expand it when you click the "more" link.

I added to my template.php

function bartik_preprocess_user_profile(&$variables){
  drupal_add_js('themes/bartik/js/moreless.js');

}

The moreless.js code is:

jQuery(document).ready( function ($) {
    $(".moreLess").hide();

    $(".moreLessSwitch").toggle(function() {
        $(this).html("Less");
        $(this).prevAll(".moreLess").slideDown();
    }, function() {
        $(this).html("More...");
        $(this).prevAll(".moreLess").slideUp();
    });
}(jQuery));

in user-profile.tpl.php I have:

stuff to always show

stuff to hide...

[+] more

This is the working jfiddle sample.

When I load a user profile nothing happens, I had all caches flushed. No js errors. When i copy the jquery code into the console it works.
This has to be something dumb simple ;-)

Also, is this really the correct way to add conditional js to some pages?

The code you should use is the following one:

(function ($) {
  $(function ($) {
    $(".moreLess").hide();

    $(".moreLessSwitch").toggle(function() {
        $(this).html("Less");
        $(this).prevAll(".moreLess").slideDown();
    }, function() {
        $(this).html("More...");
        $(this).prevAll(".moreLess").slideUp();
    }
  );
})(jQuery);

In Drupal 7, JavaScript using jQuery should be wrapped between (function ($) { and })(jQuery);. You should also use Drupal behaviors, similarly to what done in the batch.js file used from Drupal.

(function ($) {

/**
 * Attaches the batch behavior to progress bars.
 */
Drupal.behaviors.batch = {
  attach: function (context, settings) {
    $('#progress', context).once('batch', function () {
      var holder = $(this);

      // Success: redirect to the summary.
      var updateCallback = function (progress, status, pb) {
        if (progress == 100) {
          pb.stopMonitoring();
          window.location = settings.batch.uri + '&op=finished';
        }
      };

      var errorCallback = function (pb) {
        holder.prepend($('

').html(settings.batch.errorMessage));
        $('#wait').hide();
      };

      var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
      progress.setProgress(-1, settings.batch.initMessage);
      holder.append(progress.element);
      progress.startMonitoring(settings.batch.uri + '&op=do', 10);
    });
  }
};

})(jQuery);

The code in the JSFiddle works fine for me. It just be only a problem of wrapping the code correctly.


How to show logout link at the top right corner for non admin user I want to show the logout link at top right of all pages, just like when we login as admin we could see logout link at the top right corner of the all pages, but problem is when I login as normal user [non admin] the logout link showing some where in the bottom, but I want to show it in the top right corner of all the pages please help me if anyone know!!

Yo have to create a block to list all page. Then use code.

if (!in_array("administrator", $roles)) {
use logout link here(user/logout)...........
}

First you have to check whether the user is anonymous.


Admin's node set to published by default? I currently have nodes set to unpublished by default because I want to approve user submitted content before publishing it live. However, admins should have their nodes published by default. How can I accomplish this?

Assuming Drupal 6.

Define a hook_form_alter function in your custom module and set the '#default_value' of the status element to TRUE. This will only run if the user has the correct permission. This way, nodes can also be unpublished by unticking the 'Published' checkbox.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (user_access('administer nodes')) { // or other permission
        $form['options']['status']['#default_value'] = TRUE;
    }
}

Now your admin's nodes will be automatically published.

Thanks to andy for his comments.


Pull in all child libraries of a library/module/theme with dependencies in yml I have one contrib module and a custom module. The contrib module defines a lot of sub libraries and I want to depend all of it. Example:

Contrib module module_contrib.libraries.yml

module_contrib_lib: [...]
module_contrib_lib.sub1: [...]
module_contrib_lib.sub2: [...]
module_contrib_lib.sub3: [...]
module_contrib_lib.sub4: [...]
module_contrib_lib.sub5: [...]
module_contrib_lib.sub6: [...]
[...]

And in my  custom.libraries.yml

custom:
  [...]
  dependencies:
    - module_contrib/module_contrib_lib

But this doesn't pull in the subs, I tried with - module_contrib/module_contrib_lib.*, but it doesn't do anything. If I put - module_contrib/module_contrib_lib.sub1 ect it works. There's no any wildchar to pull in all of the sub libs?

Well, I suppose if you want to pull them all in, you can nest them under 1 library definition.

Or, add another library definition that contains all of the resources, so you can still use multiple or the whole shebang if you want to.


Select option in Drupal form API I've created a drupal custom form. I've used a select option for bank which get its value from the bank table. I want to store bankID in bankbranch table and which is a foreign key and display bank name in select box but it shows me an error:

  Undefined property: stdClass::$bankID in bankbranch_form() (line 40 of
  C:\wamp\www\emp\sites\all\modules\bankbranch\bankbranch.module).

My code is below:

/**
* Implements hook_permission().
*/
function bankbranch_permission() {
  return array(
    'submit bankbranch' => array(
      'title' => t('submit bank branch'),
      'description' => t('submit bank branch form'),
    ),
  );
}

/**
* Implements hook_menu().
*/
function bankbranch_menu(){
  $items = array();
  $items['bankbranch'] = array(
    'title' => 'Bank Branch Entry Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit bankbranch'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bankbranch_form'),
  );
  return $items;
}

/**
* Bank Branch Form
*/
function bankbranch_form($form, &$form_state){
  $query_bank = db_select('bank', $alias = NULL)
    -> fields($alias = NULL, array('bankID', 'bankname'))
    -> execute()
    -> fetchAll();
  $options_bank = array();
  foreach($query_bank as $value) {
    //bankID as key
    *$options_bank[$value->bankID] = t($value->bankname);* /** line for which it shows notice*/
  }
  $form['bankID'] = array(
    '#type' => 'select',
    '#title' => t('Select Bank Name'),
    '#options' => $options_bank,
    '#size' => 1,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchName'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Name'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchaddress'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Address'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchcode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['ifsccode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch IFSC code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

/**
* Submit handler for the bank_form. Insert entry into the database.
*/
function bankbranch_form_submit($form, &$form_state){
  $branchID = db_insert('bankbranch')
    ->fields(array(
      'bankID' => $form_state['values']['bankID'],
      'brachName' => $form_state['values']['brachName'],
      'branchaddress' => $form_state['values']['branchaddress'],
      'branchcode' => $form_state['values']['branchcode'],
      'ifsccode' => $form_state['values']['ifsccode'],
    ))
    ->execute();
    drupal_set_message(t('Your form entry has been added'));
}

Any suggestions?

Your lacking some code.

Try changing your code above with:

 $query_bank = db_select('bank', 't1',array('target' => 'import'));
 $result = $query_bank
   ->fields('t1',array('bankID','bankname'))
   ->execute();

 foreach($result as $value){
      *$options_bank[$value->bankID] = t($value->bankname);
 }

The import keyword above is your database settings. It must be declared in your settings.php. Assuming  you are using an external database where your bank  table is located, It must look like the code below:

$databases = array (
    'default' =>
        array (
            'default' =>
                array (
                    'database' => 'Name of Your Drupal Database',
                    'username' => 'Username of Your Drupal Database',
                    'password' => 'Password of your Drupal Database',
                    'host' => 'Host of Your Drupal Database',
                    'port' => '',
                    'driver' => 'Driver of Your Drupal Databas', //It can be mysql/pgsql depends whether you are using Postgres or Mysql
                    'prefix' => '',
                ),
            'import' =>  // This Part is where your database that contains `bank` table should be declared.
                array (
                    'database' => '',   //Fill it up according to your database settings.
                    'username' => '',
                    'password' => '',
                    'host' => '',
                    'port' => '',
                    'driver' => '',
                    'prefix' => '',
                ),
       ),
);

For more clarification, please refer to this link.


How can I overwrite uploaded file via Filefield? By default in Drupal 7, if I upload image.jpg via a file field in my node, save the node and then edit that same node and re-upload image.jpg, it will name it image_0.jpg.

I want to replace the image uploaded so I will only ever have image.jpg.  How can I do this?

As a technical exercise...programatically speaking, you would need to replace the element's #value_callback, currently file_managed_file_value(), with a custom one.

Your custom callback would invoke another custom function, a rewritten version of file_managed_file_save_upload(), which would then invoke file_save_upload() with FILE_EXISTS_REPLACE as the 4th parameter, as opposed to the current value of FILE_EXISTS_RENAME.

Real-world, you don't want to do this. As soon as someone uploads an image to a different node, it will obviously overwrite the existing one called image.jpg, and that new image will be used in place of the existing one for all other nodes.

That's why the renaming functionality exists in the first place; to avoid global collisions.


Views & Multi-dimensional table I have the following configuration with my drupal website:

Taxonomy vocabulary: Procedure
Users Role: Doctor
Node Type: Surgical Operation

When I create a "Surgical Operation" node, I can select a procedure (abdominoplasty, breast augmentation, etc...) and a doctor (users with doctor role) via entities.

What I would like to do now is create a View that displays what operations have been performed, how many times, and by what doctors in a table:

So far I have tried the following modules without success:

Views Aggregator Plus;
Views Calc;
Views Table Group;

How should I proceed? Should I create a module myself to display these informations?

Thank you for your help.

I had a very similar problem and I could solve it using Views Matrix module. It has only a dev version for Drupal 7, but it did the job perfectly.

Look at this question, it's almost the same except that I didn't need to count the items: Matrix view with content as columns and taxonomy terms as rows

There is also another answer to that question which I tested and it works as well.


How can I add markup to a link in node links? I am trying to add some markup around the number of comments link in the standard node links. I want to do this so I can theme the number of comments as a little comment bubble and hide the text (possibly only on mobile).

I can get this far:

function mytheme_preprocess_links__node(&$variables) {

 if (isset($variables['links']['comment-comments'])) {
    $title = $variables['links']['comment-comments']['text'];
    $count = 7 // need to get the actual count in here.

    $variables['links']['comment-comments']['link']["#title"] = \Drupal::translation()->formatPlural($count, ''1 comment', '@count comments');
  }
}

When I dsm the $title variable I can see that the comment count is in there, I just can't figure out how to get it out into the $count variable. Any help?

Unfortunately the object PluralTranslatableMarkup has no method to get the protected value count. The serialization was fixed to provide the count value, see issue https://www.drupal.org/node/2844181, but the class is still missing it's own getArguments() to extend it with the count value. You could file an issue and wait for a fix or use this work around with reflection:

  if ($title instanceof \Drupal\Core\StringTranslation\PluralTranslatableMarkup) {
    $reflection = new ReflectionClass($title);
    $property = $reflection->getProperty('count');
    $property->setAccessible(TRUE);
    $count = $property->getValue($title);
  }


Instance based date field granularity In my web application (Drupal 7) I'm using a date field with year-month-day granularity, but I would like, for a specific content type, to add also hours and minutes.

Is this possible to achieve? How?
Is this safe or it'll mess with the other content types, existing views etc.?

I've thought of adding an extra time only field, so I've checked some modules like CCK Time or Timefield, but they don't seem maintained anymore (last release is about two years old).

Use case:
I have an "Absence" content type. When a student is absent, the teacher selects the day when the student is absent, hours and minutes aren't needed. I'm now creating an "Early exit" content type: if a students has to go out from school before the regular school day end, in that case the teacher need also the time when the student left the school. As an alternative I was thinking on two integer fields (hours and minuter), but it doesn't sound as an optimal solution to me.

Date module has the ability to add time field with the same field , I think you need to enable that in the field settings. see screenshot:


Create a panel with related group content based on a view I'm using groups (Drupal 7) and have set up panels to show related content for each group. So that if I look at a particular group node it also shows associated group news items, members, etc. The main content is the group body field.

I now want to show a view that displays a list of related content (group messages) for a group as the main content. This should also show the associated group members and news items in a related pane, as it does in the main group panel. I can't see how I can relate the group to the view. It is straightforward to relate the view to the group but not vice versa.

Is it possible to relate the group to the view based on an argument in the path? When I create a new panel the contextual options are all about the node being viewed or the group, but nothing for views or the path.

Or alternatively, is it possible to add a variant to the main group panel page that shows the view I want to display instead of the group body field? How could I create a different context for this? Would it be possible to do it using a path?

Many thanks in advance,

Ben

Is it possible to relate the group to the view based on an argument in the path?

Yes, it is. In the view, in the contextual filters select the radio button "Provide default value", there you can decide which kind of field you want to give. If you want to get the path you should select "Row value from url" and then choose the "path component" (The numbering starts from 1, e.g. on the page admin/structure/types, the 3rd path component is "types".)

I hope this helps you.


Can you create new users without entering email, then prompt user upon first login? I want the site administrator to be able to create a user, submitting only a username and a dummy password.

This information would then be 'manually' sent by the administrator to the user, whom upon their first login, is forced to enter a verification email and change their password.

How can this be done through modules or otherwise?

Use Force Password Change module.

This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.


How can I use thre Migrate module? I installed the Migrate module, but I can't use it, nor can I find any useful documentation that explains how to use it. The page on /admin/content/migrate is empty.

How can I use this module?

The Migrate module only provides a flexible framework for data migration into Drupal. The logic and data mappings to perform an actual migration are pretty complex. Migrate does not provides an UI to build or configure your migration. IMHO, this is good because a complete UI to build such script would be at least as complex as writing it directly in PHP.

Its documentation is pretty complete and provides all the information needed to start using it. I recently started to use it and, coming from an OOP background, find it intuitive and easy to learn.


How to set default value for entity reference field in hook_form_alter following snippet doesn't   set the default value.

 $form['field_image']['#default_value']='default';

I Have content type called image and I'm trying to set the default value for a reference to it in another content type.  The above code doesn't work.  Printing out the form variable doesn't make it seem like an easy task.

You need to first check the structure of your form. Mine worked with the following:

$form['field_image']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2);

Cheers!


Webform on 'hostile development' environment A client has a 'hostile development environment' and, related to this, a list of 'blessed modules'.

One of the hard/fast rules is 'no Webform' module.

(The only answer given to 'Why?' so far is, "If the answer is Webform, you're asking the wrong question," by the Devops people who guard this hostile environment.)

Is this a justified exclusion in any way and how would you respond to this statement/exclusion?

Our use case is for a single, simple contact form which allows users to submit their email address, a Subject and a body (in plain text only).

And the reason I'm asking this is so I can explain to 'stakeholders' (also on the client side) what's going on. Devs on my side are mystified.

Coming from a huge production environment with Drupal multi-site running, the Webform can be a constant headache if there is no SPAM protection turned on, or if modules/core aren't kept up-to-date.  Maybe they had problems in the past with Drupal admins not running protection on their forms and not keeping their modules up-to-date with the latest security fixes?  Also, Drupal, the Webform module and open-source CMSs in general have a bad rap with the IT/Security crowd.  I have experience it more than once in my career.

The best thing you can do is find out why they feel the way they feel about that particular module, and then explain to them how, if maintained correctly and used correctly, it should be of little to no concern.


How can I use the grouped nid in a views template with two content types? In Drupal 8.9x, I have a view with two content types in it: Each business (and its details are grouped), and underneath each business I'm displaying multiple offers by that business...and then I want to display more business details underneath that.
For example:
Business #1 "title"
 -- offer A for business #1 (row)
 -- offer B for business #1 (row)
Business #1 Details (ideally inserted via the twig template)

Business #2 "title"
-- offer C for business #2 (row)
-- offer D for business #2 (row)
Business #2 Details (ideally inserted via the twig template)

I've got my view set up so that ALMOST all of the business details are grouped into a custom field. This outputs as "title" in the views-view-unformatted.html.twig template file, and all the offers are the "rows" that are placed inside the default twig for loop. The problem is, I need to place more business details after the for loop, and I don't know how to reliably insert that data via the template.
For example, if I try to access the Business's nid:
{% set bizNid = rows[0].content['#row'].node_field_data_node__field_business_location_nid %}

This grabs the very first row in the array, which doesn't necessarily correspond with the first business in the list. I spend a few hours looking through the twig var dump to see if I could find a reliable way of extracting the nid, but I just can't figure it out. My question is, how can I access the grouped/relationship data/fields/content inside a twig template file so I can sandwich the businesses offers between two sets of business data from the same business?
Here's a gist of my views-view-unformatted.html.twig file for more insight on what I'm trying to do.
And here's a screenshot of ultimately what the output should look like:

And here's a screenshot off my Views config page for "offers":

Thanks in advance for your help.

Here's one way to solve this. This is the easiest way to solve it through the interface, without the need for templating or coding.
It may not be the best option performance-wise because of combining data from two db tables through Views, but then again you'd probably need to build a very custom query to optimize, and caching might solve possible lags.
It can all be done through the Offers Views, without Relationships and Contextuals, but with the help of View Modes.
View Modes don't have anything to do with Views module, so this is something to keep in mind, I wish they were named Display Modes or something along those lines. You've probably already used two of them before: Full and Teaser.
View Modes are different ways you can display your entity Fields. Each mode controls which fields are shown, in which order, and with which display settings.
You need to create two additional View Modes for your Business CT (you can do that on the "Manage display" page of your CT or through Structure > Display modes > View modes, it will appear among the tabs). One mode will be for the top Business info (so you should include the fields you want to show there), and the other for what is shown bellow the Offers.
In your Offers Views add the Offers Fields how you want them displayed.
Then add two Business Entity Reference fields as well.
Rearrange the fields so you have one Business reference on top of the fields list, and the other on the bottom.
Configure the top one's Formatter to Rendered entity and choose the View mode you created earlier for it. Exclude it from display and save, then choose it as the 1st grouping field under Format Settings.
Configure the bottom Business reference to also format as Rendered entity but choose the second View mode you created for it.
You should now have it all groupped by Businesses and displaying correct info in correct places. Be mindful of the pagination you set because it can "break" one Business to display on two pages depending on the number of offers.


How to create nodes automatically using title, fields, etc from some other nodes? I want to generate nodes for a content type using fields of some other content types. For example I have three content types A,B,C. All three content types have some common fields as well like Title, Category and Date. I want to create another content type D to hold only those common fields.

Now here I want to generate content automatically for content Type D. I'm looking for a technique in which I can define that, "fetch data" from these common fields of A,B C content types to fill fields of content type D and generate nodes automatically for content type D.

Any suggestions about how to get this to work?

The Rules module is your friend here.

You may use it to create an entity (here a node) after saving a new content of type A B or C (or any other event). Then you can add actions (set a data value) to fetch field values from A, B and C for your new content of type D. The first action would be of course Create an entity, then set data values.

You may find a great set of tutorials about Rules at Learning the Rules framework series.

Here is a short example : after saving a new Drupal Article, create a new Drupal Basic Page with the Body extracted from the Article and an automatic node-title.

{ "rules_automatic_node_creation_based_on_another_node" : {
    "LABEL" : "Automatic node creation based on another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page from Article [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:body" ], "value" : [ "node:body" ] } }
    ]
  }
}


Segmentation fault at search_cron() Whenever I try to run cron on the search, using

drush php-eval 'search_cron();'

I get 'Segmentation fault' error. I have not this problem for any other tables. The site contains hundreds of text-heavy nodes. So I appreciate your hint to cope with the problem.

I believe that is a memory error. If increasing your memory limit doesn't work, you might get relief from lowering the number of nodes to index per cron run on the search settings page.

It could also be caused by running an out-of-date version of PHP.


Getting child term's Tid not the parent's I created a form via Drupal 8 API, and I am creating a dropdown of a taxonomy terms which has a parent-child hierarchy. But when i select the taxonomy term, it displays term's parent's tid. This is how i try to display the dropdown:

$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
  if($term->depth == 0){
    $term = $term->name;
  }
  elseif ($term->depth == 1) {
    $term = '-'.$term->name;
  }
  elseif ($term->depth == 2){
   $term = '--'.$term->name;
  }
  elseif ($term->depth == 3){
    $term = '---'.$term->name;
  }
  elseif ($term->depth == 4){
    $term = '----'.$term->name;
  }
  $option[] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

I have been trying to get the term's tid not the parent's tid, can anyone point out what am doing wrong? Note:I am not super experienced with drupal 8

For the further references: I changed my code to this:

$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
$key = $term->id;

if($term->depth == 0){
  $term = $term->name;
}
elseif ($term->depth == 1) {
  $term = '-'.$term->name;
}
elseif ($term->depth == 2){
 $term = '--'.$term->name;
}
elseif ($term->depth == 3){
  $term = '---'.$term->name;
}
elseif ($term->depth == 4){
  $term = '----'.$term->name;
}
 $option[$key] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

Sorry if I wasted your time.


Migrating existing groups from Commons 2.x to Commons 3 I've just installed Commons 3 on a sandbox server and am curious where to begin migrating groups data over. I realize this is may also apply generic D6 to D7, but is there additional consideration for a Drupal Distribution? What steps should I take to move content and groups from Common 2.x to Commons 3.x?

That is, how can I move existing groups from Commons 2.x into Commons 3.x that will include content types attached to those groups (discussions, postings, events, wikis)?

I know that Activity Streams are different between these versions and we can live with out that, but I'd like to bring over content attached to the appropriate groups and users.

Commons maintainer japerry is in a team that created
Commons Migration module exactly for your task.

Posted by nateswart on March 18, 2013 at 9:46pm
Provide a migration path from Commons 2.x to 3.x

It uses Migrate with Drupal-to-Drupal data migration to get the job done. Sadly, it's still in early development, and according to this feature request not quite finished yet. But at the very least you can see in code what approach original developers use.


Restrict acces to file field only to certain role I have a node-type called "download" that has a field "file" with unlimited entries. Those files are already stored inside a private path. Now I want to restrict access only to a certain role. I already tried field_permissions but when I enable View field_file, regardless of content author. and grant that permission only to authenticated users, I still can view/download that file as a guest. What am I doing wrong here?

Besides it would be nice to set permissions on a node base. Like "This Node is only Viewable by Role XYZ".

Thanks for any hints!

like Colin McClure says, to control per node you can use with http://drupal.org/project/content_access .In the respective Access Control tab of each Content Type (when you edit a content type), you will find, in the bottom, the option to enable per content node access control settings.

About control per fields, seems that exist several modules to achive this:

http://drupal.org/project/field_permissions
http://drupal.org/project/cck_private_fields
http://drupal.org/project/privacy

and, from this resource you can find hooks to get permissions per field:

http://drupalcode.org/project/cck.git/blob/refs/heads/6.x-3.x:/modules/content_permissions/content_permissions.module

<?php

/**
 *  Implementation of hook_perm().
 */
function content_permissions_perm() {
  $perms = array();
  foreach (content_fields() as $field) {
    $perms[] = 'edit '. $field['field_name'];
    $perms[] = 'view '. $field['field_name'];
  }
  return $perms;
}

/**
 * Implementation of hook_field_access().
 *
 * @see content_access().
 */
function content_permissions_field_access($op, $field, $account, $node = NULL) {
  switch ($op) {
    case 'view':
    case 'edit':
      return user_access($op .' '. $field['field_name'], $account);
  }
  return TRUE;
}


Node reference - limit so node can only be referenced once I have two nodes 'Runner' and 'Buddy'. I'm using node reference to create a select list of buddies on the runner node.

The Idea is that every runner only has one unique buddy and two runners don't end up with the same buddy.

When editing the runner the buddy select list shows all buddies, I would like it only to show buddies that don't have a runner.

How would I achieve this?

Node reference (for Drupal 6) and Entity Reference (for Drupal 7) fields can be configured to use a View to show the available choices.

So, first create a View that shows all buddies that are not related to a runner. Then configure the field that points to the buddy to use that View.

To construct that View you may use the Corresponding Node References. It syncs the node reference between two node types which have a nodereference to each other. WIth this module your View only has to list buddies that have no runner related. This module is for Durpal 6 (I'm guessing your are using Drupal 6), but there's a similar one for D7.


Specify a node type (bundle) in entity reference field I have a custom entity type which has an entity reference field.

   $fields['referenced_article'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Article'))
  ->setDescription(t('The associated article.'))
  ->setSetting('target_type', 'node')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE);

This field returns now the nodes of all the node types when finding a match. How can I specify a node type? (I only want to show the nodes of type "article")

Do I need to use a specific setting for selecting content only one node type?

Try adding

->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]),

Source


how to get a node field value in a html.tpl.php template file? I have a field in a node type called body_styles.

I need to modify html.tpl.php to get the value of body_styles to add it to the classes of the body tag.

I tried with dpm($node->content['body_styles']['#value']); but I get nothing. I think it is because $node is not available in html.tpl.php.

how do I get a node field value in a html.tpl.php template file?

@svetlio: almost done:

The class is correctly added to $variables['classes_array'] but if I inspect the body (see my capture below the code) tag is not there

    function omega_subtheme_2_preprocess_html(&$variables, $hook) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
        global $language;
        $node = entity_load_unchanged('node', arg(1));

        dpm($node -> field_body_class['und'][0]['value']);

        if (isset($node -> field_body_class['und'][0]['value']) && $node -> field_body_class['und'][0]['value']){
            $variables['classes_array'][] = $node -> field_body_class['und'][0]['value'];
            dpm($variables['classes_array']);
        }
  }

Another way - without edit template and adding code in template.php

function THEME_preprocess_html(&$variables, $hook) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = entity_load_unchanged('node', arg(1));

      if (isset($node -> field_FIELD_NAME['und'][0]['value']) && $node -> field_FIELD_NAME['und'][0]['value']) {
        $variables['classes_array'][] = $node -> field_FIELD_NAME['und'][0]['value'];
      }
    }
  }

replace THEME with your theme_name and FIELD_NAME with your field_name, clear the cache

edit: I change "$node = entity_load('node', arg(1));" to $node = "entity_load_unchanged('node', arg(1));"


SImple Query Drupal 7 I am trying to create a simple static query just to see if the data exsits but I keep getting an error:

$result = db_query('SELECT * FROM field_data_field_product_id WHERE field_product_id_value = "mnbvcxz"');

if ($result->rowCount() > 0) {
  Do something
}

I get this error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'mnbvcxz' in 'where clause': SELECT * FROM field_data_field_product_id WHERE field_product_id_value = "mnbvcxz"; Array ( ) in validate_product_id_form_alter() (line 9 of sites/all/modules/validate_product_id/validate_product_id.module).

I'm not sure exactly why but it's got something to do with the double quotes in the query. Replacing them with single quotes makes queries of that nature run just fine.

You should really be using parameters rather than putting values straight into the query string though. db_query() accepts an array as its second argument to perform parameter replacement, and doing things this way means you don't even need to worry about quotes; PDO will take care of that for you.

Plus if you extend your query to accept that argument from a variable rather than a static string, you don't need to worry about SQL injection (again PDO will take care of it).

Your query would look like this:

$args = array(':product_id' => 'mnbvcxz');
$result = db_query('SELECT * FROM field_data_field_product_id WHERE field_product_id_value = :product_id', $args);

To offer another alternative, the preferred way of querying by field data is to use the  EntityFieldQuery class. There are several benefits, possibly the most important being that it's storage engine agnostic - if you decide to move your field data to (say) MongoDB, the query will still work.

e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_product_id', 'value', 'mnbvcxz');

$results = $query->execute();
if (!empty($results['node'])) {
  $matching_nodes = node_load_multiple(array_keys($results['node']));

  // Do something with those nodes
}


Generate test data bulkly in drupal 8 I setup a website based on Drupal8,create some content type(with several fields),Now I want to enter some test data in my site.
How can I generate test data bulky in drupal8?

Devel module will Do it for you and happy Devel module is ported to Drupal 8 https://www.drupal.org/project/devel

Enable Devel and Devel Generate

go to "/admin/config/development/generate/content" give the number of content it will generate bulk content for you.


Password protection for section of a drupal website I am planning out a Drupal website, and it will have a password protected section.  All users will need a username and password to access content, but client wants to issue passwords by company (group).  For example, ABC company might have 20 employees, and they can all use the "ABC" username and password (issued by client) to access and read articles/content online. DEF company will use the "DEF" username and password, to access the same content.  What is the best module to accomplish this?

Introducing password protection to parts of a Drupal website means that you enter the the wild (and somewhat mysterious) world of node access control.

Out of the box, Drupal 7 (and previous versions) only provides a single global permission to grant a role the right to view a node (i.e. view published content in Drupal 7).  To get more fine grained access control to published content, you must use a node access module.  There are several node access modules to choose from.  This page gives a good introduction to the rules that govern node access, and lists the major modules that help you manage node access, along with capsule reviews of each.

There are no single "best" module.  Each module have different characteristics.  I suggest you identify those you think are the best fit for your site, and check them out, before committing to one of them.

Your plan (to have a company user with a company password) have some logistical problems (see last paragraph), but can be implemented (sort-off) by means of a role based access module.

A better approach (IMHO) would be to create a set of node access "groups" (this can be roles, OG groups, or ACLs - depending upon the module you choose to use), where each "group" consists of all the users associated with a single company. I.e. you assign existing users to these groups. Now users can authenticate with their primary password, but you can set up node access grants to be determined by each user's "group" membership.

The approach you suggest (with a company user and company based password) will have the problem that the company user's password can not be protected against changes without a custom module.  Also, you may run into problems if a user leaves one company and joins another.  Then the old company's passwords must be changed so that this user may no longer have access, and the new password must be communicated to all existing employees of that company.  If you do this the way I suggest, you just remove this user from the group belonging to the old company, and adds him to the group belonging to the new,. That is all that is needed to make sure that he loses access to the content belonging to his "old" company, and gains access to the content belonging to the "new" company.


Is it possible to change the "view type" from a "content view" to a "search view"? I have recently installed the Search API module and associated modules to build a better site search.

My current search function is basic out of the box search but there are is lot of custom HTML and CSS to make the search results look good. Therefore I am wondering if I will have to manually redo everything when making a dedicated "search view" (a type of view enabled by the Search views module) or if it there is some way to clone/copy my previous "content view" but change it's type.

I have looked for answers and it was not possible in Drupal 6 but I am running Drupal 7.

You can use Display Suite search module to use search view like content view. Display Suite module have a submodule namely search that extend the search results for Drupal core or Apache Solr.

Steps:

Install Display Suite Search Module after downloading from above
link.
Go to content type's manage display and check the search result option that you find under custom display settings on vertical tab after that save it.

Now Go to Search result display mode local tab link and configure your display of fields as you want and save it.

For Manage Core search result :

Go to admin/structure/ds/list/search and choose option 'search result' in view mode and save it.

Go to admin/config/search/settings and chose option Display Suite
Search for ACTIVE SEARCH MODULES and Default search module.

Now search using core search form. This will display differently as core search result.

Now Manage Search api Search result :

Go to view of desired search index views.
Choose Format show as Rendered entity

Go to Format show setting option and choose option 'Search result'

Now save this views.

After that you can see search api result is as you configure previously on manage display.


How to implement custom theme functions (theme_textfield, theme_form_element) for some forms only? How to implement custom theme functions like theme_textfield or theme_form_element?

I know we can do it using hook_theme_registry_alter:

/**
 * Implements hook_theme_registry_alter().
 */
function krown_admin_theme_registry_alter(&$theme_registry) {

  //Override some Drupal defaul theme functions

  $theme_registry['textfield']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['textfield']['function'] = 'krown_admin_theme_textfield';
  $theme_registry['textarea']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['textarea']['function'] = 'krown_admin_theme_textarea';
  $theme_registry['form_element']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['form_element']['function'] = 'krown_admin_theme_form_element';
  $theme_registry['form_element_label']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['form_element_label']['function'] = 'krown_admin_theme_form_element_label';

}

The problem with this approach, is that the custom functions are applied on all website. I just want to apply them for some forms or for a specific theme.

Those theme functions don't get a reference to the form where the element is used. Therefore, they cannot be used to alter an element for a single form.

Every form element accepts #theme, so you can alter the #theme function used for those form fields in a single form. This is what Drupal does in node_filter_form().

  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );

theme_exposed_filters() then does its job.

  $form = $variables['form'];
  $output = '';

  if (isset($form['current'])) {
    $items = array();
    foreach (element_children($form['current']) as $key) {
      $items[] = drupal_render($form['current'][$key]);
    }
    $output .= theme('item_list', array('items' => $items, 'attributes' => array('class' => array('clearfix', 'current-filters'))));
  }

  $output .= drupal_render_children($form);

  return '
' . $output . '
';

Unfortunately, this doesn't work with theme_form_element() or theme_form_element_label().


Webform select list multiple selection I've added a webform component of type Select list. How do I configure the select list to let users select multiple options?

Thank for reply to let me know there is a check box call multiple, but I have no idea where is it.

On the edit screen for your select list component (node/NODE_ID/webform/components/COMPONENT_ID), there's a checkbox labeled "Multiple" whose description says "Check this option if the user should be allowed to choose multiple values."

With that checkbox checked, by default your component will be displayed as a set of checkboxes. To get it to display instead as a select element, look further down on the edit screen for the component, under the "Display" section. There's a checkbox labeled "Listbox" whose description says "Check this option if you want the select component to be displayed as a select list box instead of radio buttons or checkboxes."

EDIT: here's a screenshot of Webform's select component interface when used with the Bartik theme:

EDIT 2:
After googling "drupal form builder select multiple", I found this issue which suggests that via form builder's UI you need to use the "checkboxes" component type in order to have a "select multiple" field. Per this question you could disable form builder's UI and then you'll get the stock webform UI where you'll find the checkbox.