How to add a link to slide elements in MD Slider? I have used the MD Slider module (which is Mega Slider, a paid module) in my websites to create slideshows.

But there is no default option to create a link for each slide.

Is there any way to hyperlink a slide?

I have created a patch with the changes to convert a slide into hyperlink. Since I cannot upload a file here, I am copy-pasting the contents of my .patch file:

From 3f72f263b3673ce27ca4114963b007752b566c2a Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 11:02:04 +0530
Subject: [PATCH 1/2] Ported changes regarding MD_Slider done for an older
 version

---
 .../templates/front/front_layers_render.tpl.php    | 13 ++++----
 .../templates/front/front_slide_render.tpl.php     | 35 ++++++++++++++++++++--
 2 files changed, 41 insertions(+), 7 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
index a8dd7fc..16c30b4 100644
--- a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
@@ -11,11 +11,14 @@
 <?php endif;?>
   <div class="<?php print $class; ?>" <?php print $data; ?>>
     <?php if ($layer->type == 'text'): ?>
-        <?php if (isset($link)):?>
-            <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?>
-        <?php else:?>
-            <?php print $layer->title;?>
-        <?php endif; ?>
+    <?php /* Raj: Changes to make MD_Slider slide as hyperlink */?>
+       <?php if (strpos($layer->title,'URL:') === false):?>
+           <?php if (isset($link)):?>
+               <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?>
+           <?php else:?>
+               <?php print $layer->title;?>
+           <?php endif; ?>
+        <?php endif; ?>
     <?php elseif ($layer->type == 'image'): ?>
         <?php if (isset($link)):?>
             <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>>
diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 8df2c39..5dd71dd 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -18,10 +18,41 @@
       <div class="md-slider-overlay" style="background: <?php print $slide->settings['background_overlay']; ?>">

     <?php endif; ?>
-

+
+    <?php
+    // Raj: Check if there is a string which starts from "URL:". If so, extract the URL and make this div a hyperlink
+    $hasURL = false;
+    $URLString = '';
+    foreach ($slide->layers as $index => $layer):
+    $layerTitle = $layer["title"];
+    drupal_set_message("Layer object: $layer");
+    drupal_set_message("Layer title: $layerTitle");
+    // http://stackoverflow.com/a/4366748/260665
+    if (strpos($layerTitle,'URL:') !== false) {
+       $hasURL = true;
+       $URLString = str_replace('URL:', '', $layerTitle);
+       break;
+    }
+    endforeach;
+
+    if ($hasURL)
+    {
+       print "";
+    }
+    print "
";
+    foreach ($slide->layers as $index => $layer):
+    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    endforeach;
+    print "
";
+    if ($hasURL)
+    {
+       print "";
+    }
+    ?>
+
       <?php foreach ($slide->layers as $index => $layer):?>
         <?php print theme('front_layers_render', array('index' => $index, 'layer' => $layer));?>
       <?php endforeach;?>
-

+

 <?php endif;?>
--
2.7.4 (Apple Git-66)

From 74c3d0644fd505729163d4803c9a0f9cb014e679 Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 14:04:39 +0530
Subject: [PATCH 2/2] Finalized the changes to support hyperlinking whole slide

---
 .../templates/front/front_slide_render.tpl.php     | 30 +++++++++++++---------
 sites/all/themes/IndianSnakes/css/custom.css       |  6 +++++
 2 files changed, 24 insertions(+), 12 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 5dd71dd..764d46e 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -9,6 +9,7 @@

 <?php if (!isset($slide->settings["disabled"]) || !$slide->settings["disabled"]):?>
   <div class="md-slide-item slide-<?php print $index+1;?>" <?php print $data_properties;?>>
+
     <div class="md-mainimg" style="<?php print $background_style;?>">
       <?php if (!empty($background_url)):?>
         <img src="<?php print $background_url;?>" alt="<?php print htmlentities($slide->settings["background_image_alt"], ENT_QUOTES, 'UTF-8');?>"<?php print $background_style;?> />
@@ -25,34 +26,39 @@
     $URLString = '';
     foreach ($slide->layers as $index => $layer):
     $layerTitle = $layer["title"];
-    drupal_set_message("Layer object: $layer");
-    drupal_set_message("Layer title: $layerTitle");
+//     drupal_set_message("Layer object: $layer");
+//     drupal_set_message("Layer title: $layerTitle");
     // http://stackoverflow.com/a/4366748/260665
-    if (strpos($layerTitle,'URL:') !== false) {
+    if (strpos($layerTitle,'URL:') === false) {
+    }
+    else {
        $hasURL = true;
-       $URLString = str_replace('URL:', '', $layerTitle);
+       $URLString = str_replace('URL:','',$layerTitle);
        break;
     }
     endforeach;
-
+//     drupal_set_message("URL: $URLString");
+//     drupal_set_message("Has URL: $hasURL");
+    $outputString = "";
     if ($hasURL)
     {
-       print "";
+       $outputString .= "";
     }
-    print "
";
+    $outputString .= "
";
     foreach ($slide->layers as $index => $layer):
-    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    $outputString .= theme('front_layers_render', array('index' => $index, 'layer' => $layer));
     endforeach;
-    print "
";
+    $outputString .= "
";
     if ($hasURL)
     {
-       print "";
+       $outputString .= "";
     }
+    print $outputString;
     ?>
-
+
+
 -->

 <?php endif;?>
diff --git a/sites/all/themes/IndianSnakes/css/custom.css b/sites/all/themes/IndianSnakes/css/custom.css
index 3d69b0d..3f0354e 100644
--- a/sites/all/themes/IndianSnakes/css/custom.css
+++ b/sites/all/themes/IndianSnakes/css/custom.css
@@ -27,3 +27,9 @@ display: inline-block;
 width: auto !important;
 height: 300px !important;
 }
+
+/* Reset the hyperlink style to normal inside slides */
+.md-slide-item a {
+    color: inherit;
+    text-decoration: inherit;
+}
\ No newline at end of file
--
2.7.4 (Apple Git-66)

I have defined a new "URL:" label protocol for each slide. If a slide has this label defined then the whole slide's div is converted into hyperlink with whatever link is provided after my URL: protocol. For example check this:

The code (patch) is configured such that label with text which begins with URL: is never rendered as text but it is used to convert the slide into a hyperlink.

For a live working example check: http://indiansnakes.org/homepage

Assumption:
The only limitation of this method is, you should not hyperlink any text or images which are used within this hyperlinked slide coz the anchor tags cannot be nested, apparently.

Edit: I thought its best to update the patch details in the MD Slider community as well, here it is: http://megadrupal.com/comment/13066#comment-13066

Also a gist is created with the contents of same patch: https://gist.github.com/gumdal/e580cd80199c871fa52f677538771551


Drupal 7: Can't Update node using php script I'm trying to update a node->body using a php script in my root directory of my Drupal 7.22 installation.I call the script through a browser (firefox) with [http://MYSITEURL/nodeupdate.php]
But somehow I don't get it to work.
Here is the code I use:

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$nid = 9; // YES node 9 exists.
$node = node_load($nid); // where $nid is the node id

echo "$node->title
"; // Just to make sure it changes the right node and it does.

$node->body[$node->language][0]['value']   = "Test updated";

if( $node = node_submit($node)) {
    node_save($node);
    echo "Node with nid " . $node->nid . " updated!
";
}

print_r($node); // Check if we see any changes.
?>

The script executes fine without any errors. Through the print_r function I can see that the "changed" field and "revision_timestamp" field are changing.
However the body doesn't change!
I have been googling and found many posts from which I gather that this is the way to do it.
What am I missing?

Make sure you're logged into the site as a user with permissions to update the specified content type, because that session will carry over to your bootstrapped script. If you're logged out, you're essentially attempting to update the node as an anonymous user in your script, and permissions will come into play.

Try adding...

global $user;
print_r($user);

...to your script and see what, if anything, that outputs.


Page not found when trying to access custom module I've followed this post and made a custom module but when I try to access it from url domain.com/module/method I get 404?

Am I missing something?

Path (URL) to call custom module function

So much could be going wrong from a finger fudge standpoint here, so just make sure you have something very similar to this going on:

For example, in quick.info:

name = quick module
core = 6.x
description = quick module
package = quick package

In quick.module:

<?php

function quick_menu() {

  $items = array();
  $items['quick/hello'] = array( // change to the url you want
    'title' => 'Quick Hello',
    'type' => MENU_CALLBACK,
    'page callback' => 'quick_hello',
    'access arguments' => array('access content'),
  );

  return $items;
}

function quick_hello() {

  $content='Hello. Thank you for surfing over to ' . $_GET['q'];
  return $content;
}

Obviously make sure your module is enabled and not so obviously that all caches are cleared, but past that, the most important piece of the above is the 'quick/hello' when it comes to page found/not found :)


How does one override default icons used to dislpay uploaded files from within a module instead of a theme? I'm attempting to add a custom icon for file uploads via a module. However, all I'm finding online is advice on using a theme function (How to change File field icons (without changing core)?). I want this in a module to make it work across various themes. I found file_icon_path, but am not sure how to implement it. How would this be done in a module?

I think you would want to do something along these lines:

function YOURMODULE_theme_registry_alter(&$theme_registry) {

  if (!empty($theme_registry['file_icon']['function'])) {
    $theme_registry['file_icon']['function'] = 'YOURMODULE_file_icon';
  }

}

and then create YOURMODULE_file_icon() based upon the core theme_file_icon():

/**
 * Returns HTML for an image with an appropriate icon for the given file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object for which to make an icon.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *
 * @ingroup themeable
 */
function YOURMODULE_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);

  return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
}

and change up either $icon_directory to point within your module and include all of the various file type icons there, or do a switch or if on the $mime type and grab them from wherever you want, eg, if it's the special mime type you want, grab them from your module's directory, otherwise, grab them from the core/default directory.


How to load image from Custom Module with javascript? I'm trying to build a custom module
https://github.com/alexseif/drupal_infinite_scroll and
I need to load the image in the images folder "images/ajax-loader.gif"
in the js file alx-infinite-scroll.js

I have this in my js file
drupal_get_path('module', 'alx_infinite_scroll') + '/images/ajax-loader.gif' I have no clue where to start, any help would be much appreciated and/or link to the relevant documentation if possible.

drupal_get_path() is a PHP function so you cannot call it in your JS.

To use the result of that function in your JS you would need to call the function in your PHP and then add the output to the JS on the page. You can use Drupal.settings for this. For example:

// Settings to pass to our JS.
$settings = array(
  'loaderImgPath' => drupal_get_path(
    'module',
    'alx_infinite_scroll'
  ) + '/images/ajax-loader.gif',
);
// Add to the JS settings.
drupal_add_js(array('alx_infinite_scroll' => $settings), 'setting');

Then you can use something like this in your JS:

Drupal.behaviors.alxInfiniteScroll = {
  attach: function (context, settings) {
    var imgPath = settings.alx_infinite_scroll.loaderImgPath;
  }
}

I recommend reading some of the documentation on Drupal's JavaScript APIs as it goes over this. For example:  https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

To do that though you need to add the above PHP code somewhere.
In your case you are loading your JS in the info file, which means it will load on every page.
I would advise against this unless you actually need your JS to run on all pages, but if you do want it on all pages you could use something like hook_page_build().

In that case since you are dealing with the page render array you can use the #attached method of adding JS and JS settings that is referred to on the documentation page I linked above.


Add JavaScript to a page without access to core files? I apologize in advance if this is a really simple question, but I'm pretty new to Drupal and still figuring out my way around things. So I was wondering if it is possible to add JS to a certain node or page of Drupal if I don't have access to the core library of files? I've searched around before and a lot of people have talked about somehow inserting a file into the directory, but I'm only granted access to the Drupal pages and the Appearance settings where I can add to/edit the CSS of a page.

Thanks!!

If the developer has granted your user role access to the appropriate input formats and and has it configured to allow JS then yes, you can.

You may see a select box under one or more of the fields that allows you to select a filter such as "filtered HTML", "Full HTML" etc..

This is however normally locked down to prevent content editors from breaking a site, so I would be surprised if your limited role had access to unfiltered HTML/JS input.

A quick way to test if it works would be to add <script>alert('test');</script> in the box and save/refresh the page.


How to create a view displaying a list of users who have logged-in user's preferences How does one create a view that filters users so as to display those with preferences of the logged-in user (the one viewing them)? I'm using Drupal 7.34, Views 3.

E.g. A user selects a preference on sign up, such as "i'm interested in a man". How do you create a view that will show this user a list of users who selected "I'm a man" on their own signups. Think of it as matchmaking.

I came across this discussion but didnt figure out this comment. All the articles out there don't seem to address this clearly.

I'm certain there is a contextual filter move I'm missing. Please help.

I had same issue but solved by using this custom code in view. I was using profile2 module for registration so as per sex field, I was done this :

global $user;
$profiles = profile2_load_by_user($user);
foreach ($profiles as $profile) {
  if ($items = field_get_items('profile2', $profile, 'field_seeking')) {
    break;
  }
}
   return $items[0]['value'];

Please check my Post HERE.

As per my post I was do this :

global $user;
    $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile)
    {
        if ($items = field_get_items('profile2', $profile, 'field_sex'))
      {
            break;
          }
    }

    $i_am=$items[0]['value'];

    if($i_am=='sdmale' || $i_am=='sbmale')
    {

    $looking='smfemale+sbfemale';
    }

    if($i_am=='smfemale' || $i_am=='sbfemale')
    {
    $looking='sdmale+sbmale';
    }
    return $looking;


EntityQuery, query by referenced entity value, I am getting an empty array when I query by the value of a referenced field.

I have the following:

$result = \Drupal::entityQuery('node')
  ->condition('type', 'custom')
  ->condition('status', 1)
  ->condition('field_category.entity:taxonomy_term.name', 'somevalue', '=')
  // ->condition('field_category.%delta', 'somevalue');
  ->execute();

Using ->condition('field_category.%delta', 'somevalue'); returns way too many results (nids) than expected.

using ->condition('field_category.entity:taxonomy_term', 'somevalue', '='): returns an empty array.

Am I using an incorrect syntax to query by a related field?

As mentioned here it seems like you only need .entity like this:

->condition('field_category.entity.name', 'somevalue', '=');


Get Entity from Path or Url Object Retrieved from Menu (Node or Page) Linking through menu link tree elements I'm getting a series of url objects and paths. What I'd like to do is turn those url objects or paths into entities. I want access to the actual entities that they refer to. Here's my code so far:

$menu_tree = \Drupal::menuTree();
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_id);
$menu_tree_elements = $menu_tree->load($menu_id, $menu_parameters);
foreach ($menu_tree_elements as $menu_tree_element) {
  $menu_tree_link = $menu_tree_element->link;
  $url_object = $menu_tree_link->getUrlObject();
  $path = $url_object->toString();
  $url_params = \Drupal\Core\Url::fromUserInput($path)->
    getRouteParameters();
  var_dump($url_params);
}

I was thinking that I could possibly get the entity from the url parameters but I get the error

  External URLs do not have internal route parameters.

Which makes sense to me because I have menu links that refer to just general Page entities not nodes. Like '/about'.

However I'm able to get to the paths just fine. Is there a way that I can load an entity since I have a url object that has a path directly leading to it?

UPDATE: I tried using

$params = \Drupal\Core\Url::fromUserInput('/about')->
  getRouteParameters();
var_dump($params);

But all that did was return an empty array.

I received the same result when using

$params = \Drupal\Core\Url::fromUri("internal:/about")->
  getRouteParameters();

I managed to come up with a solution by using the storage manager to load the entity using the path to load it.

$page = \Drupal::entityTypeManager()
  ->getStorage('page')
  ->loadByProperties(array(
      'path' => $path
  ));

I'm assuming you can use the same method for nodes.


How do I get full CKEditor working? I'm trying to get the full CKEditor working in Drupal 8, but I only see the standard toolbar. I've downloaded the full zip file and unzipped it into core/modules/ckeditor, uninstalled/reinstalled ckeditor but still it's the standard toolbar.

How do I enable the full toolbar?

There's more interaction and integration between core and CKEditor's plugins than we see in D7. In fact, in researching your question, I've learned that Drupal and the CKEditor team are actively collaborating, which is cool to know. But let's first note that the ckeditor js libraries and plugins (version 4.5.5 as of Drupal 8.0.1) live at core/assets/vendor/ckeditor, not core/modules/ckeditor. Also note that enabling ckeditor plugins requires explicit supporting code, such as noted here and here.

So, rather than "the kitchen sink" approach — it might be better to identify which CKEditor plugins you need enabled, that are not in core, and use the code examples in the URLS above to implement them. FWIW, it's much easier to manage such projects after delivery anyhow, even with D7.

Finally, as a nag, I presume kittens still get it bad when you overwrite drupal-managed code with your own code. In other words, I'd figure how to extend Drupal without changing code in core/ so that when I perform a later core update, I won't loose those changes.


Is it stable to run Drupal 7.8 on php 5.3.8? I would like to make use of php 5.3.x built-in fastcgi functionality and therefore I would like to migrate from php 5.2.x to php 5.3.8.

Is it stable to run Drupal 7.8 on php 5.3.8 ?

Yes. In fact, it is recommended to do so.


Taxonomy view doesn't display products This is the situation.

I have a product type and in this type i use a term reference field. Then i add some products.
Next step, i create the product displays using the product reference field (the default one).
So far so good. Then i use views and enable the build in view for taxonomies which in non commerce site shows the nodes for each taxonomy. Now it displaying nothing. I tried to add the product relationship but still nothing.

Any ideas?? Thank you

Do you have the devel themer enable? I have the problem with some filters lately..it was not displaying the filter. The problem was that I have the devel themer enable..
Are you using ubercart or commerce? if you are using commerce make sure to have associate the taxonomy with the display..here it is a little reference, that video helped me with my taxonomy and give me the right path Building a Drupal commerce catalog


Remember webform textfield for next entry I would like to know what is module to remember webform textfield or select option, so once fill in or selected, the next entry use the previous entry. In webfform autocomplete, typing several characters still required.

Is that possible to do that?

This is the use case of the Webform Field Repeat module:

  The Webform Field Repeat module enables the webform to remember
  selected field entries from current submission for up to an hour. It
  uses the $_SESSION to do so. If the session is active, the form will
  be populated with selected entries from remembered submission when
  opened again.

  The fields can be selected on Webform >> Form settings for each
  individual webform. Once the fields has been selected the end users
  will see a check box at the bottom of the form that they can check to
  have the form populated when they open the form for a new submission.
  This module depends on Webform module.


Module for using Twitter's timeline widget on user's profile pages? I want to use twitter's timeline widget on my site. This is different from the twitter drupal module that imports tweets as drupal content. I need all users of my site to be able to show the timeline widget on their profiles.

Is there a module that can assist with this?

Ive looked at the twitter timeline module but its not ideal. It would require giving users permission to create or edit a blocks. Also you have to enter the widget ID which I think some users will find confusing.

If you want to do this yourself, in broad strokes, you could create a custom module that does the following:

Creates two user profile fields that your users can edit if they want:

a.  Their Twitter User Name

b.  Their Twitter Widget ID
Creates a block that:

a.  Is displayed when a User Profile is displayed and these two fields are filled out that

b.  Takes these two fields from the user profile being displayed and integrates them into the HTML required by Twitter (see https://twitter.com/settings/widgets/new when logged into Twitter), eg, it outputs the twitter code from your previous question (https://drupal.stackexchange.com/questions/94079/allow-users-to-embed-twitter-feeds-without-allowing-script-tags) but fills in the USERNAME and WIDGET_ID with the values of these two fields.

Once again, Twitter is requiring this Widget ID, so whether or not this is confusing to your users is, unfortunately, irrelevant.


Overriding views fields in twig I want to override the default views-view-fields.html.twig so that I can display specific fields in a bootstrap layout, e.g.

{{ fields.field_name_1 }}

{{ fields.field_name_2 }}

{{ fields.field_name_3 }}

We have all this important code in that file that gets repeated for each field in the loop: -

{{ field.separator }}
{%- if field.wrapper_element -%}
  <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
{%- endif %}
{%- if field.label -%}
  {%- if field.label_element -%}
    <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
  {%- else -%}
    {{ field.label }}{{ field.label_suffix }}
  {%- endif %}
{%- endif %}
{%- if field.element_type -%}
  <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
{%- else -%}
  {{ field.content }}
{%- endif %}
{%- if field.wrapper_element -%}
  </{{ field.wrapper_element }}>
{%- endif %}

So I want to avoid having to repeat this over and over for each field that I manually arrange. What's the best approach here? I tried overriding the views-view-field.html.twig files but I can't seem to get to the same variables.

What's the best approach?

Thanks :-)

I have a similar issue! However, I am able to print specific field values in view-view-field.html.twig by using the syntax {{ view.field.[filed_name].original_value}}.
In my cause it was {{ view.field.title.original_value}}.

The issue I have is the each title is coming up 4 times! I don;t know how to fix. I also overrode views-view-fields.html.twig to add my own HTML wrapper outside the loop:

      {% for field in fields -%}
        {{ field.separator }}
        {%- if field.wrapper_element -%}
          <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
        {%- endif %}
        {%- if field.label -%}
          {%- if field.label_element -%}
            <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
          {%- else -%}
            {{ field.label }}{{ field.label_suffix }}
          {%- endif %}
        {%- endif %}
        {%- if field.element_type -%}
          <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
        {%- else -%}
          {{ field.content }}
        {%- endif %}
        {%- if field.wrapper_element -%}
          </{{ field.wrapper_element }}>
        {%- endif %}
      {%- endfor %}

which is rendering well on the page, but I cannot get rid of multiple title issue. Any suggestion would be greatly appreciated.

Here is a screenshot of how my page looks now:


Product Variation as Thumbnail rather than Dropdown I am wondering if someone has tackled having product variations as thumbnails rather than a dropdown option.

Have a look at this page: http://www.partytimerentals.com/catalog/product/basic-poly-rounds

You see that I have loads of variations for that particular table linen, but my end user has to look through a load of item options. I need a way to show them the associated swatch, and when they click load that variation. The same as now, just as I said, an image thumbnail rather than a select box.

Any direction on this would be greatly appreciated. Thanks.

Here is a mockup of what I am looking for: http://cloud.um-me.com/0f1a2p1b1T0A

Aaron

Once i've got the same problem and I went through this issue Here there are different solution and suggestion.

I was looking for a module who shows the color instead of text so I have chosen this module Fancy Attribute . You can create a taxonomy with a field color and add the hex code of the color, then you can use it as a variation.


Is there any way to clear the cache with specific cid? I set some data in cache using cache_set($cache_id, $temp_data, 'cache', CACHE_TEMPORARY); from a custom module. It's cleared when I clear all the cache.
Is there any way I can clear that specific cached data using its ID?

You can pass a cid to cache_clear_all() to clear a specific bin.


I can't fetch anything else than '1' to my PDO query Here is my PDO request :

$query = db_select('review_ratings_table')
   ->fields('review_ratings_table',array('review_nid'))
   ->condition('loc_id', $loc_id, 'LIKE')
   ->condition('user_id', $user_id, 'LIKE')
   ->condition('valid', '1', '=')
   ->execute();
while($record = $query->fetchAssoc()) {
 drupal_set_message('
test '.print_r($record).'
');
}

I have tried many ways to get the result of this request (fetchAll, fetchField, fetchAssoc ...) and I keep printing "1" instead of the review_nid or anything else.

Thanks for you help.

Will

=> Hi,
If I use dvm($query) I get that :

  DatabaseStatementBase::__set_state(array(
     'dbh' =>
    DatabaseConnection_mysql::__set_state(array(
       'needsCleanup' => false,
       'target' => 'default',
       'key' => 'default',
       'logger' => NULL,
       'transactionLayers' =>
      array (
        'drupal_transaction' => 'drupal_transaction',
      ),
       'driverClasses' =>
      array (
        'SelectQuery' => 'SelectQuery',
        'DatabaseTransaction' => 'DatabaseTransaction',
      ),
       'statementClass' => 'DatabaseStatementBase',
       'transactionSupport' => true,
       'transactionalDDLSupport' => false,
       'temporaryNameIndex' => 0,
       'connectionOptions' =>
      array (
        'database' => '*******',
        'username' => '*******',
        'password' => '*******',
        'host' => 'localhost',
        'port' => '3306',
        'driver' => 'mysql',
        'prefix' =>
        array (
          'default' => '',
        ),
      ),
       'schema' => NULL,
       'prefixes' =>
      array (
        'default' => '',
      ),
       'prefixSearch' =>
      array (
        0 => '{',
        1 => '}',
      ),
       'prefixReplace' =>
      array (
        0 => '',
        1 => '',
      ),
    )),
     'queryString' => 'SELECT review_ratings_table.review_nid AS review_nid
  FROM
  review_ratings_table review_ratings_table
  WHERE  (loc_id LIKE :db_condition_placeholder_0 ESCAPE \'\\\') AND (user_id = :db_condition_placeholder_1) AND (valid = :db_condition_placeholder_2) ',
  ))

and

  Error message
  Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in review_ratings_table_node_presave() (line 52 of C:\Bitnami\drupal-7\apps\drupal\htdocs\sites\all\modules\custom\review_ratings_table\review_ratings_table.module).

and

dvm($query->fetchAssoc()); gives me that

  array(
    'review_nid' => '2',
  )

Which is what I want but I don't know how to access it.

Thanks

With drupal_set_message('
test '.print_r($record).'
'); you're putting the return value of print_r into a string, not printing the contents of $record.

You can acccess the value you need with:

$result = $query->fetchAssoc();

// make sure we found something
if (empty($result) || empty($result[0]['review_nid'])) {
  dpm("No result");
}

// load the noad we found
$node = node_load($nid)
dpm($node);


Drupal as a simple file manager I'm wondering how easily it would be to achieve the following.

I want to create a Drupal site where users have a small "file area" to upload files.
I would like to be able to take those files and upload them to another server (using FTP, HTTP posts, or XMLRPC).
It would be also nice to get the "remote server" directory listing.

I obviously think this can be easily achieved by ftp; but can I tell to the FTP manager to use the username/password couple of the Drupal user? How can I hide those information to the end user?

What I have in mind is the implementation in Drupal of the Dropbox service, where the Drupal site would be the Dropbox provider.

Any ideas on where to get started ?

Take a look at the IMCE module.

It's a powerful upload manager that requires either CKEditor or IMCE Wysiwyg API bridge to work.

It supports per-user upload directories and space quotas, amongst other useful stuff.

As for the XML-RPC, you should take a look at the Services module.

Regardless of the path you take, you will definitely need to add some custom code and, to help with that (Drupal 7 only) take a look at the FileTransfer class. (related question)


hook_user_login, hook_user_logout not firing I created a custom module because I want to execute some actions when a users logs in / out.

function mymodule_user_login(&$edit, $account) {
  $url = 'https://www.some_url';
  $additionalHeaders = '';

  $process = curl_init($url);
  curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
  curl_setopt($process, CURLOPT_HEADER, 1);
  curl_setopt($process, CURLOPT_USERPWD, $user.":". $password);
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_POST, 1);
  curl_setopt($process, CURLOPT_POSTFIELDS, $data);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_close($process);
}

function mymodule_user_logout($account) {
  $url = 'https://www.some_url';
  $additionalHeaders = '';

  $process = curl_init($url);
  curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
  curl_setopt($process, CURLOPT_HEADER, 1);
  curl_setopt($process, CURLOPT_USERPWD, $user.":". $password);
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_POST, 1);
  curl_setopt($process, CURLOPT_POSTFIELDS, $data);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_close($process);
}

I tested the code before to put it in the hook implementations, and it works.

Does anyone have the same problem?

If you are directly editing the code of a module that is already enabled, then the problem is that the list of hooks implemented by modules are cached by Drupal. Drupal doesn't have a setting for disabling this cache; the only cache you can disable/enable on Drupal is for the content served to the anonymous users.

Both the hooks you are referring are invoked by functions that, directly or indirectly, call module_implements(), which contains the following code:

  if ($reset) {
    $implementations = array();
    cache_set('module_implements', array(), 'cache_bootstrap');
    drupal_static_reset('module_hook_info');
    drupal_static_reset('drupal_alter');
    cache_clear_all('hook_info', 'cache_bootstrap');
    return;
  }

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

The cache containing the list of the implemented hooks is cleared when a module is updated, enabled, or disabled. Actually, it is enough you visit the page showing the list of the modules, click on the button to save the configuration, and the cache should be automatically reset; if that doesn't work, then you can disable and then re-enable a module.

I see the code is using variables that are not defined, nor set, by the code you are showing; I take you didn't show all the code, but if you are effectively showing all the code, then the $user, $password, and $data variables are not initialized.

As side note, you should use drupal_http_request(), instead of using the cURL functions.


Translations string email not work in D8 (multilanguage site, with two languages) i wanna send email for registration, etc by user preference of language of user (People -> Edit people -> Language Settings)

I've enabled all modules for translations and translations are saved correctly (see the attachment).

I followed this guide: https://www.valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8
but not work for me.

The language code passed for the email is correct but the email is always send in default language (in my case, english).

Be sure that the string you sent by mail is already translated in the target language. Otherwise it will not work. You can check it here http://youwebsite.com/admin/config/regional/translate


Schedule appointment form in popup I'm looking for a schedule appointment form in Drupal 7 which looks like the below image:

Before I'm going to start building a custom module I'd like to know if there's any other module like this? And I also need to integrate Google Calendar with this.

You can build this without a custom module, and without a specialty contrib module specifically for "appointments".

I would build this using Entityform but you could also just use a basic content type with custom fields. Modules that would go into your recipe would be Date, Date Restrictions, Email field, Page break field, and perhaps Field Group and Display Suite for nailing that layout.

These modules together should allow you to construct an entity (node or entityform) with all of the functions of your screenshot, without custom modules or custom code. Also, you will want Rules to handle the actions that happen when the form is submitted.

You didn't specify if this is just an "Appointment request form" that is later confirmed by a salon employee, or if it is actually to book an appointment that is confirmed automatically. The latter would be much more complex as it would require that Drupal knows about all of the existing appointments and have the logic/ability to eliminate conflicts. For this, see Appointment Scheduling


How to show SUM of values from referenced entity fields in a View? Okay, I've a two content types "A" and "B". "A" is a parent and have a field referenced(Entity Reference) to the child content type "B". Now I've created a View(Table) with a list of "A". And I want to add a field to show the SUM of field values from the referenced type "B". How to do this? Is it possible to solve with a Rules?

Under Relationships, add a relationship for the desired field. "Entity Referenced". Not "Entity Referencing".
Under Fields, add the field you want to sum. Add the relationship in the field settings.
Under advanced, enable Use Aggregation.
Under fields, click Aggregation Settings next to the field and choose "Sum".


CCK migration From Drupal 6 to Drupal 7: Which tables can I delete? After migrating the CCK fields from Drupal 6 to Drupal 7, which tables can I delete?

As far as I can see, the tables that are safe to be removed (if they are not removed from an update function) are the ones matching the content_* pattern, which are not used anymore in Drupal 7.


node_save() null tid column I am trying to create a node programatically like so,

$newNode = (object) NULL;
$newNode->type = 'job';
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->tid = 0;

$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][2] = 2;
$newNode->field_job_category['und'][4] = 4;

//die(print_r($newNode));
// save node
node_save($newNode);

Here I have potentially 4 taxonomies to pick from (their id indicated in brackets) Creative (2), Technical (3), Marketing (4), Client Services (6).

On node_save I am getting the following error,

  500 Internal Server Error : An error occurred (23000):
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tid'
  cannot be null

How do I overcome this this I would have thought setting the field_job_category to the id of the taxonomy would be enough?

If you have one tid by node use:

$tid = 0;
$newNode->taxonomy[0]->tid = $tid;

if the node can have more than one term use:

$tids = [0, 3, 4, 5];
$i = 0;
foreach ($tids as $tid) {
  $newNode->taxonomy[$i]->tid = $tid;
  $i++;
}


Is it possible to get Entity Connect and Entity Reference View Widget to work together and if so how? It seems to me this should be a fairly common problem, but I can't seem to find and answer despite looking!

Here is my use case: I have two types of content: Activity and Participants. When I create a new Activity I want to be able to add multiple Participants to the Activity, and allow the user either to pick the Participants from a list of those already in the system, or to create new ones "on the fly".

I'm using an "Entity Reference" field in the Activity content type, to reference one or more Participants

So far, I have managed to do one part of my use case, or the other, but not both at once. Entity Connect works fine and creates a modal window in which I can create a new Participant or modify an existing one. Entity Reference View Widget also works fine, and allows me to create a view which I can then use to multi-select existing Participants. But I can't get both to play together (although the Entity Connect project page suggests it should work). Entity Connect only seems to work with the autocomplete widget, whereas Entity Reference View Widget only works with its own widget (logically!).

Has anyone been able to get these two modules to work nicely together and if so how, or should I be using another combination (References Dialog and something else for example)?

This week a patch for both modules was released that may fix the issue (see Can't get Entity Connect to work with Entity Reference View Widget, which also links to the second patch). As of today (23 Mar 14), the patches still need review.


image share issue for single variant product I am using Service Link module. On product display page, one of the product variant is displayed. The products having more than 1 variant, sharing proper image [shows meta property="og:image" content="..." in view source ].
But single variant product is not producing og meta tag.

I am using token [node:field-product:1:field_images] in Images input field of 'Open Graph' meta tags.

Use the 0 instead of 1 in node image token

1) Go to : Site setting -> configuration -> Metatag

2) Edit the “Node”

3) Click On Open Graph field set

4) Add “[node:field-product:0:field_images]” in Image

Hope this will solve your issue


How can I retrieve a user name and password? Someone installed the drupal 8 site and did not share the password. I do not know what email he has used to install the site either.
I do not have the password.
In phpmyadmin, I clicked the database name. I ran the sql

UPDATE users SET pass = MD5( 'NewPassword' ) WHERE uid = 1;
Select * from users.

  1146 - Table 'xxx.users' doesn't exist

How can I retrieve the drupal 8 website password?

Drupal does not store passwords, but rather password hashes. There is no way to recover the password. You can use Drush to either set a new password or generate a one-time log-in link:

Reset PW: drush upwd <username> --password="<password>"
One-time login-in link: drush uli <username>


How to make views slideshow, shows more items per page than one I made a slideshow using views slideshow in drupal 7 to show bunch of logos, but it only shows one item per page, what I want is to show for example 6 logos per page when the visitor hit next, it slides to next 6 items and etc.. I checked views slideshow field setting, but couldnt find anywhere that I can set how many items to show per page.

thanks.

In Views Slideshow 7.x-3.0, you can find this option by selecting slideshow as your format and then clicking on settings. From there, you need to find the Action section and check "View Action Advanced Options", there you can choose how many items to display.


Database query in template.php Is it ok to query the database in a template.php file of a sub-theme. If not where do I put it? Below I have function that is querying the database and it works fine but I want to make sure I doing it the right way =).

function inTheTemplateFile() {
   $query = db_query("SELECT tid FROM taxonomy_menu");
   return  $query->fetchAll();
}

The template should idealy not be used to do database queries or other code that belongs in the Model or Controller of the MVC pattern.
The problem is that it is impossible to have a perfect implementation of the MVC pattern in Drupal.

What I mostly use as a rule of thumb is this:

Is this functionality that belongs to a module? Then put it in a module.
Would I have to copy this to a new theme if I made a second one? Then put it in a module (or parent theme if it should be in a subset of themes).
Does this function get/compute data or results which should be provided by a module? (like fetching user-data or a list of items) Then put it in a module.

In general the theme should only contain HTML, JS, CSS and a minimum of PHP used for simple loops, printing and simple conditional statements.

So the answer to your question would be; Probably not, it should probably be in a preprocess function or a getter function (like book_get_books()) in the module.

Edit: As Clive points out in the comments, Drupal does not strive to be fully MVC. The MVC pattern is only used to make it clear what belongs in the template, the controller and view don't really exist in drupal. Even the view is not as clear cut as it is in something like Symfony or Zend framework.


File field URI to URL link in module I'm creating a custom file field display formatter module..
https://www.drupal.org/sandbox/vincer/2779871

Right now it's just printing the URI as..

public://my-file.mid

I'm trying to get the default output that I would get by using the File module - a full path as a link, like..

http://my-site/sites/default/files/my-file.mid

The field_formatter_view looks like..

function fieldmidity_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'midi_formatter') {
    foreach ($items as $delta => $item) {
      $element[$delta] = array('#markup' => $item['uri']);
      // Options for $item; filename, uri, description, filesize, timestamp, fid, uid
    }
  }

  return $element;
}

Based on code I see in the File and Field modules, I'm suspecting that the solution might be more complicated than the approach that I'm attempting.

Any thoughts would be appreciated.

Use this:

function fieldmidity_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'midi_formatter') {
    foreach ($items as $delta => $item) {
        if ($item['uri']){
            $element[$delta] = array('#markup' => file_create_url($item['uri']));
        }else{
            $element[$delta] = array('#markup' => $item['uri']);
        }
      // Options for $item; filename, uri, description, filesize, timestamp, fid, uid
    }
  }

  return $element;
}


How do I programmatically get a field's value? I copied node.tpl.php and I pasted it to node--my_content_type.tpl.php. My content type has a price. How can I get its value as a string?

Make sure the field is displayed in the display settings of your bundle (admin/structure/types/manage/bundle/display; replace bundle with the machine name of the content type) and define its settings (e.g., delimiter, prefix suffix).

In your template file, add <?php echo render($content['your_field_name']); ?>


Alter the path of the more link from Views In Drupal 8 how do I alter the more link?

I need to give it a path which is based on a taxonomy id that is based on the current path (where the view is on) which has the taxonomy name in the path.

The current page also has a field which has this taxonomy name as a result. (but changes per page)

--

I'm trying to retrieve the taxonomy ID based on the taxonomy that is placed on the node and give the id to the more link

I am not sure if this is clear. But I have a views page with filters. And the taxonomies are the filters. Certain pages (theme pages) have their own taxonomy directed to it with a views block. The more link of that block links to the views page, I want the link to automatically check the filters of the taxonomy that is being used on these theme pages.

If I have understood your question, I have been needing the same thing.
I solved it by means of:

1) add the field 'link to taxonomy term' and exclude it from visualization

2) format the description field as 'clipped version' (I am using right now a Spanish version of Drupal 8, not sure what the English option name is called)

3) rewrite the output for the description field as '{{ description__format }} {{ view_taxonomy_term }}'

That did the trick.

I hope that that's what you had asked, and that someone can take advantage of it.

EDIT: After re-reading your question, I realize that what I was trying to solve is different: a taxonomy terms view, which returns a list of terms, the description shortened to 160 chars, with a 'read more' link based in the taxonomy term's custom path (/path instead of /taxonomy/term/2).

Since I haven't been able to find an online answer to that, and given that google drove me to this question while trying to find an answer to mine, I think I could still leave this answer here. However, if the OP or some mod tell me to remove this answer, I gladly will.


Entity Type Manager: How to retrieve webform entries with webform_submission_data conditions I would like to get the webform entries submitted by a user with a particular webform_submission_data field value. E.g. field_account_type = "normal"

How can I supply such a condition?

$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $submission_storage->loadByProperties([
  'webform_id' => 'my_form_id',
  'uid' => $uid,
  'field_account_type' => 'normal' // Not found exception!
]);

Don't think you can query webform fields like entity fields, but it should be possible in an SQL select query:

$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data')
  ->fields('webform_submission_data', ['sid'])
  ->condition('webform_id', 'my_form_id')
  ->condition('name', 'field_account_type')
  ->condition('value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);

If you want to query the uid from the main table too, join both tables:

$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data', 'd');
$query->join('webform_submission', 's', 'd.sid = s.sid');
$query->fields('d', ['sid'])
  ->condition('d.webform_id', 'my_form_id')
  ->condition('s.uid', $uid)
  ->condition('d.name', 'field_account_type')
  ->condition('d.value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);


How to auto assign node reference value D7 I have user profile with fields:

date field: "date of birth" (format: y-m-d)
node reference field "card_ref" which should automatically reference to content-type "cards" node. (users cannot change it only view it)

and content-type "cards":

title field
date field (multiple values, format: m-d)

so i'd like to make auto-reference to existing node "cards" which have same date-field value but different format.

For example:

I have "cards" nodes:
    (title - dates)

Card A - 01.23, 03.11, 05.02
Card B - 02.14, 07.01
Card C - 11.11
Card D - 02.10, 03.02, 05.07, 09.14

After new user registers his account with date of birth: 1977.07.01, I need "card_ref" field to automatically assign him "Card B"
or if entered date of birth: 1234.03.02, "card_ref" should be assigned to "Card D" and so on...

should i use custom module or it is possible to use some existing modules? maybe with views reference field, or rules?

any suggestions please? (for drupal 7)

Thank You..

I found the answer by creating own module.

First I create the View which finds Card nodes by dob field of the user, then inside the hook_user_presave() function I call views_get_view_result() and finally assign the card_ref field like this:

$edit['field_card_ref']['und'][0]['target_id'] = $card;


How do I avoid duplication in a view result? I want to list the states from the state/province field (handled by the Location module) in a content type. I used views, but it shows the same state name more than once.

I enabled distinct in the Views module, but it doesn't works. How can I avoid the same state name is shown more than once?

Current Result: Illinois, Georgia, Alabama, Illinois, Alabama, Alabama, Georgia.

I attached the screen shot of my view (I used table format and views group by module).

Expected Result : Illinois, Georgia, Alabama.

This is my views set up.

This is what I'm getting from my view.

I'm expecting this result no matter how many nodes have the same state; I want to display the state name only once.

This is the table style I used, and views group by module.

If Views' distinct parameter doesn't work for your case, you can always use a views_pre_render() hook to do anything with the result before it is rendered.  Something along the lines of...

YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFVIEW') {

    // drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

    $states_found=array();

    foreach($view->result as $delta => $row) {

      if (in_array($row->LOCATION_FIELD_NAME_VALUE, $states_found)) {
        unset($view->result[$delta]);
      } else {
        $states_found[]=$row->LOCATION_FIELD_NAME_VALUE;
      }

    }

  }

  // any other pre_render()ing here...

}

What this does is loop through the rows of your view result keeping track of what states have been found and unsetting any duplicates.  The commented out dsm at the beginning will help you figure out what LOCATION_FIELD_NAME_VALUE you need to use in your specific case.


add a template file to custom theme I've added a new theme to my site and I've added a new content type called code_excerpt. Now, I've created a new template called code_excerpt.tpl.php and added it to my theme folder but when I created a new page using the newly created code_excerpt as content type it appears that the template used is still page.tpl.php as opposed to code_excerpt.tpl.php. As I'm pretty new to drupal, is there anything else that I need to do in order to get my content type to utilize that template? Any suggestion would be much appreciated.

I believe it needs to be node--code-excerpt.tpl.php

don't forget to clear the cache.

Copy node.tpl.php to node--code-excerpt.tpl.php then modify code as necessary.

Here is my node.tpl.php file

<?php
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - $title: the (sanitized) title of the node.
 * - $content: An array of node items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $user_picture: The node author's picture from user-picture.tpl.php.
 * - $date: Formatted creation date. Preprocess functions can reformat it by
 *   calling format_date() with the desired parameters on the $created variable.
 * - $name: Themed username of node author output from theme_username().
 * - $node_url: Direct url of the current node.
 * - $terms: the themed list of taxonomy term links output from theme_links().
 * - $display_submitted: whether submission information should be displayed.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default values can be one or more of the following:
 *   - node: The current template type, i.e., "theming hook".
 *   - node-[type]: The current node type. For example, if the node is a
 *     "Blog entry" it would result in "node-blog". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - node-teaser: Nodes in teaser form.
 *   - node-preview: Nodes in preview mode.
 *   The following are controlled through the node publishing options.
 *   - node-promoted: Nodes promoted to the front page.
 *   - node-sticky: Nodes ordered above other non-sticky nodes in teaser listings.
 *   - node-unpublished: Unpublished nodes visible only to administrators.
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Other variables:
 * - $node: Full node object. Contains data that may not be safe.
 * - $type: Node type, i.e. story, page, blog, etc.
 * - $comment_count: Number of comments attached to the node.
 * - $uid: User ID of the node author.
 * - $created: Time the node was published formatted in Unix timestamp.
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $zebra: Outputs either "even" or "odd". Useful for zebra striping in
 *   teaser listings.
 * - $id: Position of the node. Increments each time it's output.
 *
 * Node status variables:
 * - $view_mode: View mode, e.g. 'full', 'teaser'...
 * - $teaser: Flag for the teaser state (shortcut for $view_mode == 'teaser').
 * - $page: Flag for the full page state.
 * - $promote: Flag for front page promotion state.
 * - $sticky: Flags for sticky post setting.
 * - $status: Flag for published status.
 * - $comment: State of comment settings for the node.
 * - $readmore: Flags true if the teaser content of the node cannot hold the
 *   main body content.
 * - $is_front: Flags true when presented in the front page.
 * - $logged_in: Flags true when the current user is a logged-in member.
 * - $is_admin: Flags true when the current user is an administrator.
 *
 * Field variables: for each field instance attached to the node a corresponding
 * variable is defined, e.g. $node->body becomes $body. When needing to access
 * a field's raw values, developers/themers are strongly encouraged to use these
 * variables. Otherwise they will have to explicitly specify the desired field
 * language, e.g. $node->body['en'], thus overriding any language negotiation
 * rule that was previously applied.
 *
 * @see template_preprocess()
 * @see template_preprocess_node()
 * @see template_process()
 */
?>
<?php if (!$page): ?>
  <article id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php endif; ?>
    <?php if (!$page): ?>

    <?php endif; ?>
      <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
      <h2 class="title" <?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($display_submitted): ?>
        <?php print $submitted; ?>
      <?php endif; ?>

    <?php if (!$page): ?>

  <?php endif; ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // Hide comments, tags, and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

  <?php if (!empty($content['links'])): ?>

      <?php print render($content['links']); ?>

  <?php endif; ?>

  <?php print render($content['comments']); ?>
<?php if (!$page): ?>

<?php endif; ?>


Profile2 regpath move account email field, into profile2 form and handle submit I have a profile2 regpath displaying my profile2 form, and the system default account registration form below it. I need to move the account email field up into the container with the profile2 fields.

I have altered the form and moved the account mail field from the account form, into the profile form, and I have created an additional validation handler to try insert the mail value into the $form_state value so the user_account_form_validate() doesn't choke on a missing ['mail'] index:

function si_student_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  // remove fieldgroups and tabs for anonymous users, e.g. /student/register
  if($user->uid == 0) {
    // move email field from account to below profile2 name fields
    $email = $form['account']['mail'];
    unset($form['account']['mail']);
    // add email to profile
    $form['profile_student']['mail'] = $email;
    // change weights
    $form['profile_student']['mail']['#weight'] = 3;

    // custom validation handler to inject mail value into
    // correct place in $form_state['values'] array
    $form['#validate'][] = '_si_student_register_anonymous_validate';
    //dpm($form);
  }
}

function _si_student_register_anonymous_validate($form, &$form_state) {
  $form_state['values']['mail'] = $form_state['values']['profile_student']['mail'];
}

However this isn't working, and I get the following:

Any ideas? I'm not sure I'm taking the right approach here. Thanks

Found solution here: move fields in the user profile form in fieldsets

But I also needed to add the submitted $form_state mail value, back to the location it would have originally existed.

function si_student_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  // remove fieldgroups and tabs for anonymous users, e.g. /student/register
  if($user->uid == 0) {

    // move email field from account to below profile2 name fields
    $email = $form['account']['mail'];
    unset($form['account']['mail']);
    // add email to profile
    $form['profile_student']['mail'] = $email;
    // change weights
    $form['profile_student']['mail']['#weight'] = 3;

    // replace original validation handler
    $form['#validate'][0] = '_si_student_register_anonymous_validate';
  }
}

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

  // add field back to account
  $form['account']['mail'] = $form['profile_student']['mail'];
  // add submitted value from profile2 submission handler into default mail value location
  $form_state['values']['mail'] = $form_state['values']['profile_student']['mail'];
  // call validation function with update field
  user_account_form_validate($form, $form_state);

}


Should I learn Symfony 2? I saw this,  How much of Drupal 8 will rely on or be compatible with Symfony? but I don't understand if it applies to my question.  Should I learn Symfony 2 to develop with Drupal?

Symfony 2, as in the full stack Symfony 2 has no bearing on Drupal 8 -- we do not use its bundles, we do not use the same routing as Symfony does (we use a botched up work on top called Symfony CMF which is made less dog slow by bastardizing my menu work on top of it but it's still undocumented, incomprehensible, does not yield to static code analysis tools and altogether is broken and slow). We do not use the same ORM (Doctrine). We are using some Symfony 2 components however there is very little visible of it to the "end" developer. For example, confusingly enough, sometimes you need to use events (what was hook_boot/hook_init in D7 is replaced by Symfony HTTP kernel events) whereas most often Drupal still uses its hooks. Confusing is the name of the game where Symfony 2 interacts with Drupal. It's an extremely poor fit and the (non)amount of the documentation of how this fit (does not) happen makes it even harder.

Edit: we do use the service container http://symfony.com/doc/current/book/service_container.html at least the static parts of it -- however dynamic service additions and alterations are done via Drupal specific means (service providers which attaches to the system via a special magic way which is neither events nor hooks. Welcome to Drupal 8.)

So: if you know Symfony 2 inside and out then a little of that will be usable in Drupal 8. If you don't then don't bother with Symfony 2 books or tutorials.


How to create 10 extra nodes when a node of a specific content type is created? I have some business logic in my application where i need to create 10 extra nodes of a content type, when a node of a specific content type is created from Drupal Content Creation page. I know how to programmatically create a node, and I can achieve it via menu hooks, but cant get them done via hook_node_insert() which takes my application into some sort of a loop(maybe because of node_save()). My menu code is an under but I want it to be run from node insert hook.

function nodecreator_menu() {
    $items['admin/create/nodes'] = array(
      'page callback' => 'nc',
     'access arguments' => array('access content'),

    );
    return $items;
  }
function nc(){
      $node2 = new stdClass(); // We create a new node object
  $node2->language = LANGUAGE_NONE;
  $node2->field_vote_year[$node2->language][0]['value']="2009-01-01 00:00:00";
  //$node2->field_select_base_vote[$node2->language][0]['target_id']=$node->nid;
  $node2->field_select_base_vote[$node2->language][0]['target_id']=8;
  $node2->type = "vote"; // Or any other content type you want
  $node->title="Test";
   $node2->title = $node->title.$node2->field_vote_year[$node2->language][0]['value'];

  node_object_prepare($node2); // Set some default values.
  $node2->uid = 1; // Or any id you wish
  $node2 = node_submit($node2); // Prepare node for a submit
  node_save($node2);

}

You might experience an infinite loop here since every time you save the node (auto-generated or not), hook_node_insert() gets invoked. To prevent this infinite loop, you can use an extra pseudo-property in your hook_node_insert() to dictate if whether or not nodes should be automatically created.

Below is an example of how your hook_node_insert() might look like:

// If the node is an auto-generated node, don't create additional nodes.
if (!isset($node->auto_generated)) {
  // Auto-generate 10 nodes.
  for ($i = 0; $i < 10; $i++) {
    // Create a new node object and populate its fields.
    $node2 = new stdClass();
    $node2->language = LANGUAGE_NONE;
    $node2->type = "test";
    $node2->title = "Auto-generated (" . $node->nid . "-" . $i .")";

    $node2->created = REQUEST_TIME;
    $node2->uid = $node->uid;

    // A flag to let hook_nodeapi() implementations know that this is an automatically
    // generated node.
    $node2->auto_generated = TRUE;

    // Finally, save the node.
    node_save($node2);

    watchdog('test', "Auto-created node: <pre>@node</pre>", array(
      '@node' => print_r($node2, TRUE),
    ));
  }
}


Display child terms in term taxonomy page I have a vocabulary named "Catagory" with a term tree structure including parent and child taxonomy terms.

In every term's page I want to display all the child terms for that current term.
Terms are using alias.
As far as I understand it can be acheived with views, but how?

Thanks!

Set up a new view of type "taxonomy terms"
Give the view a "block" display (not a page)
In the "advanced" section of the view (on the right) you can set up a "contextual filter" based on "parent term".
The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
Go to admin->blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/* (this will work even though your term is aliased).


communicate new/changed values between taxonomies I have a taxonomy called Species, and another taxonomy called Protected Areas.

Inside of the Protected Areas I have a multifield widget (Taxonomy reference pointing to Species), where user can select different Species present on the Area.

Users are able to manipulate also the Species taxonomy, when adding a new Species they are able to choose in which Protected Area is this specie present. Then, when users do it, I would like to automatically update the user selected Protected Area taxonomy (for this Species), adding on the multifield widget the recently added Species value.

Even shorter: how to communicate new/changed values between taxonomies.

Some chances to avoid writing my own module? thanks

Unfortunately you are probably stuck writing your own module. You need to implement hook_taxonomy_term_update and hook_taxonomy_term_insert.  In each you can check the item being updated and force a change on any associated terms in the other taxonomy.

The one thing to be careful of is an update spiral. Forcing an update on associated terms will then force an update of the original term, because it is now associated.  Because the changes in those two hooks are not committed to the db until the whole mess resolves it will lock up unless you put in a variable to keep it from spiraling.

For example:

if ($term->tid == args(2)) _update_related_terms($term);

should check the term being updated against the current page.  If they do not match it won't fire. (I haven't tested this snippet, so test thoroughly!)

Then in _update_related_terms

function _update_related_terms($term){
  $associated_terms = $term->associated_term_field;
  if (isset($associated_terms['und'][0]['tid']) && $associated_terms['und'][0]['tid'] != ''){
    foreach ($associated_terms['und'] as $key => $value){
      if (isset($value['tid']) && $value['tid'] != ''){
        //check the associated term here.  You could load it, or check the db, or all sort of things
      }
    }
  }
}

I know I am using und in this example, but it is off the cuff.  Again, not tested

Please note: this example is for d7.


How do I update core to only include security patches? I have a old Drupal 7 installation and I would like to update my Drupal 7 to the latest release, but I know for a fact that some of my custom module will break on the latest update.

All I want installed is the security patches up to the latest Drupal 7. How can this be done or is it even possible without much effort? Also where and how can I view what is being patched during an update of Drupal 7 core?

If you use Drush you can update all security issues with your site via (this is Core and 3rd party modules):
drush up --security-only

if you want to see what it will do, but not do any of the actual changes you can issue:
drush up --security-only --simulate

If you want an easy way to update Drupal Core to the newest release you can use a patch site such as:
http://fuerstnet.de/en/drupal-upgrade-easier


Is there way to use existing content type field to custom form in drupal? I want to use existing content type field in my own custom form.
Like In content type, we can use existing field.

In Drupal 7 you can use field_attach_form

function hook_form($form, &$form_state) {
  $form['fname'] = array(
    '#type' => 'textfield',
    '#title' => t('first name'),
  );
  $form['lname'] = array(
    '#type' => 'textfield',
    '#title' => t('last name'),
  );
  //attaching existing content type fields
  $node = new stdClass();
  $node->type = 'article'; //content type
  field_attach_form('node', $node, $form, $form_state); //it will attach all the fields
  unset($form['body']); //unset other fields like this.
  //..
  return $form;
}


Is it possible to create a "Meta-Forum" view when using organic groups? We are using Drupal 6.x with organic groups. The groups have very different users and permission sets, and each group has a forum.

I was wondering if it is possible to have a kind of "Meta-Forum" view, i.e. one view in which all of the different Forums the user has access rights to are displayed, organized by group.

I have had a look at configuring a View for this, and while I am able to get things like a list of the most recent forum entries in all the subscribed groups, I was not able to get a "forum type" view where I have the groups on the highest level, then the individual forums and posts below this.

Is something like this possible?

It is very easy to build such of "forum" using Views. If you are using Organic Group Access, the view will be automatically filtered and only the content accessible to the user will be displayed.

Note that the OG Forum module has been abandoned due to security issues and should not be used. Depending on your requirements, it might be easier to simply use standard Views for the group forums (after all, a forum is nothing more then a View of taxonomy terms attached to a View of nodes).


Display a view in search results I have Search API SOLR running on my Drupal 8 site and I'd like to know if there is a way to have view pages display in my search results.

As an example, I have a database content type that allows users to put in the name of the database, the custom URL to link to the external database and a short description of it. The way I display this content on my site is with a view that can be filtered with certain criteria.

The actual node of these databases is never linked to and I never want users to end up on these node pages. However, if I search for the name of a database, it won't show up because I've disallowed that content type in my search settings but I still want that view page to be found when searching for the name of a database.

Can anyone help me figure out how to get view pages or pages with view block result to show up in my search results so that certain content type nodes that are never meant to be seen don't end up in the results?

The Search API supports views out of the box.  You just need to create a new view and select the "Index" you want to search.  E.g. Index Full Site or Index Resources.  These match the indices you have created in the Search API setup.

This will let you get any 'fields' in the index and use some Search API specific filters (e.g. Fulltext search which looks across all index fields.).

There are some options that refer to Datasource information.  This is the way you can take information from the index and related it to the full node.  Depending on your needs, you may need to use Relationships to get to other items, e.g files or images.

There are a fair number of tutorials on this, just search for them.


Running Drush returns an error I am running Drush version 6.2.0 and the latest Drupal 8 beta on Dreamhosters. When I run drush cc all within the sites directory, I receive the following error immediately after executing the command:

  Fatal error: Class 'Drupal\Core\Session\AccountInterface' not found in
      /home/mywebsite/mywebsite.com/core/includes/bootstrap.inc on line 63
      Drush command terminated abnormally due to an unrecoverable error.

  Error: Class 'Drupal\Core\Session\AccountInterface' not found in
      /home/mywebsite/mywebsite.com/core/includes/bootstrap.inc, line 63

Why does it happen? How can I fix this?

Drush 6 does not support Drupal 8.  You must use drush 7.0-rc1 with Drupal 8 beta 9, or drush master head with Drupal 8 head.

UPDATE: Drush 7 no longer supports Drupal 8; now, use Drush 8 with Drupal 8.


reference a view page with entity reference I have an entity reference field for referencing and rendering a teaser display of nodes.

I would like to be able to include a View page in the list. I this possible in some way?

View Reference Module makes it possible

Defines a field type View reference which creates a relationship to a
Views display and allows the view to be displayed as the content of
the field.

OR
Entityreference View Widget Module is another solution

This module provides an advanced Entity Reference widget that uses a
view embedded in a modal dialog for selecting items.
In the Field UI for the Entity Reference field select "View" as the widget

Edit your Content Type or Entity
Add or Edit the field with "Entity Reference"
Next make sure your "field" - "widget type" is set to "View"

Check for the following "field" settings in your content type field:

"View": make sure you select your "Entity Reference View Widget"
Pass selected entity ids to view


View: No Result = Last I have a field 1 Name and another field 2 Year and have it sorted in Views first by Name and second by Year. If Year is empty I want it to be placed last under each letter. So lets say I have 5 James in my list and 4 of them have a Year and the one without Year to appear last in the list of those names but before Jane.

I've installed Rules and Views Rules but I don't know how use Rules for this kind of thing. Any suggestions?

Assuming that the Name field is text and the Year field is an integer, if you sort the Names ascending and the Years descending, the empty year of James should come last and before Jane (which should be what you are after). That's the default behavior of Views. If your views has contextual filters or relationships, you may be getting different results.

In any case, you can configure the Year field and under the "No Results Behavior" you can set a very low (or high depending on what you want) value for year and hide it. This way, you will guarantee that it will be sorted as expected.


How can I change a menu link dynamically? (D7) I'm trying to change the link of a menu item dynamically based on the language that is selected in the language switcher.

Let's say I have the following links in my main-menu:
-Home
-About
-Products

If the language selected is English, I want the About item to link to node/73. If the language selected is Dutch, I want the About item to link to node/74.

Is this possible and how would I best go about this?

Any help is very much appreciated.

EDIT: Some extra information. I have the Internationalization, Content Translation and Entity Translation modules installed. Because of the hierarchy of the menu and a mix between content translated nodes and entity translated nodes, I don't want to add two seperate links to the menu but have one link and change the path dynamically in code.

You want to implement hook_translated_menu_link_alter().

This hook is not called for all menu items. According to the API documentation:

  It is only invoked if $item['options']['alter'] has been set to a
  non-empty value (e.g., TRUE). This flag should be set using
  hook_menu_link_alter().

Here's an example:

function MODULE_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['options']['alter'] = TRUE;
  }
}

function MODULE_translated_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['href'] = 'node/5';
  }
}

Some notes:

you may want to filter additionally by $link['menu_name']
MODULE_menu_link_alter() is invoked on cache clear for all menus items declared via hook_menu().
For menu items created via web it is only invoked on save, that is, for this code to take effect you need to edit-and-save menu links you want to alter.

For reference, this technique is implemented by core in user.module (see user_menu_link_alter and user_translated_menu_link_alter) and by menu_token module.


Add a class to all the blocks in a region I'm theming a Drupal 7 site and I'd like to add a class to all the blocks in a given region using preprocess_block().

I think this should work, but it doesn't seem to:

function MYTHEME_preprocess_block(&$variables) {
        // Other stuff in this function
        $variables['title_attributes_array']['class'][] = 'title';
        $variables['classes_array'][]='clearfix';

        // Now I want to add a 'col-md-4' class to all the blocks in the 'bottom-content' region
        if($variables['block']->region == 'bottom-content') {
                $variables['classes_array'][]='col-md-4';
        }
}

Any ideas why this isn't working?

As manikandan kannan is saying, you probably have the name of the region wrong. It probably is: 'content_bottom'

So your if-statement would become:

if($variables['block']->region == 'content_bottom') { ...


Related block by entity reference I have a 2 content types.

Article
Page

and the Article content type can reference pages from an entity reference field.

Now I want to display a block on Article nodes that have a same reference.

So I tried this:

Create a views block listing Articles.
Add some fields.
Add a relationship field_page_reference: Content
Add contexual filters of Content Id and provide default value to Content Id From URl and Specify validation criteria set to Content and select article.

But it doesn't work? Any idea?

You're on the right track, but you're missing another Relationship.

You've added the Relationship that points to a referenced Page. Now you can show that Page info in your views, but that isn't what you want. You want to show all other articles that reference that page (siblings).

To do that you need to add another Relationship that goes in reverse, from Page back to article: Content using field_page_reference and make it use the first Relationship (this is where the matching is happening!).

Then modify your ID Contextual filter to use the second Relationship.

Now you'll have a list of all articles that reference the page that is referenced on the article you're currently viewing.

That includes the current article BTW, so if you want to exclude it from the list you have to add another ID Contextual filter "Content Id From URl" but don't use any Relationships and under More select Exclude.


Modify existing block programmatically by block id I have a block with the id 'block-block-8'. In my template.php I would like to have a function that changes that block's content so I am able to add a dynamic "back to category link" (category needs to come frome the url) on my products page back to the category page.

Something like this:

function ga2012_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'block-block-8':
      $block = array(
        'content' => 'Back to $_GET["category"]',
      );
      break;
  }

  return $block;
}

Does someone has a working implementation of this code? Please ask me questions if I haven't been clear enough, thanks!

You might try with hook_block_view_MODULE_DELTA_alter which:

  Performs alterations to a specific block


How to add 'style="width:100px"' in Global Custom Text field in a view? It seems that the Global Custom Text field in a view delete part of my text.

I write this:

Hello

but get this:

Hello

The text removed is this

style="width:100px"

I need to be able to include it.

The value of the 'width' is provided by a token ([field_width]), that's why I need to add it here. It is dynamic value.

Update: I just see that this is a security measure, then how can I make View accept this using a function?

Here is a fun and a little naughty solution to this:

1.) Instead of style, set the token as value="[token]" - make sure your token is only a number, no alphabetic characters like px etc.

--- Value is set and DIV is spat out ---

2.) Use jQuery to get the value of value="" - define it and use it when the page loads:

$(document).ready(function(){
var div_width = $('.my-div').val();
$('.my-div').width(div_width);
});

The width will now be appended to the div via inline-style using jQuery. Not optimal, not recommended but it should work.

More on adding custom jQuery to your Drupal installation: https://www.drupal.org/node/171213


Custom template for content type, How to print a link field as a hyperlinked image I am making a site for a music festival. I have one content type for attending artists, which includes the following fields of the fields type Link: soundcloud, youtube etc.

I would like to print these fields with an image (small icons) instead of the written link.

How can I do that?

( The path I am looking at for the moment: copy node.tpl.php, rename to node--artist.tpl.php, add some code, put in sites/all/themes/default_theme. )

It's easier and more practical apply a preproccess hook:

Function YOUR_THEME_proprocces_node__artist(&$vars){

 // $vars contain the fields to be renderable in content attribute

}

I resolved a similar question a few days ago: change links read more and add comment

Inside of array tree $vars['content], you will have to change the title attribute adding the html mark you want.

If you have a problem to find the tree or change the array, print the array with the dpm($vars) in your code and capture an screenshot to publish here.


Getting terms for only one taxonomy from services module I have the services module installed, and I have both taxonomy_term and taxonomy_vocabulary checked. However I'm having problems getting just the terms for one vocabulary. when I do curl -g "http://domain.com/endpoint/taxonomy_term?args[0]=machine_name_of_vocabulary" or curl -g "http://domain.com/endpoint/taxonomy_term?args[0]=2"

I get an xml result like this:

<result>
  <item>
    <tid>2</tid>
    <vid>2</vid>
    <name>Blue</name>
    <description/>
    <format>filtered_html</format>
    <weight>0</weight>
  </item>
  <item>
    <tid>1</tid>
    <vid>5</vid>
    <name>Apple</name>
    <description/>
    <format>filtered_html</format>
    <weight>0</weight>
  </item>
</result>

which is the terms of all the vocabularies. In other words, I have the argument wrong, or the request wrong, or something else wrong.

How do I configure services and make a request to it to get only one vocabulary?

I was working on exactly the same thing the other day, the format is like this:

http://domain.com/endpoint/taxonomy_term?parameters[vid]=2

To explain that a bit further...

If you look at the code in _taxonomy_resource_definition() the index resource defines a few arguments:

page (int)
fields (string)
parameters (array)
pagesize (int)

The way to pass any of those is:

http://domain.com/endpoint/taxonomy_term?arg_name=value

Since parameters is an array you need to format it as if it was an associative array in the URL, so you use (e.g.) parameters[vid]=2.

It will also work for other parameters, e.g. parameters[name]=TermName.


How to create block to list all children of an entity? I want to list all the nodes that have the currently viewed node as their parent.
To make this more tangible and less abstract, let's do an example:

I have a content type Locations which has an Entity Reference field called parent_location with an unlimited number of values.
For example:
- USA (3)                             [country level]
  - New York (4)                        [state level]
    - New York City (6)                   [city level]
      - Central Park (8)                    [landmark level]
      - Empire State Building (9)           [landmark level]
      - Times Square (10)                   [landmark level]
  - Illinois (5)                        [state level]
    - Chicago (7)                         [city level]
      - Sears Tower (11)                    [landmark level]
      - That bean looking thing (12)        [landmark level]

So when I view the content for USA (3), I wanna list all the children, meaning New York (4) and Illinois (5).
When I view New York City (6) I want to list Central Park (8), Empire State Building (9), and Times Square (10).
I want these to show up when I view /node/6 and be clickable, so that I can browse this nested child/parent structure.
It's already possible by default to traverse UP on the tree. Meaning I can easily get from Times Square (10) all the way up to USA (3).

However, I can't figure out how to list all children of the appropriate level!
I did create a block view called List Child Locations. And I've placed this view on the block Content. It shows up correctly, but it does not list the appropriate children.

When it comes to editing my view, I have no clue what I'm doing or how...
I see there's two options:
admin/structure/views/view/list_child_locations/edit/block_1
and
admin/structure/views/view/list_child_locations/edit/entity_reference_1
I think I have to do something with contextual filters, while I'm in the Entity Reference Display. But I can't find anything that looks like what I need...

Out of all those many options, which one do I chose to make sure it does something like
SELECT * from Locations WHERE parent_location = %current_location% ?
What's the right settings for my entity display to only list the children?

Finally, I figured it out!
First, I learned more about contextual filters and relationships, and what they each mean and do (relationships basically relates to the FROM query, contextual filters to the WHERE query)
https://www.youtube.com/watch?v=mRWtpcUm9pI
Another user had a similar question and solved it like so:
https://www.drupal.org/project/views/issues/1724396
So all I had to do was:
/admin/structure/views/add

show content of type "Locations"
Create a block

Then under "advanced" add a contextual filter, check "parent_location (field_parent_location)", press the button to "Add and configure".
Then under "When no filter is available" say "provide a default value" and select "content ID from URL"
Hit apply, save the view.
Under /admin/structure/block place the block to the content region and make it visible for Locations.
This was super simple! :-)


Views relationship not been added by code Im trying to make a abandoned cart notification module, trying to relate my notification table with the commerde_order table by its order_id in views. Right now i have this in my hook_views_data

function commerce_abandoned_cart_notification_views_data(){
    $data = array();

    $data['commerce_abandoned_cart_notification']['table']['group']  = t('Commerce abandoned cart notification');

    $data['commerce_abandoned_cart_notification']['table']['join'] = array(
        'commerce_order' => array(
            'left_field' => 'order_id',
            'field' => 'order_id',
        ),
    );

    $data['commerce_abandoned_cart_notification']['table']['base'] = array(
        'field' => 'id',
        'title' => t('Commerce abandoned cart notification'),
        'help' => t('Commerce abandoned cart notification'),
    );

    $data['commerce_abandoned_cart_notification']['id'] = array(
        'title' => t('Notification ID', array(), array('context' => 'A Commerce abandoned cart notification internal ID')),
        'help' => t('The unique internal identifier of the notification.'),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    $data['commerce_abandoned_cart_notification']['order_id'] = array(
        'title' => t('Order ID', array(), array('context' => 'A Commerce order ID')),
        'help' => t('The unique internal identifier of the order.'),
        'relationship' => array(
            'base' => 'commerce_order',
            'field' => 'order_id',
            'handler' => 'views_handler_relationship',
            'label' => t('Referencing order'),
        ),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    return $data;
}

The problem is that when creating a view i do not see my relationship to commerce orders or viceversa, (the hook works because i can create a view of type commerce_abandoned_cart_notification and add some of its fields). I know there is a commerce_abandoned_cart_notification or commerce_notification module but they seem incomplete and/or abadoned

Should i use hook_views_data_alter to alter commerce_order relatations and add one to my custom table?

Have you considered using the module Commerce Notification?


How to use url() correctly? I'm trying to generate a custom token to a prepopulated URL.  My code looks like this:

        $replacements[$original] = url('user/login', array(
          'query' => array('edit[name]', $account->mail),
          'absolute' => TRUE,
        );

The resulting URL looks like this:

http://example.com/en/user/login&edit[name]=myemail@example.com

But the & should be a ? because it's the start of a query string.  What am I doing wrong?

This should work for you:

    $replacements[$original] = url('user/login', array(
      'query' => array('edit' => array('name' => $account->mail)),
      'absolute' => TRUE,
    ));

Sidenote: you are naming the argument as name but you are passing the mail.


I need help grouping links under one title So this is how my webpage looks at the moment.

However, I need to group each of these links under a certain title.
The titles are the following (bolded):

How do I get each of those links, for ex "Bon Appetit", "Brubakers" to be under the title "Eateries" and so on. How do I create the Group titles?
I just want to know how to get started on it. Do I have to do some coding? (I have no experience on this, by the way.)

I'm assuming that each of these items are nodes, that have a field referring to the group they're a part of. In your view settings, look for 'FORMAT'. I'm guessing you're using an unformatted list. If you click 'Settings' next to that you should see a 'Grouping Field Nr.1' dropdown box. There you can choose what field to group all the items by and it will automatically group your results with the group title at the top. You have to make sure that you have the group field listed in fields section first.


drupal_find_theme_functions called on every page - is our theme registry being rebuilt? Our new D7 site was running very slowly so I did some profiling with devel/xhprof and found that D7 was doing millions of preg_grep function calls within drupal_find_theme_functions() in theme.inc. This happened on every page load.

It's my understanding that the drupal_find_theme_functions function should only be called when the theme registry is being rebuilt - am I correct in that?

I made sure that "rebuild theme registry" was off in devel, and then disabled devel entirely. However, I'm still seeing those millions of function calls to preg_grep in drupal_find_theme_functions on every page load (I added a piece of code to theme.inc to log when the function was called).

We're using a theme based on Omega and if we are rebuilding the theme registry each time I'm not seeing how/why it's happening. We're turning off as many contrib modules as we can in the meantime. Any help/advice would be MUCH appreciated!!

Nice job on using XHProf to debug what's going on here. drupal_find_theme_functions() should get called once per registry rebuild for the core and installed modules, then once again as each installed theme is utilized.  Are you noticing it once per page load, many times per page load, etc?  I'm going to send you down a slightly different path on this as you should be more interested on what's causing the rebuild, not what happens when the rebuild occurs.

I'm assuming that you're working with a recent release of D7.  Use the devel module and put code below into drupal_theme_rebuild() at line 350 of includes/theme.inc to see what functions are being called on the way to the registry rebuild and that should give some clue as to what is triggering it.

dsm(debug_backtrace());

A quick note on what you should expect to see.  I've done some testing and with a mostly empty Drupal install with only a few popular modules installed.  The registry rebuild is only happening when I clear the theme cache or perform some action that causes it to be cleared.  If you look at the functions being called prior to the rebuild, you should see some indication as to what was responsible for causing it.

When I clear caches from the normal admin screen (admin/config/development/performance) my call stack is 9 functions deep and it passes through a form submission handler that triggers the process.  When I clear the cache from the admin_menu contributed module, my call stack is 5 functions deep and it passes through a page callback that initiates the cache clear.  Your case should be showing something a bit out of the ordinary.