limit db_select query by the value of a specific field I am trying to build a custom drupal module to return the 'staff' that work at a specific charity when you are on the page of the charity. Both the charities and the staff members exist as separate content types. These content types are updated dynamically from a CRM system. The charities and the staff members both have a common field 'Account ID'.

I can get the account id of the charity whose page we are viewing:

    //Get Account ID of Charity for page we are on
    $charity_account_id = $node->field_member_account_id[LANGUAGE_NONE][0]['value'];

I can query the database and return only the contacts of the staff members type ('salesforce_contacts') and optionally limit it by the title of the returned results (e.g: n.title','Abouzeid')

    //Use Database API to retrieve the appropriate contact(s)
      $query = db_select('node', 'n')
        ->fields('n', array('nid', 'title', 'created'))
        ->condition('status', 1) //Published.
        ->condition('type', 'salesforce_contacts') // content type is salesforce_contacts.
        ->condition('n.title','Abouzeid','=') // I can limit the returned results by a specific title
        ->orderBy('title', 'ASC') //Most recent first.
        ->execute();
      return $query;

I need to know how to limit the returned results by the value of a specific cck field from the staff member content type ('salesforce_contacts'). This will allow me just to return the contacts for the charity we are looking at.

I have tried adding the drupal machine name for the field (or the mySQL database table name) to the field array as in below but both of these throw a PDOException error.

      ->fields('n', array('nid', 'title', 'created', 'field_account_id'))

I would really appreciate some help with this. This is my first Drupal database query and I am pretty new to DB queries in general. I have tried reading through the documentation but am struggling to where to look to get ideas as to how to go about achieving what I need to.

Thanks.

Scott's answer and Triskelion's comment are both spot on, but there are also a couple of other solutions that are worth mentioning.

Query the database for some node IDs that match a condition, load them using node_load_multiple(), and inspect the field data:

$nids = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('status', 1)
  ->condition('type', 'salesforce_contacts')
  ->condition('n.title', 'Abouzeid')
  ->orderBy('title', 'ASC')
  ->execute();

$nodes = node_load_multiple($nids);

foreach ($nodes as $node) {
  $title = $node->title;
  $created = $node->created;
  // etc.

  if ($field_items = field_get_items('node', $node, 'field_account_id')) {
    $account_id = $field_items[0]['value'];
  }
}

Use an EntityFieldQuery to query the nodes. This method has the advantage of being able to add conditions based on fields, as well as just the columns available in the node table.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'salesforce_contacts')
  ->propertyCondition('status', 1)
  ->propertyCondition('title', 'Abouzeid')
  ->propertyOrderBy('title')

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

  // Loop through the nodes as in the above example.
}


Transfer (export/import) url aliases and menu links automatically I want to transfer/synchronize url aliases and menu links from one site to another. Is there any way (drupal module, drush command, script) to do it automatically? The module menu_import looked promising but it does not take care of aliases.

A good idea for solving this issue (at least until a more definite solution is implemented, with uuid etc.) is described in this article:
http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal/

This is a related issue: data export import module how to keep alias drupal


How do I change the currency display from USD to $? I haven't been able to find a way to change the display of a price from 1.23 USD to $1.23.
How do I change the currency display from USD to $?

You could try

hook_commerce_currency_info_alter

For example,

function EXAMPLE_commerce_currency_info_alter(&$currencies, $langcode) {
    $currencies['USD']['symbol'] = '$';
    $currencies['USD']['symbol_placement'] = 'before';
    $currencies['USD']['code_placement'] = '';
}

See commerce_commerce_currency_info for the default currency info implementation.


Drupal 404 redirect to a custom PHP file Is there any possibility to redirect Drupal 404 to a custom php file without sending actual 404 headers.

Ofcourse there is a module for this too.. !!!
Search 404 Module would help you achieve this

Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL
It also has Support for Custom Text and Title to be displayed in search404 pages


What's the best module to serve mp3 or audio files securely? Problem with jPlayer, etc I'm trying to protect (in this example) audio files from being downloaded.  I'm currently using jPlayer because it is supposed to provide download protection (which it supposedly does, but it breaks when I enable it).
Surely there is a way to prevent leeching and downloading of files.
The Drupal private file system, as I understand it, only restricts access per user role.  Creating a path system/files/file.mp3.  Which tells Drupal to check if the user has permission to download the file.
So if I set that up - with the file storage outside my public root - when i type     http://site.com/system/files/file.mp3, Drupal just serves up the file and it starts downloading.
Its a public file system by default, the audio file is a private file field.
If I turn on protection in the jPlayer module then it wont play.

In the reports, immediately when viewing the node that the audio is on I get
that the file cannot be accessed - twice in a row. Clicking on play gets me this:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '1-30-1318255859' for key 'PRIMARY': INSERT INTO
  {jplayer_denied} (uid, fid, hostname, timestamp) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3); Array (
  [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => 30
  [:db_insert_placeholder_2] => {my ip address here} [:db_insert_placeholder_3]
  => 1318255859 ) in drupal_write_record() (line 6868 of /var/www/html/drupal/includes/common.inc).

Can anyone steer me in the right direction here?

EDIT:

Well I finally got the private serving working actually - kind of.  It will serve up the file once when the page is first loaded and will only serve it again if I almost immediately try and hit the URL again.  Then after a couple seconds it will block it like it's supposed to.  This works good enough for now I suppose.

For a real good private file protection use the Private Files module.


Dropdown Menu with 20+ items gets cut off by a views content rotor I'm trying to spruce up a Drupal 6 site, but I'm running into some issues with a views slideshow (specifically, rotorbanner) and having a menu with ~20 items.

When the menu expands, I can see all the links, but whenever I mouseover on a link that's within the "slider" block, the list disappears.

My thought was to fix this by just making the menu two column, but I'm running some difficulties with that and maybe fixing this will be easier.

I'd prefer not having 20 menu items, but that is the way my org does things, alas : )

For an example, go this dev site and hover over the "networks" section on the menu

Thanks!

This is an awfully localized question, but I got this to work fine in Chrome and Firefox by adding:

position: relative;
z-index: 1;

to the slideshow block (
) or any of its containers (
,
, etc)


How to set default value for textfield programmatically in drupal 7? I need a form_alter code or something that I could use to set my field value. I'm getting the value from the parameter and I've tried a lot of ways but nothing works for me. This is the list of codes I've tried on my custom module:

function custommodule_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom_package') {
      $default = $_GET['field_product_add_ons'];
      $form["field_add_on_nids"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE]['#default_value'] = $default;

  }

  if($form_id == 'custom_package') {
      $default = $_GET['field_product_add_ons'];
      $form["field_add_on_nids"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE]['#default_value'] = $default;

  }
}

I think the code will be simple but the field is still blank. My field is just a single text field.

Thank you in advance for your help!

Try

 $form['field_add_on_nids']['und']['#default_value'] = $default;

Thanks


Auto populate a node add with values of another node Is there any module that auto-populates the fields of a node/add form with the values of an already existing node? I would like to pass the node ID in the URL and get the form prepopulated with the values taken from that node.

I know it is possible to do; I am just wondering if someone has already done it in a module I could use.

Did you mean node clone module?

  The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.


More Pager not showing on Front page I'm not sure what I've done wrong, but I just noticed that the front page of my site isn't showing the pager at the bottom so that visitors can get to older posts.

http://www.theresatutors.com/

I don't remember changing anything to hide this anywhere. What would cause this? Where can I look to turn it back on?

I've been searching trying to find a solution, but all of the pages that show up in my searches are people trying to hide the pager, not show the pager. :/

As far as I can tell I'm not overriding the mainpage in anyway or using Pages or anything like that. Just the standard Drupal homepage with standard Drupal blocks.

My theme settings for Bartik are set to allow 10 posts per page. I have 16 posts which are Published and Promoted to Front Page.

Any help is appreciated.

Found the problem.

I had a View in the Featured section which showed an image gallery. The Views configuration had a pager on that data and so it was overriding the main pager on the page. I changed the Pager config on the View to "Display All Items" and the main pager is showing now.


Wrap link around an element in twig I have a twig template for a custom block, I want the entire block to be wrapped in a link. I'm using the link field, but I'm not sure how to get the url from the field within the twig template. This seems like it should work, but doesn't:

{{ content.field_link.0.getUri() }}

I've looked at url() and path(), but they are dealing with routing, so I don't think that's what I'm looking for.

Note, I would like to use either external or internal links in the field.

Ah, I was missing the ['#url'] part of the array. In order to get the url from the link field I called:

{{ content.field_link.0['#url'].getUri() }}

I do miss the ability to copy-paste from dpm().


How to add another entity type to Search API multiple types index? I created a multiple types index using Search API. Now I would like to add another entity type to it, but it's not possible. Is there any solution? I really would like to avoid recreating the index.

Not a proper answer, more like a workaround:

Load index.
Delete it.
Mark it as new.
Change the datasource settings.
Save it again.

Source: https://www.drupal.org/node/2632880#comment-11208443


How to get page type in page.html.twig I need to set some classes in page.html.twig based on page type (node, view, etc..) and if possible in more details (node type 'article', view 'blog') etc.

some ideas how to do this? I can't figure out how to get that done in page.html.twig?!

thank you!
Matthias

There is no page type in Drupal 8. But you can get the route name in a page preprocess hook to identify the type of page:

Route name

function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::routeMatch()->getRouteName();
}

and in twig:

{{ route_name }}

Route parameters

For route parameters:

 if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }

This code for the node is already in theme.inc, so you can use it right away in twig to get the content type:

{{ node.gettype }}

The node is the only route parameter that is loaded by default. You have to get parameters from other routes in preprocess, for example the view id and display id from a view route:

function mytheme_preprocess_page(&$variables) {
  $variables['view_id'] = \Drupal::routeMatch()->getParameter('view_id');
  $variables['display_id'] = \Drupal::routeMatch()->getParameter('display_id');
}


How to process single queue item using QueueWorker on cron runs? For each cron run, I would like to be able to process only 1 item in my queue using QueueWorker. At the moment it seems to me that Drupal keep processing items until it reaches the time parameter for the queue worker. I want to change this behavior to process 1 queue item at a time regardless of the time param. This is what I have so far:

/**
 * Processes Tasks.
 *
 * @QueueWorker(
 *   id = "data_provider_queue",
 *   title = @Translation("task worker: data provider queue"),
 *   cron = {"time" = 60}
 * )
 */
class SomeQueueWorker extends QueueWorkerBase {
  /**
   * {@inheritdoc}
   */
  public function processItem($data) {
       // Do something with data.
       // This seems to keep getting called for more than
       // one item in the queue. How do we change that?
  }
}

Is this possible with QueueWorker or should I just process queue items in a cron hook manually?

Queue workers are meant to be processed in batches, not 1-each-cron-run.

If you want to process only a single item every cron run, then use the cron-hook.


Panel pages context and View contextual filters - cannot get it working I have a content type which has field_section of type Taxonomy term.

Views

I created a View pane with contextual filters set to field_section. It means that the view pane should show all nodes which have field_section set to a specified value. It works when manually setting the section in Views preview, e.g. to 39.

In the Views contextual filter settings, in the section "WHEN THE FILTER VALUE IS NOT AVAILABLE", it says "This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'." But what default value to choose? All values with "url" are no good, because there is nothing in the url.

Panels

I created a Panel Page for the home page. The page address is like http://example.com. I added the View pane.

In the Panel page, View pane settings there are no settings at all:

I've added a context and a relationship to the Panel page (not sure if relationship is necessary):

Previously, I've been passing page arguments to view panes by configuring the "Argument input" setting in Views, and it was working. But in this case, there are no page arguments. I want to pass a specific term ID tid=39 to the view pane and don't know how.

1) Views -> Contextual filter: add a filter

2) Views -> Pane settings -> Argument input: choose "Input on pane config" (notice the label)

3) Panel page -> Content: add the View pane

4) Panel page -> Content: in the pane settings, set the argument (notice the same label)

5) For this scenario, the Panel page -> Context is not needed


Get params cookie_domain I would like to retrieve the parameter cookie_domain set in the services.yml like this:

parameters:
  session.storage.options:
    cookie_domain: '.domain.ext'

I try this:

(new SessionConfiguration())->getOptions(\Drupal::request());

This recovers the default value not my value

You can get the cookie domain this way using the session_configuration service.

$sessionConfig =\Drupal::service('session_configuration');
// Get the current request.
$request = \Drupal::request();
// Get options from the request.
$options = $sessionConfig->getOptions($request);
$cookie_domain = $options['cookie_domain'];


Drush was not able to start (bootstrap) the Drupal database - MySQL Access denied error I've installed Drush 7 using Composer and working with Drupal 8 and 7 on Ubuntu 12.04 with PHP 5.4.31, mysql 5.5.38

Drush will dl modules and themes just fine but when I want to en a module then it gives me the Drush was not able to start (bootstrap) the Drupal database.

So upon further investigation I did this:

$ drush -v -d sql-cli
Starting Drush preflight. [0.02 sec, 1.15 MB]                        [preflight]
Cache HIT cid:                                                           [debug]
7.0-dev-commandfiles-0-87f720da39665f2c425de5e651f2ac4d [0.05 sec,
1.19 MB]
Bootstrap to phase 0. [0.2 sec, 3.19 MB]                             [bootstrap]
Bootstrap to phase 0. [0.28 sec, 3.19 MB]                            [bootstrap]
Found command: sql-cli (commandfile=sql) [0.28 sec, 3.19 MB]         [bootstrap]
Calling hook drush_sql_cli [0.56 sec, 3.21 MB]                           [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.56 sec,    [bootstrap]
3.22 MB]
Initialized Drupal 8.0-dev root directory at                            [notice]
/home/wavesailor/My_sites/bootstrap-business [0.62 sec, 3.52 MB]
Cache HIT cid:                                                           [debug]
7.0-dev-commandfiles-1-67528d048330f8c38ed66ea20e647906 [0.62 sec,
3.52 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.63 sec,    [bootstrap]
3.57 MB]
Initialized Drupal site default at sites/default [0.63 sec, 3.57 MB]    [notice]
Cache MISS cid:                                                          [debug]
7.0-dev-install_profile-66ecfeb9791a023150773849f1550c5d [0.64 sec,
3.57 MB]
Cache HIT cid:                                                           [debug]
7.0-dev-commandfiles-2-027a7d06ad1248d56c7499a21fb8d2df [0.65 sec,
3.57 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.65[bootstrap]
sec, 3.57 MB]
Calling proc_open(mysql --defaults-extra-file=/tmp/drush_ST3u9r --database=bootstrap_business --host=127.0.0.1 --port=3306);
ERROR 1045 (28000): Access denied for user 'my_username'@'localhost' (using password: YES)
Returned from hook drush_sql_cli [0.87 sec, 3.72 MB]                     [debug]
Command dispatch complete [0.87 sec, 3.71 MB]                           [notice]
Peak memory usage was 5.21 MB [0.87 sec, 3.7 MB]                        [memory]
$

It seems it cannot connect to the database so I did the following:

$ drush sql-connect
mysql --user=my_username --password=my_password --database=bootstrap_business --host=127.0.0.1 --port=3306
$ mysql --user=my_username --password=my_password --database=bootstrap_business --host=127.0.0.1 --port=3306
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 286
Server version: 5.5.38-0ubuntu0.12.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

I can connect manually to the database with the connection string given by drush.

So then I deleted the .drush folder in my home directory but that did not help.
I did try this for both Drupal 7 and 8 sites.

So then I downgraded to drush 6 (composer global require drush/drush:6.*) and drush then worked flawlessly with Drupal 7 sites. I then upgraded to drush 7 (composer global require drush/drush:dev-master) and it stops working again

Any ideas on how to solve this??

The answer to the problem was that I had a file .my.cnf in my home directory which I used a while back. It contained the user=username and the password=old_password. This was the cause of problem as it contained the correct username but an old password.

Previous drush versions (< 7.x) did not use the mysql option --defaults-extra-file=/tmp/mysql_credentials to connect to database and that's why the problem didn't exist when I used an older version of drush.

I would have thought that the '--defaults-extra-file=/tmp/mysql_credentials would supercede the .my.cnf in my home directory but it doesn't seem to.

One thing which would be useful to help debug this issue it to make drush not delete the /tmp/... files when you select the -d option.


Manually enter custom timestamp So I'm making quite a few nodes through a script, an action. To do this I'm using the form_state drupal_execute method.

However because there is a lot of processing per node in one batch I get lots of nodes with different time stamps.

Is there any way to manually edit the timestamps a part from going into the DB? I've tried this:
outside loop:

$time = time();

inside loop:

form_state['values'] = $time;

And give the same timestamp to all the nodes. But apparently druapl_execute gives them a new time stamp.

Thanks.

EDIT: Solved!
I ended up adding this line, it was the fastest solution I could think of.

db_query("UPDATE  {node} SET  created = %d WHERE  nid = %d", $time, $form_state['nid']);

Another solution is assigning the created property of the $node object before calling $node->save.

e.g.

$body_text = 'This is the body text I want entered with the node.';
$created_time = time();

$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);

$node->title    = 'Node Created Programmatically on ' . date('c');
$node->language = LANGUAGE_NONE;

$node->body[$node->language][0]['value']   = $body_text;
$node->body[$node->language][0]['summary'] = text_summary($body_text);
$node->body[$node->language][0]['format']  = 'filtered_html';

$path = 'content/programmatically_created_node_' . date('YmdHis');
$node->path = array('alias' => $path);

$node->created = $created_time;

node_save($node);

For more information please see the API docs on node_save().

The solution above has the added bonus of not requiring additional databases queries to clean up the timestamps after the node was created.


How can I adjust Drupal links on shared hosting so that they don't point at the root? I have installed Drupal on shared hosting. Drupal is installed in the public_html folder of an Apache user directory (UserDir). Unfortunately, I notice that Drupal always defaults its administrative links to the root, for example: http://www.domain.com/?q=admin. I don't want this, since my site is located in the user directory. Therefore, I want Drupal links to look like: http://www.domain.com/~sitename/?q=admin. How do I get this to happen when the url contains a tilde?

Is there a setting(s) I can change to make a global adjustment?

Thanks in advance,
Doug

You have a variable ($base_url) for this in settings.php, in /sites/default usually.

Set $base_url to match the address to your Drupal site:

$base_url = "http://www.example.com/~stef";

Hope that helps!

PS: There is also a url setting in .htaccess you may want to look at if the above does not work.


How do I get a plaintext list of tags from a multi value entity reference field? I have a module that's making custom RSS feeds for me.

In a content type, I have my tags stored in "field_tags" entity reference field.

My goal is to get the names of all the tags, and ultimately put them into an array, so they can go into a markupless  RSS field.

When I'm pulling the data, I get it with this:

foreach ($this->dbh->selectVideos(self::RPP) as $nid) {
  $node = $this->entityMgr->getStorage('node')->load($nid);

  if (!empty($node)) {
    $data->nodes[] = [
      'title'    => $this->filterTxt($node->title->value),
      'body'     => $this->filterTxt($node->get('field_paragraph')->value),
      'body2'     => $this->filterTxt($node->get('field_paragraph')->value),
      'created'  => date('D, d M Y H:i:s', $node->created->value) . ' GMT',
      'guid'     => $node->id(),
      'img'      => $this->getImgUrl($node, self::IMG_FIELD),
      'keywords' => $this->filterTxt($node->get('field_tags')->value),
      'video'    => $node->get('field_vid_url')->getString(),
    ];
  }
}
return $this->render($data, 'nameoffeed');

}

The problem is that 'field_tags' is an entity reference field, so it's turning up blank.

I had partial success with this:

    if ($node->hasField('field_tags')){
      $entity_ref = $node->get('field_tags');
      if ($entity_ref->count() > 0){
        $tagoutput = entity_view($entity_ref->entity, 'default');
      }

Then setting 'keywords' to equal $tagoutput. This grabs the first tag, which isn't great as I need them all, and then along with it comes a whole html layout enclosure that won't work for an RSS feed.

I'm confused what the correct way is to get a proper list of tag names. In D6 I had this list as plain text, which wasn't great because you wouldn't be able to click on one in the page view and be taken to a list of all pages with that tag, but at least the tags worked on the feeds easily.

Any thoughts?

You can get the array of reference entities from node using

  $node->get('field_tags')->referencedEntities();

So the code will look something like below:

// Get the referenced entities
$tags = $node->get('field_tags')->referencedEntities();
// Check if we have output. (Assuming we get an array, You will have to check what your output it.)
if (!empty($tags)) {
  // Go through each entity.
  foreach ($tags as $tag) {
    // Write your Business Logic here to create your Keywords Array.
  }
}
// Use the Keywords Array for further use.

I Hope this helps you.


Zen theme not compatible with IE8? I am using a zen theme, the default styles and template and while the Main content displays correctly in Firefox, it is all the way to the left in IE.

In firefox, Navigation menu on top, sidebar on the left, main content on the right.
In IE, Main content area on top, with navigation menu underneath and sidebar first underneat that. All left align...

What am I missing?

I just overrode all the css and everything and it is still displaying the same...

"I fixed the issue by setting the bandwidth optimization to: Aggregate and compress CSS files." said kine456.
kine456 answered his own question.

This is because js files like respond.js that comes with the zen theme must get applied after you aggregate the css files for it to look correctly in ie8. I'm pretty sure its documented in the theme's readme.


User role specific login link This may sound like a strange question but it is desired functionality from a client. They would like to have a login screen that only staff members can log in through. What I mean by that is if an anonymous user logs in, and if their role is staff (or admin) then they are logged in. If it is any other role, then they are not logged in and redirected to a 'normal' login page.

I know this seems unorthodox but is there a way to accomplish this?

Thanks.

Which ever role you want to allow to login give the role the permission.

Drupal 6

Please change the permission to an appropriate one. This is just for test purpose.

function modulename_perm() {
  return array('allow modulename login');
}

function modulename_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'login') {
    if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
    }
  }
}

DRUPAL 7

function modulename_permission() {
  return array(
    'allow modulename login' => array(
      'title' => t('allow modulename login'),
      'description' => t('allow modulename login.'),
    ),
  );
}
function modulename_user_login(&$edit, $account) {
 if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
 }
}


Field collection - Delete "Remove button" on line I need to delete the "Remove button" on every edit field collection for specific role users. I have 3 roles (Admin, Project, Test). Just Admin and project can see the "delete" button and "add" button to remove lines or add a new line. The others roles are not allowed to delete or add new line in the field collection.

I tried to change some permissions (Administer field collections - Create and delete fields on field collections.) But it didn't work...

I need to use HOOK ? or maybe just JQuery ?

To complete my explication, here an example :

Thanks

PS : "Supprimer" = "Remove"

Write following code in your theme template.php file. It will added css classes to body of a specfic page.

    <?php

    function hook_preprocess_html(&$variables) {
      global $user;
      $args = arg();

        if( isset($args[0]) && ($args[0] ==  'your-page-url-first-argument')){ // Check ur page url parameters
        $account = user_load($user->uid);
        if(in_array("test", $account->roles)){
          $variables['classes_array'][] = 'test_user';
        }
      }?>

CSS:

.test_user [remove_button_class/id] {

  display:none

}


Email field anonymizer I want to allow anonymous users to create nodes, and their email address (entered by them into a field) will show on the node view as 'anonymized'.

The idea is that anyone can enter an email address, and the page will show an email address that looks something like "siouent-12393@this-site.com", which automatically forwards to the actual person's email.

Are there any modules for doing this? I have seen something about tokens for the email field, but I think that is not the right direction.

Does this require some deeper server system?

You are looking to integrate your MTA's (mail transfer agent = mail server's) virtual user table with something that can be managed through code running through Drupal. There are multiple ways to do that and the exact mechanics will depend heavily on the particular MTA you are using, but the general idea will be the same. As for specific instructions for your particular MTA, I'd try Google or ServerFault.

That said, if I can be allowed to use Postfix as an example, what you are looking for seems to be configured primarily through the virtual_mailbox_maps configuration setting. Official documentation, Postfix and MySQL howto, quick guide to get you started and Virtual mailhosting guide with Postfix on Gentoo.

Once the MTA looks to a database table for address translation, adding a forwarding address becomes a simple INSERT SQL query with appropriate values. If everything is set up correctly it should then take the e-mail that was received and redirect it to the user's real e-mail address.

Oh, and one more thing; make very sure you properly validate the user's provided e-mail address, so you don't become a source of spam for others. Send them a short e-mail with either a link to click on or a code that needs to be entered to activate the forwarder.


On entity save, identify the user fields that have been changed I have a need to track changes to users in a separate database, apart from Drupal. When a user changes their email address or their password, I need to communicate that change with a shadow table in MSSQL.
I've created an event and listener. The event is triggered by hook_entity_update. That works fine, but I don't know what was changed in that request. Is there a way to pass the value that was changed to that event listener?

Per the hook_entity_update() documentation:

This hook runs once the entity storage has been updated. Note that hook implementations may not alter the stored entity data. Get the original entity object from $entity->original.

In your event listener, you can compare the email/password fields on $entity & $entity->original to check if they have changed.


Hide Superfish menu on selected pages I have installed Danland Theme and it is cool. I want the superfish menu to be appeared on few pages, not all the pages. For example if I type a wrong URL address in the address bar, it says Page not found and it still gives that Superfish menu there on the page.

I have some pages, where I don't want that superfish menu to be appeared.

Can anyone help?

Goto /admin/structure/block/ configure your superfish menu block

Scroll down to the bottom and locate "Show block on specific pages"

select this option " Only the listed pages "

and define the paths of the pages on which you want superfish menu to appear.


Remove duplicate data in revision tables in database Possible Duplicate:
  How to disable the revision feature completely?

How can I disable duplicate data in database. one example is this image:

You can't unfortunately.

The concept of storing field data and revision data in two different tables is hard coded into entities at the very lowest level.

If you want to change this behaviour you're looking at a major rewrite of the entity and field systems, and I very much doubt there's any way to do it without hacking a fair few of the core files.

The best thing to do is just accept that this is how Drupal stores its data and try to work with it rather than try to get around it.


Disabling the form field on submit I have a webform where I've used form alter to do some functionality and validation.

Now in my validation I want to disable a field for a purpose. How can I do so? Is it possible in form validation?

I think what are looking for is hook_node_validate()

  Perform node validation before a node is created or updated.

  This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.


How do I theme a block created with the Views module? I'm Newbie user in drupal, i need to custom design theme block created for views module.

Example HTML:

title1

content1

title2

content2

I'm not perfectly sure what you are asking...

If you want to theme a view then you can add a css class name under the advanced drop-down, or add a  css class to any field.

Or are you looking to adjust how a block appears using views?


Locating a specific position on the page I want to provide a clickable link on drupal such that it easily locates the position of the content in a page. e.g http://asblab.mie.utoronto.ca/people , I want to have a link , that automatically scrolls this page to locate "Past lab member" without requiring me to create a new node. Thank you in advance.

If you put whatever you want in a div or span with an id, you can then use that id for an anchor.  For example, GO HERE will GO HERE


How to remove a Views row if field equals value? In my view I have a made a customised global field that returns a boolean result.

What I now need to do is if this field equals zero then the whole row should be ignored/removed from the view.

The issue here is that I cannot see this field in Filter Criteria to add as a filter.  I have also looked into a programmatical solution but have looked at hook_views_post_render and hook_views_pre_render but cannot see how I can achieve this.

Any help, module suggestions or push in the right direction would be very much welcome.

I would use a views row template override for this. Do the following in a Development site first.

1) In the view, expand the Advanced options and click on the Theme: Information link. This displays all the available theme template suggestions.

2) Under the heading "Row style output" you will see all the possible template suggestions. Which one you override depends on your needs, but the last listed is the most specific so I would start there. Select it with your cursor and copy the file name.

3) Open this file in your code editor: sites/all/modules/views/theme/views-view-fields.tpl.php

4)Save it as the most-specific suggestion (the value you copied in step 2) and save it to your theme's template directory (e.g., sites/all/themes/yourtheme/templates or sites/all/themes/yourtheme/templates/views)

5) Now you can edit the template (the one we just saved to your theme). You can use a combination of html and PHP to achieve the exact markup and logic you want. Generally it's best practice to not code a lot of logic into your templates (use preprocess functions instead), but simple logic like checking if a field is present or has certain values is fine to include in the template.

There are many different ways to do this, but here is an example (change field_custom_boolean to the machine name of your custom global field ...

 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>
  <?php
  /* if custom field is present and set to 1 */
  if (isset($content['field_custom_boolean']) && $fields['field_custom_boolean'] == '1'): ?>
    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

6) Save file and flush all caches. Now when you check the view Advance:theme information settings, you should see your template override listed in boldtype. When you load your view it should only display rows for records where the custom global field is set to 1.

Good luck.

For more info on Views templates, see:

https://api.drupal.org/api/views/theme%21theme.inc/group/views_templates/7.x-3.x

https://www.drupal.org/docs/7/modules/views


Script for collecting all translatable strings in the codebase? I have hundreds of strings in my code-base that which translation i.e. strings inside t() function.

Is there a script that can traverse through my code-base and collect all the strings and export them to an excel file?

Or else, Is there any other way?

By default, every string you wrap in the t() function is going to be added to the localization database by the core Drupal locale module as soon as Drupal encounters the occurrence. You can then use the translation interface to search for these new strings and update them manually or export a Gettext Portable Object Template file

http://example.com/admin/config/regional/translate/export

These files are in text format and easily editable by non-technical users, ex:

#: misc/tabledrag.js
msgid "Hide row weights"
msgstr ""

There are a number of tools available for working with gettext files, I would recommend the Localization client module for doing this work within the Drupal interface. There is also an option to convert these files to excel and back using csv2po but I haven't used this:

http://docs.translatehouse.org/projects/translate-toolkit/en/latest/guides/using_csv2po.html


programmatically taxonomy update node DrupalDefaultEntityController error When I programmatically create a taxonomy term and update node, in hook_node_presave() I have the following code:

$node->field_status_tags[LANGUAGE_NONE][]['tid'] = $value->tid;

I get the following error:

  Notice: Array to string conversion in DrupalDefaultEntityController->cacheGet() (line 369 of  includes\entity.inc).

This is the code I am using. I'm sure the value for tid is right.

/**
 * Implements hook_node_presave().
 */
function love_layout_node_presave($node) {
  /*
   *if ($node->nid && $node->moderate) {
   *  // Reset votes when node is updated:
   *  $node->score = 0;
   *  $node->users = '';
   *  $node->votes = 0;
   *}
   */
  if($node->type == 'status') {

   $pattern = '/#([^\\#|.]+)#/';
   preg_match_all($pattern, $node->title, $matches, PREG_SET_ORDER);
   $node->field_status_tags[LANGUAGE_NONE] = array();
   foreach ($matches as $key => $value) {

      $term_name = $value[1];
      $term = taxonomy_get_term_by_name($term_name);
      if(!count($term)){
       $term = new stdClass();
       $term->vid = 1;
       $term->name = $term_name;
       taxonomy_term_save($term);
       $term = taxonomy_get_term_by_name($term_name);
       foreach ($term as $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }else{
        foreach ($term as $key => $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }
   }
   //dpm($node,'love_layout_node_presave-node');
  }
}

Basically I would think that $value->tid when you are using it is not a number but an array. Because I do the same assignment and it works.

So I suspect you are misusing the taxonomy term you created. This is how I created the taxonomy in a function:

function create_new_term($term_name, $vocabulary_id, $language = LANGUAGE_NONE, $i18n_tsid = 0){
  $tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name'=>$term_name,
    'vid'=>$vocabulary_id,
    'language'=>$language,
    'i18n_tsid'=>$i18n_tsid,
  ))->execute();
  db_insert('taxonomy_term_hierarchy')
    ->fields(array(
      'tid'=>$tid,
      'parent'=>0,
  ))
  ->execute();
  print "Created new taxonomy term tid #".$tid." $term_name in $vocabulary_id<br>"."\n";
  return $tid;
}

And here is how I add that term:

$my_new_node->field_my_term['LANGUAGE_NONE'] [] ['tid'] = $returned_tid;

I hope this helps.


Error - Sharing the Same URL for two different views in exposed filter My goal is to prepare glossary based on contents

I have used two views, one is alphabetical search and another one is keyword search filter.

In alphabetical search, I grouped the alphabets and setted in the block and then clicking the letters, It will take to the page which contains the particular content. And here, I have used the URL is local host/glossary.

In Keyword search, Here also used the same URL (localhost/glossary), I setted the search functionality in the block and when searching the content using keywords of contents.

Its not filtering for keyword search, does only for alphabetical search.

I want to filter the both in same URL.

Please help me to sort out this issue.

You can use Views Glossary to create a glossary that is grouped alphabetically, and then add an exposed filter to search by Keyword.

Enabling the module provides you with an example view that you can clone and modify to get the functionality you need.

Clone the view "Views Glossary Example" to create your /glossary view
Add your exposed filter for your keyword search.
Open contextual filters and change the Title filter to "Display all results for the specified field" when the filter value is not in the URL. If you don't do this, the view will only display results for 'A' when no letter is selected.

This will allow users to simultaneously search the glossary using keywords and/or filter the glossary alphabetically.


Retrieveing config for a custom ctools content type I've created a custom ctools content type to make a custom pane for my node/%nid panel. The content type has an edit form with some configuration options for the pane, that I would like to access from a function call from a custom module.

I haven't been able to find where this information is stored in the DB, or how I might be able to access it with some of the ctools functions.

For more context, the form has a toggle between public and private users. And I would like to know when submitting an unrelated form on the page, if that block is set for public or private use, and wanted to get the information directly from what I chose when configuring the pane.

What I think you want might be possible, but it is not easy.
The configuration settings are saved in the DB in the panels_pane table as serialized data in the 'configuration' column. That allows each instance of the pane to have its own configuration. In order to get that you would need to know how to get the specific instance of the pane being displayed, grab the column, and then unserialize it.

You are probably better off figuring out a different way to handle this (if you haven't already).


Can payment be done in pop-up rather than using redirect? We have an online store with a few hundred products, and we'd like to streamline the checkout & payment process.
Currently our payment processor requires the website to be redirected to their site to make the payment, then the user is redirected back to our site for confirmation.

Instead of redirecting our users to the payment processor's site, can we open the payment processor's site in a popup? I think the popup could either be a separate window (though that might be extra complicated), or as a lightbox (possibly using an iframe).

Does Drupal Commerce support this sort of thing, and is it safe to do or not recommended (as a security risk)?

We're using Drupal 7. Our site is a fairly standard online store.

If your gateway tells you to redirect, you redirect.
If you need a modal-based gateway, choose another gateway.
Changing the flow recommended by your gateway puts you firmly in unsupported waters, and definitely exposes you to additional risk.
This is especially true since redirected gateways require PCI A compliance, while modals require the slightly more complex PCI A-EP compliance.

I would also expect most gateways to have protection against this.


How can I remove the "This translation is published" checkbox? In my custom entity module I have already defined a status checkbox to determine the entities status. What I noticed is when I enable show_revisions_ui in the annotation and have the entity setup to support multiple languages there are two check boxes at the bottom of the page.

One of them is to publish this entities language copy and as a result the published checkbox I created is being ignored. How can I disable the multilingual published checkbox?

So it turns out I needed to define a translation handler for my entity.

inside of MyEntityTranslationHandler that extends the ContentTranslationHandler I override the entityFormAlter function and add this:

$form['content_translation']['status']['#access'] = FALSE;


How to implement a cancel button with required elements I have a form in which I have added a cancel button which looks like this:

$form['cancel_button'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
  '#name' => 'cancel',
  '#access' => TRUE,
  '#submit' => array('mymodule_cancel'),
  '#limit_validation_errors' => array(),
);

This form has required elements in it as well and what is causing the problem. I thought that by having the #limit_validation_errors statement would prevent the required elements check, but that is not happening. How do I prevent the required elements from being checked?

EDIT: I found this answer on a different question Isn't it possible to have multiple buttons  along with a submit button?

This would explain the behaviour I am seeing but it seems to contradict the Drupal documentation about limiting error checking. This would really screw up people who want to save a draft of a form that has required fields. I am pretty sure I have seen this done before, so there must be away around this.

You can make something like this in your function validate :

function FORM_validate(&$form, &$form_state) {
if ($form_state['values']['op'] == 'cancel')
{
 ///  Do something
/// drupal_goto() for example
}
}


Submit form elements as email I have a requirement in which the user should not be able to register to site, but only request registration by filling the form (first name, last name, email, company, etc.). The request should go to site admin's e-mail id. Using webform I have created the form, but I am not able to send it as email.

Also the "Per user submission limit" option of webform is decided by the IP address or cookie (for anonymous user), whereas I would like to limit the form submission by the e-mail ids of the submitting users. How can this be done?

With all due respect, I think Webform is the wrong way to approach this.  Drupal core can be configured to handle registration in the manner you are requesting with less workload for your site admins (no manual registration of webform data).

On  Administration >> Configuration >> People (admin/config/people/accounts):

Set Who can register accounts? to Visitors, but administrator approval is required

As for the fields in the Webform (first name, last name, e-mail, company, etc.), you should create those on the Administration >> Configuration >> People >> Account settings page (admin/config/people/accounts/fields) under the Manage fields tab.  Make sure to mark the fields as required and to display them on the registration form.  Note that storing these fields as part of the user account will cause all of this information to be displayed in the user profile.  If you need field-level control of the information (to make last name private/hidden, for example), you can use the Field permissions module.
edited per Berdir's comment By default, Drupal will send an e-mail to the site administrator when an account is registered.  If you need a special notification, you can use the core Trigger and Actions modules (or the contributed Rules module) to set up an action (or rule) to e-mail the administrator(s) when a new account is registered and pending approval.


Make drupal theme responsive How do i make a custom drupal theme i already have responsive. I mean the easiest way to do this?

What about integrating my current custom theme on top of a drupal base theme like omega?

You can retrofit your custom theme to make it responsive. Emma Jane Hogbin has written a great tutorial for this (available for purchase at http://www.responsivewebdesignguild.com/). I have used it to retrofit a couple of drupal sites that use the zen base-theme, the principles should work for any theme.

The basic principles/steps are:

Add a new style sheet to your css directory (and .info file)
Determine break points in your theme depending on the content - what do you want to display wide - medium - narrow views, how do you want to reorganize the page
Add media queries to the stylesheet reflecting the break points, like this:

@media screen and (max-width: 960px) {
  #main {width: 100%;}
}
@media screen and (max-width: 750px) {

}
@media screen and (max-width: 500px) {

}

Basically, adjust the width/etc. for the elements and width determined earlier.
The navigation menu is a special case. At the max-width that makes it most likely that the user is using a table or a phone, the menu should be "fat-finger" enabled, by changing the ul and li styles so that each link has a larger width and height. For me, links changing from horizontal to "one link per line with padding" works best.

Then, copy the core html.tpl.php file into your theme/templates directory, and add the following to end of the header section:

<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="width" />

Emma Jane demonstrated this approach for the Domicile theme, the result is available at:
https://drupal.org/project/domicile_responsive


Is there a way to alter output/markup for a field in node edit view? I am looking for a way to alter field output when rendered in the normal edit view.

I have looked at the hook_quickedit_render_field function which helps out in quick edit mode but are there something similar for the normal edit view? Drupal 8.

You can use hook_form_alter or hook_form_FORM_ID_alter

You'll need the ID to target specific forms; otherwise, you will endup altering every single form. See How can I find the form ID of a form?

Example of hook_form_FORM_ID_alter:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'article') {
    // Alter the 'article' form here.
  }
}


How to specify the numbers of characters for teaser for views block? I know we can specify the specify limit for the teaser by going to content type -> manage display -> teasers. I have made the views block for teasers and I want to display only few lines for that content in particular views block and do not want to affect the stand treasure setting. So, is there any setting in Views which specify the teasers limit for the particular Views block?

I would use TRIM to achieve that. Go the desired field in the View, click "Rewrite results", there "Trim this field to a maximum length", and insert a number value.


Letting a view know in which pane it's being displayed I've got a very non-trivial question on integrating Panels and Views. Maybe there's no solution out of the box, but I would really appreciate any help.

Essentially, I've got a lot of tagged nodes. For simplicity, let's say image nodes that are tagged as "flowers", or "animals", or "mountains", etc.

Then I have a view block that displays the images depending on their tag. This view block is then used in panel panes across the website.

Here's the issue: I can't use the URL to pass the tag information. In fact, on the same web page, I need to show several blocks (within panel panes) with different sets of images. One block would show "animals", another one "flowers", etc. And that depends only on the panel pane in which the view block is being displayed.

Of course, I could just create several preset view blocks, one only for "animals", another one for "flowers" etc, but I've got tens of different tags and can't create a separate block for each tag. So I was thinking of a more elegant solution.

Here's what my idea is: when I add content to a panel pane, I've got an option to override the title. I was thinking of adding another text field there "Tags to display" where I would say "flowers", or "animals", etc. Then I would just add the view block to the pane and that view block would pull that tag from the panel pane.

So, bottom line: how can I let the view know in which panel pane it's being displayed? Just pane ID would be enough, the rest (the tag to use) I could simply pull directly from the database.

Thanks for your ideas.

Build your views as "view content pane" displays.  That way any context you require for use in contextual filters can be provided in the panel UI when you set up the pane.


Migrate Module: How to construct a map on a UNION query I am trying to create a hierarchical taxonomy from two different tables in the source database, one containing the parent entries, and the other containing the children.  Here is my query:

    $query1 = $this->getConnection()
      ->select('envirolib_area', 'a')
      ->fields('a', array('areaname', 'areaname_japanese', 'sort_order', 'acronym', 'areaid'));
    $query1->addExpression(':empty','parentid',array(':empty'=>0));
    $query2 = $this->getConnection()
      ->select('envirolib_task', 't')
      ->fields('t', array('taskname','taskname_japanese','sort_order','acronym','taskid'));
      $query2->addField('t','areaid');
    $query1->union($query2, 'UNION ALL');

    $queryx = $this->getConnection()
      ->select($query1,'x')->fields('x', array('areaname','areaname_japanese', 'sort_order', 'acronym', 'areaid', 'parentid'));

The envirolib_area table has a primary key of areaid, and the envirolib_task table has a primary key of taskid.  The envirolib_area table doesn't have a taskid column, and in my union I am actually calling a.areaid and t.taskid areaid, with t.areaid called parentid and 0 inserted in that column for rows from the envirolib_area table.

the addition of $queryx was necessary to stave of errors about unven numbers of queries in a union, which seems to be caused by the mapping method joining onto the query (thought the explanation I read, claimed that shouldn't happen if 'map_joinable' => FALSE as it is in my case.

So here is my attempt at MigrateSQLMap:

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'areaid' => array('type' => 'int',
                       'length' => 3,
                       'not null' => TRUE,
                       'description' => 'Area ID',
                       'alias' => 'a'
                      ),
    'taskid' => array('type' => 'int',
                        'length' => 3,
                        'not null' => TRUE,
                        'description' => 'Parent ID',
                        'alias' => 't')
    ),
  MigrateDestinationNode::getKeySchema()
);

When I try to run the migration I get a wall of errors like this:

Undefined property: stdClass::$taskid File /Users/bob/ultrabob.prv/www/sites/all/modules/migrate/includes/migration.inc, line 943(file: /Users/bob/ultrabob.prv/www/sites/all/modules/migrate/includes/migration.inc, line 943)
Could not save to map table due to NULL value for key field taskid

How should I set up the MigrateSQLMap in a case like this?  Would it make more sense to migrate this taxonomy in two migrations, one for each table?

Either do 2 migrations. Or create a derivative table of your term data to easily set the $query for the migration before running the migration task.

You can do this by writing a custom php script to be called by drush php-script or by using the preImport migrate hook to build/rebuild the derivative table.


How to select FROM {commerce_product} p WHERE p.field_TERMFIELD = $given_tid and the resulted p.product_id is referenced on a given nid Known values:

The nid of a node that has reference to more than one commerce_product
The tid from the field_TERMFIELD field attached to the commerce_product entity

commerce_product entity is referenced on the node entity via a multivalued entity reference field. When my known node has more than one referenced commerce product, I gotta figure out which one of those referenced products has a given tid.

A solution via either db_select() or EntityFieldQuery() are welcome.

I think I got it figured out:

$query = db_select('commerce_product', 'p');
$query->join('field_data_field_TERMFIELD', 't', 't.entity_id = p.product_id');
// This is the product reference field table. This field is attached to our node.
$query->join('field_data_field_product_reference', 'pr', 'pr.field_product_reference_product_id = p.product_id');

$query
  // This is the product_id we are looking for.
  ->fields('p', array('product_id'))

  ->condition('field_TERMFIELD_tid', $tid)
  ->condition('pr.entity_type', 'node')
  ->condition('pr.entity_id', $nid);

 $result = $query->execute();


Views get total row count in views-view.html.twig I need to get the total rows count in views-view.html.twig file. So that I can loop through it and create the indicators required for my bootstrap carousel view block.

I tried the solution provided in this thread Drupal 8 Views get total row count in views-view-fields.html.twig but nothing seems to be working.

Can any one please guide me how its possible.

This can be achieved as follows. NB this outlines a simple approach which works. It can be finessed and improved upon by stripping our unnecessary divs, applying classes more elegantly, etc, but this will work:

Adding a views attachment display and attaching it to your main
display of the slides (display: after);
Set this attachment with an ordered list display format with List class = carousel-indicators;
Add one custom text field (it will not be displayed so it does not really matter what this is);
Set it to evaluate the same conditions as your main display (eg content filtered by a boolean "display in slider" = TRUE ... or whatever). This way number of bullets definitely = number of slides;
Copy the core views-view-list.html.twig to your theme and override with your
display name (see api.drupal.org/api/drupal/core!modules!views!views.theme.inc/group/views_templates/8.3.x for general suggestions);
Return the rows as follows:

{% for row in rows %}
     {% if loop.first %}

{{ row.content }}

     {% else %}

{{ row.content }}

     {% endif %}
    {% endfor %}

This gets the active class on the first item and includes the index number, thus matching the requirements at: getbootstrap.com/javascript/#carousel

Controls and required wrappers can be set simply in the views-view.html.twig:

 {% if rows %}

 {{ rows }}

`
(...etc..)

Slide wrapper and active class can be set in views-view--unformatted.html.twig for the slides themselves:

 `<!-- Wrapper for slides -->`

{% for row in rows %}
   {% if loop.first %}

    {{ row.content }}

{% else %}

    {{ row.content }}

{% endif %}
 {% endfor %}

Working example: http://wri.netuxosandbox.co.uk/en


Custom validation for a form? I need to add custom validation to a form, lets says add article form.

I was expecting something like hook_FORM_ID_validate() to handle this, but cannot find anything relavant in the API documentation.

What is the way to add custom validation to a form?

You can add any number of validation functions to any form in hook_form_FORM_ID_alter() like so:

function mymodule_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_article_form_validate';

  // As mentioned above you can add as many as you want
  $form['#validate'][] = 'mymodule_article_form_validate_2';
}

function mymodule_article_form_validate($form, &$form_state) {
  // Random example, if the title is 'test' throw an error
  if ($form_state['values']['title'] == 'test') {
    form_set_error('title', 'Title cannot be "test"');
  }
}


How do I show all the images in my public:/images/ folder? So i have successfully uploaded my images into my public:/images folder now i want to output/display all of them in page how do i retrieve all the images?

here's  code by the way of handling the form.

 function testform($form, &$form_state) {
   $form = array();
   $form['file'] = array(
      '#type' => 'file',
      '#title' => t('Image'),
      '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
     );
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
     );
 return $form;

}

here's the code for validating it.

      function testform_validate($form, &$form_state) {
         $file = file_save_upload('file', array(
        'file_validate_is_image' => array(),
        'file_validate_extensions' => array('png gif jpg jpeg'),
          ));
       if ($file) {
       if ($file = file_move($file, 'public://')) {
       $form_state['values']['file'] = $file;
    }
else {
        form_set_error('file', t('Failed to write the uploaded file the site\'s file   folder.'));
     }
  }
else {
   form_set_error('file', t('No file was uploaded.'));
}

}

here's the code for submitting.

    testform_submit($form, &$form_state) {
         $file=$form_state['values']['file'];
         unset($form_state['values']['file']);
         $file->status = FILE_STATUS_PERMANENT;
         file_save($file);
         drupal_set_message(t('The form has been submitted and the image has been saved,   filename: @filename.', array('@filename' => $file->filename)));
          }

Firstly get fid of the images and then put it in the function below Like i did:-

$file_load=file_load($fid);
$url=$file_load->uri;

$url retrieve you image path where you have uploaded your image.
Like:- public:/images/image_name

Use this fuction to display your image. image_style

$variables= array(
'style_name' => 'style_name',
'path' => $url,
'getsize' => FALSE,
'attributes' => array(
 'width' => '100',
 'height' => '100')
);

echo theme('image_style',$variables);

Note :-if you are using drupal theme('image_style',$variables) function to display image.then put url like public:/images/image_name in path given above.else you are using  to display image then use below code.

Or You can also do this.

$file_url=file_create_url($url);
echo '<img src="'.$file_url.'"'>;

Hope this will help you.


Migrate user passwords salted and hashed with md5 I have quite complex migration for some legacy non drupal site to migrate it into D7. The whole migration works fine but it turned out that source user passwords are salted and hashed with MD5. Because they are salted I can't do this in my migration class:

 $this->destination = new MigrateDestinationUser(array('md5_passwords' => TRUE));

I've found this solution which boils down to reimplementation of original hashing algorithm in new drupal site. I don't like this solution because it decreases security of the site and throws away whole D7 password hashing code.

Something tells me that the only way to migrate those old passwords and keep the drupal hashing algorithm is to copy-paste whole includes/password.inc and add "temporary" hashing algorithm from the old non-drupal site in similar way drupal core handles old MD5 passwords without salt.

Or maybe there is a better way to migrate those old passwords?

I don't like this solution because it decreases security of the site and throws away whole D7 password hashing code.

How does this decrease security? The D7 hashing function is pluggable, you can migrate the fields without (re)hashing them by setting $this->md5Password = FALSE and then using your own hash function from the legacy system, as commented on in the issue you posted:

https://www.drupal.org/node/1326450#comment-5192996

You're still using the Drupal API to perform authentication and more than likely the legacy hashing technique while not stellar is probably not brain dead.

Now, if you don't like side-stepping the default Drupal7 password semantics -- then don't. Or do it for a temporary amount of time as you mentioned and inform your users of a pending system-wide password reset. This happens alot all over the net even recently on Drupal.org.

You may force all site users todo a password reset and setup strict password enforcement using the Password Policy module:

  A password policy can be defined with a set of constraints which must
  be met before a user password change will be accepted. Each constraint
  has a parameter allowing for the minimum number of valid conditions
  which must be met before the constraint is satisfied.

  Example: an uppercase constraint (with a parameter of 2) and a digit
  constraint (with a parameter of 4) means that a user password must
  have at least 2 uppercase letters and at least 4 digits for it to be
  accepted.


What is the most drupal-like way to bring the title of a single node page into the rest of the content? This is similar to Considerations displaying page titles in page or node template which in turn claims to be similar to another question, but the questioner doesn't mention how they achieve what they are doing, and what they are doing may be different from what I'm doing.

In my case, on single node view pages, for certain (most) content-types, there is an optional image field, that needs to be floated left of the title.

I'm not sure if it would be best practice to move the title output down into the node.tpl.php template or to keep it in the page.tpl.php template and load the relevant field for the node in the page template.

This is what I've done:

template.php:

function enviroscope_preprocess_page(&$variables, $hook) {
  if (isset($variables['node']->field_doc_cover)) {
    $node = node_load($variables['node']->nid);
    $output = field_view_field('node', $node, 'field_doc_cover', array('label' => 'hidden'));
    $variables['field_doc_cover'] = $output;
  }
}

page.tpl.php:

<?php print render($title_prefix); ?>
<?php if ($title): print render($field_doc_cover); ?>
<?php print $title; ?>
<?php endif; ?>
<?php print render($title_suffix); ?>

This gets the image field printed before the title, but I'm not sure if there is an equivalent here to hide($content['field_doc_cover']);?  Currently this has field_doc_cover printing twice.

So the main question is,

  Is this the right approach?

but this breaks down into some more specific questions:

Should the title definition stay in page.tpl.php for single node pages?

If so, is there a good way to exclude the field_doc_cover field from being rendered in the node.tpl.php file without messing with that template too?

Is there a good reason not to handle the title in the node.tpl.php, and remove it from the page.tpl.php file for these content_types?

If there is a good reason for it to not be in nodes, would it be sensible to render the element in page.tpl.php and send it as a variable to be used in node.tpl.php?

I'm pretty new to drupal theming as is probably obvious, so examples with your answers would be very helpful!

Update: I was asked to create a visual representation of what I'm trying to do, which was a good call because it reminded me of one more issue: The last modified date should be printed above and to the right of the title.

I guess one of the main things I don't understand is whether there is some good reason why the title needs to be part of the page.tpl.php template.  It sure would be easier if it were down in the node template.

It is valid to do it the way you are doing it and it would also be valid to not print the title in the page tpl for certain nodes and instead print it in the node template.

It's subjective as to which is preferable (if one is even better than the other) and the preferred solution may change based on your specific requirements for a given project.

One thing to consider is anything that usually prints out between the title and the content in your page template.
Will moving the title into the content (in this case the content is essentially the node template) mean these nodes will be inconsistent to the rest of the site (for example, will messages/tabs/help/etc. be in a different place on these nodes)?
If they were to be different would it matter to you?

Yes, you can still use hide($content['field_doc_cover']); in your node template in this case.

There are also alternatives depending on your site and requirements. For example the Panels module allows you to assign specific fields to different regions and there are a number of ways to get a block to show parts of a node so that you can assign that to a different region using Drupal core or the Context module or similar.


Is there a way to add a foreign key to a table? My question is not regarding hook_schema but regarding hook_update_N: I need to add a foreign key to an existent table in drupal 7.

I was looking Here but it does not seem to exist one explicitly for foreign keys.

Q: How can I create a foreign key in an existent table? Which call should I do?

The underlying DBMS all support this, but Drupal7 Core doesn't really care about Foreign Keys (FKs). Views will notice them and use them abit within joins.

Drupal 7 only supports FK in documentation:
http://www.interworks.com/blogs/jkhalaj/2012/04/12/drupal-7-usage-foreign-keys-schema-api-and-current-default-fk-erd

But, if you know this and understand this, then you can still use this foreign key defintion to create the FKs in a module.install file specific to your DBMS.

I use MySQL typically -- and I have done this for a foreign database my settings.php is aware of within a module.install file:

function _idremotedb_add_foreign_keys() {
  $schema = _idremotedb_schema_definition();
  db_set_active('sa_webextracts');
  foreach ($schema as $table => $table_schema) {
    if (isset($table_schema['foreign keys'])) {
      foreach ($table_schema['foreign keys'] as $fk_name => $fk_details) {
        $src_col = $fk_details['columns'][0];
        $dest_col = $fk_details['columns'][1];
        $dest_table = $fk_details['table'];
        // Create the FK using your DBMS convention. Change this as necessary
        // or add a lookup to the database handler driver type (mysql, postgres, whatever) ...
        db_query("
          ALTER TABLE $table ADD CONSTRAINT $fk_name
          FOREIGN KEY ($src_col) REFERENCES $dest_table($dest_col);
        ");
        drupal_set_message(t('...added foreign key: !fk', array('!fk' => $fk_name)));
      }
    }
  }
  // This index added for either mail-list or login.
  #db_add_index('students', 'uniqueidnumber', 'campusuniqueidnumber');
  db_set_active();
}


How can I create a view of child nodes based on the menu relationship? Say you have the following pages in a menu tree:

Projects

Project One
Project Two
Project Three

I'm looking for a way to create a view that will be embedded in the Project (parent) page that will show a pic, title and text (summary) from the child pages.

The relationship between the parent and the children is defined in the menu tree.

I know I can use node reference, but that would mean every time someone creates a page they would have to define the menu relationship and then the node reference relationship.

Also I know that I could create another content-type but I think this is overkill as all content pages look the same.

You can do exactly this using the Menu Node API
and the Menu Node Views modules.

Create a view with your required content type, and choose a contextual filter of "Menu: Menu link ID" (this is only available with the above modules installed).

Under, "When the filter value is not available," select "Provide default value" and choose "PHP code."

The following snippet will do it, then you just expose a block from the view and you are there:

if (function_exists('menu_node_get_links')){
   $node = node_load(intval(arg(1)));
   if (isset($node->menu_node_links)){
      foreach($node->menu_node_links as $mlid=>$data){
         return $mlid;
      }
   }
}


How make a virtual field for view? i want a vitual field for print value of sum in another entity :

My 2 custom entity content :

  commandes_entity

  commandesLignes_entity reference to commandes_entity

In the commandes_entity i have a view table who liste all my lines.
i want to add a custom column who sum all the children in commandesLignes_entity.

For that i make a field in .module :

function hook_views_data()
{

  $data['commandes_entity'] = array(

      'totalCommandeTTC' => array(
          'title' => t('Total Commande TTC'),
          'help' => t("Le total des commandes"),
          'field' => array(
              'id' => 'machine_name',
              'options callback' => 'Drupal\boutique\Controller\TestController::content',

          ),

          'sort' => array(
              'id' => 'standard',
          ),

      ),

  );

return $data;
}

This field is in my select field view, when i add it all is ok except one thing :

  SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'commandes_entity.totalCommandeTTC' in 'field list': SELECT
  commandes_entity.totalCommandeTTC AS
  commandes_entity_totalcommandettc, commandes_entity.id AS id FROM
  {commandes_entity} commandes_entity WHERE (( (commandes_entity.statut
  LIKE :db_condition_placeholder_0 ESCAPE '\') )) ORDER BY
  commandes_entity.created DESC LIMIT 21 OFFSET 0; Array (
  [:db_condition_placeholder_0] => payer )

This field

  totalCommandeTTC

doesn't exist in my table, i want it virtual.

For now my callback just return 'test'.

Any idea for make this field really virtual ?

I try to move it to views group like this :

function boutique_views_data()
{

  $data['views'] = array(

      'totalCommandeTTC' => array(
          'title' => t('Total Commande TTC'),
          'help' => t("Le total des commandes"),
          'field' => array(
              'id' => 'machine_name',
              'options callback' => 'Drupal\boutique\Controller\TestController::content',

          ),

          'sort' => array(
              'id' => 'standard',
          ),

      ),

  );

return $data;
}

The field is in the Global group but SQL still try to get it into the commandes_entity table.

Thank to Clive for guide me :

This is how i make a virtual field :

First you need to create the handler for the field :

<?php

namespace Drupal\boutique\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * Field handler to present the path to the node.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("totalCommandeTTC")
 */
class TotalTTC extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);

    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {
       return 'test';
    }

}

I remove the query for this handler.

Then in my module file, i use the hook_views_data :

function boutique_views_data()
{

  $data['commandes_entity'] = array(

      'totalCommandeTTC' => array(
          'title' => t('Total Commande TTC'),
          'help' => t("Le total TTC des commandes"),
          'field' => array(
              'id' => 'totalCommandeTTC',
          ),

      ),

  );

return $data;
}

And the result in views after add the field with views ui :

The field is Total commande TTC.


I'm creating a form in a module but when I try to add a radio group the title displays but not the options $form['todo'] = array(
'#type' => 'fieldset',
'#prefix' => '
',
'#suffix' => '
' . $image,
'thot_dialog' => array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
'
),
'add_thot' => array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => t('Add New Thot, Related to Current Thot'),
  'new_thot_nid0' => array(
      '#type' => 'hidden',
      '#default_value' => "",
  ),
  'new_thot_name' => array(
      '#type' => 'textfield',
      '#title' => 'Name Your New Thot:',
      '#default_value' => 'Type Name Here',
  ),
  'new_thot_rel' => array(
      '#type' => 'select',
      '#title' => 'Select One:',
      '#options' => $t_rels,
  ),
  'new_thot_reverse' => array(
      '#type' => 'checkbox',
      '#title' => 'Reverse the direction?',
      '#attributes' => array('#id' => 'new-thot-reverse'),
  ),
  'new_thot_options' => array(
      '#type' => 'radios',
      '#title' => 'Choose One',
      '#title_display' => TRUE,
      '#options' => array(0 => 'Create the Thot', 1 => 'Edit the Thot (Add text, etc.)'),
      '#access' => TRUE,
      '#default_value' => 0,
  ),
  'new_thot_submit' => array(
    '#type' => 'submit',
    '#value' => 'Submit Thot',
  ),
);

Your #options setting only has keys, but no values. You need something like

'#options' = array(0 => t('Closed'), 1 => t('Active'));

Example from Radios form API reference.


how to upload an image of product in drupal commerce I would like to upload an image of product in drupal commerce programmatically while creating a product, Here is my code for create product, but drupal return error said

Call to a member function set() on a non-object in <b>C:\xampp\htdocs\mySite\sites\all\modules\api\mymodule.inc

any suggestion is greatly appreciated.

Thanks

mymodule.inc

$wrapper = entity_metadata_wrapper('commerce_product', commerce_product_new('product'));
$properties = entity_get_property_info('commerce_product');

$wrapper->title = $title;
$wrapper->sku = $sku;
$wrapper->commerce_price->amount = $price;    // Price in minors units 500 = 5$
$wrapper->commerce_price->currency_code = 'MMK';
$wrapper->cmp_store = 2;
//$wrapper->field_category = 137;
$wrapper->field_product_color = 106;

$file_path = file_save_data(file_get_contents('C:\\Users\\ASUSS\\Desktop\\Nexus_5_(1).jpg'), 'public://products/Nexus_5_(2).jpg');
$wrapper->field_product_image->file->set($file_path);

try{
    $wrapper->save();
    $result = "success!" ;
}catch(Exception $ex){
    $result = "not success! -> ". $ex;
}

Finally, I found the way, field_product_image can only accept array value. Here is my code,

function commerce_services_product_create($data, $flatten_fields) {
    $status =1;
    $commerce_price = array();

    $sku = $data['sku'];
    $title = $data['title'];
    $type = $data['type'];
    $commerce_price = $data['commerce_price'];
    $price = $commerce_price['amount'];

    $wrapper = entity_metadata_wrapper('commerce_product',  commerce_product_new('product'));
    $properties = entity_get_property_info('commerce_product');

    $wrapper->title = $title;
    $wrapper->sku = $sku;
    $wrapper->commerce_price->amount = $price;    // Price in minors units 500 = 5$
    $wrapper->commerce_price->currency_code = 'MMK';
    $wrapper->cmp_store = 2;
    $wrapper->field_product_color = 106;

    $file = file_save_data(file_get_contents('C:\\Users\\ASUSS\\Desktop\\Nexus_5_(1).jpg'), 'public://products/Nexus_5_(2).jpg');
    $image_val = array(
        array(
            'fid' => $file->fid,
            'title' => $file->filename,
            'filename' => $file->filename,
            'filepath' => $file->filepath,
            'filesize' => $file->filesize
        ),
    );

    $wrapper->field_product_image = $image_val;

    try{
        $wrapper->save();
        $result = "success!" ;
    }catch(Exception $ex){
        $result = "not success! -> ". $ex;
    }

    $reply= (array('status' => $status,'result' => $result) );
    return $reply;
}

Thanks,


The $directory variable doesn't contain the correct value When I print the content of $directory in my theme's page--front.tpl.php, it outputs "modules/system."

This is not I want; I want to output "sites/all/mytheme/images/…." How can I do it?

if you want to find the folder of your theme you have to use something like this:

<?php echo drupal_get_path('theme','your_theme').'/images/whateverfile.ext'; ?>


Automatic way to delete users with no content I have created an artist registry that needs help deleting users that have not created a content type node "Artist Page".

I can find ways to delete users that are inactive, but in this case, some users might be inactive for years if nothing on their page has changed.

Preferably, I would first like to send a reminder email notice to users without an "Artist Page". When a user registers within the site they are instantly directed to fill out their artist page, but some users are only registering and not filling out their page, and of course, some registration spam is getting through.

Once an email is sent,  and if no content is provided after a certain amount of time, I would like to delete them from the system to keep the site as clean as possible.

Any help would be greatly appreciated.

if I understand you correctly then you have somekind of users and one content type "Artist Page". That users must fill (create) a node of that Artist Page content type. but some users may skip this step. In that case you can do following I think:

node table has a uid field (author of content).
Fetch separately (as array) uids of node and users tables and compare them;
Get difference of arrays and compare there created time with current time, if difference is reaches(notification time) then send them an email, if difference is reaches(deletion time) then delete them.... These operation can be done on cron job. I recommend Elysia cron module.

Example:

function MY_MODULE_cronapi($op, $job = NULL) {
  $items['my_custom_task'] = array(
    'description' => 'My custom task description',
    'rule' => '*/20 * * * *', // Example rule - execute job every 20 min
    'callback' => 'my_custom_task',
    'arguments' => array(),
  );

  return $items;
}

function my_custom_task() {
  $subquery = db_select('node', 'n');
  ->fields('n', array('uid'))
    ->condition('n.type', 'MY_TYPE', '=')
    ->execute()
    ->fetchCol();

  $uids = db_select('users', 'u')
    ->fields('u', array('uid', 'created'))
    ->condition('u.uid', $subquery, 'NOT IN');
  ->execute()
    ->fetchAll();

  if(!$uids) {
    foreach($uids as $key => $uid) {
      $user_id = $uids[$key]->uid;
      $user_created = $uids[$key]->created;

      $notif_time_min = time() + 60*60*24*7; // example
      $notif_time_max = time() + 60*60*24*8; // example

      $del_time = time() + 60*60*24*15; // example

      if((time() - $user_created > $notif_time_min) && (time() - $user_created < $notif_time_max)) {
        // send_email()
      }
      elseif(time() - $user_created > $del_time) {
        //del_user()
      }
    }
  }
}

//P.S: I'd recommend to modify the callback part of cronjob. You can have too many users and every time cron job queries the tables(users and node tables) for existence of left users;
Good solution will be creating a custom module which holds somekind of flag, which verifies that user is valid or not, you can flag as unverified  on registration and change to verified on creation on node. This can be achieved by Rules or Action or custom code...


Drupal 8 View - get url field How do I get the URL, not the link html for a taxonomy field in my view.

For Drupal 7 I found this ticket:
How do I get the raw URL as a field in Views?

This mentions getting the content: path - but this doesn't show up as an option.

--- Updated ---

I am creating a block view, not sure that matters. I have no path option, I actually am not seeing any content in the field type options.

You can do the following.

Add Taxonomy ID field too your view
In your template or rewrite use the following as your url {{url('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}} or {{path('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}}


Can I combine multiple "no results behavior" to avoid repetition? I have a Search API view that has 3 attachments. This is so I can display different content type results with unique layouts.

If the user searches something too specific, they'll see the No Results Behavior up to 4 times in a row. This looks bad.

How can I only display the No Results Behavior (custom textarea) when there are no results in the view AND its 3 attachments?

I solved it myself (that's a first and probably a last)!

I'm sure this isn't the best code but it works and I don't know enough PHP to clean it up.

I disabled all "No Results Behaviors" in the view settings. I'm using the hook_preprocess_views_view hook to count the number of results for each of my attachments. Only if all 4 === 0 will it print the correct empty message.

function MYTHEMENAME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'search_results') {
    $view1 = $view2 = $view3 = $view4 = $view;

    if (is_object($view1) && is_object($view2) && is_object($view3) && is_object($view4)) {
      $view1->setDisplay('page_1');
      $view2->setDisplay('attachment_1');
      $view3->setDisplay('attachment_2');
      $view4->setDisplay('attachment_3');

      $view1->execute();
      $view2->execute();
      $view3->execute();
      $view4->execute();

      if (count($view1->result) === 0 && count($view2->result) === 0 && count($view3->result === 0 && count($view4->result) === 0)) {
        $variables['empty'] = "Sorry, but we couldn't find any results for your query. Try broadening your search terms.";
      }
    }
  }
}


Advanced menu theming in Drupal 7 I've cruised around the web and it is not at all obvious how to theme custom menus.  I've looked for hours and have not found one single post that illustrates the process, from start to finish, of creating a menu and customizing its output.  It seems like this is a multi-stage process:

Create the menu through the Drupal interface.
Create a theme function in your template.php file to theme the output.
Expose this menu to a template file (somehow) by adding it as a variable.
Call the theme function on the menu in the template file.

1 is easy enough to do, the problems I run into are with 2, 3, and 4.  Looking at the default page template, I see that it exposes the main menu in the variable $main_menu.  Later down the page you can see the function theme('links__system_main_menu', array('links' => $main_menu..., which means it's looking for an appropriately named theme function somewhere and using it to generate the output.

I know if I place function theme_links__system_main_menu(&$variables) {...} in my template.php file Drupal will use that function as opposed to function theme_menu_links(&$variables) {...}.

What I don't know is how Drupal links the custom menu I created with that function.  Let's say for example that I created a menu called My Menu.  Could I create the following function in my template.php file and theme the output for that menu? function theme_links__system_my_menu(&$variables) {...}

Also, how does one make that custom menu available to a template file?  How does Drupal expose the $main_menu variable to page.tpl.php?

I think the key I'm missing here is how to embed the variable that represents my custom menu into a template page.  For the most part though I'm completely lost with what to do after having created the menu.

Thanks for the help.

EDIT: Probably should post what I'm doing.  Per my comment to BetaRide below, I need to inject customized HTML into the <li> elements of the menu items. Specifically, I'm adding Twitter Bootstrap icons.

Drupal's implementation of menus is a bit special, It doesn't always work the way it seems it should.

You can take a look at the core implementation of template_preprocess_page() to how the Main Menu links are added as a variable to the page template. You have to drill down a bit in the API docs, but the function you want to call in your implementation of theme_preprocess_page() is menu_navigation_links(), which will return an array of links in the menu.

Looking at line 106 of Drupal core's page.tpl.php file, you can see how the main menu links are themed in the template by calling the theme() function with a hook of 'links__system_main_menu'.

Theoretically, this implementation should be able to be duplicated with a custom menu by following the standard naming conventions. So, in template.php, you could have:

function THEMENAME_preprocess_page(&$variables){
  $variables['custom_menu'] = menu_navigation_links('menu-custom-menu');
}

function THEMENAME_links__menu_custom_menu(&$variables){
 //custom theme function here
}

and in page.tpl.php, you would add something like this:

<?php print theme('links__menu_custom_menu', array('links' => $custom_menu, 'attributes' => array('id' => 'custom-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Custom menu'))); ?>

However, adding the custom menu as a variable on your page template is not necessary. You could easily place the custom menu's block into a desired region via the Drupal admin interface.  Also, you could change the site's settings for the Main Menu source, effectively replacing the default $main_menu variable in page.tpl.php with your custom menu.

EDIT: I am just seeing your addition about your end goal being to just add some custom html to the menu items for icons. Depending on how you are adding these icons, there are a couple different Drupal module options.

Menu Icons - allows you to upload an image via the Menu item's settings and automatically generates CSS (customizable via a template) that adds the image as a background on the menu item.

Menu Attributes - allows you to add a custom class to each menu item via its settings in the admin. Once a unique class is added to each menu item, you could use CSS to add an icon to the menu item or use javascript to inject the additional HTML into the menu item.


Can I disable a cookie from a contrib module, in this case fontawesome I believe I have a D8 site v8.9.6 and have some questions on cookies.
I would prefer not to have any cookies on my site unless they are really required for a properly functioning website. With all things going on like GDPR and APP I prefer to have this as clean as possible.
In order to find out which cookies are in use I checked Chrome DevTools and it shows me just 1: _ga with source of fontawesome.com (I installed the FontAwesome module).
First question, can I disable this cookie somehow?
Second question is related to Dropdown Language, a module that gives me a dropdown select list for the user to select its language of choice. I can't find anything in the documentation about how this tracks the user's choice and I don't see anything in DevTools (cookies, session), so this is not working with cookies?

The Font Awesome Icons module provides an option to use the Font Awesome library locally rather than from a CDN. It's the CDN that is creating the tracking cookie, so if you follow the instructions to download Font Awesome to your own server, you should not have that cookie to worry about.
The Dropdown Language module simply extends Drupal's built-in language switching, which defaults to storing the language in the current session, so will not require any additional cookies.


Block not showing input fields I have a block as part of my custom module, I was it to show 2 text boxes (Input & Output) and have a generate button. I cant get it to show the input boxes! It seems they are being stripped out for some reason? I have tried with and without twig but my example below is without twig to keep it simple:

    <?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\GenerateBlock.
 */

namespace Drupal\mymodule\Plugin\Block;

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

/**
 * Provides a 'generateblock' block.
 *
 * @Block(
 *   id = "generate_block",
 *   admin_label = @Translation("Generate Code"),
 *   category = @Translation("mymodule")
 * )
 */
class generateblock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    // $twig = \Drupal::service('twig');
    // $template = $twig->loadTemplate(drupal_get_path('module', 'mymodule') . '/templates/generatecode.html.twig');
    // $output = $template->render([]);
    $output='

Generate Access Code

    <input class="form-control" id="codeToCheck" placeholder="Enter Input" type="text" value="" /> <button class="btn btn-default mr-xs mb-sm" type="button">Set</button>

<input class="form-control" id="validationCode" placeholder="" readonly="readonly" type="text" value="" /> <button class="btn btn-default mr-xs mb-sm" type="button">Copy</button>

    Learn More

';

    return array(
      '#type' => 'markup',
      '#markup' => $output,
    );
  }

}

I do not know why the inputs are being stripped out? What am i missing

**** Update ****

I have changed my code to the following and it is no longer stripping out the input boxes but it feels a bit "hacky" Do I need to specify a different render type or something:

class AccessCode extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $twig = \Drupal::service('twig');
    $template = $twig->loadTemplate(drupal_get_path('module', 'mymodule') . '/templates/accesscode.html.twig');
    $output = $template->render([]);

    return array(
      '#markup' => $output,
      '#allowed_tags' => ['input','span','div','a','button','h2','strong','i',],
    );
  }

try to follow best practises:
as no need to render anything on your get the twig template as drupal core handles this.

module structure:

mymodule

mymodule.module
mymodule.info.yml
mymodule.libraries.yml
templates (dir)
-- templates/accesscode.html.twig
src (dir)
-- src/Plugin/Block
----- AccessCode.php

in mymodule.module

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
    return [
      'accesscode_block' => [
        'variables' => [
          'test' => null,
         ],
         'template' => 'accesscode',
//no need for full accesscode.html.twig as drupal knows.
      ],
    ];
}

then in your src/Plugin/Block/  AccessCode.php

 /**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['my-block'] = [
      '#theme' => 'accesscode_block',
      '#test' => 1234,
  ];
  // Attach js or css easier.
  $build['#attached']['library'][] = 'mymodule/mymodule-accesscode';

// Could even add a form element like ..
 $build['some_field'] = [
   '#type' => 'textfield',
   '#title' => 'My Field:',
 ];
  return $build;
}

then in your accesscode.html.twig you can use the twig var {{test}}


form_set_error checkbox CCK 2 drupal 6 How can I highlight the checkbox boxes when be validated a CCK field? (CCK 2.9). Data is validated correctly, and message is displayed correctly in the head of the form, but the checkboxes does not appear highlighted.

<?php
$quantity_options = count($form_state['values']['field_checkboxes']);
if ($quantity_options > 2) {
form_set_error('field_checkboxes', 'message.');
}
?>

Have a look if the class error has been added to your <input>. It has on my side, it's the CSS that does not highlight the elements properly.

You can either adjust your stylesheet for .form-item input.error or you can use a piece of jQuery to make the parent of the radios styleable, such as

$('.form-radios:not(.error):has(.form-item input.error)').addClass('error');

Another option would be to add the appropriate class via the Drupal's theming system (theme_optionwidgets_buttons()).


how to a link in Admin black toolbar I created a custom module and how to add a link along with icon. Basically, I want to add notification icon

backlinks_notifications.index:
  title: 'Notifications'
  parent: system.admin_config_ui (whats the name of that blad navigation bar on top.)
  description: 'Notificationsx'
  url: internal:/home

FYI : Its Admin theme.

/**
    * Implements hook_toolbar().
    */
    function backlinks_notifications_toolbar() {
        $items = [];
        $items['toolbar_menu_backlinks_notifications'] = [
            '#type' => 'toolbar_item',
            'tab' => [
                '#type' => 'link',
                '#title' => 'Notifications',
                '#url' =>  Url::fromRoute('<front>'),
                '#options' => [
                    'attributes' => array(
                        'title' => t('Backlinks Notification'),
                        'class' => array(
                        'toolbar-item',
                        'toolbar-icon',
                        'toolbar-icon-backlinks-notifications',
                        ),
                    ),
                ],
            ],
            '#weight' => 999,
            '#attached' => array(
                'library' => array(
                    'backlinks_notifications/backlinks_notifications',
                ),
            ),
        ];
        return $items;
    }

Hook available at
https://api.drupal.org/api/drupal/core%21modules%21toolbar%21toolbar.api.php/function/hook_toolbar/8.2.x