Set path for favicon.ico and apple-touch-icon.png I would like my favicon.ico to be accessible by http://example.com/favicon.ico and http://example.com/apple-touch-icon.png, but I can't manage that.
I tried few things, but nothing helped. My favicon.ico/apple-touch-icon.png is located in the theme root folder.

How can I achieve this?

use a symlink, I typically keep my main favicon in my root theme folder, and then in the terminal navigate to the site root and symlink to that icon

ln -s PATH/TO/THEME/favicon.ico

it makes the most sense to me to keep my theme assets in my theme directory, but then I also like to have the same favicon accessible from the doc-root as well


If "tag" is "event" - how to do condition with php I need to do a condition on a tpl.php

Basically I have a content type with taxonomy "tags" - some are News, some are Events.

On the page.tlp I want to do the following condition:

if ($content['field_tags']=='Events'):

test

endif;

But this doesn't work.

Can you help me? Thanks.

This is where you will find it in node.tpl.php

$content['field_tags']['#items'][0]['taxonomy_term']->name

Be sure to test it for empty() or run it through isset() before you use it.


How to Alter Views Result in Drupal 7 i've several list of products display on a Drupal block. I get the list of products using views module. Then, i've several pages dedicated for each product. Before the list of products display on a block, i need to check if the page for the product exist of not. if exist, i need to display the product as list, but if not exist, i don't want to display it as link.

Example:

I have pages:

Product/A for product A

Product/C for product C

I have products:

A

B

C

D

So, views result that display on the block, should be:

A -> as link

B -> not a link

C -> as link

D -> not a link

How can I achieve that?

The only way I can think is to use a views field template file to be overridden.

Copy the template sites/all/modules/views/theme/views-view-field.tpl.php to your current enabled theme folder. Assuming that you have a block view "product-listing", you could rename it to views-view-field--product-listing--block.tpl.php.

Rescan template files in your view theming information. The file views-view-field--product-listing--block.tpl.php just created should be highlighted with bold. Now, you have an active custom field template for your block view.

Then, you can edit the template as you need. Here is a sample code:

<?php
 $alias = drupal_get_path_alias('node/'.$row->nid);
 if(drupal_valid_path($alias)){
     $url = url($alias);
?>
    <a href="<?php print $url; ?>"><?php print $row->node_title; ?>
<?php
}else{
?>
    <?php print $row->node_title; ?>
<?php
}

You can check if a page ( or path ) exists or not by using drupal_valid_path().


How to override the /taxonomy/term/% for specific terms? I would like to override the standard /taxonomy/term/% view for certain terms in a given vocabulary in two situations: one is for a given term, another is for all childs of a given term (so if and only if the current term has XXX has parent, the view must be triggered°.

When one of the condition above is met, then this view must be triggered, the standard view must be displayed otherwise.

What is the proper way to achieve this?

EDIT

Example:
Standard taxonomy page orders teasers by published date and it is generally what I need except for all the children of the term "Regions" (Africa, Asia, Caribbean,...) where I need to order them by Country and provide exposed filters.

I don't want to create a view for each of those terms. I would like to create a view that is triggered only when the parent term is Regions. In all other cases, the standard /taxonomy/term/% view must be rendered.

In D6, the taxonomy term page is themed by default with a function, but it can be overridden by creating a template in your theme called taxonomy_term_page.tpl.php (or of course writing your own function if you want).

In D7, it provides a default taxonomy-term.tpl.php that can be copied to your theme and modified.

So, you would have to look to see what term is being displayed and if it's one of the ones you want customized, embed your view output for it; otherwise, let taxonomy do it's thing by default.

There is good commentary in the D7 template that should make that pretty straightforward.  In D6, there is a Crazy-Awesome Taxonomy Pages Video with Bob from Mustardseed Media that I found to be quite helpful but there you basically have a $tids array that you can look at to decide what to do.


Add a unique Banner Image to each page I've been teaching myself Drupal 7 for the past 2 weeks. So far, I've gotten the general idea, and figured out how to use Views (i think) but it's the most difficult CMS I've ever had to learn and I've pulled out lots of hair.

The problem I'm stuck on now is that I want to be able to let the site administrators attach a unique banner image that will appear at the top of every page in my theme. There is a 'banner' region in the theme that was intended to hold this image. I've added a banner image field to the Basic Page content type.  But now I can't figure out how to get that image to show up in the banner region and not in the flow of the rest of the page content (body).

I've tried a few things with views and blocks, but nothing works.  Please Help!

This method is pretty similar to what Shoaid Nawaz has said above. For Drupal 7, you can use the Views module. Coupled with a custom theme region, you can create a block using the views module which will show an image for each node from a custom image field specified for the content type. You need to have a basic working knowledge of the Views module.

Here is how:

Create a custom theme region, name it something like "Banner Region"
In your content type, add an image field, name it something like "Banner image". If you need description, enable Alt tags for the image field. If you do not need slideshow, restrict the number of image to 1. For slideshow, you can use the views_slideshow module.
To create similar sized banner images, you can create a new image style.
Create a new View. Name it something like "Banner". Choose "block" display and not "page".
In the filter criteria, choose your content type.
Add a contextual filter for "Content: Nid" and save the view.
Now go to the your blocks administration page and add the newly created views block to your new banner region.

In short:

Banner image is a new image field in an existing content type.
Views module understands which image is attached with which node using the contextual filter.

Tip: You might want to disable this block on the frontpage if your frontpage is not a node.

Further tip: You might consider adding other content types to the filter criteria if you banners for multiple content types. Alternatively, you can create a block for each content type and block control visibility using "No results behaviour" in the views' settings.


How do i customize theme_link() for a particular node, or view only? i have a View that displays some DVD product teasers. What id like to do is customize or change the wording of the 'Read More' link of each teaser.

i also have another view where i want to remove that link altogether. now i know how to do this with CSS but i'm trying to learn how to override theme functions.

i have Themer Info turned on see a candidate function name for theme_link() but i think that would override all the theme_link functions for the entire site. how do i customize theme_link() for a particular node?

and how do i find out what function calls theme_link() ?, if i want to remove it entirely?

in other words, i need to get into $content variable!, how do i do that?

much thanks in advance!

You can use hook_node_view_alter(&$build) and overwrite the link. Here is an example to change the Read More title and removing Add comment link. You can use dpm()  function of devel module to see the array structure.

function mymodule_node_view_alter(&$build){
  if($build['#node']->type == 'DVD' && $build['#view_mode']=='teaser'){
    $build['links']['node']['#links']['node-readmore']['title'] = t('New Title');
    unset($build['links']['comment']['#links']['comment-add']);
  }

}


How to implement autocomplete for address field using google places/maps api? When using Eventbrite event creating form, i noticed their address field has an autocomplete feature powered by Google.
Is there a Drupal module that does something similar ?

Demo link on Google Code

I have created a working sandbox version of address autocomplete. https://drupal.org/sandbox/adammitchell/2126989. I will endeavour to get it created into a full blown project. However if you could help me and test it that would be greatly appreciated.


Uploading images so that they are searchable How would I go about uploading images so that they are searchable, and so that the search results are actually displaying the image thumbnails?

How difficult would it be to integrate this search into the site search?

To include image data in the core search index, you perhaps could implement hook_search_info and hook_search_index to add the custom image field text attributes (alt, title text etc..) to the search index.

You can then theme the output of the search results by overriding search-result.tpl.php or using hook_preprocess_search_result to add the image thumbnail.

Further core Search API docs here


How do I act after quantity change in cart? I am writing a Commerce submodule that needs to run some code on the line items in an order when the Update Cart or Checkout buttons are clicked in the shopping cart form, but I'm not sure where to put it. More specifically, I need to see if the user updated the quantity of a line item in their cart and then write code that acts on the quantity change (without using Rules).

I am already using hook_form_FORM_ID_alter() to alter the Remove buttons in the shopping cart, I figured I could just add a submit handler in this hook but that doesn't seem to work.

function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  $form['#submit'][] = 'MYMODULE_cart_submit';
}

function MYMODULE_cart_submit($form, &$form_state) {
  dsm($form);
}

When I hit either Update Cart or Checkout, dsm doesn't load on the next page. Am I in the right spot?

Thanks! :)

You could use the Entity API type hooks (load, presave, update etc..) to act when the commerce_line_item is updated

e.g:

/**
 * Implements hook_entity_update
 */
function MYMODULE_entity_update($entity, $type){

  if($type == 'commerce_line_item'){
    // Do stuff with line item in $entity;
  }

}

You might have access to $entity->unchanged or similar in $entity which stores the entity content prior to the save. Useful for comparing quantity to see if it's changed!

dpm($entity); // for details.

You can also use hook_ENTITY_TYPE_update

/**
 * Implements hook_ENTITY_TYPE_update
 */
function MYMODULE_commerce_line_item_update($entity){

  dpm($entity);

}

The hooks for load, presave, insert, update and delete are available for all Commerce entity types.


View filtering based on entity reference revisions (Paragraph) type I am working on a Drupal 8.3 installation and I want to create a single content type for each organization to be able to update their own content on the site (using the core permissions on content types).

For each content type, I want to use an entity reference revision field (Paragraph) and have the view display based upon the type of entity being referenced (there will a limit of one).  I tried looking at using conditional fields (not production ready) and taxonomy term in the content type (not able to force matching of term to paragraph type).

I was hoping there was a way to build the filter criteria based on the paragraph type but only target_id and target_revision_id are selectable.

The brute force approach would require I create 6 content types per organization, but having over 100 content types seems overwhelming effort to create.  Is there another solution to keep this DRY and easily understood for novices to add content?

Go to the Advanced section of the view and add a relationship:

RELATIONSHIPS
field_paragraph: Paragraph

Then you can add filters for all paragraph fields including the field for the paragraph type.


Is there an issue reporting module with these features? We have 3 departments and we give IT support for all project users. We would like to receive there support request using our drupal 7 site  instead of receiving phone call.

We just need a support request form
The form sends a notification email to experts
The submitted issues should be listed by project group; only experts can access the list.
The form access privilege is only for authenticated users.
There is no progress status report for the users.

What do you suggest?

The Webform module might do what you want. It lets you create forms using the user interface. You can configure which actions happen when a user submits a form, such as email one or more users and store it in a table.

Update about your comment, which looks like so:

  Webform seems good but i drop it by one important reason. that is it doesn't give a privilege form submission only the authenticated user!

Forms created with Webform are just a type of node. If you want to restrict access to the forms you create, you can either not allow anonymous to access any node or you can use more fine grain permissions with another module like Nodeaccess. If this is for an intranet site, the first option might be the best


How to use Represenstive Views to display users representative nodes? Main view (User entity):
Fields:

(Representative node) Content: Nid
(Representative node) Content: Type
(Representative node) Content: Post date
(Representative node) Content: Title
other fields

Filter criteria:

user roles, user active

Relationships:

User: Representative node

Represantative view (Content based)
Fields:

Content: Nid

Filter criteria:

Content: Type (in Innovation, ...)
Content: Language (= Current user's language)
Content: Promoted to front page (Yes)

Sort:

Content: Post date (desc)

Generated query: http://pastebin.com/cvKD3zzB
Error:

Error message SQLSTATE[HY093]: Invalid parameter number: number of
bound variables does not match number of tokens

Could someone give me any advice?

The error has to do with a bug related to User: Representative node. Checkout https://www.drupal.org/node/1417090. Comment #35 has a patch for the latest dev version of views that will possibly fix the issue.


7 - access callback get currently checked path In my module I have lots of different pages. All pages, as defined in mymodule_menu, access the same access callback function mymodule_user_access and perform different things based on the parameters passed. Now as far as I understand drupal calls that function for all the menu items that may be rendered on the page, which means that if there are 10 menu items visible, it will call the function for each one of them separately. What I would like to have is some way of seeing what path drupal is currently checking when the function is accessed. So if I have

$items['mymodule'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
);

$items['mymodule/path1'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
    'type' => MENU_LOCAL_ACTION,
);

$items['mymodule/path2'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
    'type' => MENU_LOCAL_ACTION,
);

which means that when I access mymodule page the mymodule_user_access page is accessed 3 times (for mymodule, mymodule/path1, mymodule/path2). What I would love to do is:

function mymodule_user_access() {
    drupal_set_message($path); //This should output 3 different messages: mymodule, mymodule/path1, mymodule/path2
}

Is it possible without explicitly sending the path as a parameter in access arguments?

UPD: I tried current_path but it returns the path I am trying to access. Same with arg()

Based on my research, I checked first the current_path() function and in it's code it gets the path by $_GET['q'] w/c indicates only getting the values fro the URL so this wouldn't work.

I also checked the access callback and access arguments' functionality and initially I noticed that access arguments are meant for the actual use that you are trying to bypass where links needs to be checked to let Drupal know if it will display a link. The only way is does this is by specifying the access arguments.

In my opinion, the access arguments array standardizes where the "access specifications" would come from like this menu's access specs are basing on the second and third arguments. So developers would know what they're dealing with by looking at the access arguments array and user the access callback just to do mostly logic.

I hope this could help.


Restricting "view content" to members of a group I would like to make a site with content that anonymous users can read, and private content that only group members can read.

How do I achieve this? I have installed Group, but any group content I add can be viewed by anonymous users.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

It seems that you would want to grant access to what, in Group, is called "Members" (similar to what in your question is called 'Group members'). But you woudn't allow access to "Anonymous" (site visitors that are not logged it). However, you also need to think about which access you want to give to "Outsiders" (=  logged in users who are not a member of a group).

With the above in place, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.

More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.


How can I include a third party library in my custom module without using Composer Manager I'm trying to create a custom Twitter Pull module in Drupal 8.  I would like to include https://github.com/abraham/twitteroauth.

I can't seem to get it working adding it via composer in the root composer.json file, or by using Composer Manager and creating a composer.json file in my module root, so for the sake of this question, how else can I include and make use of the library?

Can I add a dependency to my custom module .yml file?
How would I handle the namespacing/autoloading for this library in my custom module?

General: Composer Merge Plugin

In your Drupal's main composer.json you can use the Composer Merge Plugin to scan certain directories for composer.json files and merge them into your main composer.json.

You'd then have a composer.json in your custom module requiring the 3rd party library. In your root composer.json you require the merge plugin and configure it under the extra section to include certain directories.

{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "web/modules/custom/*/composer.json"
            ]
        }
    }
}

Optional: Composer Custom Type Installer

If the 3rd party library in your custom module is available on GitHub and you want to define a location where the lib should to be downloaded to (extra helpful especially for all front-end libs) you can use Composer Custom Type Installer in your main composer.json.

You'd then require the 3rd party library in the repositories section in your custom module's composer.json assigning it a package type you pre-configured in the extra section of your main composer.json to define a location where the lib should be downloaded to.

"repositories": [
    {
        "type": "package",
        "package": {
            "name": "select2",
            "version": "4.0.3",
            "type": "theme-library",
            "source": {
                "url": "https://github.com/select2/select2.git",
                "type": "git",
                "reference": "tags/4.0.3"
            }
        }
    }
]

And the corresponding extra section in the main composer.json:

"extra": {
    "custom-installer": {
        "theme-library": "web/themes/custom/MYTHEME/libs/{$name}"
    }
}

Of course, for simplicity you could also do everything (composer-merge-plugin and custom-installer and requiring the GitHub repo) just from you main composer.json. I'd recommend that.

If you do so, then run at least once composer require PACKAGENAME (in my example composer require select2) after you manually incorporated the lib into the composer.json file.

Last but not least, don't forget to bind your library with MYMODULE.libraries.yml and hook_page_attachments (latter called from MYMODULE.module). See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.


Is there any way to know which theme hook or template is being used to output certain area of a page Is there any way to know which theme hook or template is being used to output certain area of page? I am showing different menus on a page and i want to know which theme hook is being used to output particular menu and links of menu.

I tried dpm($variables) in function theme_menu_links($variables) in common.inc just to make sure if this theme hook is being used to output the links of menu but this theme hook is not being called and no output is printed. Then certainly this theme hook is overridden by other module or by theme.

Is it possible to know list of all available hooks and templates files for a particular are of a page like block, menu etc with the active theme hook used to output that area?

Yes, there is a module for that: Theme Developer.

  Firebug for Drupal themeing

Note that this is a heavy module, enable it only when needed and on your local machine.


Open Menu Link In New Browser Tab/Window I am having a problem with opening a menu link defined in a module.links.menu.yml in a new browser tab or window. Code for the link:

mymodule.mm_google:
  url: 'https://google.com/'
  parent: mymodule.admin_mm.external_index
  description: 'Search Engine'
  title: 'Google'
  options:
    attributes:
      target: _blank

I am working with Drupal core 8.2.4 8.2.5 and the link currently works except for opening a new browser tab or window.

Update:
The links are opening in a new tab/window when rendered by the Toolbar/Admin Toolbar modules but not when rendered and displayed by  admin overview controller \Drupal\system\Controller\SystemController::overview. The controller will also not render included classes for the anchor element.

Doing a review of how \Drupal\system\Controller\SystemController::overview builds an Admin Overview page and I found that template_preprocess_admin_block_content was only constructing each link item as an array values that did not include a URL object. While menus built by the admin Toolbar did. The importance of the URL (Drupal\Core\Url) instance being generated is that it includes an Attributes (Drupal\Core\Template\Attribute) instance that Twig can use to render an item's HTML attributes.

The fix:

The template_preprocess_admin_block_content function can be located in a custom module but, there is the requirement to add an overriding template file in the admin theme so it is best to locate the function a custom admin theme. (It is important that you remember the difference between your front-end theme and your admin theme as they are not the same)

/themes/myadmintheme/myadmintheme.theme

/**
 * Implements template_preprocess_admin_block_content().
 */
function myadmintheme_preprocess_admin_block_content(&$variables) {
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $key => $item) {
      $variables['content'][$key]['attributes'] = new Attribute(empty($item['options']['attributes']) ? array() : $item['options']['attributes']);
    }
  }
}

/themes/myadmintheme/templates/admin-block-content.html.twig

{#
/**
 * @file
 * My admin theme implementation for the content of an administrative block.
 *
 * Uses unordered list markup in both compact and extended modes.
 *
 * Available variables:
 * - content: List of administrative menu items. Each menu item contains:
 *   - url: Path to the admin section.
 *   - title: Short name of the section.
 *   - description: Description of the administrative menu item.
 *   - attributes: HTML attributes of the administrative menu item.
 * - attributes: HTML attributes to be added to the element.
 * - compact: Boolean indicating whether compact mode is turned on or not.
 *
 * @see template_preprocess_admin_block_content()
 * @see seven_preprocess_admin_block_content()
 * @see myadmintheme_preprocess_admin_block_content()
 */
#}
{%
  set classes = [
    'admin-list',
    compact ? 'compact',
  ]
%}
{% if content %}

    {% for item in content %}

{{ item.title }}
{{ item.description }}

    {% endfor %}

{% endif %}

In the example code here the theme My Admin Theme (/themes/myadmintheme) is a child theme of Drupal's default admin theme Seven.


CDN JS -- cannot seem to weight it I'm adding external JS in my Drupal 8 site (//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js) and I cannot seem to weight it using hook_js_alter. I can weight it if I throw it in a themename.libraries.yml file but then it gets rendered in every page. Ideally I want to only render the script in the home page. So this works:

function MYTHEME_js_alter(&$js) {
  if (drupal_is_front_page()) {
    $leaflet = '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js';
    $js[$leaflet] = drupal_js_defaults();
    $js[$leaflet]['data'] = $leaflet;
    $js[$leaflet]['type'] = 'external';
    $js[$leaflet]['every_page'] = TRUE;
    $js[$leaflet]['weight'] = -100;
  }
}

... but it weights it last and I'd like to weight it so it loads much earlier.

if I load it via a theme.libaries.yml file, it weights it lower but it renders on every page.

MYTHEME-corescripts:
  version: VERSION
  js:
    //cdn.leafletjs.com/leaflet-0.7.2/leaflet.js: {}
    js/scripts.js: {}

I'm open to this method if I could somehow add context to the YAML file to indicate only fore the home page.

The method below works superbly. hook_page_alter is the way to go and the #attached method. (as suggested in a comment instead of hook_preprocess_page I didn't know this would work for external js but it does. Pretty cool. With this method and a nested array with weight, it works as expected.

function MYTHEME_page_alter($cache) {

  if (drupal_is_front_page()) {
    // Render leaflet only on the home page
    $leaflet = array(
      '#attached' => array(
        'js' => array(
          '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js' => array(
            'group' => JS_LIBRARY,
            'weight' => -999
          ),
        ),
      ),
    );
    \Drupal::service('renderer')->renderRoot($leaflet);
  }
}

Also of note is that we use JS_LIBRARY instead of JS_THEME here.


Help me to implement this plan - limit users to edit content I have a plan that need your help to be implemented.

I am using Drupal 6.x

Let me describe it at first.

We have a content type called it Article

This content type has Title, Description, Link, Status & belongs_to fields.

Title : Title of article record.
Description : brief description of record
Link : the source link [HTML]
Status : the status of record. Available options are FREE , Finished, In progress [it is drop down menu]
Belongs to : it is the name of user that is working on this record.

At first Some article records are added by admin.
Note: Only admin of site can add new article record.
When the new record is added it has FREE status and doesn't belong to users.

Then a user can select one article record and edit it.
Note : user can edit only the article records that has FREE status .
Also the user is able to edit the record that it is belong to him/her

He/she is able to edit only Status. and set it to another case [in progress , finished or free]

After editing the specific article record, the other users are not able to edit this record.
but the last users who have edited this record is able to edit status field.

after editing a record, the belongs_to field is set to the name of user who has edited it.

For example user1 open a Free status article record and edit it's status to in progress , or finished.

Note: if a user edit his own record' status field from "in progress" to FREE , the belongs_to field is set to empty.

Note: The users are not allowed to edit the records that their status is Finished. [only admin can do it]

There is a page [created by view] that users can see the records. which article records are free, which articles are in progress ? which are finished. and also the users who are working on articles....

Now what is your suggestion to implement this plan?

I would look into the Node Access User Reference module as well as a lot of the other content/node access modules out there, eg, this list off drupal.org.  After getting a good grasp there, it would be up to you to code up the integration of permissions unique to your site, but basically you would need to alter the node forms for this content type, check in there if a user reference is NOT yet set, and if so, set it to user editing the content and then be on your way.


Cannot install core in the root of site I am going absolutely insane.  I have been up for several hours scouring the internet, installing, removing, installing, removing, and I CANNOT get Drupal (7 or 8) to install at the root of a site (hosted Linux server, not local or vm). If I try to run the drush si with the package outside of the target site's directory structure I get the site-install needs a higher bootstrap error.  Of course, if I move the the install base into the root of the target site's directory, it installs fine...in a subfolder with the name of the install base! I have followed all of the documentation, reviewed hundreds of comments on multiple sites, watched YouTube videos, looked at Pluralsight tutorials.  I am at a loss. I saw suggestions to edit the settings.php file (which the install package creates during the install process and doesn't exist beforehand...). I saw suggestions to rename files that are not yet existant because the install hasn't happened.  I'm sure much of these apply to an upgrade, but not a new site install.  Can anyone please offer some insight into this.  Installing with drush is supposed to make things easier. I have now wasted 4 hours trying to figure this out when I could have just manually installed it. But now it's principle.  I want to know. Besides I might have to do this again for other sites.  Thank you in advance.

When you download and install Drupal, it will install inside the directory that contains the files. So if you download Drupal into public_html and the directory with the Drupal files is called "drupal" it's going to install in public_html/drupal. Depending on what server you are running, you will need to identify the new webroot. In this example, you would change the webroot from public_html to public_html/drupal. The folks over at StackOverflow or your hosting company should be able to help you with your specific server settings for your new Drupal root.

Alternatively, you may be able to copy all the contents from the unzipped folder containing all the Drupal files into the webroot, but I've never tried that because I like keeping Drupal in it's own root.

Also, check sites/default/settings.php and see what it says for your Drupal root.


Compare two menu tree objects I'm trying to add custom css class to a particular menu, same task mentioned here.

I moved a little further and found this article. So I put following code in template.php:

<?php
function phptemplate_menu_tree($tree) {
  if ($tree == menu_tree()) {
    $output .= "
";
    $output .= $tree;
    $output .= "
\n";
    return $output;
 } else {
  return '
'. $tree .'
';

 }
}
?>

but constantly getting 502 error when trying to compare $tree and menu_tree().

Can anyone suggest what am I doing wrong?

UPDATE

I've fixed the initial issue in the question and posted the solution here. Hope it helps.

You cannot call menu_tree() from within theme_menu_tree() because menu_tree() contains a call to theme_menu_tree(). Your code contains an infinite loop.


Q&A/ticket system help with permissions I am trying to build a Q&A / Ticket System with custom nodes.
the current status is:

Nodes:

Company: on the company node you get a link with "I want to ask a question"
Question: on the question node you get a link with "add comment"
Comment: on the comment node you get a link with "add comment"

Multiple comments create a thread.

The relation is made with Node Reference URL Widget. The question node has a reference to  company. The comment node has a reference to question.

I have 2 user roles:

Company
Clients

Companies can only react on questions and comments related to themselves. e.g. pcpower can only react on questions for them and not on those asked to pcworld.

How can this permission be accomplished. For now a company can react on all questions.

Clients: can ask questions to anyone (is working) BUT must only reply on comments/reactions on subjects created by them.

At this moment clients can make comment to any question or comment in the system.

Any help regarding to this would be really helpful.

Kind regards,
Jos

You could accomplish this with a custom node.tpl.php for the content types - whereby it checks if the author of the node is the currently logged in user, and if not, it doesn't display the comments links (or the comments all together).


How to hide a published Taxonomy page unless you're an authorized user? I have a link on my website, I'm currently using Taxonomy Access Control Lite, I have a Taxonomy vocab "Manitoba" and I would like to not let the contents of this page be seen unless the user logged in has the permission role to view it.

How would I go about hiding contents from a page belonging to a taxonomy and all the sub-pages that entail?

To get tac_lite to work covering your question on a vanilla Drupal 7, one has to do the following:

Enable at least one tac_lite permissions scheme for the target vocabulary, in your case, "Manitoba" (scrsht.1)
Configure the scheme to allow 'viewing' for authenticated users (scrsht.2)
Create a node, e.g. an article and assign a term to it. Authenticated users should be able to see it (scrsht.3), anonymous not (scrsht.4).

Hope that helps!


Migrate user-data from a non-drupal site I have to migrate 9000 users (name, address, email, tel, photo...) from a non-drupal-site into a new drupal7-site.

How can I programmatically mimic the registration process and push the data in corresponding fields? And is there a way to change the original password, stored as a MD5-hash, to the drupal7-format while processing the data?

Thanks!

Take a look at the Migrate module.  From the project page:

  The migrate module provides a flexible framework for migrating content
  into Drupal from other sources (e.g., when converting a web site from
  another CMS to Drupal). Out-of-the-box, support for creating core
  Drupal objects such as nodes, users, and comments is included - it can
  easily be extended for migrating other kinds of content. Content is
  imported and rolled back using Drush commands.


How to make a form on the backend? I want to create a form for the backend in Drupal 7, something like the following:

label 1   text box
label 2   text box
label 3   text box
label4    image
image

I then invoke the form output in the front page and other pages.

You could do this by creating a content type with fields, or using Webform module. A lot depends on who will be filling out the form (anonymous visitors, content editors) and what you need to do with the results.


Generate PDF and send mail I have need to send pdf via drupal mail. I want to use tcpdf library but when im trying to use example i have error:
http: //..../tcpdf_example/download/simple

Fatal error: Call to a member function DrupalInitialize() on a non-object in C:\xampp\htdocs\drupalac_gw\sites\all\modules\tcpdf\tcpdf_example\tcpdf_example.pages.inc on line 55

  $html = theme('tcpdf_example_basic_html');

  // Never make an instance of TCPDF or TCPDFDrupal classes manually.
  // Use tcpdf_get_instance() instead.
  $tcpdf = tcpdf_get_instance();
  /* DrupalInitialize() is an extra method added to TCPDFDrupal that initializes
  *  some TCPDF variables (like font types), and makes possible to change the
  *  default header or footer without creating a new class.
  */
  $tcpdf->DrupalInitialize(array(
    'footer' => array(
      'html' => 'This is a test!! Bottom of the page',
    ),
    'header' => array(
      'callback' => array(
        'function' => 'tcpdf_example_default_header',
        // You can pass extra data to your callback.
        'context' => array(
          'welcome_message' => 'Hello, context array!',
        ),
      ),
    ),
  ));

then somehow...

  ...
  $attachment = array(
  'filecontent' => $tcpdf->Output('', 'E');
  'filename' => 'test.txt',
  'filemime' => 'text/plain',
  );

  switch($key) {
  case 'notice':
  $langcode = $message['language']->language;
  $message['subject'] = 'example submission from' . $account;
  $message['body'][] =''. $account .' has submitted an example.';
  $message['params']['attachments'][] = $attachment;
  break;
  ...

What i need to correct to get rid of error?

Ok First off all Installing drupal TCPDF module is not enough to have working pdf-s. We are also obligated to download TCPDF libray from http //www.tcpdf.org/ and place it to drupal files so that library will be avaible like this

  C:\xampp\htdocs\drupalac_gw\sites\all\libraries\tcpdf\tcpdf.php

above will solve:

  Fatal error: Call to a member function DrupalInitialize()

With working pdf library sending emails with attachments is easy i have like this:

drupal_mail('module', 'notice', "to@mail","", array(), "from@mail");

where:

function module_mail($key, &$message, $params) {
  $attachment = array(
    'filecontent' => generatePdf("S"),
    'filename' => 'example-filename',
    'filemime' => 'application/pdf',
  );

  switch($key) {
    case 'notice':
      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from ';
      $message['body'][] ='my example.';
      $message['params']['attachments'][] = $attachment;
      break;
  }
}

And where:

function generatePdf($where="S") {
  $pdf = tcpdf_get_instance();

  $pdf->setFontSubsetting(true);

  // set font
  $pdf->SetFont('freeserif', '', 12);

  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 008', PDF_HEADER_STRING);

  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

  // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP+10, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  // set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  return $pdf->Output('example_008.pdf', $where);
}

Above is now my working example :)


Service provider not loaded I have:

services:
  entity.query.external:
    class: Drupal\m_entities\Entity\Query\External\QueryFactory
    arguments: ['@plugin.manager.my_entity_storage_client', '@my_entity.storage_client.response_decoder_factory', '@http_client', '@entity.manager']
    tags:
      - { name: backend_overridable }
  my_entity.storage_client.response_decoder_factory:
    class: Drupal\m_entities\ResponseDecoderFactory
    tags:
      - { name: service_collector, tag: my_entity_response_decoder, call: addDecoder }
  plugin.manager.my_entity_storage_client:
    class: Drupal\m_entities\MyEntityStorageClientManager
    parent: default_plugin_manager
  entity.my_entities.routes:
    class: Drupal\m_entities\Routing\MyEntityRoutes
    arguments: ['@entity.manager']
  access_check.my_entities.add:
    class: Drupal\m_entities\Access\MyEntityAddAccessCheck
    arguments: ['@entity.manager']
    tags:
      - { name: access_check, applies_to: _my_entity_add_access }

but my service provider is not loaded in below code:

ModifyServiceDefinitionsPass

$providers = $kernel->getServiceProviders('app'); // <-- not loaded in here
foreach ($providers as $provider) {
  if ($provider instanceof ServiceModifierInterface) {
    $provider->alter($container);
  }
}

how to make a service provider loaded?

services.yml files are not service providers.

ServiceProviders are to dynamically add or modify service definitions, a yml file is just content that's parsed and merged together with everything else.

If that's not loaded then my guess is that you named it incorrectly, but you didn't include the filename, please add that including the other files you have, specifically the info.yml file.


Disable past dates in date_combo Is there a way to disable the past dates in the date pop-up while using the date combo form api? Specifically, I have a date type field in a content type, on which I want to do this.

Help appreciated...

Use hook_date_combo_process_alter(&$element, &$form_state, $context).

I have used it in commerce discount module: while adding discount.

Example :

  $current_path = current_path();
  if ($current_path == "admin/commerce/store/discounts/add") {
   $element["value"]['#datepicker_options'] = array(
     'minDate' => 0,
   );
   $element["value2"]['#datepicker_options'] = array(
    'minDate' => 0,
   );
  }


What filter should be used for date field in views I am building a view for showing upcoming events.

I have my own content type with CCK field with format  Date (Unix timestamp)  and widget as Pop-up calendar. All works fine, but i views i don't know how to filter it out. I have shown the filter criteria in a screeshot and i don't know what to give in the value field.

You need to activate the date_views module to see the filters appearing in the Views module interface.


Embedding renderable forms api Is there any way to embed form fields (i.e. textfield) within other field (i.e. radios). I'd like to create something like radiobuttons list: first default and second (if selected) allow user to enter text value.
Maybe I should create custom compound cck field?

This module may help: Select (or other)

Or maybe you want use form alter and #state attribute: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states


Add some custom fields in Views exposed filters and preserve their data to Url (GET) I have a Views list of Boats and every Content Type 'boat' has a location. So I have created an exposed form that already contains a location <select>, and when changed, the boats are successfully filtered by the location selected.
I want to put other inputs in this form, like:

Check in Date
Check out Date
Number of visitors

But these data are not filters, they are just input that can be used in the next step (explained later).

Is there a simple way to add these custom fields in the exposed filter form (or look like being inside it somehow)?
How to retrieve this information, so when a specific boat is selected (that's the next step) the number of visitors,check in/out dates, etc will be shown in a similar form (Webform) which finally sends a mail..

Thanks in advance!

PS: I am a newbie on both Drupal and Drupal Answers!
I've searched but I am confused whether I should create a custom module or use an existing one that I currently am unaware of.

I think I found it! I got to the the Views' theme folder and did what exactly I show here!

Then the data-passing through different pages needs some script and is done!


Views: two filters on one term reference (=wrong join) Strange effect in my view:

I have a list of nodes. On of the fields is a term reference.

I want the list to only show nodes related to 3 specific terms. that's one filter.
I want the user to optionally select one of these 3 terms. that's another (exposed) filter.

It almost seems to work. But if the user selects that term from filter 2, in the sql, the first filter is rewritten to explicitly deny that term. zero results. In an almost duplicate display of that view, the same happens, but with one other term (of the same three).

So without selecting anything in filter 2, the sql is:

SELECT DISTINCT bla
FROM
{node} node
...
INNER JOIN {field_data_field_publication_cat} field_data_field_publication_cat ON node.nid = field_data_field_publication_cat.entity_id AND (field_data_field_publication_cat.entity_type = 'node' AND field_data_field_publication_cat.deleted = '0')
...
WHERE (( (node.status = '1') AND (node.type IN  ('publication')) AND (field_data_field_publication_cat.field_publication_cat_tid IN  ('48', '50', '49')) ))
ORDER BY ... LIMIT .. OFFSET ..

and as soon as I select one of the terms in filter two, it reads

SELECT DISTINCT bla
FROM
{node} node
...
INNER JOIN {field_data_field_publication_cat} field_data_field_publication_cat ON node.nid = field_data_field_publication_cat.entity_id AND (field_data_field_publication_cat.entity_type = 'node' AND field_data_field_publication_cat.deleted = '0')
LEFT JOIN {field_data_field_publication_cat} field_data_field_publication_cat2 ON node.nid = field_data_field_publication_cat2.entity_id AND field_data_field_publication_cat2.field_publication_cat_tid != '48'
...
WHERE (( (node.status = '1') AND (node.type IN  ('publication')) AND (field_data_field_publication_cat.field_publication_cat_tid = '48') AND (field_data_field_publication_cat2.field_publication_cat_tid IN  ('48', '50', '49')) ))
ORDER BY ... LIMIT .. OFFSET ..

The number 48 in the second query, second join seems fairly random. If I remove and reattach the filter it seems to change.

cat2 is only a left join, but in the where clause, the number 48 is required again. Thats why I get zero results.

What's going on ?

Notice that filters are by default added in AND logic. You probably want OR logic so the one filter does not affect the other.

Of course if the two fields are not relevant at all you should have used different vocabularies (e.g. terms and someothercategory)and not only terms


How do I implement hook_views_pre_render()? I need to alter the result of a view. I read I can use hook_views_pre_render(), but in a custom module. I don't have any custom module implemented and I would like to know where and how should I put the code in my project.

You need to read and understand the Module developer's guide first, then it's as simple as adding the following to your .module file:

function MYMODULE_views_pre_render(&$view) {
  // Do stuff with the $view object.
}


Drupal 8 master site for managing customer Drupal 8 sites? Possible? Question: Drupal 8 master site for managing customer Drupal 8 sites? Possible?

Goal:

There will be a master drupal 8 site developed for managing basic business modules.
These basic business modules should be available to all customer sites. (shared)
Also the user roles and users must be shared.

There is no 1 shared codebase.
There is also the need for customer site-specific modules that can be installed.
So log in with the credentials from the master site at a customer site is also needed.

A picture of the goal:

Research:

I have researched several solutions like:

Multi-Site
Domain Access

These solutions I have explored share the same code base.

Expected solution:

The solution that I want to achieve is no shared code base, each project has its own code base,
but also the modules of the master Drupal 8 installation.
This would come as basic business modules required for each customer site like
autopath and xmlsitemap.
So if I install a module on the master site must also be available in the customer site.

The master site code may be shared thus not 100%, but also not completely independent from each other.

Is that possible ? Are they better/other methods for achieving this goal ?

It sounds very much like you'll need two solutions. For sharing the code and parts of the configuration a distribution/install_profile makes sense (https://www.drupal.org/docs/8/creating-distributions). When you make changes to the distribution you'll need to write hook_update_N functions to make these changes on the sites that are using it. So updating a customer site becomes the number problem of deploying coding and running update.php (or doing a cli command).

With respect to sharing roles and users this I might look to do something different. Maybe integrate with a third party identity services that allows you to share the identities across your sites. The roles can be deployed as configuration as part of the install profile. Buried somewhere in this presentation https://events.drupal.org/dublin2016/sessions/no-compromises-%E2%80%93-react-relay-and-graphql-drupal-8 is something about integrating Drupal 8 with an identify provider. And there's also things like https://www.drupal.org/project/openid_connect


drupal 7 profile 2 how to create field profile url as NAME Why is it so hard to create a view so others can see it? I just read the instructions at dupal.org documentation and checked out ep#33 of daily dose but neither are helping.

My view is set up with a grid of fields filtered by type main profile. I can't get the names as link to profile; all I can get is profile:url which looks ridiculous.

How can I get my profile:url field to be the link for a name?

[url] == Profile: URL   <--- how is this inputed for replacement field?

Worked it out finally.

You need to add fields in correct order to then use replacement which is [url]

for link to profile name.


How to customize the add-to-cart form using hook_form_alter? How can add-to-cart form be customized using hook_form_alter.  Or better yet can layouts like display suite or panels be applied to the add to cart form using hook_form_alter?  I have custom line item types that I would like to show using some kind add_to_cart form regions in 2 or 3 stacked columns.

You can use this snippet to customize the add to cart form:

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // Your form modifications go here.
  }
}

The $form_id changes based on the product that is in it, so you have to check for the string at the beginning of the $form_id variable.

You can theme it and/or change markup in the form like you would a regular form.


How do I write this PHP query the Drupal way (database abstraction)? I am using the code below to evaluate if a panel pane should display. I've read the docs on database abstraction, but I just don't really understand how to apply it. Of course, the dpm values are for debugging.

(Just to be clear, this code is currently functioning exactly how I need it to, and I am not having any problems with panels itself. I just don't understand how to sanitize this the Drupal way to avoid injection.)

Any help would be appreciated. Here's the code:

// Gets NID of viewed node as well as the parent (passed by entity reference field)
$nid = $contexts['argument_entity_id:node_1']->data->nid;
$parent = $contexts['argument_entity_id:node_1']->data->field_webisode_series_reference['und'][0]['target_id'];

// Returns the 3 newest nodes with same parent as the view node
$recentNIDs = db_query("
    SELECT entity_id
    FROM field_data_field_webisode_series_reference
    WHERE field_webisode_series_reference_target_id = $parent
    ORDER BY entity_id
    DESC LIMIT 3
    ");
$result = $recentNIDs->fetchAll();

// Checks NID of the viewed node against NIDs of the 3 nodes above.
// If true, and NIDs match, then the block is displayed.
foreach ($result as $k => $v) {
    $nid2 = $v->entity_id;

    if ($nid2 == $nid) {
        $top3 = 1;
    }
}

// If $top3 is set, display. Else, do not.
if (isset($top3)) {
    dpm('TRUE', 'top 3?')
}

elseif (!isset($top3) {
    dpm('FALSE', 'top 3?')
}

I think that you can review this answer:

  If you use db_query() all the time without directly inserting
  variables, but using the arguments.

I hope information be useful.


Re-writing View Comment link to display node title I'm trying to re-write the [view_comment] field in a Comments View with the [title]. I have the [title] excluded and I'm re-writing [view_comment] with [title].

What I'm hoping is to show the node title in the view and it will link to the latest comment on the node. I think I need to 'output the [view_comment] field as a link' possibly with node/???? (or similar) as the absolute link.

Can anyone point me in the right direction?

If you are using Drupal 7 you can take advantage of core's new API to create permalinks to comments.

From the patch on d.o

  Since comments are paged there is no way to guarantee which page a
  comment appears on. Comment paging and threading settings may be
  changed at any time. With threaded comments, an individual comment may
  move between pages as comments can be added either before or after it
  in the overall discussion. Therefore we use a central routing function
  for comment links, which calculates the page number based on current
  comment settings and returns the full comment view with the pager set
  dynamically.

In drupal 7, this routing function is

comment/%comment

So it would be best in your view (with comment as a base table) to pull out:

cid (display none)
title (node relationship, required)

Display title as a link, path it to

comment/[cid]

If you are using Drupal 6, I would suggest rolling with contrib to fix core - with https://drupal.org/project/permalink which backports the above functionality


What is the correct way to organise and separate functions in a Controller into their own files? Here is my test.routing.yml:

test.alpha:
  path: '/test/alpha'
  defaults:
    _controller: Drupal\test\Controller\TestController::testAlpha
    _title: 'Alpha'
  requirements:
    _permission: 'access content'

test.bravo:
  path: '/test/bravo'
  defaults:
    _controller: Drupal\test\Controller\TestController::testBravo
    _title: 'Bravo'
  requirements:
    _permission: 'access content'

sitelog.charlie:
  path: '/test/charlie'
  defaults:
    _controller: Drupal\test\Controller\TestController::testCharlie
    _title: 'Charlie'
  requirements:
    _permission: 'access content'

Here is my Controller: TestController.php:

namespace Drupal\test\Controller;

class TestController {
  public function testAlpha() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testBravo() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testCharlie() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
}

My Controller file is set to grow. I will be adding many more functions, and adding hundreds of lines of code to all of those functions.

What is the correct way of organising and separating out those functions into their own files, in a Drupal 8 project?

In Drupal 7 we used .inc files to keep files from getting too large. Sometimes a common.inc would be used to group reusable functions.

What I like about React is that functionality is broken up into separate components, into separate files. I prefer lots of files, containing a small amount of code, organised into folders.

I'd like to bring this same approach into my Drupal 8 projects, but follow the correct PHP standards/Drupal best practice. My goal being to improve: the readability of my code, ease of finding my code, and possibly, the organisation of reusable code.

There are a few things that you can do.

As already suggested by Jaypan, you can have as many controllers as you like, grouped by whatever makes sense for you. You can also have a base classes/hierarchy and re-use code through that
You can define services and also static classes/methods to extract re-usable logic (or also not-reusable logic). I'd say that's the 1:1 replacement for functions in include files. Services are defined in a yourmodule.services.yml and you can use dependency injection to make each service self-contained with explicit dependencies to other systems, so that you can also write (unit) test for that code.
You can also use Traits, a relatively new PHP feature that basically allows you to put a few methods into a separate file and include it in one or several classes where you can use them internally as if they were defined on that class. Kind of like a base class except that you're not limited to a single trait, you can have as many as you want.


What is the first function read by Drupal in a custom module? I've got a custom module working fine in Drupal 7.

In some pages, I have parameters in the URL that I'd like to get in order to perform certain actions.

For example, if a=logout or a=forgot_password or a=subscribe.

I'd like to know which function, in the mymodule.module file, is called first so I can check whether there's a special parameter and perform certain actions accordingly ?

Thanks in advance!

The first hook invoked is hook_boot(), if the Drupal variable page_cache_invoke_hooks is TRUE, otherwise is hook_language_init() (followed by hook_init()).

I am assuming the module is not implementing alternative versions of bootstrap functions; in that case, the version of cache_get() implemented by the module is called first.

About hook_boot() keep in mind that:

hook_boot() is invoked too early, when Drupal has not completed its bootstrap. This means that the only loaded modules are the ones implementing hook_boot(). Even in this case, your module can use function implemented from modules implementing hook_boot(), and already loaded from Drupal, which uses the following code.

foreach (module_list(FALSE, TRUE) as $module) {
  drupal_load('module', $module);
  module_invoke($module, $hook);
}

If your module is aaaa.module, and it tries to call zzzz_create_object() (where zzzz.module implements hook_boot()) from aaaa_boot(),  aaaa_boot() will cause an error message about a not existing function.
When hook_boot() is invoked, Drupal has not yet initialized its database, its Drupal variables (only when $conf['page_cache_without_database'] is TRUE), and its session.

As consequence, the functions hook_boot() can call are restricted. For sure, the functions the hook can call are the ones that are part of bootstrap.inc, and all the PHP functions (with some restrictions too).

References

drupal_bootstrap()
_drupal_bootstrap_page_cache()
drupal_language_initialize()
_drupal_bootstrap_full()


Why is cache_discovery not rebuilt on cache-rebuild? In my local dev environment drush cr does not rebuild the cache_discovery table.  I have to manually truncate it.  Is it because expire is set to -1 on all rows?  If so, did I mess something up in setting up this site?

I think I could add $settings['cache']['bins']['discovery'] = 'cache.backend.null'; in my local settings file, but then I'd have to truncate it in production when making changes like the one that brought this up.  This doesn't seem right.

Maybe I'm just missing a setting somewhere, but drush cr, rebuild.php, and restarting apache all leave cache_discovery exactly as it was.

If you truncate the table cache_discovery and then do a cache-rebuild the table is filled again with data, what would not be, if this was still a cache-clear. In D8 clearing the cache is more like rebuilding the cache, hence the new name. Some tables are still cleared, like the render cache or the twig cache, because these are filled with new data from the result of each request. But the structural data like discovery, router, config and some more are rebuilt, so that the first request after clearing the cache doesn't take too long.

If you set $settings['cache']['bins']['discovery'] = 'cache.backend.null';, then you freeze the table content. It is not touched, even not by a cache rebuild, until you remove this setting.


Adding CSS around taxonomy terms in node field In my node, I have a taxonomy field that displays one or more taxonomy terms (as plain text using DS).  I want to wrap a CSS class around the term, depending on the term value.

Where is the best place to do this?

I did this in preprocess_taxonomy_term(), and just added to classes_array.


How to use contexual filters for registration events? I want to create a block on the side of the page that will show registered users to a event. I already have a event type and calendar system + a registration system.

When a user registers for a event, I can get the view to display it. However, it is displaying literally ALL registration users for ALL events. I am trying to get the contextual filter to just narrow it down to the specific event, but cannot get it to work.

Any help?

You don't use contextual filter for this, you need to use relationship.

Make sure the Registration Views module is enabled.

In views under Advanced, RELATIONSHIP click add and select User: Registration

Checkmark require this relationship.
Checkmark your registration type name.


How to call a function of one module in another module How can I call a function of one module in another module? I want to call uc_stock_adjust() function of uc_stock.module in my own custom module. Is it possible?

Here is my code so far:

function my_module_node_presave($node){
  if($node->type == 'add_stock') {
    $stock_value = $node->field_stock_value['und'][0]['value'];
    $sku = $node->field_sku['und'][0]['value'];
    if (module_exists('uc_stock') && function_exists('uc_stock_adjust')) {
      uc_stock_adjust($sku, $stock_value);
    }
  }
}

I want to add and delete stock of products by using reference uc_stock_adjust(), which is defined in uc_stock.module, in my custom module. But when I try the above code, it doesn't work.

It giving an error, and the error is:

  Notice: Undefined variable: sku in my_module_node_presave() (line 29 of \sites\all\modules\my_module\my_module.module)

To call the function of one module in another module:

If the function is not in the .module file, call module_load_include()

//Load node.admin.inc from the node module
module_load_include('inc', 'node', 'node.admin');

Call the function from the other module

function_you_want_to_call();


Git workflow for Composer-based projects I would like to install/manage Drupal with Git, Drush, and configuration synchronization.

Should I add core/ and vendor/ into the .gitignore so that instead of pushing/pulling core I simply update core on prod/dev and synchronize configuration only?

This way I could potentially manage a Drupal site with few repositories:

Repository for configurations
Repository for a custom theme
Repository for custom modules

When updating a module, this would be my workflow.

On development

git pull
drush up
drush config-export to-prod
git push

On production

git pull
drush up
drush config-import to-prod

I ask because it doesn't seem to make sense that I have to push/pull all of Drupal 8 with every update.

If your goal is to minimize the size of your repository, then you should use Composer, following the pattern described in the project drupal-composer/drupal-project.

One possible workflow would then be:

On dev:

git pull
composer install
drush config-export
git add / commit / push

On stage:

git pull
composer install
drush config-import

On live:

rsync from stage to live
drush config-import

The workflow you propose will not work. The command drush pm-update will not do anything if Drupal is already at the most recent version. drush pm-download is not a good alternative either, as it will overwrite portions of your code base. You could potentially repair this with a git reset --hard or some similar trick, but that would not be very clean.

If you do not wish to use Composer, your best option is to simply commit the core and vendor directories.


Time field in EntityForm How can I add a field in my entity form that allows the user to add time.
When I use date, I can add time field but there is always a date field.

I don't want the user to add date field, just the time (for time in and time out).
And also, I will use the value of that field in my query.

As per your requirement Timefield module will be the best choice(considering that you are using Drupal 7)

  Timefield is a Field API field for storing simple non-timezone time
  values, with an optional end time, utilizing a simple JQuery
  timepicker widget for input. Normally, you will want to use a Date
  field for all date/time values; however, this field is for use when
  you don't want to implement a Date field or have time values that are
  not dependent on the Gregorian Calendar, i.e., when Year, Month
  granularity is irrelevant.


Paginate results of entity reference widget type I have entity reference field with checkboxes/radio as the widget type. The issue is the I have hundreds of nodes and this results in a having a big list. Is there a way to paginate the results or have a "load more" button/link which loads more results via ajax?

I should mention that I tried the entity_view_widget module but had other issues with it and can't really use it for this project.

Found a nice article related to Entityreference Multiselectors here.

You can choose one from variety of options mentioned in above article which suggests using of

Using of Multiple Selects.
Using of Chosen
An additional possibility is the Dynamic Multiselect Widget.
Another option is Entityreference Views Widget
There is jQuery UI Multiselect
And Improved Multiple Select

Hope one of the above works for you :-)


is it ok to use system_check_directory in a custom module? I love the easiness of applying system_check_directory to a form field. You just add

'#after_build' => array('system_check_directory'),

to your field definition in a form and it does it all :

check if the dir exists

create it if not

check if it is writeable
report to the user

As seen (on TV) in the drupal core.
Indeed, it probably does a little too much - the extra .htaccess file ... Could that cause any problem ? The description of the function looks almost as if it was only for the system form.

Of course it is ok to use this function in a custom module as long as you take care of securing the form where this is used in. You should keep in mind that the error messages generated by this function could give valuable information about your file system to malicious users. If you limit access to the form that uses this function to trusted users only then there shouldn't be problem.

The function is tailored for core use, you can already see that in the way that it generates the .htaccess file depending on the #name attribute of the form array. But if you want to provide a configurable private directory to store uploaded files for a custom module then it seems like a convenient solution.


Why is this extremely simple form not getting an upcast entity from its route? I have a my_job_board.routing.yml:

my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'

(this is nearly identical to the route defined at line 56 of User module's user.routing.yml),

and a src/Form/UserRegisterForm.php:

<?php

namespace Drupal\my_job_board\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RoleInterface;

class UserRegisterForm extends FormBase {

  public function getFormId() {
    return 'my_job_board_user_register';
  }

  public function buildForm(array $form, FormStateInterface $form_state, RoleInterface $user_role = NULL) {
    var_dump($user_role);
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

(my buildForm() has an identical signature to that of Drupal\user\Form\UserPermissionRoleSpecificForm which corresponds to the route I mentioned above).

Visiting /my-job-board/register/employer gives me the following error:

TypeError: Argument 3 passed to Drupal\my_job_board\Form\UserRegisterForm::buildForm() must be an instance of Drupal\user\RoleInterface, string given in Drupal\my_job_board\Form\UserRegisterForm->buildForm() (line 31 of modules/custom/my_job_board/src/Form/UserRegisterForm.php).

If i visit the same path with string instead of RoleInterface as the 3rd typehint for buildForm(), I see the output of var_dump($user_role): string(8) "employer".

Why am I not getting a RoleInterface passed into buildForm()? What am I missing?

It seems entity routes (beginning entity.), like those in the user module, get the Drupal\Core\ParamConverter\EntityConverter converter automatically applied; other routes don't.

You should be able to apply it yourself easily enough:

my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'
  options:
    parameters:
      user_role:
        type: entity:user_role

See Parameter upcasting in routes for more info.


How can I ensure a user field is hidden by default for the logged in user? Module X provides a field-definition and attaches it to the user-entity.

Attaching metadata to the user in that way makes for a very convenient way to access it across the site.

However, by default, a logged in user will also be able to both view and edit this data, which is not always desirable.

Is there a way for the same module to ensure that this field is hidden by default?

If you don't want to depend from a module implemented by others, you can implement hook_field_access() in your own module. It is quite easy to change the access permission for an entity field, knowing its name.

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return user_access('edit field of interest', $account);
  }
  return TRUE;
}

$op is 'edit', or view'; $entity contains the object for the entity to which the field is attached; $entity_type is the entity type.

With a module that aims the specific fields for which you want to control the access, it is easy to enable the access control: Just enable the module when you need it, and disable it when the access control is not necessary.


How can I hide the title in a custom page made with hook_menu? I need to hide the title on a custom page created using hook_menu. I don't have a nid, so probably I can't use one of the existing modules to do that.

function mymodule_menu() {
  $items['mypath'] = array(
    'title' => 'My title',
    'page callback' => 'mymodule_page_callback',
    'access arguments' => array('access content')
  );
  return $items;
}

I know this could be done using this css

body#pid-mypath {
  h1.title {
    display: none
  }
}

but I want to know if there are other alternatives. I'm working with Drupal 6.

Not sure if processed on time but I would try using drupal_set_title. And making sure you have an if statement around the h1 or h2. So use drupal_set_title to create empty title and use:

if(!empty($title)){
echo '<h1>' . $title . '</h1>';
}


What's the difference between content type and node? I have been reading information about what is a content type and what is a node. I understand what a content type is (a collection of fields), but I don't know exactly the difference between a node and a content type.
In drupal website, I can read:

A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry
Content-Type is a pre-defined collection of data types (Fields) which relate to each other by an informational context

For example, I think an article is a content-type, but it seems that, at the same time, it's also a node. So I don't understand the difference.
It seems that a node is a super-category while a content-type seems to be a sub-category. Is it right? How would you explain to me as simple as possible?

Newcomers to Drupal who aren't tech savvy often struggle with the concept of Content types and Nodes.

I find it beneficial to remind them of the real world equivalent—forms and filling in forms.

Remember in the olden days when you were given a piece of paper out of a whole stack of them, with labels and boxes and you used a pen to fill in your information by hand (name, address, DOB, etc.) when applying for a college or anything?

The Drupal equivalent to a real-life stack of blank sheets of preformatted forms is a Content type. When you're creating a Content type in Drupal, you're actually designing a form of blank fields. You're designing a structure, it holds no data.

In the digital world, we don't have to have multiple copies of Content types, one is enough because it doesn't have to be printed on paper. It is printed on the screen and we can always use the same "source". That's way we only have one “Create article” form and not thousands of them like you have to in paper form.

When you fill in one sheet of paper in ink with your specific information it is considered one form submission. The Drupal equivalent to this one filled-in sheet of paper is a Node. Node is the actual data entered into the structure defined by the Content type. You can create many Nodes (data submissions) for a Content type.

When you want to publish an Article you are first presented with a form to fill—Create Article page. This is the Content type form. Once you enter specific data into it and Save, you have created one submission of that form, one Node. You can create many nodes, with different data, as submissions to the same form.


Trying to write my own Views filter handler Partially as an exercise, partially as a real need, I'm trying to wrap up a views plugin to provide a filter labeled Taxonomy Term: Has children terms - so to allow terms that do/don't have direct children (depending on the option form setting). So far none of my hits was successful, they all ended up in "Broken handler" messages. Most probably because I declare table relations the wrong way.

Looking at how taxonomy.views.inc does it:

$data['taxonomy_term_hierarchy']['parent'] = array(
  // ...
);

I tried:

function taxfil_views_data() {
  $data = array();
  $data['taxonomy_term_hierarchy']['tid'] = array(
   'title' => t('Has children terms'),
   'help' => t('Check if the term has direct children'),
   'relationship' => array(
      'base' => 'taxonomy_term_data',
      'field' => 'tid',
      'label' => t('Has kids'),
   ),
   'filter' => array(
      'help' => t('My Help'),
      'handler' => 'views_handler_filter_taxfil',
    ),
  );
  return $data
}

I am also unsure about the parent class of the filter handler to extend, but at this point I'm close to thinking it does not really matter, as there is bigger problem in front of it.

Usually the example/tutorials base on own tables that a module creates, whereas mine has to re-use the existing.

Could anyone point me to the right direction?

In your specific case, since "taxonomy_term_hierarchy" already exists in the views data, you want to implement hook_views_data_alter() instead, making your implementation much simpler (untested):

function foo_views_data_alter(&$data) {
  $data['taxonomy_term_hierarchy']['has_children'] = array(
    'title' => t('Has children terms'),
    'help' => t('Check if the term has direct children'),
    'filter' => array(
      'help' => t('My Help'),
      'handler' => 'views_handler_filter_term_children',
    ),
  );
}

As far as what filter to extend, a good one might be views_handler_filter_boolean_operator but you can just start from views_handler_filter too.


hook_form_alter isn't being called when node fails validation I'm noticing that hook_form_alter isn't being called when a page has errors that display a message from form_set_error.  Changes to my form aren't taking effect, and the error page is effectively broken.

I've tried to output a dpm statement in hook_form_alter, but it isn't appearing on the error page.

Is there a way to get drupal to call the hook and alter the form?

Forms are cached in Drupal so the form is loaded once (where your form_alter runs) and then it's loaded from cache to be reloaded when there are validation errors.

You should use an #after_build callback, which always gets run.

Just remember to return $element in your #after_build callback or you'll be getting WSODs.


Drupal 7 multisite setup white screen I have attempted to set up a Drupal 7 multi site set-up. I followed the instructions online and have one site (site1) that is setup like a regular single install Drupal site and a second site (site2) set up in the sites/sites2 directory. The sites use separate databases.

The issue I am having is that while site1 displays and operates normally, site2 only displays a white screen. When I executed the install.php script for site2, everything seemed to go normally until I actually try to view the site. Any ideas as to what the issue could be? I am sure that settings.php file in both installations is set up correctly so I am a bit lost.

Thanks.

It is impossible to tell you exactly what is wrong with the information that is given.  I run several multi-sites using separate databases, and they work as advertised when I set them up following the standard instructions.

The White Screen of Death is usually caused by some error in the PHP.  To see the error message, you need to turn on PHP error reporting.  To do this, add the following to the settings.php, just below the initial <?php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

This will usually show an error message that tells you where you've left out a semicolon or some other trivial PHP-error.

See also: https://drupal.org/node/1056468 and https://drupal.org/node/158043


What is the best way/api to load a node by node content type and a field value? Aside from plain SQL, is there any Drupal api to retrive node(s) by passing a node CCK type and a field value?

For example, I would like to get the node which is an Assignment CCK type, by matching an integer CCK field Assignment Score value >= 65.

In PHP.

In both D6 and D7, you can use Views. Explaning all of Views is out of scope for this answer, but you can either add two, "Filters" one on content type, and one on field value. This however will require reconfiguring the View if you want to change the score, or type. If you add the same filters as "Contextual Filters", or "Arguments", depending on your Views version, the values can be pulled from the URL. This will allow completely different listings with a single view.

Two URL examples for using contextual filters:

example.com/results/easy_assignment/50
example.com/results/hard_assignment/75

In D7 you have entities, and could in code do:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'assignment')
->propertyCondition('status', 1)
->fieldCondition('field_assignment_score', 'value', 65, '=');
$result = $query->execute();


How to implement User registration settings email in my registration form I have a custom registration field that i have in my drupal 6 site.Once a user has been registered a mail will be send to the corresponding user with his or her account credentials.I have used drupal_mail function for this purpose.Is there any means by which i could create such a mail through the back-end. I have seen User e-mail settings.Is it possible to implement this mail function through the back-end rather than programatically. Is yes i would be really curious to look up on that.Hope someone might help me with this..

You could use the Rules Module for this.

Steps:

Define an Event that whenever a registration is there.
Then Define the Action to send Mail with proper Format.

For more details about the Rules module go through README.txt of this module.


hook for maintenance mode I would like to send an email to some users, when i put my Drupal-7 website in maintenance mode. Are there any hooks that allow me to do this? I could not figure it out for myself.

As @Clive said you can use hook_form_alter() or hook_form_FORM_ID_alter() and add extra submit handler to send email notifications.

function YOURMODULE_form_system_site_maintenance_mode_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'email_system_settings_form_submit';
}

function email_system_settings_form_submit($form, &$form_state) {
  // Add your email code here
}


Adding block below Header Logo I am placing a couple of static elements into the header, the issue is that the elements are being placed below the menu instead of below the header logo. Is this possible to put the block below the header logo image? I had to hack the css with a negative left margin and absolute top for now but it does not behave properly when elements are declared above it. (e.g. if admin logs in, or is not logged in, will affect the position vertically, etc)

If you are trying to place some block below the site logo, there should be a region below it. CSS come later.

If your block is going below menu, that means the region where you are placing are rendered below menu in the page.tpl.php

You have two choice here - either render the same region just after site logo or create another region in there.

Open your page.tpl.php & try to find -

<?php if ($logo): ?>
  /*more text*/
<?php endif; ?>

Render your region just after it (assuming your region name is header) --

<?php print render($page['header']); ?>

You can add DIV class or ID according to your need around it or do it in if-else, like -

<?php if ($page['header']): ?>
  <div class="header" >
    <?php print render($page['header']); ?>
  </div>
<?php endif; ?>

You can add your own region in theme.info file if you don't want to use the same where you were trying to place your static content.


Duplicates in a View with Taxonomy I created a view that has a global combined fields filter setup to search through node's title and a set of taxonomy terms. It works fine but only if I include a "Taxonomy term: Name" field.

This field currently causes each node to appear in the results for each term that is assigned to it. I checked Aggregation Settings for that field but only have these options:[]1

I also tried the Views Distinct module which worked but at a great performance cost. Is there either:

a way I can include terms in the global combine fields filter that I haven't thought of or
a way to prevent the duplicate results?

Thanks for your help

You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation
settings for which fields you want to group by or distinct.


URL contains a number after node/nid: why? I have just inherited a site to maintain.

The site has many pages ending with /node/$nid. I notice that appending /x to the end of this URL seems to change nothing. That is, if I browse to http://example.com/node/123/1, I get the same result as if I browse to http://example.com/node/123/2.

What are those numbers typically used for? I notice that in my sidebar, it seems to be sending people to the /2 version.

Drupal's path-matching is greedy. The path node/%nid will match anything with that string at the start, that has a separator after it. e.g

node/%nid/1
node/%nid/giraffe
node/%nid/barack-obama
node/%nid/this/is/just/too/much

The 'extra' path segments are passed on as extra parameters to the item's page callback, whether it wants/uses them or not.

The page that you see at node/%nid/1 isn't different at all from the standard node/%nid page.

You'd do well to keep those URLs out of the page source at all costs, or make sure you have an appropriate canonical URL set, as Google will consider them duplicate content otherwise.


First four free - changing product pricing based on cart quantity in Commerce using Rules Brief:

Product with SKU "sample" has a unit price of £0.00
Once quantity > 4, product unit price is £2.50
First four remain free. E.g if five in cart = (4 x £0.00) + (1 x £2.50).

Currently I have the first two requirements working, I can change the price of a particular product once there are more than 4 items, my current problem is that because the unit price changes, it counts for the four "free". So currently 5 samples bill at £12.50, instead of £2.50.

You can see my rules set up here:

The easiest solution would be to apply a discount of £10.00 to the cart, but I can only see options to alter a unit price of a line item, rather than applying a discount to the order.

How should I do this?

Possible solution avenue

I added a second action "Add line item to cart" and created a product with value of -£10.00. The problem here is that when the quantity is reduced to 4 or below, the line item remains. I cannot see a rule option to then remove that line item.

You can add a custom rules condition for line item which will check next:

if the amount of items in cart is more than 4
if the current line item position is greater that 4 (load cart, sort cart line items by created date)

Use the custom condition in pricing rules for line item.


How can I manually edit the search options in a facet block? I have a facet for a field, the values of which are:

(FACETAPI DEFAULT)

yes (db: y)
no (db: n)
maybe (db: m)

By default, the facet shows all three of these options.  However, I only want to show yes or no to the user, and I want to include the value of maybe in both:

(WHAT I WANT)

yes (db: y or m)
no (db: (n or m)

What I have tried

I know I could try to do an OR search with the facet and rewrite my links to search both, but I don't want to give users the option to search just "maybe"; I only want two options, not three.

It would be great if there was a stable version of the Apachesolr Facet Builder for D7.  One can dream...

I am using the Facet API Bonus module but this allows me to "Rewrite items" or "Exclude items," not combine three items into two as I described above.

I read this wunderkraut article on extending Facet API but it covers adding sorts, plugins, widgets, dependencies, and the like-- not the facets themselves.

I also looked at this wunderkraut article, which suggests I should use something like hook_facetapi_facet_info_alter(), but I don't know how to edit the field values to combine them.

I decided to implement this by creating a new facet instead of editing an existing one.  This article describes the process.

The basic code looks like this:

/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_gender'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Gender'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_gender_getter_callback',
  );
}

/**
 * Getter callback for agg gender property.
 */
function MYMODULE_search_agg_gender_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  switch ($account->field_gender['und'][0]['value']) {
    case 'F':
      return 'f';
      break;
    case 'M':
      return 'm';
      break;
    case 'O':
      return 'fm';
      break;
  }
}


How do you apply timezone formatting to a date? I'm trying to build my own output for a date field *see Group multiple times by day (multi-value date field) *, but the problem I'm having is how to apply the timezone?

This article -> Date value to different date format and nearly every other reference out there tells me that it should be applied by default. But it isn't.

What I'm doing is theming the field with:

function theme_field__field_times($vars){
    $dates = $vars["element"]["#values"];
    foreach($dates as $item){ // there are many dates, so we'll cycle through each one
        $date = ('U', strtotime($item['value'])); // convert to unix time
        print('This date renders as: '.format_date('$date', 'custom', 'D d/m/Y - g:ia', '', date_default_timezone_get());
    }
}

Which outputs, for example, 27/07/2011 -1:10pm. The value should be 27/07/2011 - 11:10pm, or the date that my function spat out +10hours - the timezone ('Australia/NSW') that should have been applied...

date_default_timezone_get() is returning the correct timezone.

If I let Drupal render the dates using it's default field theming, the dates are right.

So why isn't the timezone being applied? How do I fix it?

The arguments you pass to the function are wrong; in particular, what you pass as last argument should be the one before it.
The arguments the function accepts are format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL), but your fourth argument is an empty string, and then you pass the timezone identifier as last argument, which should be the language identifier.
You are also using '$date' as first argument.

Try with the following call:

format_date($date, 'custom', 'D d/m/Y - g:ia', date_default_timezone_get()).


How do I read the node ID? I have few articles that were deleted by accident.

Can I add these again using their nids?

No, Node ids are unique.

But yes you can avoid this kind of issues in feature by using url alias in drupal as you can generate same URL for different node id if current node is deleted accidentally.

Documentation for URL alias https://www.drupal.org/node/120631


Views: if fieldvalue (external link) is set, use it, if not, link to node For my articles, i've added a field "external_link". If this link is set, the headline should link to an external website, and if not, the headline should open the articles detailview.

Now i have the fields of my view two fields, which are excluded from the display, the external_link, and the nid. And on the headlinefield, i can do a

"rewrite results -> output this field as a link"
and write either node/[nid] or [external_link],

but how to use conditions in views, to use the external_link if set, and the node/[nid] if not set? I'm new to Drupal and i have no idea how or where to add this condition...

There is no direct way of using conditionals inside of Views.  However, you might be able to fake it out with something like this:

Order the fields in your view in nid, external link, title order.
In your external link field, set empty field behavior to node/[nid]
Always use it as the link in the last rewrite.

In my just woke up and enjoying espresso before getting to some real work state of mind, this should do what you are asking for, eg, linking to node/nid if there is no external link, but using it if it exists.


How to theme a list based field I have a text field attached to my node.
The user can add an unlimited number of values.

I want to out put all the values as a HTML list in my node.tpl.php file.

Contemplate module suggests to use the following code to out put the field:

<?php print $node->field_body_list['und'][0]['safe_value'];?>

This, however, has two problems:
1) It only outputs the first value of the field.
2) It uses UND, which is apparently bad.

I have tried using theme developer, but it doesn't produce any code that I can use in my node.tpl.php file.

Any help would be greatly appreciated it.

It's easiest to stay out of node.tpl.php for this one and instead use a field specific template file.

You'll need two copies of /modules/field/theme/field.tpl.php in your theme folder. The first is an exact duplicate with no changes and the same filename. The second you should rename to field--field-body-list.tpl.php. Consult Drupal 7 Template Suggestions if that filename doesn't work for you.

In field--field-body-list.tpl.php I would change the div with class="field-items" to <ul> and the div with class="field-item" to <li>.


Should I use the Activity or Message module? I want to create a view of user activity on my social site as shown below:

User A is now following User B
User C just joined "My_Site_Name"
User D just gained 30 points for posting "User D_Blog"

I have the user points modules installed for assigning points and other modules such as entity and tokens are also in place, along with rules. What i am not sure is which module should i use: the Activity module or the Message module. I first thought of using the Heartbeat module but its functionalities are all in the Message module as well.

Heartbeat and Activity are both specifically intended for showing user activity (like on Facebook, Twitter, etc.)

Heartbeat is going to be deprecated in favor of Message.  According to the Heartbeat module page:

  This project will be deprecated. The future would be in the module
  Message. It's much smaller and it cannot be compared to heartbeat when
  it comes to features. However the possibilities as API would be the
  same.

Note "the API possibilities are the same."  This means that you will have to write custom code to get Message to do what you want, but as a result you will have more control than the Activity module.

Use the Activity module if you want a solution that works mostly out-of-the-box; use Message if you want to have a highly custom configuration.


Current Password issue for New Register User My registeraion is set to "Require e-mail verification when a visitor creates an account" on Drupal 7. Any user who register will automatically receive a confirmation email with "One time login url". However the problem is, user does not have the "Current Password" to set their new password. How can I fix this?

PS: user does have current password on database "users" table

added info:
using module logintoboggan

added on July 2nd:
I found a similar issue from Durupal.org, but i dont wanna use another module to solve this issue.

with the one time login the user is logged in automatically and he can set the password without inserting the current one.


$(...).accordion not a function error in drupal7 views accordion module I had enabled a views accordion for a field in view. On displaying it in a page its not working and I got an error "$(...).accordion is not a function". Can any one help me in solving this?

Install the jQuery Update module and set jQuery of your website to 1.7+.


Use Twig to render HTML email body for SwiftMailer I have a custom module with a controller where I'm building a PDF file with a node's data that will be mailed to a certain user.

I have installed the SwiftMailer module and I have been able to produce my desired outcome, but it isn't very clean.

I was wondering if I could use a twig template to build the body of my HTML email. Is there anyway I can make use of Drupal's Twig Extension for this purpose?

I already created a email.html.twig file with the layout I need and I already have a $parameters array with all the variables I need to use in the template, but as SwiftMailer uses an HTML string in the setBody() method, I'm trying to use Twig to produce the HTML I need to use there. Any thoughts?

Please note that I don't want to use the twig template in my module ( to show a Drupal page or something), but rather have Twig render an HTML string I can use with SwiftMailer.
Also, the instructions for the SwiftMailer module regarding theming are rather confusing for me and they are for Drupal 7, so I don't see how I can make use of them in my case.

Any help would be very welcome!

Sure, that's possible. It works exactly as if you would render something for the page.

After preparing your render array like you always do, all you need to do is call the renderPlain() method of the renderer service, that gives you a string (Actually, a Markup object containing a string).

contact_mail() does exactly that, the relevant part:

$build = entity_view($contact_message, 'mail');
$message['body'][] = \Drupal::service('renderer')->renderPlain($build);

PS: The fact it is a Markup object is important, do not try to cast it to a string.


Don't print $title on certain content types How would you go about not printing $title on only the 'article' content type? Do i do this through theme-settings.php or page.tpl.php?

Here's a start, but I don't think I'm going in the best direction with this in the theme file.

if ( !empty($node) && $node->type == 'article') { }
else {
  print $title;
}

There is also a module for this:

Exclude Node Title

  Info

  This module handles a very simple functionality, decide whatever to
  exclude a node title from full node page or node teasers.

  It provides a checkbox on node-edit pages for easier exclusion.

  Also provides the option to hide all titles of a certain Content type.
  From the administrative interface you can select a content type to
  hide title for.

And if you have Display Suite installed then this article explains how to do it with that module:

Hide “Page Title” quickly using Display Suite in Drupal 7

  This is something that is so simple to do, once you have figured out
  the steps to get to the right little click boxes to appear. I wish
  that it were more intuitive to find, but for all those who struggle
  with “hiding” the page titles, Display Suite makes it really easy to
  choose to hide the page title for a specific Content Type or for a
  particular Node.


How can I re-write feeds xpathparser data? I have a feed content type with an author(s) field. Some of the nodes have several authors, so I am able to explode the data into an array with feeds tamper. However, I'd also like to re-write the author entries from LAST_NAME, FIRST_NAME to FIRST_NAME LAST_NAME. Before I dive into writing a plugin, I was wondering if there were another option for this, it seems like a common use case.

You can use the REGEX find/replace plugin in Feeds Tamper to do it.

Find: ([^,]+),\s*([^,]+)

Replace: $2 $1

Note: The above regex is more-or-less a guess and assumes that there are no commas in the FIRST_NAME or LAST_NAME.


How do I render the 'user_picture' of a user account? I load a user object, and I would like to be able to show the user's picture somewhere. I tried the following code.

$row_user = \Drupal\user\Entity\User::load($uid)->user_picture->first()->view('large');

What I get is this (using kint()).

This user has a picture and it is shown correctly in the user page.

How do I exactly show the picture associated with a user account?

Just like every other render array, render it.

If you print it out in twig, that just works, in PHP, use \Drupal::service('renderer')->render().