Add language switcher in section where i need I want to add the language switcher block along with menus as show in the example. Please see this website http://rafedh.sa . I want to do something like this. Drupal by default does this. But i am not able to move it to top to shown in menu. By default its shown at end of the node.

I am using this theme http://drupal.org/project/danland

Move the print render($content['links']); up, as this outputs the alternative language links (among others).


How can I use stemmer with Search API Solr but show non-stemmed results in the autocomplete form? I'm trying to use the Greek stemmer with Apache Solr. If I edit the schema.xml and add the lines:

    <filter class="solr.GreekLowerCaseFilterFactory"/>
    <filter class="solr.GreekStemFilterFactory"/>

in both analyzers (index and query) of the text fieldType, the stemming works without problems and proper results are being returned. However, the suggestions that are created both in the facets and in the autocomplete form, include the stemmed version of the various keywords. I suppose that this makes sense from a developer's point of view, but the stems that are produced have no actual meaning in Greek.

I did a lot of research (I'm not a Solr expert but I'm starting to learn the basic stuff due to this issue) and I'm hitting a wall. I tried to use many variations of the solution that is described in the question: "How to index fulltext fields with and without stemming" but I can't get solr to copy the fields that I'm interested in, into the dynamic fields that I create (I can see the dynamic fields in the solr interface but no content is copied to them). I even tried to use the filter only in the query analyzer and only in the index analyzer (you can guess how that went).

Any ideas on how I can get this to work properly?

This is not a "best practice" answer but it might help you get an acceptable result (at least till you figure out how to solve this):

Enable just the GreekLowerCaseFilterFactory in your schema.xml (not the stemmer).
Use the NGramFilterFactory to get partial results in your keywords. You can find information on how to do this here.


Customize admin content type page design i have created template file for my contenttype wallpaper but i don't know how to get form design in that page.

for example

my content type name is wallpaper, so i create template file for page--node--add--wallpaper.tpl.php in that page how to get title,body etc ..

(ie)node add to page design.

Thanks for advance

See Drupal 7 Template (Theme Hook) Suggestions

You can do something like page--node--edit.tpl.php or page--node--1.tpl.php

See the available variables in page.tpl.php

Also you can try hook_preprocess_page

<?php
function themeName_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add' && arg(2) == 'product')) {
    $vars['template_files'][] =  'page-node-add-type';
  }
}
?>


table view tr class row numbering I would like to have row numbers in my tr classes when displaying my view as a table. My rows seem to have only classes saying they're even and uneven.

Only possible in a tpl file?

Why dont you just override views-view-table.tpl.php by copying/pasting this to your template folder in your theme, then use $row_count for your classes.

<tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .' row-' . $row_count . '"';  } ?>>


How do I remove the Previous and Next links? The Previous and Next button links are causing accessibility errors and I would like to remove them (don't really need them for what I am using them anyway).

Is there a way to do this?

The error message is the following one:

  This button element does not have a name available to an accessibility API. Valid names are: title attribute, element content.

I have managed to hide the links from being displayed, but the error messages are still there. All I managed to do is get the css to set the display to none. Is there a way to completely remove the links from the code?

On the MANAGE DISPLAY of the content type that has this image edit the formatter for the colorbox image. There set the Gallery (image grouping) > No Gallery.


How to theme D7 search results The default search results in D7 seem to include details of the node author, date, number of comments as seen here but I don't want these in my search results.

I have copied search-result.tpl.php and search-results.tpl.php to my theme file. I have added

print '<pre>'. check_plain(print_r($info_split, 1)) .'</pre';

to search-result.tpl.php. The result is here ie showing the array with [user] [date] [comment] etc

What do I need to do to exclude author / date / number of comments from the search results? If it involves my theme's search-result.tpl.php what should be the contents of search-result.tpl.php ?

Copy search-result.tpl.php into your theme folder..

Override above tpl using below code..

<?php

/**
 * @file
 * Default theme implementation for displaying a single search result.
 *
 * This template renders a single search result and is collected into
 * search-results.tpl.php. This and the parent template are
 * dependent to one another sharing the markup for definition lists.
 *
 * Available variables:
 * - $url: URL of the result.
 * - $title: Title of the result.
 * - $snippet: A small preview of the result. Does not apply to user searches.
 * - $info: String of all the meta information ready for print. Does not apply
 *   to user searches.
 * - $info_split: Contains same data as $info, split into a keyed array.
 * - $module: The machine-readable name of the module (tab) being searched, such
 *   as "node" or "user".
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Default keys within $info_split:
 * - $info_split['module']: The module that implemented the search query.
 * - $info_split['user']: Author of the node linked to users profile. Depends
 *   on permission.
 * - $info_split['date']: Last update of the node. Short formatted.
 * - $info_split['comment']: Number of comments output as "% comments", %
 *   being the count. Depends on comment.module.
 *
 * Other variables:
 * - $classes_array: Array of HTML class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $title_attributes_array: Array of HTML attributes for the title. It is
 *   flattened into a string within the variable $title_attributes.
 * - $content_attributes_array: Array of HTML attributes for the content. It is
 *   flattened into a string within the variable $content_attributes.
 *
 * Since $info_split is keyed, a direct print of the item is possible.
 * This array does not apply to user searches so it is recommended to check
 * for its existence before printing. The default keys of 'type', 'user' and
 * 'date' always exist for node searches. Modules may provide other data.
 * @code
 *   <?php if (isset($info_split['comment'])): ?>
 *
 *       <?php print $info_split['comment']; ?>
 *
 *   <?php endif; ?>
 * @endcode
 *
 * To check for all available data within $info_split, use the code below.
 * @code
 *   <?php print '
'. check_plain(print_r($info_split, 1)) .'
'; ?>
 * @endcode
 *
 * @see template_preprocess()
 * @see template_preprocess_search_result()
 * @see template_process()
 *
 * @ingroup themeable
 */
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

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

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>

Clear Cache

Author / date / number of comments from the search results is getting rendered using below code

<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

which we removed from above overridden tpl....

You can also remove it using below function in your theme template.php

function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
}


How to split and link date field to view (imdb style) I have created content type call person (list of persons)
added a date field to content type (birth_date)

how to split date to year/month (or should it be two date fields)
how to link year to all the people born on that year and month/day to all people born on that day. I know how to create view, but how to make date output as link to it?

Pretty match like imdb does it, not display calendar but text in one line.
birthday: year[link]/ month day[link]

Use module and code in your theme:

/**
 * Override theme_date_display_single().
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function theme_date_display_single($variables) {
  if($variables['dates']['format'] == "d F Y"){
    // In this case i keep only start date. For keep end date use value2.
    $date = $variables['dates']['value']['formatted_iso'];
    $timezone = $variables['timezone'];
    $attributes = $variables['attributes'];

    $day = format_date(strtotime($date), 'custom', 'd');
    $month = format_date(strtotime($date), 'custom', 'F');
    $year = format_date(strtotime($date), 'custom', 'Y');

    // Wrap the result with the attributes.
    return '' . '' . $day . '' . '' . $month . '' . '' . $year . '' . $timezone . '';
  }
}


How to create a Rule to email referenced authors after saving new content? I am trying to create a review platform. I have multiple content types, and I have created review content types which are referenced to these content types.

I want to create an action (tell me if you think there is a better way) which would send an email to the original content author to notify them that a review has been published about their content.

Any ideas how to do this or if it's possible?

Actually it's a LOT easier than I thought. I found that the following worked for me so far:

node:referenced-field:0:author:mail

I hope that this helps someone.


How to solve the error " Could not determine command name from tag @command" with Drush? I'm installing drush v9 on the server as well as I try to port my command. I did several things but now get the error:

drush status

In BespokeDocBlockParser.php line 65:

  Could not determine command name from tag @command

I really have no idea where to look. I googled for the php file but could not even find it :-(

Any suggestion is appreciated.
...

I removed the drush.services.yml and rebuild the cache.
Drush status is now giving normal feedback so probably it is sometiming in the drush command.

My drupal.services.yml

services:
  tb.commands:
    class: \Drupal\tb\Commands\TbCommands
    tags:
      - { name: drush.command }

My generated php template

<?php

namespace Drupal\tb\Commands;

use Drush\Commands\DrushCommands;

/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 *
 * See these files for an example of injecting Drupal services:
 *   - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
 *   - http://cgit.drupalcode.org/devel/tree/drush.services.yml
 */
class TbCommands extends DrushCommands {

  /**
   * Start data collecting for the traderbot
   *
   * @param $para
   *   parameters in case i need this
   * @validate-module-enabled tb
   *
   * @command
   * @aliases tb,traderbot
     */

    public function traderbot($para) {
      // See bottom of https://weitzman.github.io/blog/port-to-drush9 for details on what to change when porting a
      // legacy command.

    tb_log(3,'Start runnning traderbot from drush');

    tb_log(3,'End runnning traderbot from drush');

    }

}

The composer.json

{
    "name": "org/tb",
    "description": "This extension provides new commands for Drush.",
    "type": "drupal-drush",
    "authors": [
        {
            "name": "Author name",
            "email": "author@example.com"
        }
    ],
    "require": {
        "php": ">=5.6.0"
    },
    "extra": {
        "drush": {
            "services": {
                "drush.services.yml": "^9"
            }
        }
    }
}

function tb_log is part of the custom tb drupal module.

What is wrong?

The comment on the traderbot method is incorrect:

   * @command
   * @aliases tb,traderbot

There is no value after @command. I believe you want:

   * @command traderbot
   * @aliases tb

See: Porting Commands to Drush 9

Clear the cache after the change and try again.


JS and CSS in hook_preprocess_hook() In the project I am working on I have created a theme hook that renders a .tpl.php file:

/**
 * Implements hook_theme().
 */
function my_module_theme() {

  $theme['my_module_list'] = array(
    'variables' => array(
      '#markup' => array(),
    ),
    'path' => drupal_get_path('module', 'my_module'),
    'template' => 'templates/my_module_list',
  );

  return $theme;
}

Then I want some JS and CSS to be added only when this theme hook is used in the current page. Thus I implemented of theme_preprocess_hook() as such:

/**
 * Implements template_preprocess().
 */
function my_theme_preprocess_my_module_list(&$vars) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
  drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_module.css');
}

However it appears that the preprocess function is not called every time the hook is used resulting in CSS and JS not being added. What am I missing? Is it bad practice to add it there? And if yes where should I add it in order for it to be loaded only when necessary? I couldn't find any documentation that clarifies it and I've also seen it done other places.

Thanks a lot in advance :-)

I would add JS/CSS files inside the preprocess_page() function. If I don't want the CSS/JS files loading on some pages I will use an IF statement and check for a setting or if something exists etc, this will depend on the project.


Point dev URL to the default folder of a multisite In a multisite set up, the default domain www.domain.com point to the 'sites/default' folder.
I want a temporary subdomain point to the default site for development.
In the sites.php files I have:
$sites['dev.domain.com'] = 'default'; // this line can be removed due to the default behavior (see comment below)
$sites['sub1.domain.com'] = 'sub1.domain.com';
$sites['sub2.domain.com'] = 'sub2.domain.com';
$sites['sub3.domain.com'] = 'sub3.domain.com';
Pointing to the 'default' folder is not working for some reason?
What is wrong?

Above settings are correct. But there was an error in the DNS settings.


XML Sitemap for Media I'm looking for a module, that creates a special sitemap for media (using the Drupal Media 2 module).

You can use the Custom sitemap for achieving this

  The Custom Sitemap module allows users/site admins to add custom
  sitemaps to a site, unlike currently available module that binds users
  to build a sitemap using the primary menu.

  This module enables you to add or promote random URLs from SEO
  viewpoint. It also facilitates you to add independent sitemaps for all
  domains in a multi domain Drupal setup. This also helps you to have a
  domain specific custom sitemap.


Make the suggestions of an autocomplete exposed form clickable I'm using Drupal 7 and Views.
I have an exposed form of type "autocomplete".
I would like the suggestions to be clickable, which avoids having to click on apply.
Do you know how to do it ?

Install Better Exposed Filters module , got to your views, in Advanced section In Exposed form style: select better exposed .

The Better Exposed Filters module replaces the Views' default single-
or multi-select boxes with radio buttons or checkboxes, respectively.
Description fields and Select All/None links can be added to exposed
filters to make for a better user experience. Views Filters is a
powerful tool to refine the results returned by a given view. When you
expose a filter, you allow the user to interact with the view making
it easy to build a customized, advanced search. For example, exposing
the node type field as a filter lets your site visitor limit their
search queries to just blog entries. Better Exposed Filters gives you
greater control over the rendering of exposed filters.
Why use this module? Because it provides a better user experience than
the default option. Try telling a client that they should click on an
option, then scroll to the next option and ctrl+click on it. Don't
just click 'cause you'll lose your first selection. Oh, and ctrl+click
again to unselect an option... Yeah, not user friendly.

additionally,

What else can you do with BEF?.
The BEF handbook page provides some basic recipes making exposed
filters a much better user experience.
Add help text for each exposed filter Tame long lists with scrollable
checkbox/radio button lists or select all/none links Provide instant
feedback by updating the View using AJAX whenever an exposed filter is
changed Use the jQuery Slider widget for greater-than, less-than or
in-between types of filters If you've got any ideas not covered on the
handbook page, add a feature request to the issue queue. You can also
rate this module on DrupalModules.


Don't show a field when a more important field is shown in a View Drupal 7 On my homepage blog messages from the users are shown. When a user adds a Youtube movie and/or one or more pictures these are shown as a preview.
The thing is though that when a user picks a movie and one or more pictures the home page message show the Youtube movie and the picture. But when both are added to a blog message I only want to see the youtube preview, so Youtube is more important than the picture so the picture should not be shown.
When there are only pictures 1 picture is shown (this works fine).
How can I change something in my View to make it prioritize Youtube over the picture so it doesn't the picture when there is a Youtube movie.

Screenie of what I have now, so the picture has to leave:
http://imageshack.com/a/img844/1833/bqer.jpg

I have a multisite setup with 11 websites so the easiest solution is welcome :)

Thanks in advance!

Use the Views Conditional module. It does exactly what you want to achieve.

  How to use Views Conditional in your Views:

  Create a view. Add some fields under "FIELDS".
  Click on "ADD" next to fields. Scroll down to "Views: Views
  Conditional", probably found near the bottom of the list.
  Add and configure fields...
  Choose a field to run a condition against, and provide values
  accordingly.
  Save, views conditional handles the logic and returns as specified.


js file run again when file upload ajaxly I have a js file that I add it to my form in hook_form_alter with drupal_add_js, in my js I set a click handler on Html object(lets name it ".myhtml" ), everything work correctly in first load. I have a multi value image field in my form and when try to upload a image ajaxly , my js run again , and when I click on ".myhtml" my click handler called twice ( if I upload two image it fired triple and ... ).

One of my solution was first unbind then bind click,it work but I used icheck Jquery plugin for that  field,then when I unbind it( icheck plugin ) will not work.
So my problem is  prevent run js file to again when file uploaded by ajax.

part of my code
in hook_form_alter

    $scripts = drupal_add_js();
    $jspatah = drupal_get_path('module', 'tgdev') . '/tgsp.js';
    if(!isset($scripts[$jspatah])) {
        drupal_add_js($jspatah, array(
            'type' => 'file',
            'scope' => 'footer',
            'every_page' => FALSE,
            'weight' => 10,
        ));
    }

and part of my js file

 (function ($) {
Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      $(document).ready(function(){
            if($('#edit-field-images .image-preview').length==0){
            $('.form-item-field-feature-und-email .iCheck-helper ').on('click', function () {
                  if($(this).parent('.icheckbox_line').hasClass('checked')) {
                  console.log('checked');
                     getSubsAj('mail');
             });
             }
        console.log($('#edit-field-images .image-preview').length);
        });
      }
    };
})(jQuery);

Solution: Using jQuery Once

Drupal 7 integrates the Jquery Once plugin into Drupal 7 core. This plugin adds a simple class to the HTML element to ensure that the behavior is only processed one time. Here is how we would modify our JavaScript to work with the Jquery Once plugin.

(function ($) {
  Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      if($('#edit-field-images .image-preview').length==0){
        $('.form-item-field-feature-und-email .iCheck-helper ').once('click', function () {
          if($(this).parent('.icheckbox_line').hasClass('checked')) {
            console.log('checked');
            getSubsAj('mail');
          });
      }
    }
  };
})(jQuery);


How to check if parent variables My login form generated by theme_form() contains a password field, which is generated by theme_password().

My goal is to add certain variable into $variables of theme_password(). But ONLY in case, when parent's form NID == 5.

You can use your theme's template.php to add a theme_password() wrapper to inject your custom vars:

function MYTHEME_password(&$variables) {
  $node = menu_get_object();
  if(isset($node->nid) && $node->nid == 5) { //Check for display on node/5
    //@TODO: Add $variables altercation
  }
  return theme_password($variables);
}


Drupal 8 add javascript and pass data in a hook with custom module I am building a custom module with Drupal 8. One of the requirements of the module is that it sets up a javascript file based on the configuration settings, which the user of the module sets up in module configuration.

The javascript which needs to be added to the page depends on the configuration settings. Hence I can not add it using Libraries as mentioned in this article: Adding assets to Drupal module.

I first implemented it using a block. I use Twig templates to pass the configuration variables in PHP to the twig file, and in the twig file, I have a <script> tag to add the javascript based on the config variables. Refer Using twig templates.

The problem with this approach is that user needs to add the block on the page, and there is no UI facing element on that block. I also find it very messy.

Is there a cleaner way to add my javascript using hook and pass variables to it? I looked around and found hook_install and hook_page_attachments. So I can add Javascript, but don't know how I can pass any php variables to it.

I am new to Drupal development. Any help with this is really appreciated.

TL;DR I need to find a way to add Javascript using Drupal hook and pass some PHP variables to it.

You can add variables into the scope without generating a Javascript file and then use a hook like preprocess_html to add them in:

$variables['#attached']['drupalSettings']['mymodule']['config']['color'] = $config->get('mymodule.color');

These value(s) are then available in the drupalSettings scope, which you can read out in your module Javascript file in order to do things. Just pass drupalSettings into it.


Sending client to channel messages with nodejs integration I've been struggling with this for some weeks now and so far I have not found a proper solution yet. I guess this is a bug, but since there is no response on nodejs issue queue I'd like to ask this question here as well. (Drupal.org issue)

The situation:

I am working on a conference plugin using webRTC, where the initial handshake is done using Nodejs integration module. (Needed Nodejs for some other applications as well so I thought this would be the best way.) There is some documentation on how to send messages from client > node server > backend (> other clients). However for my handshake it has no added value to use the Drupal backend, so I want messages to go client > node server > channel.

The Nodejs integration module has settings for allowing clients to write to channels and in fact the messages arrive on the server, the server sends them to the connected clients and the clients reject the messages.

The idea:

I've tracked it down to the following piece of client side javascript in the nodejs module, where both message.clientSocketId and Drupal.Nodejs.socket.sessionid are undefined (thus equal) and the callback is left.

Drupal.Nodejs.runCallbacks = function (message) {
  // It's possible that this message originated from an ajax request from the
  // client associated with this socket.
  if (message.clientSocketId == Drupal.Nodejs.socket.sessionid) {
    return;
  }
  ...
}

Is there somebody who managed to get client > node server > channel communication using only JavaScript? Did I miss an authentication step somewhere?

Commenting out the return statement does work, but then clients respond to their own messages, leading to undesired behavior.

I can no longer reproduce this. Since the module did not update in the meantime I guess it a new version of socket.io that got updated via npm update.

The posts here have been of great help in further development of the functionality: http://theoleschool.com/tags/nodejs


Repeat the alt text and title text for a series of image field values I have created a content type for an image gallery, and added an image field with alt text and title tags and gave unlimited upload feature.

If I upload 10 images I want to give the title and alt tags 10 times. Can I bypass each individual image by giving these details one time and applying for all subsequent images?

Is this possible to do via the Drupal admin UI?

You could just implement a custom template for your field and implement whatever logic you require there.

So, in admin, you could enter the alt and title just for the first image, and then with the template you could apply the alt and title to all the images.

Does that make sense to you ?


Minus Userpoints for down votes I have configured Vote up/down module for voting. For every vote, content author will be awarded 5 points for up-vote, but i am facing problem for down votes! i can not understand how to minus userpoints for down-votes? Say, if a voter hit down vote then 3 point will be minus from userpoints!Installed Modules:

Vote up/down
Userpoints
Voting API
Voting Rules
Rule module...

As I mentioned on this answer already: I guess one of your problems is to determine wether upvote insert rule or downvote insert rule was triggered - vote up/down is storing this in two separate voting sets. (I might be wrong here, when I am good for you).

Let's say it is just one vote set and there are minus votes. you would have to adjust the positive check in the condition to a negative points check. I had my rules still in the environment so I cloned them and did those changes:

(minus points will be probably just negative grants.)

Event: User votes on a Node

Condition: User has role(s)
Parameter: User: [vote:user], Roles: authenticated user

Condition: Check the value of the vote
Parameter: Vote: [vote], Operator: is lower than or equal to, Data value: 0

Action
Grant points to a user
Parameter: User: [vote:user], Points: -3, Points category: General, Operation: Insert, Moderate: Use the site default

Export:

{ "rules_substract_down_voter" : {
    "LABEL" : "substract down voter",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "IF" : [
      { "user_has_role" : { "account" : [ "vote:user" ], "roles" : { "value" : { "2" : "2" } } } },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "operator" : "\u003C=", "value" : "0" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-3",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}

So there are still some things for you to check:

does vote/up down use one or two rule sets?
if it uses two, how to determine that in rules?
if it's only one with negative votes than you're done.


db_condition : nid = tnid I need to retrieve all nodes whose node ID is equal to their tnid, or whose tnid is equal to 0. I am using the following code.

$db_or = db_or();
$db_or->condition('nid','tnid','=');
$db_or->condition('tnid',0,'=');

$query = db_select('node', 'n')
  ->condition($db_or)
  ->fields('n',array('title','nid','tnid','type','language'))
  ->extend('PagerDefault')->limit(50)
  ->condition('type','article','=')
  ->orderBy('created', 'DESC');

It does not work. It returns 0 node IDs, which is not the expected result, since the following code returns a different result.

db_query_range("select * from {node} where (nid = tnid or tnid = 0) and type = 'article' order by created DESC",0,1000);

If I remove $db_or->condition('nid','tnid','='); the first query returns only nodes with tnid equal to 0.

So, why does the first OR condition break my code?

You need a where, condition always uses the value literally:

$db_or = db_or();
$db_or->where('nid = tnid');
$db_or->condition('tnid',0,'=');


Theme a specific view with Twig Is it possible to write a twig template for a specific view?  I have a view with multiple blocks and I want all these blocks to look the same.  But I am having trouble with my views actually knowing which theme to use.  I am trying to inherit the block.html.twig template but none of my changes render.

I am also afraid that my changes will change every block not just the blocks for that view.  How can i limit it to just my view?

Views in Drupal 8 has pretty much the same template options as in Drupal 7. If you are in doubt, what suggestions are offered, you should turn on twig debugging (settings in service.yml). You will get the suggestion output as HTML comments. Unlike in Drupal 7, Views in Drupal 8 does not have a button to see the templates files being used along with suggestions.

This might be added later as Drupal 8 is still in beta, at the time of this writing.


Allow non-admin users to view an EntityForm submission I've created an EntityForm wich authenticated users can submit.

Then I've created a view wich list every entityForm submissions and everyone can see this view.

Now I want to add a field to this view. This field will contain a link to this specific EntityForm submission.

2 solutions:
-Display the direct link "Entityform Submission: Link"
-Display an URL "Entityform Submission: URL"

As an admin:

Those solutions both work, but only as an administrator!

The link is invisible for non-admin persons.
The URL leads to a "Access denied - You are not authorized to access this page."

As a non-admin:

Question : How can I allow non-admin users to access entityForm submission pages?

Thanks!

By creating a new permission maybe ? Then create the access page via an menu item with the new permssion you created
Give this permission to non authenticated users then.


Selecting one result from database I am storing some data into the database

try {
      $fields = array(
        'uid' => \Drupal::currentUser()->id(),
        'value' => $form_state->getValue('blood_sugar'),
        'created' => time(),
      );
      Database::getConnection()->insert('blood_sugar_monitor')->fields($fields)->execute();
}

Later on I would like to check the latest inserted row to check if it was inserted within the last hour.

Could someone provide an example of fetching one item from the database?

You can follow the Database Abstraction API documentation. Although most of that documentation points to using the deprecated methods. You may find the current classes and methods, by clicking into each function that you need (such as db_select), and reading the deprecated messages.

This is very similar to what you have done for inserts (using Dynamic Query).

$id = Database::getConnection()->select('blood_sugar_monitor')
  ->fields('blood_sugar_monitor', ['my_primary_key'])
  ->range(0, 1)
  ->orderBy('my_primary_key', 'DESC')
  ->execute()
  ->fetchField(0);


Limit taxonomy terms that can be selected to 2nd level terms only? Is it possible to limit taxonomy terms that can be added to a node to 2nd level tags only?

So if my taxonomy is as follows:

Open

-forum1

-forum2

Closed

-forum3

-forum4

How can I limit the selections to forum1, forum2, forum3 and forum4, and exclude Open and Closed?

This may need to be a separate question but I also need to limit tags that can be created to 2nd level only. So a new tag would need to be a child or either Open or Closed.
Thanks

One way would be to install the Hierarchical Select module which gives you the option to limit selections to lowest-level terms only:

The module overrides the default widget for the hierarchy on the default taxonomy page as well, so it might even take care of your second question for you (although I haven't tried that myself before).


Statistics module not effect with Services module I created a Services Views, I added a Statistics field(total view) to the Views.

Then I try to use the browser to visit the node through RESTful api, like this url: http://daxuebao.local:8083/api/node/61

But, when I try to visit the Service Views, the Statistics field not effect, It still zero.

How to make Services support Statistics?

Statistics increments hits in hook_exit i.e:

statistics_exit

It's normally called as part of drupal_exit in drupal_page_footer

In any case, statistics_exit for the node counter actually checks

if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {}

That won't be true on an api request URL.

You might need to implement

hook_services_request_postprocess_alter

check the node request and make the stats increment call yourself.

Something like:

/**
 * Alter results of the services call.
 *
 * @param $controller
 *   Controller definition
 * @param array $args
 *   Arguments passed to services callback
 * @param array $result
 *   Array of results that can be altered
 *
 * @see services_controller_execute()
 * @see services.runtime.inc
 */
function MODULE_services_request_postprocess_alter($controller, $args, &$result) {
  // Increment hit count for node view api requests.
  $nid = $result->nid; // May need to confirm this is the node id.
  if($controller['callback'] == '_node_resource_retrieve'){
    // See statistics_exit()
    if (variable_get('statistics_count_content_views', 0)) {
      // A node has been requested, so update the node's counters.
      db_merge('node_counter')->key(array('nid' => $nid))->fields(array(
        'daycount' => 1,
        'totalcount' => 1,
        'timestamp' => REQUEST_TIME,
      ))->expression('daycount', 'daycount + 1')->expression('totalcount', 'totalcount + 1')->execute();
    }
  }
}


Aliases for user profile URLs For example, the URL http://example.com/user/20/edit/cocktail?destination=user%2F20 leads to a page with the form to add content.

I want to create an alias like bartender/add/cocktail, or
(if possible) bartender/profile/[current-loggedin-bartender-name], [current-loggedin-bartender-surname]/add/cocktail.

Is this possible? How can I do it?

Those kinds of aliases cannot be achieved by path auto, because as far as I know, it is difficult to add tokens into the menu settings. To help with this in the past, I have used the Me Alias module.


Send Email using rules or other module depending on a field value? What I'm trying to do is when a user creates a node on content type "Sample" with the field "Priority" set to "High" that said user will receive an email notification containing the field values of the node and a link.

I tried using rules but I can't seem to find a condition that supports a field containing value. I'm thinking into creating a hook function when the user creates a node. But the problem is I'm very new to drupal and I still don't know where to start. Can anyone enlighten me on what to do?

You would need to expose the node's field using the condition "entity has field" as the very first condition. Then Rules will allow you to select the field in the condition "data comparison".


Error embedding drupal views to twig template I'm getting an error Twig_Error_Syntax: Unknown "drupal_view" function when I try embedding my views to my twig template {{ drupal_view('newsdesk', 'block_1') }}.

I have already installed twig_tweak, twig_extensions and also installed twig_extensions via composer.

I'm not sure what else I'm missing, I've already also cleared the cache during installation

That's an error you would get if the twig_tweak module is not enabled, are you sure you have enabled it? If you have multiple clones of your site, make sure you're on the right one.


Group entity reference field by a field on those entities I have a content type of Location that has a list (text) field with options for Full Service or Quick Stop.

On another content type, I have an entity reference field that pulls in all the locations (using a select list widget).

On the node creation/edit form, I am trying to group those locations with optgroups into Full Service and Quick Stop based on the value of the nodes in the entity reference field (i.e. a location with field_location_type of "Quick Stop" would go into the Quick Stop optgroup).

Right now I am manually sorting them with the following, but it would be nice to do it automatically via my field_location_type field so that new options are automatically added.

$form['field_location']['und']['#options'] = array (
   'Full Service' => array(
      19 => 'Main Street',
      20 => 'Oak Hills',
      21 => 'Cherry Trail',
    ),
    'Quick Stop' => array(
      22 => 'Montreal',
      26 => 'Washington Place',
    ),
);

Use the module Entityreference View Widget and set up a view with grouping based on location type.

Alternatively, using custom code:

// Grab our list of all possible location types.
$location_types = list_allowed_values(field_info_field("field_location_type"));
$options = array();

// Cycle through each location type.
foreach ($location_types as $location_type_key => $location_type) {
  // Find all the nodes that are set to use this location type.
  // You may need to adjust this query if you need to limit it to only nodes of a specific type in the event you use field_location_type on other content types that you don't want showing up in this list.
  $efq = new EntityFieldQuery();
  $locations = $efq->entityCondition('entity_type', 'node')
    ->fieldCondition('field_location_type', 'value', $location_type_key)
    ->propertyOrderBy('title', 'DESC')
    ->execute();

  // If any nodes are found with this location type, add them to the options array under the appropriate location type
  if (!empty($locations['node'])) {
    foreach($locations['node'] as $location) {
      $options[$location_type][$location->nid] = entity_label('node', node_load($location->nid));
    }
  }
}

$form['field_location']['und']['#options'] = $options;


How to get the alt tag from an image field in twig? I have a page of field images which are coming out quite weirdly when I kint their values. I can't seem to get the image url and the alt tag.

The code in the twig file looks like this:

field--field-staff-gallery.html.twig

{% for item in items %}
    {{ kint(item) }}
{% endfor %}

It's output looks like this:

Now I can easily get to the url by doing:

{% for item in items %}
    {{ file_url(item.content['#markup']) }}
{% endfor %}

So how can I get the alt tag?

You can get the alt of image with:

item.content['#item'].value.alt


How can I customize the display of messages sent with privatemsg? Use case: When a user is viewing a private message (from the privatemsg module), I would like to display the following:

a picture field from the user's profile (not the user's profile picture)
a link to flag the user (to report potential abuse)

Senders should see values for recipients and recipients should see values for senders.  How might I go about implementing this?

What I've found out so far:

Out of the box, privatemsg cannot be overriden by Panels.  The Panelizer project is not able to add panes on, either.  There is a Privatemsg Panels sandbox project for which some work has been done but I need a more mainstream, maintainable solution.

Work on the D7 version of Privatemsg Views is currently stalled.

I've just implemented the Privatemsg Panels plugin with the D7 Patch through the pm_existing_pages plugin and it's working quite well! Here's how it all goes down for Drupal 7:

Grab the master branch of the privatemsg_panels module and upload to your modules directory
Patch Manager is super handy - install it and run the panels_privatemsg7.patch file to upgrade the module to a 7.x branch (or patch by hand or drush or eclipse etc)
Optional: Install PM Existing Pages and add override the default /messages/ path with a new panel. Of course you could create a new panels page just as easily.
Add content to your panel - Privatemsg should be a menu item now:
Create a nice little custom link block from the instructions over here - might be useful for your particular view!
Optional: override privatemsg-view.tpl.php for a more custom layout. I haven't quite got this far, will try to remember to update this when I give it a shot.

Edit - Adding info!

Overriding privatemsg-view.tpl.php works great, just remember to clear the cache after you add the file to your theme folder.
Take a look at the Privatemsg Theming Documentation. All of  the functions that start with phptemplate_ can be overridden by your own theme. Example: drop this into your template.php file

function YOURTHEMENAME_privatemsg_list_field__participants($variables) {
    $thread = $variables['thread'];
    $field = array();

    if ($thread['has_tokens']) {
        $message = privatemsg_message_load($thread['thread_id']);
    }
    if (!isset($message)) {
        $message = privatemsg_message_load($thread['thread_id']);
    }

    $participants = _privatemsg_generate_user_array($thread['participants'], -4);

    $field['data'] = theme('user_picture', array('account' => $message->author));
    $field['data'] .= '
'. _privatemsg_format_participants($participants, 3, TRUE).'
';

    $field['class'] = 'privatemsg-list-participants';

    return $field;
}

This will add a user picture to the recipients field! AWESOME! Just remember that each overridden fuction expects to have 3 things returned: a field, a header theme pattern, and a field theme pattern - the documentation explains it better than I can ;)
The functions at the Privatemsg Theming Documentation starting with theme_ can be overridden using a function YOURTHEMENAME_form_alter() hook. If you add this function to your template.php, drop dsm($form_id); dsm($form); in to get a better idea of exactly what form you're working with.
Looking to change column order around? It's easier than you might think - check out the drag-and-drop column order at /admin/config/messaging/privatemsg

There has been a bit of discussion about how to add custom columns to the output but I'm not there yet.. I'll have to point you at the Privatemsg Issue Queue for that one.

Good luck!


Remove drupal parameters from form submitted via POST When I submit form created with Form API, the POST variable contains values like form_token, form_build and form_id.

The problem is, I need to send submitted form values to external website. Is it possible to remove such values from POST request?

In particular, I am implementing redirection callback to commerce payment method

This callback is defined within Drupal Commerce. The callback works OK, but how can I remove the mentioned form parameters? (The third party payment service does not accept them in received POST variable).

I am not sure whether I can just unset them in hook_form_alter. This callback is just part of the order process and I am not sure if I  can just unset it.

You can make a call to external website using drupal_http_request in form submit handler.. Define extra submit handler using hook_form_alter and

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

For Example

// Adds a submit handler/function for your form

function YOUR_FORM_SUBMIT_HANDLER($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}


add amount to shipping cost per product I have some products type , I want when  a specify product type is in order add amount to shipping cost.
my idea was  create a rule with condition Order contains products of particular product types  ,and select action add a amount to unit price but  in  item identifier *
Specify an identifier of a commerce Line item section I try everything but returned me error.

I try commerce-order:commerce-line-items: and commerce-order:commerce-line-items:0,commerce-order:commerce-line-items:1 ,commerce-order:commerce-order-total:

but all of them return me Data selector commerce-order:commerce-line-items: for parameter commerce_line_item is invalid. error.

what I should input there ? is my idea correct way to add amount to shipping price when specify products are in order?

You're probably wanting the basic solution explained in this video: https://commerceguys.com/blog/using-calculation-rules-add-item-shipping-commerce-shipping-screencast

With a little modification, it looks like this:

Add a new "Calculation rule" for your shipping service.
Add an action loop that loops through the line items in the order.
Add an action "Calculate a value" and multiply the quantity times a field which holds the shipping price you want to charge for that item and store it in a named variable.
Add an action "Add an amount to the unit price" that adds the named variable to the unit price of the shipping line item.


Date ISO Custom format My Drupal offers only three types of rendering a Date ISO field (Display management in Content Type admin panel). What if I want to see my date in a different way? Is there any way to set my own formatter?

Second question. Is there any possibility to indicate while calling render(...) or field_view_value(...) (or anywhere else) what formatter to use? For example, I want for specific set of nodes to show not brief date variant but a full one. How can it be achieved?

There are two thing to do for the date format:

First create a date format (admin/config/regional/date-time/formats/add): this where you define how the date will be display and a simple PHP string date format is all you need something like 'm/d/Y' will show the date as 08/20/2012.

Once the date format is added you can use it on any "Date Type" (admin/config/regional/date-time) or you can create your own date type and assign the date format to it.

To display different date formats depending on what view of node is you have multiple options:

Use panels, views, context or display suite and format the date to your date type or date format
Edit or create a template for your node type (node--CONTENT-TYPE.tpl.php if D7 or node-CONTENT-TYPE.tpl.php if D6) and use the format_date function to format it.

if ($teaser) {
format_date($node->created, 'custom', 'Y-m-d H:i O'));
} else {
format_date($node->created, 'custom', 'H:i O Y-m-d'));
}

OR using your date type:

if ($teaser) {
format_date($node->created, 'DATE-TYPE'));
} else {
format_date($node->created, 'DATE-TYPE'));
}


How to create a profile page? I'd like to create a profile page (visible for every visitor) for every user on my website. There should be displayed some personal information about the user (name, date of birth, bio...) and some things related to their activity on the website (favorite articles, own articles...).

I've already added a lot of fields to users (wich have to be filled in during the registration) in the People > Account settings > Manage fields section and created some views with the Views module in order to display their favorites etc.

I'm struggling with the next step. I'm not sure whether I should create a profile page myself or use the Profile2 module (wich is installed at the moment). First of all, I don't know how I can create a profile page myself. How can I set this up, assign it to a user...? Secondly, I'm not very convinced by the power of Profiles2: I managed to add fields to a user's profile page, but I can't find a way to add blocks or views to it. A nice feature is the 'private' field option, but I'm wondering if that can't be realised without the module.

Can you help me in finding a good solution?

You can consider using Panels module to override the user page.

UPDATE:

You must be knowing default user page has path of form 'user/[uid]'. Now to replace that with our new panels page, visit this link: "admin/structure/pages".

There, you can enable "user_view".

Now when you edit that, you choose layout and content (add the fields). Then when you visit user page at user/[uid], the new layout will take effect.


How to create an Audio playlist Are there any opportunities to create "classic" playlists with Audio or any other similar modules? I primarily would like to let mp3-files be played, but in a way that it cannot be easily directly downloaded (considering the fact that as it's written on Audio module's admin interface, "You should be aware that even when audio is not marked as downloadable, clever users can still download it, this just makes the work harder.")

After uploading some separate Audio nodes, Audio players can be displayed via Views module like this (with some randomly uploaded tracks):

But this is NOT a good solution for me as it's not like a normal playlist, as these are separate audio players...
There is support in Audio module for the little bit ugly-looking XSPF Web Music Player - Extended, but I didn't find any opportunities to create a playlist with it either.

Any suggestions with Audio or any other suitable modules?
Thanks!

The http://drupal.org/project/jplayer module allows for playlists and so forth, but unless you are up for some obfuscated javascript and a whole bunch of other coding (that in the end is nevertheless subvertible [sp?]) the mp3s will still be downloadable by most advanced users.  (Or perhaps investigate the private file serving methods drupal offers, but then you have to balance the overhead there)


Converting Simplenews Subscribers to Users I was wondering if there is a way to convert SimpleNews subscribers into actual Drupal users?

Currently, I have something similar going on using custom fields in the user-register form, but wanted to know if I can leverage the Simplenews module for my needs.

I want to create a block where users can register to receive weekly e-mails in which they receive information about our weekly ad.

Cheers,

Elm

this may be useful
http://bouteillenicolas.com/expertise-drupal/simplenews-save-subscribers-info

All you have to do is use rules, create a webform, and then use rules that handdles that webform and create the suscriber and the the user using the information sended through the webform


If I use Panels and Views, do I need to use Blocks at all? My understanding is that if I go the full panels route (i.e. every node is a panel) then I only need to worry about prepping views to populate the panels. Is this the right way to think about it? Or am I missing something in regards to where blocks are still relevant for site building under an all-panels site?

Well, it depends on what your needs are.  Panels and Views is a very powerful combination that can handle almost anything.  That said, there may still be times when you need or want a block.  For example, the Heartbeat and Revisioning modules both supply useful blocks that I use on my (mostly Panels and Views) site.  Yes, these two modules have Views integration, but their built-in blocks are already configured and easier to use than customizing views to meet my needs.

If you need a custom block and are trying to keep things in Panels, you can add a custom content pane.  As a bonus, such panes can be exported with the Features module if you have a complicated deployment.


Allow tables in content with CK-Editor I have problems to configure my dupal 7 installation to allow entering tables.

I will add the link to the page I mean because not everytime sure that I use the right words.

I have created a type (admin/structure/types) which has four fields (admin/structure/types/manage/my-type-name/fields). The field body (admin/structure/types/manage/my-type-name/fields/body) has set filtered text as text processing. The selectbox under the CK-Editor has the value Filtered HTML. I tried to set its value to a custom clone of Filtered HTML which allows the attentional tags table, td, th and thead.

How can I allow tables for a special kind of type?

You can use Full Html to allow tr th and table but If you need to use Filtered HTMl for security reason you can use wysiwyg_filter Module that allow you to add some html tags to filtered html
about select box under ck-editor it's a permission problem that only filtered html appear


How to customize Commerce order admin view I would like to customize the Commerce order admin layout, the tables shown when admin clicks View or Edit in the Orders table.

These pages are typically shown on the following URLs:
yoursite/admin/commerce/orders/order_id/view and
yoursite/admin/commerce/orders/order_id/edit
where order_id is a number.

I want to add a custom column (a field from my product content type) to these tables. I have searched all the views which were created automatically when I installed Commerce but wasn't able to find the one which is rendering these pages.

In Drupal 7, Commerce 1 (7.x-1.x)

For the actual individual order page, you'll want to edit the view entitled "Line items (Commerce Line Item)"
Bear in mind however, the column you add may cause errors if the field only exists for some product types and not others. You might need to add an additional relationship to the view to get the field of data.

For the actual order summary page found at /admin/commerce/orders, you'll want to edit the "Orders" view.  You'll probably need to add a relationship for Commerce Order Line Items.


Get the submitted values of a multistep webform I need to get the submitted values of a multistep webform. It looks like webform doesn't save values from earlier steps in the usual place: $form_state['values']['submitted'] or $form_state['input']['submitted']. I just need the submitted values of every form component at the last page.

I actually made a custom submit handler to store the values from each form in my own location in $form_state, but I was wondering if there was a better way.

You will find the multi-page values stored in

$form_state['storage']['submitted']

Note that this array does not contain values from the current page and will be empty if the current page is 1.

And incidentally you can find out which page was just submitted by checking

$form_state['storage']['page_num']


Using pathauto for taxonomy pages I'm using pathauto on a D8 site successfully for pattern type Content using a pattern like this:

[node:content-type]/[node:title]

But I'm not having any luck at all when trying to use it for pattern type Taxonomy term using a pattern like this:

[term:vocabulary]/[term:name]

I just keep getting /taxonomy/term/123 instead of /taxonomyname/taxonomyterm

I have searched and searched and every article I find only covers the tokens for Content, not Taxonomy. I did find one youtube video that covered it in D7 and the pattern was identical to mine, yet his worked but mine doesn't. I've cleared caches and even tried bulk generate to no avail. But Taxonomy (list) pages don't create aliases though, so I'm wondering if that has something to do with it.

Have you actually tried to visit /taxonomyname/taxonomyterm?

The /taxonomy/term/123 isn't actually a taxonomy page, it is a Views showing content tagged with the term from the URL. It's a separate thing.

What do you expect to see on that page? Just the term name and description? That should work with the Pathauto as you have set it up.

If you want to see the content, like that Views page, you can use the Taxonomy term Views, Duplicate it and disable the original just for future reference, and modify the Contextual filters and Path to your preference.

You will need to add the Relationship to the term so you could use the Taxonomy: Name Contextual filter to get the term name in the URL.

You can also set up aliases for the default Taxonomy term Views so they use names, but I think it would have to be done manually, and isn't at all elegant/smart solution. It make more sense to set up the Views as you intend it to be used.


Custom validation for a custom field in comment form I'm currently trying to set up a custom validation script to prevent spam on a comment form with hidden elements.  The problem involves setting up the conditional for the submitted form values.  I'm currently using the hook_form_FORM_ID_alter.  Here is my existing code.

function STARTERKIT_form_comment_node_contact_page_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'comment_validation_function';
}

function comment_validation_function($form, &$form_state)
{
    if ($form_state['values']['field_website'] != 'http://') {
        form_set_error('field_website', t('Please do not change the value of this field.'));
    }
}

The problem is that $form_state['values']['field_website'] isn't returning the value inside the text field.  I've looked at so many pages showing a script very similar to this, yet I haven't been able to get this even close to working.

The field id is "field_website".

Assuming the field is a text type (and your site is monolingual) you'll find the value here:

$form_state['values']['field_website'][LANGUAGE_NONE][0]['value']

There's an explanation here.

Instead of doing this, though, you might want to have a look at the Field Validation module, which will let you add the same validation rule through the UI.


How to add a counter about the total number of nodes visited by a user? I have one block that display individual user details.

How can I add a counter which counts the total number of nodes visited by a user?

Have you checked the Node view count module: Node View Count module allows to count node views.

  Unlike statistics module, this module records each view of node with
  user uid and timestamp.

I guess at max. you only would have need to write the correct database query to get the count of total number of nodes visited by a user as rest of the things are being done by this module.


How to use Drush with Apache Directives? My Drupal installs are set up with apache environment variables/directives (SetEnv DB_NAME somedb) to store the database name, username and password. It appears that Drush isn't able to use these by default as it fails to recognise the apache directives. Is there another way of doing this or can I use some kind of alias or something else to pass the database credentials directly to Drush?

This is not a Drush function; it is a BASH function.  For example, you could do this:

DB_NAME=mydbestting drush status

Optionally, you could set your DB_NAME environment variable in your .bashrc file.

However, this is probably not what you want.  You would probably prefer to have Drush set the environment variable for you, after you specify the alias.  Drush does not have this feature, but there has been some discussion of it in the issue queue on drupal.org:

https://drupal.org/node/1848766


Applying image style to Privatemsg Drupal 7: Privatemsg.

The following statement, when included in the privatemsg-view.tpl.php template prints the author's picture:

print theme('user_picture', array('account' => $message->author));

How do I modify it to include an image style?

Any help is greatly appreciated. Thank you. :)

This is off the top of my head with some parts but I think this is the way you would do it.

print theme('image_style', array('path' => $message->author->picture->uri, 'style_name' => '{image-style}'));

With {image-style} replaced with image style that you want like thumbnail.

If this doesn't work I will take a second look.


Programmically populate select list with hook_form_alter I have no trouble populating other fields, but am struggling with populating a select lists #options. Anyone know of a slick way of going about that or have any good reference material?

I'm not sure to understand what do you want but here is a sample of code I've that may answer to your question.

$form['remise'] = array(
    '#type' => 'select',
     '#options' => array(
        0 => t('Sur les catégories & les marques'),
        1 => t('Sur les catégories uniquement'),
        2 => t('Sur les marques uniquement'),
     ),
    '#title' => t('Remises'),
    '#required' => TRUE,
    '#default_value' => 0,
  );


Pages with embedded views - a good aproximation? I have a view with a listing of nodes. I want to create a page which contains the view as a block and lots of others features. I have followed this approach, but it seems to me that it is a little clumsy and there are better ones:

1) I have created a new type of content, with no fields.
2) I have created a new node of that content.
3) In the template.tpl.php I have made a suggestion for that type of content, to load a specific page--type-of-content.tpl.php page.
4) In that page I embed (php) my view and all the other features.

Is there a more straighforward method? This one works, but it seems rather convoluted.

Maybe creating the view as Page and altering the page? How can I do that?

You better use Panles Module to display everything in a single page and It allows you create complex layouts

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.


How to do menu rebuild when having PHP Fatal error? I have been trying to get the command menu_rebuild(); to work on drush. However, I keep getting this error:

I, of course, think I installed Drush correctly. However, I can't be 100% certain since I've never used Drush before.

The reason why I am trying to run this command is because my admin menu is giving me problems. Whenever I install new modules, the settings pages corresponding to those modules are missing. Yet, they are installed and working according to Drupal.

Make sure you're running drush in your web root and drush status is showing Drupal bootstrap: Successful.

Then try the following steps:

drush cc all to clear the caches or clear cache tables manually, e.g.:

echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

try rebuild menu again: drush eval 'menu_rebuild();'
try rebuild your Drupal registry via:

drush -y dl registry_rebuild
drush rr

consider disabling caches

In case your drush status doesn't show Drupal bootstrap as Successful, you either running it outside of your Drupal webroot or your db credentials are not configured properly in settings.php, or you've some missing/corrupted files which prevents from bootstrapping your Drupal core.

If you're using multisite, then don't forget to specify your profile by either running inside sites/X dir or make sure you're specifying the right --uri parameter, e.g.: drush -l http://myprofile status (see: drush topic core-global-options for proper syntax).

If you still having the issue, try: drush -vd status to troubleshoot the source of your problem.


Oauth social login services not working Can any body help me out how do I accomplish social networking login using login using loginprovider.

I have done this for website using oauth connector.

I tried lot but no success for mobile services. What should I pass in parameters, end point I got is something like http://www.example.com/oauthlogin/api/login/info.json. Any body having  idea how legged process is done through oauth 3.x and services 3.x. Or any other options available?

I use HybridAuth Social Login for login system via social networks


How can I access the paragraph fields from my node via Tokens? Token Version: 8.x-1.7
Paragraphs Version: 8.x-1.12
I have one main node. In this main node I have referenced another sub-node. This sub-node has two fields with paragraphs. Each of these paragraphs consists of further text fields.
I would like to access these fields in the pargraphs by token. Unfortunately, I cannot find a suitable token for this. Neither in my token browser nor under /admin/help/token .
The only token with which I can access the field is the following:
[node:field_agent_reference:entity:field_gratification_for_agents].
But unfortunately this only gives me the whole content of the paragraph and not the fields individually. What am I doing wrong?
All other tokens that start with paragraphs, such as:
[paragraph:field_agent:entity:field_gratification_fur_agents]
[paragraph:field_agent:entity:field_bonus_number_or_percent]
[paragraph:field_percentage_media]
[paragraph:field_percentage_media:value]
do not function for me.
Thanks a lot
Bavra

The token browser stops spitting out chained suggestions after a sensible level of nesting - otherwise the memory use and (lack of) UI responsiveness could easily get out of hand. That doesn't mean that chaining stops, just the available hints.
You can keep right on going, e.g.
[node:field_agent_reference:entity:field_gratification_for_agents:entity:field_foo:value]


Customize days that can be clicked on a Calendar popup I am creating a form in Drupal 7 with the form API. Right now, I can create an ordinary calendar input field with the following code:

   $form['services_tab']['schedule_datepicker'] = array(
    '#title' => t('Pick the desired date'),
    '#type' => 'date_popup',
    '#date_year_range' => '0:0',
    '#date_format' => 'Y-m-d',
    '#prefix' => '
',
    '#suffix' => '
',
  );

Right now I can get the beautiful calendar popup to appear. What I am trying to achieve is enable or disable certain dates based on a rule like: disable all Saturdays and Sundays; or even remove the click state from specific dates based on a list of national holidays...

Is this something that can be achieved with PHP coding, or does it need to be done with jQuery? In case jQuery is the solution, I would appreciate any hints on how to do that... The calendar is a table, but table cells don't have an ID or something that could help me find and disable them based on a rule...

Thank you.

You can pass some Datepicker options from php to the date_popup element through the '#datepicker_options' key:

<?php
$form['date'] = array(
  '#title' => t('Pick the desired date'),
  '#type' => 'date_popup',
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

With this method you can pass almost any option but those that accept a function as value, as beforeShowDay, the one needed to restrict weekends or holidays according to the answer referenced by Nikit: https://stackoverflow.com/questions/501943/can-the-jquery-ui-datepicker-be-made-to-disable-saturdays-and-sundays-and-holid

Hence, javascript is required. First you need to include a custom js file from your module code:

<?php
drupal_add_js(drupal_get_path('module', 'FOO') . '/FOO.js');

and provide some code in FOO.js to extend the settings set by date_popup module with our own options.

Here's an example that add the basic option to disable weekends for all datepicker widgets in the page:

(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = $.datepicker.noWeekends;
    }
  }
};
})(jQuery);

Extend to holidays is left as an exercise to the reader :)

Note: the three occurences of FOO in my examples doesn't need to be the same literal, ie: you can provide a BAZ behaviour in BAR.js from FOO.module.

Update: to extend the above for custom days availability, just add a function returning true/false for the day received by parameters.

(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = checkDate;
    }
  }
};

function checkDate(date) {
  if ((date.getDate() % 2) == 0) {
    return [false, 'Even days not available'];
  }
  else {
    return [true, 'Odd days are fine'];
  }
}
})(jQuery);

You can find a more complete example in Date Restrictions module.


content profile title token issue (trying to write own module) /**
* Implementation of hook_token_values().
*/
function content_profile_token_token_values($type, $object = NULL, $options = array()) {
  $values = array();
  switch ($type) {
    case 'user':
      if (isset($object)) {
        $account = user_load(array('uid' => $object->uid));
      }
      else {
        global $user;
        $account = user_load(array('uid' => $user->uid));
      }

      $node_profile = content_profile_load('profile', $account->uid);
      $values['profile'] = ($node_profile->title) ? $node_profile->title : '';

      break;
  }
  return $values;
}

/**
* Implementation of hook_token_list().
*/
function content_profile_token_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens = array();
    $tokens['user']['profile'] = t('Profile title of authors content profile');

    return $tokens;
  }
}

I have created a module, and added a .info file as intended, but when I check the token list for a image field title I don't see any of the tokens implemented by my module.
What am I doing wrong?

UPDATED!!!

Now i see my token in imagefield token list, but it doesnt works == doesnt add content profile title for img...

It is not appearing because the ImageField module is using user tokens, for the image title, while your module is defining node tokens.
You can see this from the code in imagefield_widget.inc (imagefield_widget_settings_form()), which is the following one:

  $form['title_settings']['title_type'] = array(
    '#type' => 'select',
    '#title' => t('Input type'),
    '#options' => array(
      'textfield' => 'textfield',
      'textarea' => 'textarea'),
    '#default_value' => !empty($widget['title_type']) ? $widget['title_type'] : 'textfield',
    '#description' => t('Choose type of field to be displayed to the user.'),
  );
  $form['title_settings']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Default Title text'),
    '#default_value' => !empty($widget['title']) ? $widget['title'] : '',
    '#description' => t('This value will be used as the image title by default.'),
    '#suffix' => theme('token_help', array('user')),
  );

The tokens you define in your module are node tokens, which are not shown when the code calls theme('token_help', array('user')).


How to update the language in a existing node entity? Using kint($node) gives me some availables methods to use but none seems to be able to set the language of the node

By guessing i found $node->landcode which gives me a method setLangcode($langcode) but it does not work

After loading the $node->langcode->setLangcode('cat'); and $node->save();, the node in the interface still have not updated the language

You should be using the get()/set() methods (of the FieldableEntityInterface), sth like this:

// Get the current node's language.
$node->get('langcode')->value;
// Set the current node's language.
$node->set('langcode', 'de');
// Save the node to persist the change.
$node->save();

Hope this answers the question for you.


Template name does not take effect I got a field with xyz as machine name, and I created a field--field-xyz.tpl.php template file, but it does not take any effect.
I used the template file to add views-field and views-field-field-xyz as CSS classes, but they don't show up.

What did I do wrong?
Is it because I am using the Adaptive theme?

Does xyz field name contain underscores?

  Note that underscores in a Field's machine name are replaced by
  hyphens. Also remember to include "field-" in custom field names, e.g:
  field--field-phone.tpl.php.

https://drupal.org/node/1089656

EDIT:
Add a hook_preprocess_field(&$vars) in your theme and dpm($vars) to check up on theme_hook_suggestions array for this field.


Patch a contrib module with a patch that contains new files How do I patch the recaptcha module with the invisible recaptcha patch using drush make? I patch modules all the time in project.make.yml with yml that looks just like this:

...
# Recaptcha 8.x-2.2 - 2016-07-30
recaptcha:
  subdir: contrib
  version: '2.2'
  patch:
    # Integrate Invisible reCAPTCHA option from Google
    - 'https://www.drupal.org/files/issues/recaptcha-invisible-option-2852269-56.patch'
...

What's different with the invisible recaptcha patch is the patch contains two new files.

I would recommend you consider switching to composer and composer-patches. I don't think drush make is still actively maintained?

Quick google search pointed me to http://www.anexusit.com/blog/how-to-apply-patches-drupal-8-composer for example. That works fine, also for patches that add new files. The only case where that is a problem is core, due to different path structures in drupal/core and then it doesn't apply it correctly.


How do I remove /web from the URL? I have a site using Drupal 8.5 I installed with Composer.
When users want to visit the site, they'd normally need to add /web after the domain to access it. I have a cpanel redirect that redirects users from domain abc.com to abc.com/web, so they don't have to add /web.
This solution is still a bit silly because the visitors still see the abc.com/web while I really want it to look like a regular website domain, domain.com.

I'm not allowed to use virtual hosts, but I am allowed to use htacces or symlinks.
How do I "redirect" visitors from domain localhost/temp-project to localhost/temp-project/web/index.php without having /web in the URL?

--Update 2--
I've tried to add a .htaccess snippet (from GitHub) in my root (localhost/temp-project) to point to /web and browsed to localhost/temp-project:

#Redirect to www location with subdirectory
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} localhost/temp-project [NC]
RewriteRule ^(.*)$ /web/index.php[R=301,NC]

This just doesn't do anything, what's going wrong here?

You should have your host point directly to the "web" directory instead of your project root. I've run into this issue on webfaction hosting and my solution (actually my co-worker's) was to have 2 "apps." The first app is not web accessible and this is where my drupal-composer/drupal-project's root is. Then I create a second app that is web accessible, e.g. domain.com and is a symlink to the first apps /web directory. Maybe you can use this same approach.


Disabling node editing after first node flagging I use flagging for signing petitions. Petitions should be editable until the first signing (flagging) is done.

Now I look for a solution to disable node edition after first signing.

My first thought is doing it with Rules. I have access to flagging reactions, node type conditions but I have no action for editability of nodes.

Is there another way to get it done with Rules or something without it?

D7, no need of rules, place this code in your MODULE

function MODULE_node_access($node, $op, $account) {
 if ($op == 'update') {
  $flag='';
  $flag = flag_get_flag('YOUR_FLAG_MACHINE_NAME');
            if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
  return NODE_ACCESS_DENY;
    }
  }
}

done, enyoy.


How can i reload jQuery scripts after form submit in views using ajax? I have a views with ajax enabled using B.E.F. to filter some content. After submitting these filters jquery scripts stop working.
Please help me to find an answer how to reload any of these scripts after using submit button with ajax?
I`ve tried to do something like this and load it as a simple script using drupal_add_js in template.php:

Drupal.Behaviors.reload = function (context) {
jQuery(".form-submit").submit(function() {
  jQuery("table").stickyTableHeaders();
});
}

I know that this code can hardly work but still firebug says Drupal.Behaviors is undefined.

If you wrote your JS code like this.

(function ($) {
  Drupal.behaviors.tableStickHeaders = {
    attach: function(context, settings) {
      $("table").stickyTableHeaders();
    }
  };
})(jQuery);

It should automatically be reapplied when needed. This is the recommended way if writing JavaScript for Drupal.


Can't Create Content Type This is from the node_example from the Examples module on Drupal.org, I cut most part of them off now this should be an edited version of node_example.install: http://newstartpoint.com/public/node_example.install.txt

Now this is what I managed to get by myself: This http://newstartpoint.com/public/tudou_update.install.txt. This above one works but the one I programmed doesn't. Can anyone give me some ideas? They seem pretty much identical.

Thanks!

I think because of overriding 'base' property, change it to 'node_content'

  using the "base" return component of hook_node_info() as the function
  prefix. For example, poll.module defines the base for the Poll content
  type as "poll", so during creation of a poll node, hook_insert() is
  only invoked by calling poll_insert().


Link to send message is not displayed I am trying to get Privatemsg and DrupalGap working together.

I have installed both modules, configured the privileges and everything is working fine in the drupal site.

But with phonegap I am getting trouble displaying the 'Send this user a private message' link in the view of each user. I have set 'visible' the 'private msg' field in the drupalgap display in: admin/config/people/accounts/display/drupalgap but it's not working.

I have noticed It's always displaying only the history field even if I set to 'hidden' all the fields in the view configuration page: admin/config/people/accounts/display/drupalgap

I have cleared all caches.

What am I missing? How can I have the 'Send this user a private message' link displayed?

DrupalGap's implementation of Private Message has not evolved enough to take into consideration any Private Message configuration set on a DrupalGap Manage Display page for User Entities.

That being said, I would recommend creating your own page to custom render a User Entity. With these docs, essentially replace the usage of node with user and that'll give you a custom page in which you can render your users.

Then in your page_callback function to render the users, you can add a widget to the content render array, which could display a button that when clicked will navigate the user to a custom DrupalGap form+page where you can build the input elements (recipient, subject, message, etc).

Then in your form's submit handler, you'll actually send the message to the user.


Cron stopped running; logs say: "Attempting to re-run cron while it is already running." What are the steps to troubleshoot and resolve this issue as per title?

When I try to run manually, I get a  page immediately, and the error message "Attempting to re-run cron while it is already running."

Summary

The error message you are seeing would happen if the following two conditions are met:

You cron jobs do not finish (error) or take more than 4 minutes to finish ;
You invoke cron more often than every 4 minutes (According to your crontab setting, not the setting in Drupal)

This error message is therefore a symptom of a cron tasks that is either failing or taking too long to run. (Note: I realise you have already found the culprit, but I wanted to add an answer for people who find this page via searches, as I did)

Background

The first thing to understand is how Drupal cron tasks are run. The Drupal cron is invoked at regular intervals - either through a cron job on your server, or after every page load if you use the poor man's cron which is Drupal's default.

The cron tasks are not necessarily run every time cron is invoked however - there is a setting in Drupal (default is 3 hours) which says how often cron tasks should be run. But this delay of 3 hours only applies if the cron tasks have finished successfully.

In Drupal 7, cron uses Drupal's locking mechanisms, which provides a cooperative, advisory lock system. One of the features of this lock system is that locks expire after a certain time. In the case of cron, it expires after 4 minutes - so if your cron is invoked every 3 minutes and the previous cron job hadn't finished by that time (either it crashed or was very slow), you would indeed get this error message.

The fact you set the cron to be every 12 hours does not make a difference - because the Drupal cron task is failing/taking too long, Drupal assumes it hasn't been run so tries to run it again as soon as cron is invoked. The twelve hour delay only applies to successful cron runs.

The cron semaphore variable does not exist any more in Drupal 7 - this was for an older version of Drupal. In Drupal 7 there is no reliable way to manually release a lock, because the locking backend might change - however if you are using the core locking mechanism then you can release cron locks by editing the database:

DELETE FROM semaphore WHERE name = 'cron';

But by doing this you would only be fixing the symptoms - the problem that needs addressing is why is cron failing / taking so long to run.


Drush disable module updates email notifications Is there a Drush command to disable email notifications about Module updates.

You can turn off just the email notify feature like this:

drush vdel update_notify_emails

(See in update.fetch.inc: $notify_list = variable_get('update_notify_emails', '');)

You might also want to consider the following alternative:

drush pm-disable update

This will completely disable the update module on your live server, which will also disable email notifications about Module updates.  At first blush, you might be sad that you won't be able to see the module updates page on your live server any more; however, you should really be doing your updating on a development machine anyway, so you can just re-enable update on the dev server.

To automatically re-enable the update module every time you sql-sync from live to dev, see symc_enable.drush.inc.

Finally, to insure that your dev machine does not send out unwanted email notifications, enable the devel module, and then add to your settings.php file:

$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);
$conf['devel_debug_mail_directory'] = '/path/to/dir/to/save/email';

Then, devel will intercept all email that is sent and write it into the target directory instead of emailing it.


Allow Role to edit Custom Node Type This is for Drupal 6.

I have a module that creates a custom node type called program.
I have a role called "marketing" and it has a permission entitled "edit marketing copy"

I've used hook_access to grant update permissions to users who meet this criteria, but the edit tab does not appear on the content when I view it.

function programs_access($op, $node, $account) {
    switch($op) {
        case 'update':
            if(user_access('administer programs', $account) || user_access('edit marketing copy', $account)) {
                return TRUE;
            }
        case 'delete':
        case 'create':
            if(user_access('administer programs', $account)) return TRUE;
    }
}

I know that the user has the permission because the view template shows specific things based on permissions and those work as intended. I just do not receive the "edit tab"

How do I make the edit tab appear on the page for the user? What am I missing?

Check if the user has permissions to use that node's input filter.

If that is OK, try rebuilding the content permissions.


Drupal nodes VS direct database I am writing my first Drupal module and am having a little bit of a hard time wrapping my head around when I should use nodes vs storing data directly in the database. Is there any documentation I can read on this subject or does anyone have any advice on this?

I've actually already written most of the module entirely using direct database access and my own tables. I am planning on open sourcing it but I want to make sure I'm following common Drupal development standards and I think this is the most glaring error I made. So now I am trying to figure out how much I need to move from my own tables into nodes.

What started me down this path of looking a nodes is that I need to implement permissions. The module has a bunch of projects and I need to be able to control which users have access to each individual project and all the data related to it. It's not obvious to me how to do that using nodes so I was considering doing this as yet another table in the database.

Typically Nodes are content. Permissions in a webapp are typically not content. Content is a piece of factual text, an image, an uploaded pdf.

It sounds like you want to look at the Organic Groups module.


User role can't view/edit their own unpublished content I have a Drupal 7 site where users have a listing they can edit.

This all works fine when the listing is published but as soon as it's set to unpublished they can't view the page or the edit page.

They've got all the relevant permissions:

View own unpublished content Edit own content

I've even got the Override Node and View Unpublished modules installed but still I get the page trying and trying to load but never actually loading.

As soon as I set it to published it's all fine.

Open to any ideas.

Thanks

For me, the solution was to enable the "Bypass content access control" permission setting.  In my case it was for an internal role, so I was comfortable with that but some roles I would not give that to.

I am running Drupal 7, BTW.


Kill border by using PHP? In my theme on Drupal 7:50 there is #banner just beneath #menu. For #banner I have made {border-bottom:5px solid blue} The problem is that sometimes #banner is empty and then the #border remains and goes up beneath #menu and that kills the layout.

Is there a way to #banner{display:none} if "banner is empty by using PHP or how to do it. All suggestions are welcome. Killing the border with JS and CSS if #banner height is below 5 ?

Hans

One way would be to set a minimum height on #banner. That way when #banner is empty of content, there will still be a space between #menu and the border. This solution does not require you to involve PHP at all.

#banner {
  min-height: 10px;
}


Using REST to create user with CAS username I would like my CAS server to POST an account to my client site when a new user registers. My CAS server is using D7, clients are using D8.

Using the entity/user endpoint I can create a new user, assign roles and  complete custom fields. It all works well apart from adding the cas_username.

When trying to pass the CAS username I get en error:

  "InvalidArgumentException: Field cas_username is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 586 of /mysite/html/core/lib/Drupal/Core/Entity/ContentEntityBase.php)."

Is it possible to POST a user with cas_username field via the create user endpoint?

Do I need to create a custom endpoint that extends the functions of the default entity/user endpoint?

Answering with the workaround I used. It is far from ideal, but works. It relies on having access to the DB of the client site. This uses D7 rules with the php-filter module. It would be much more elegant in it's own custom module.

The site sending the POST request uses sql to update the authname table on the site receiving the POST request. The created user then has a cas-username.

Below is the code for the rule action - creates the POST request, then alters the DB.

// Generate random password
$bytes = random_bytes(10);
$pass = bin2hex($bytes);

// data for user fields
$data = array(
  'name' => array(
    'value' => '[account:name]'
    ),
 'mail' => array(
   'value' => '[account:mail]'
 ),
 'status' => array(
   'value' => 1
  ),
 'pass' => array(
   'value' => $pass
    )
  );

// POST code
$data_string = json_encode($data);

// POST with cURL
$url = 'https://example.com/restendpoint';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$response = curl_exec($ch);

// Get UID from response
$newuser = json_decode($response, true);
$newuseruid = $newuser['uid'][0]['value'];

// DB update
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO authmap (uid, provider, authname, data)
VALUES ($newuseruid, 'cas', '[account:name]', 'N;')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

curl_close($ch);


Blacklisting specific tags from an input format instead of whitelisting I need a filter for the "Full HTML" input format that allows me to strip specific tags. I want to allow all HTML tags, except the ones specified in the input format options.

I am using Drupal 7.

You can get that functionality out of the box with the HTML Purifier module.

Once you've installed the module, go to the admin/config/content/formats page, choose the text format you want to edit, and select the "HTMLPurifier" checkbox. In the settings below, quite a bit further down the page, you'll find the ForbiddenElements textarea:

That's where you need to put your disallowed tags. It's probably worth looking at the rest of the settings to make sure they match up with your expectations (there are a lot of them though, HTMLPurifier is pretty configurable).


How do I overwrite Facet API tokens for active items? I'm using "Facet API" and "Search facets" modules on Drupal 7. I'm trying to change the values of the active items' tokens provided in the search blocks (especially the [facetapi_active:facet-label] token) , I tried to use the "Facet API Bonus" module and the function hook_facet_items_alter with no success, could someone help me? Thanks!

I didn't need the "Facet API Bonus" module, I wrote a module to implement THEME_facetapi_link_active (included in facetapi.theme.inc)
then i simply replaced the label's text using the function str_replace like this:

$variables['text']=str_replace("Price » Amount (decimal)","Price",$variables['text']);


Bots still register on website even though CAPTCHA is activated I have activated CAPTCHA but bots still register on the site. If someone can advise how this can be prevented.

To specifically block bogus registrations, I've found the project MotherMayI to be a great help.

  Mother May I provides a simple to use extra hurdle to reduce the bother of spamming account requests. It's primarily useful to sites with a limited target audience (at least for authenticated accounts) where valid users have some side information about the group. The site administrator can define a site-specific "secret word." Anyone requesting an account must enter the secret word before even a temporary account is created.

As the quoted text says, it is best suited for sites with a limited target audience.  However, the module lets you give a "hint" that is supposed to make it simple for humans to find the secret word, and I've found that even ridiculous easy task where where the hint is "Please type in cartoon character Fred Flint's last name" (and the secret is "Flint") works great.

MotherMayI allow you to have a long "hint" text and use a RegExp for the answer, but only allow one "secret" word.

There is an alternative in the CAPTCHA family called Captcha Riddler that works similarly.   It allow multiple riddles to be defined to separate humans from robots, but only allow short texts for riddles and have no RegExp function.

Since you define the "secret" word (MotherMayI), or "riddle" (Captcha Riddler), these methods are more immune to the "training" feature of Xrumer and other pests.  This means the 'bot need to be trained specifically for your site.  Unless your site is really huge, you'll be able to fly under the radar for a long time. And it is trivial to replace the secret word or riddle if the robot is trained to recognize your site.

Are You A Human playthru (also mentioned by Mołot) is in the same genre as the previous two, but IMHO slightly more cumbersome for humans to "solve".


How to disable or make fields unpublished, but not delete them I have some fields I need to disable from user registration, but no delete them, just make them unpublished or disable them temporarily, is there a way to do that?

The easiest solution offhand is to make the fields non-required for registration. And then setup the Field Permissions module temporarily to not give Edit permission to Role(s) you don't want to see those fields.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


Handle Page Content when URL is /abc/1 I want to handle the page content via a drupal module.

If the called URL is abc/[x] (for example abc/123, abc/456), then I want to render [x] on the page.

which is the best way in drupal to do this without views?

Thanks for your answer.

There are many ways you can accomplish this, here a few ideas;

You could create custom templates based on the node ID of those
pages...Examples here: http://drupal.org/node/1089656
Also you could make use of the Context module:
http://drupal.org/project/context
You could also, create content in blocks, and set them to only show
on the specified paths under the page visibility settings of any
given block you create.


Using field api to get key of select list option I need the safe output of a key from a select list field within a field collection item.

I'm theming a field collection item and one of the fields is a select list like:

icon-map|Map
icon-info|Info
icon-pencil|Pencil

I'm using the following to create some easy to use variables;

$fields = array_keys($content);
foreach ($fields as $field) {
  $field_items = field_get_items('field_collection_item', $content[$field]['#object'], $field);
  $$field = render(field_view_value('field_collection_item', $content[$field]['#object'], $field, $field_items[0]));
}

This works fine for all fields except for the select list.  I need the key of that select list.  For this select list field, $field_items is an array which looks like:

array(1) { [0]=> &array(1) { ["value"]=> string(13) "icon-map" } }

However, $field_icon (result of $$field = render(..) ) is Map, which makes sense.

I can get the key by using $field_items[0]['value'] but I'm not sure that's the best way.

I hope this may help

 $key = $form_state['values']['whatever'];
$options = list_allowed_values("field_whatever");
$value = $options[$key];


Add Constraint to Paragraph Field I'm attempting to follow this documentation to add a custom constraint to a field in a Paragraph but I'm having trouble actually accessing that field.

Currently I have my_content_type with paragraph_field. This field accepts a number of different paragraph types. I'd like to be able to add a constraint to a field on a specific paragraph type that could be added to that field.

I've tried using hook_entity_bundle_field_info_alter, hook_form_alter, and hook_field_widget_form_alter but am having trouble actually accessing the proper field.

Is there a better way to do this?

@Vecta I hope this help you

function MYMODULE_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  //with a node
  if ($entity_type->id() === 'node') {
    if ($bundle == 'article') {
      if (isset($fields['title'])) {
        // change constraint id
        $fields['title']->addConstraint('UniqueCode', []);
      }
    }
  }
  //with a paragraph
  if ($entity_type->id() === 'paragraph') {
    // use the paragraph machine name
    if ($bundle == 'paragraph_name') {
      if (isset($fields['field_name'])) {
        // change constraint id
        $fields['field_name']->addConstraint('ConstraintId', []);
      }
    }
  }
}