Why doesn't this Views 3 contextual filter work? I have expanded the article content type to include a few more fields and want to display an article node as a page.  Each article node (content) I give an alias with the following pattern: press-releases/[name-of-article]

I've set up A "Press Releases" view which has three displays.  Two of the displays are block displays and these work perfectly. I also want to make a page display with this view, and that's where I'm running in to problems. I want this view to be active for any node (content) that has the url press-releases/[name-of-article] and so I set up the view like this:

And the Contextual Filter has these settings for the Node ID:

But when I visit any press-releases/[name-of-article] it's like the Contextual Filter is completely being ignored and I just get the node spit out all the default fields as determined by the content type, and not according to the View's Page display. Why is this, and how can it be corrected?

In order to play nicely with other modules, views will not override any aliases that point to something already. You're trying to make a view show up on an alias that is already pointing to a standard drupal full page node. This simply will not work.

Options:

Stop giving aliases to press release nodes so they are only available at node/nid
Use a different path for your view so it doesn't conflict with your nodes
Use Panels to override your full node page and show that view

Some other things to consider
A view is really useful for display a list of things, you should probably consider not using it as a node page in this way. You can get a lot of control over your page layout using the standard display tools Drupal 7 gives you.

Using Content: Nid as a contextual filter will not recognize a url in the form of press-releases/name-of-article. You would need to use Content: Title. You also don't need to specify the raw url value as a default value or add % in your view path. The order in which the contextual filters are configured are the order in which they are pulled from the URL.


Why are some contrib module functions not recognized? I can't seem to get the latest twitter module to work with my site.

I have a custom module that does some sanity checks on user-imported twitter accounts and my site keeps failing at this point. After some digging I noticed the twitter module functino twitter_account_load() is not recognized at all.

Devel test code to reproduce:

dpm(module_load_all()); // returns 1
dpm(module_exists('twitter')); // returns 1
dpm(twitter_account_load('@twitter')); // returns white screen of death

Apache error log:

  PHP Fatal error: Call to undefined function twitter_account_load() in /var/www/mysite/httpdocs/sites/all/modules/contrib/devel/devel.module(1285) : eval()'d code on line 4, referer: http://my.site.com/devel/php

Drupal Version 7.26
Twitter Version 7.x-5.8

What I have tried so far:

Cache cleared
Twitter module upgrade to latest 5.8
Cache cleared
Twitter module reinstall
Cache cleared
...

Nothing worked.

Any idea why?

Do module load include of twitter.inc in which above function was defined.. .module files are automatically included, but .inc are not. So you need to include them using above function...

module_load_include('inc', 'twitter', 'twitter');
dpm(module_load_all()); // returns 1
dpm(module_exists('twitter')); // returns 1
dpm(twitter_account_load('@twitter'));


Node Validation and Dereferncing I have some content types (nodes) that are attached to various taxonomies.  For specific node types, I want to do some validation on the taxonomy.  I do not want to hard-code the nodes types and their corresponding fields that reference the taxonomy.  So I put them in array.  However, I am unable to dereference the field names.  I've tried double $$, quotes, etc, but can't get it to work.  Is what I want to do possible?

<?php

$node = (object) array(
    'nid' => NULL,
    'vid' => NULL,
    'uid' => '1',
    'type' => 'price_document',
    'language' => 'und',
    'field_taxonomy_price' => array(
        'und' => array(
            array(
                'tid' => '94'
            )
        )
    ),
);

  $nodes_to_check = array("price_document" => "field_taxonomy_price",
                          "package"        => "field_taxonomy_package",
                         );

  if (array_key_exists($node->type,$nodes_to_check)) {
    $taxonomy_field = $nodes_to_check[$node->type];
    print_r($taxonomy_field);
    $tid = $node->field_taxonomy_price ['und'][0]['tid']; //  <- this works but, how
    //$tid = $node->"$$taxonomy_field" ['und'][0]['tid'];     <- can I deref variable?
  }
?>

You just need to use curly braces; there's no need for variable variables in this case:

$tid = $node->{$taxonomy_field}['und'][0]['tid'];


How to align three blocks on the front page using CSS I've got three blocks on my front page and I want them to be centered and aligned.

"About us" block is to be aligned to the left side of the front page what I managed to achieve. The other two blocks are to be aligned to the right side of the front page and one above the other what I managed to achieve as well.

However:

Different browsers show different results which is caused by the reference of the language switcher block I guess. It is moving my right hand side set of blocks up and down. IE is showing the result I would like to achieve (the example: test site).
I would like to be able to reference language switcher block to the content region which is not the case right now and I am not sure how to do it.

Can someone help or guide me into the propriate direction?

Thanks and regards

Well, after looking at your code I concluded that your css codes are terrible! you may use this code (I didn't test it but it should work or at least a few modifications will make it to perfectly match what you need):

                    //In here load the slider block and display in here

                    //In here load the top right  block and display in here

                     //In here load the bottom right  block and display in here

This is CSS

#content{
       text-align:center;
       width:100%;
       height:auto;
       display:inline-block;
}
#blocks-container{
       margin:auto;
       width: 975px;
       height:auto;
       display:inline-block;
}
#left-block{
       float:left;
       width: 760px;
}
#right-block{
       float:right;
       width: 215px;
}
#right-block > div{
       clear:both;
       width: 100%;
      float:left;
}

Never use margin to align elements to the right, because the margin is calculated based on the parent which in your case is the browser, so If you resize the browser, the browser will try to move the elements to regard the margin.

I recommend you strongly to forget about the DIV and float, try to learn how to work with flexbox it is very easy to use.


Get the nid of a node As you know drupal has a function " node_type_get_types " that we can use to get the type of the node, so is there also a function that we can use to get the nid of the current node that we are viewing?

it's just a property of the Node itself, the nid of the node. It is the value $node->nid.

EDIT

There is also entity_extract_ids() which is 1 level up from a Node in the object hierarchy and this function interacts with Entities -- if you're trying to do something more generic than merely interact with solely Nodes ... such as a process a Queue of Entity objects all of different types but sharing a field you want set with a certain value.

  Helper function to extract id, vid, and bundle name from an entity.

  Parameters

  $entity_type: The entity type; e.g. 'node' or 'user'.

  $entity: The entity from which to extract values.

  Return value

  A numerically indexed array (not a hash table) containing these
  elements:

  0: Primary ID of the entity.

  1: Revision ID of the entity, or NULL if $entity_type is not versioned.

  2: Bundle name of the entity, or NULL if $entity_type has no bundles.


Allow Anonymous user to Subscribe while site under maintenance mode The title says it all.
I have customized the Maintenance mode page, to Coming soon!!
how i want to enable the visitors of the website to Subscribe So they'll will be notified when the website is officially lunched.
how can i Achieve this, am developing the website in Drupal in 7.

Maintenance mode is not really for this.

I would recommend using a custom theme for "Coming soon".   That way you can have them come to a home page with information and sign up/register for the site.

When you're ready to put the real site up, change themes.


For a non-english single-language site, is it still best practice to write t()-strings in the theme in English? On Drupal 7 with the i18n-modules, in what language should your default strings be written in? In modules it's obvious that all strings should be in English (for reuseability) and use t().

But a custom theme will only be used for the specific site. If the site is not in English it seems lika an awkward practice to first write everything in English and then translate to the specific language.

If you're 100% sure that you do not need to (re-)use this code in a multi-language environment, now or in the future, you're safe using foreign language strings. Personally, I consider it best practice to always use t() because you never know what's going to happen in the future.

Be aware that strings in code that are run through t(), are assumed to be in English, so you have to choose between t('English text') or 'Svensk text'. Never use t('Svensk text').


User create its content type I created a content type called successful story; in this content type, there is a title field and a text field.

I have two types of users, Role1 and Role2; Role2 can only create or delete a successful story.

For example, The user called Michael is a Role2 user and can create its successful story

But how can I make this relation works between a content type and an user?

Your question is not clear but I think you want to know how to set the right access to the different Roles

Go to your_site/admin/people/permissions
Search from the successful store content type
For Role 2 check the "Create new content" and "Delete own content"
Click save at the end of page

Now users of Role 2 can create and delete their own content.

You can also create a link for Role 2 users to access their own content.

Go to your_site/admin/people/permissions
Search from the Access the content overview page
For Role 2 check the box for Role 2
Click save at the end of page
Create a menu item and add the link as admin/content


Generating node title from node fields So, this is a newbie question. I'm using Automatic Nodetitles with a custom content type. I'd like the node's title to be equivalent to one of my fields. After some snooping around I came up with this:

<?php return $node->field_my_field ?>

I put this in the "Pattern for the title" field, but this just returns 'Array'. So, it must be an array. However, I'm not having any luck figuring out how to index it to get the value I'm looking for. Everything I tried just gives me 'Undefined offset' errors.

This can't be too hard.... Thanks!

I think it's better idea to use token instead of php code for this simple replacement.

When you have the token module installed you'll have a list with available tokens under the Pattern for the title: input box. And if your field is named *field_my_field* then you'll have the tokens

[field_my_field-formatted]
[field_my_field-raw]

or something like that to choose from.


Can't access links in block_view_alter hook I have a two-language site with the standard language switcher block. I want to remove the link that points to the current page language (I only want the user to see one link to switch to the language they're not seeing).

I've tried this:

function mymodule_block_view_language_block_alter(&$build, $block) {
  $build['links'] = []; //for now for debugging purposes, remove all links
}

It doesn't work (though it runs the code). The $build array doesn't have a links key, or anything it's supposed to according to the build method in core/modules/language/src/Plugin/Block/LanguageBlock.php. Why might this happen? How can I alter what I'm seeing there?

BTW I also tried the block_build_alter hook. Similar situation.

Those hooks are unfortunately not very useful; I don't really know why they work like that. The actual block view didn't happen yet; that's in a preprocess. You'd need to add another preprocess that runs later.

However, for your specific use case, why not use the hook that's designed exactly for this? hook_language_switch_links_alter()?


Sub Menu's are not coming under main menu I am using this code to fetch menu's in drupal. I have given Home as parent menu and other are sub menu's like submenu1, submenu2 etc. But in front end they are not coming under Home menu. Only Home menu appear on front end.

<?php if ($main_menu): ?>
     <?php
          // This code snippet is hard to modify. We recommend turning off the
          // "Main menu" on your sub-theme's settings form, deleting this PHP
          // code block, and, instead, using the "Menu block" module.
          // @see https://drupal.org/project/menu_block
          print theme('links__system_main_menu', array(
            'links' => $main_menu,
            'attributes' => array(
              'id'=>'s5_nav',
              'class' => array('menu'),
            ),

          ));
          ?>
    <?php endif; ?>

You can use Nice Menus to solve your issue.


Filter content in view by user field I'm having problems filtering a view. This is my case:

When a user registers he has to select some suppliers of a list (This is a term reference as a field of my user).

A user can also create a product. Now I would like to show the products where the suppliers reconcile.

This is an example:

USER 1 has suppliers A & B.
USER 2 has supplier A.
USER 3 has supplier B.

USER A can see the products of USER 2 and USER 3.
USER B can see products of USER 1, but NOT USER 3.
USER C can see products of USER 1, but NOT USER 2.

But I'm having trouble making this filter in a view. Could someone help me on my way on how to make this?

If the Supplier field lives in the user profile you could make the Product fields dependent on the Supplier field using the Conditional Fields module, grant various roles field/taxonomy term access to Product fields using the Field Permissions or Taxonomy Permissions module, and then create a rule that fires based on Supplier field values that modify user role assignments accordingly

Then you would add all Supplier and Product fields to your view, hiding each Product field in the display, and then add a Global: Custom text field called "Products" and use replacement patterns to reference each of the hidden fields one after the other. (Make sure the hidden fields appear before the Global: Custom text field.) Anything that comes up empty simply won't appear.

If those fields live in a node, that may require a slightly different strategy, but the idea should be more or less the same.


Drush alias - @alias status could not be found Problem

I'm trying to create a drush alias following the excellent example posted here.

EXAMPLE:

$aliases['dev'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'dev.mydrupalsite.com',
 );

MINE:

<?php
$aliases['main'] = array(
    'root' => '/srv/www/mysite/public',
    'uri' => 'main.mysite.net',
  );
?>

According to the example the following two commands are equivalent:

 $ drush @dev status
 $ drush --root=/path/to/drupal --uri=dev.mydrupalsite.com status

And if I run:

$ drush --root=/srv/www/mysite/public --uri=main.mysite.net status

I get a full report. But if I run

 $ drush @main status

I get the error @main status could not be found.

The alias file has been discovered, running drush status in the drupal root shows it has been found. It's ~/.drush/mysite.net.alias.drushrc.php. What have I done wrong?

The filename pattern mysite.net.alias.drushrc.php will only be parsed for aliases named @mysite.net.  Rename this file to mysite.net.aliases.drushrc.php, and you'll be fine.


Unable to install drush on mac 10.9.2 Lately I was trying to install drush for the first time. This is what I did..

Installed the drush tool manually
Extracted and renamed the tool to /Library/Drush
Gave the /Library/Drush/drush tool execution permissions.
Created an alias for drush in ~/.bashrc
Tried to bash drush by entering the alias drush, that's when I got the first problem:
Unable to load autoload.php. Drush now requires Composer in order to install its dependencies and autoload classes. Please see README.md
After lots of searching I tried way to many things:

which drush doesn't return anything.
Installing the composer (at /usr/local/bin/composer) results in this The requested package drush/drush 1.0.0 could not be found problem when executing composer global require drush/drush:dev-master

Help would be appreciated, because I don't know what I could do to make it work.

Thank you in advance, `F.

I have encountered the same error while installing the drush on MAC, I have tried the following and that worked for me:

composer self-update
ln -s /path/to/drush/drush /usr/bin/drush

I have downloaded the Drush from this git repository: https://github.com/drush-ops/drush

And followed the method described here for installing the Drush on MAC: https://www.drupal.org/node/1674222

For Installing Drush on Mac using Homebrew, check https://www.drupal.org/node/954766


Send E-Mail When User Profile Fields Updated I am looking to update my brain regarding a set of rules in Drupal 7. What I am wanting to do is:

Send e-mail to arbitrary e-mail address (mine) when a user updates any of their user profile fields.
I want the updated fields to appear in the e-mail template.
It would be helpful to have the old information showing the new updated field information.
Avoid sending e-mail when password is reset or changed.

I am probably missing something basic here with data comparison but thought I would seek out some thoughts on this.

Just Install Rules Module and set the conditions something like this:

Event: After updating an existing user account

Actions: Send a HTML Mail ($account variable is available to send updated values through mail)

Conditions: If needed


How to expose individual form elements from user-register-form So I have a work flow/use case as such:

an administrator user creates a user account, associating it to the "guest" role
the guest users receive a login link
once they log in, I want them to provide some information (in this case, rsvp status, a custom field I've added to the user profile)

Is it possible to display just the rsvp form field of the registration form, so they can update it when they log in (e.g., they submit one field only and the profile is updated)?

Is there another way to do this? I'd rather do this in code since it's part of a custom module that is nearly completed.

If your doing your own module hook_form_alter is the way to go. so long as all required fields are already supplied you should be able to set all other fields to have type hidden.

If you are looking to do something similar you may want to look at the event and rspv modules.


Conditional View Output? A view I'm working on has a linked Title field. By default, this field should link to an internal page with the [nid]. E.g. http://www.example.com/node/[nid]

However, there is a second link field where, if filled in, the link should be re-written to go to the specified link.

So, if the link field is blank, link to a URL with the [nid]. If the link field is filled in, link to the specified URL. I'm unsure of how to have a default behavior and then override it.

How could I accomplish something like this from within Views? Thank you!

Views Conditional module, can help you.

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To Not Equal To Greater Than Less Than Empty Not Empty Views
  conditional allows you to output text based on the result of the
  condition.

Example screenshots

Added Fields in view

Views Conditional Field configuration


Book revision page showing access denied if no revision present I've edited the content type Book to "create a new revision" whenever user publishes the page (while creation and editing the page).

I have created a custom menu Book revisions, with path node/[node:nid]/revisions using menu token module. It renders http://site-url/4/revisions with 4 as the node id of current node.
I am using Nice menus module to create the menu block and have placed it on every book page so that user can see the revisions whenever he is on the book page.

When I first create a page, and click on this menu, it gives me Access denied page (I'm logged in as user1). But, the moment I edit the page and save it, it works as expected - showing the different revisions.
Requirement: I want to display "No revisions" instead of "Access denied" to users. How can this be done?
I'm also open to suggestions to hide the menu for the first time, and again show it as soon as a revision of the node is created.

Edit: I find that if a node is not revised (edited), node_revision table has only one vid for the nid of node; and if the node is revised the table contain one vid per revision.
Using this information and a database query, I think it would be possible to find out whether a node has revision. Something like

$result = db_query('SELECT n.nid from {node_revision} n WHERE n.nid LIKE :uid',array(':uid' => arg(1)));
$temp_var = 0;
foreach ($result as $result_item) {
  $temp_var++;
}
//If revisions are present $temp_var>1
//Only one version present if $temp_var == 1
if($temp_var == 1) {
  //menu unset code goes here...
}

I am just not sure in which hook should I implement this.

EDIT: I'm using Diff module to enable the users to view the differences in two revisions.

If I understood this right, you have a (Nice) menu on node pages, and you've added the node/[node:nid]/revisions item to that menu. You're not actually listing revisions, just making a link to the revisions page, right?

If so, the problem is that the access callback for that menu item is hardcoded to return access denied if a node doesn't have revisions. Actually looks like this is being fixed for D8. Normally the tab wouldn't show, but it is in your case because you're creating the menu item in a different way, and the access is not checked when the link is printed. The solutions I can think of:

Replace the page with a view listing node revisions. Easy, but I don't know if you can replicate all the core revisions page functionality.
Create a wrapper menu item around the core revisions page using hook_menu(). Call it something else, like node/%node/revs. In the callback for that menu item, check if the node has revisions. If so, return the output of node_revision_overview($nid), the core function that generates that page. Otherwise, return 'No revisions'
Use hook_menu_alter() to take the existing revisions menu item (node/%node/revisions) and move it to your menu. Take a look at the definition of the menu item in node.module line 2043. You'll need to change it to not be a LOCAL_TASK and then use the menu_name property to tell it to get into your custom menu. I'm pretty sure this can work.


Display message instead of redirecting to Access Denied page I'm using Commerce Auction module for an auction site. I want to display a message when the auction time out occurs for a certain product and at the same moment the user clicks on place bid tab.

Scenario:

Created an auction item
Started bidding with different users.
When auction time out just occurs and at the same moment any user clicks on Place Bid tab that user is redirected to Access Denied page.

Now instead of redirecting to access denied page, how to display a message on the same page?

I have set a rule for mailing purpose on the same event. I also tried using "display message" rule for this event. But still it is displaying Access Denied message. I want to show different message only for this event.

1st attempt

Maybe the Disable Messages module can help here? Here is an excerpt from its project page:

  Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features which might help in this specific case:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Apply filtering only for specific paths.

2nd attempt

If the 1st attempt doesn't help, then you may want to try to expand the rule you already seem to have (as per your "I have set a rule for mailing purpose on the same event"). I.e by adding a rules action to flag the user (using the Flag module, with a flag you only use to indicate your scenario just happened to that user (let's say you label it "TimeOut").

Together with this, create an additional rule like so:

Rules Event: Drupal is initializing
Rules Conditions:

Current path matches your "no access" path (whatever that is in your case).
User is flagged with the "TimeOut"

Rules Actions:

Remove the "timeOut" flag (=unflag) for the current user.
Set your message.
Perform a redirect to a path that fits your needs.


Clean Url not enabling I have problem in clean url i am trying to enable it but it showing radio buttons deactivated and showing Your system configuration does not currently support this feature.

My web is on shared hosting under the sub directory Like This
http://tailoredsuitonline.com.previewdns.com/oceanwis/ The main Web is "Oceanwis"

Your help is really appreciated

Check if mod_rewrite is enabled (if you are using Apache as your web server).
Add .htaccess file to the root of Drupal installation. Here is a link to documentation.


Customize search output I was trying to modify the search results page using a preprocess function:

function arras_preprocess_search_result(&$variables) {

    $type = $variables['result']['node']->type;
    $variables['search_results'] = '';
    $nodeTypes = node_type_get_types();
    $resultTypes = array();

      $resultTypes[$type][] = $variables['result'];

    foreach ($resultTypes as $resultType => $resultTypeResults)
    {
        echo $resultType;
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result)
        {
            $value .= theme('search_result', $result,$resultType);
        }

        // add fieldset
        $variables['search_results'] .= theme('fieldset',
            array(
                '#title' => $nodeTypes[$resultType]->name,
                '#collapsible' => TRUE,
                '#collapsed' => FALSE,
                '#value' => $value,
            )
        );

    };

}

but I get this error:

( ! ) Fatal error: Unsupported operand types in L:\wamp\www\drupal\includes\theme.inc on line 830

i.e on the line

        $value .= theme('search_result', $result, 'cameras');

What is wrong?

From the Drupal 7 API theme_search_result:

  This function is never used; see the corresponding template file
  instead.

Try overriding the page using search-result.tpl.php


Stylesheet for specific page overwritten by standard css In my subtheme.info I have :

stylesheets[all][] = css/style.css

And in my template.php I have:

function subtheme_preprocess_page(&$vars) {
    $path = current_path();

    if ($path == 'user/login') {
        drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css");
    }
}

But when I load the page, my style.css is declared after my login.css. So my styles in login.css are overwritten by styles.css. How can I make sure the login.css is declared after the styles.css?

Add weight to the CSS:

drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css", array('weight' => 100));

See the drupal_add_css() API page for more info. The group option may also be relevant as this also affects the weight.

Also if the specificity of a rule in style.css overrules a rule in login.css it won't matter what order the CSS files are included.


Drupal 8: Performance Impact of frequently clearing all caches I have a relatively large production site that uses some custom views to filter by taxonomys and other factors through dropdowns. I have come across the issue that adding a new taxonomy does not allow it to appear in these dropdowns until the cache has been cleared.

I have had a read around and it seems like the most specific thing to do would be to locate the cache tags for these views and invalidate them on creation of a new taxonomy term. However this could be quite complex for me and I was hoping there would be something like cache_clear_all('*', 'cache_view', TRUE); from Drupal 7 so I could just rebuild by views cache when in a hook but this doesn't seem to be the case.

I have come across the D8 drupal_flush_all_caches() method however this appears to clear and rebuild ALL caches with no options to limit its effect. My first question is, what would be the performance effect on my site if I used hook_cron to flush all caches every ~3 hours? Would it be noticeable for the users?

Also, if anyone has a D8 method for clearing specific caches for views/custom blocks etc. I would love to hear them?

You can clear the cache tags of a specific view whenever a term is created.

function hook_taxonomy_term_insert(EntityInterface $term) {
  if ($term->bundle() == 'VOCABULARY_ID') {
    Cache::invalidateTags(Views::load('view_name')->getCacheTags());
  }
}


Hide Views with custom module Hi I would like to create a custom module where I can do extra checks on a view and if those checks are not pass deny access. I'm not sure what hook to implement to achieve this.

You need to implement two Views hooks: hook_views_api() and hook_views_plugins(). Have a look at views_views_plugins() in Views' /includes/plugins.inc file for an example implementation of the plugin hook; specifically, look at the plugins in the 'access' key.

Beyond that, look at the views_plugin_access* files in /plugins/ for examples of actual implementations.


How to filter URLs for embedded IMG tags? This is a great presentation about Drupal security. They were talking about ways to only allow  tags from certain trusted domains.

Any ideas how to do that? I couldn't find a D7 module for that.

If you mean disallowing <img> elements where the src isn't on a whitelist, then you can make a custom input filter.

The first step is to make a hook_filter_info to declare your input filter.  You would then make a callback function that does the work.

The callback would do some regex matching, looking for <img> elements and pulling out the src attributes.  Then regex match the src against your whitelisted domains.  If everything is OK, let the image pass, else replace it with whitespace.

Finally, make a hook_menu which sets up a settings page so you can enter your whitelist via the UI.

Once you have done all of this, you add your filter to the appropriate input formats.  When the page gets rendered out, the filter will be applied.

All of this is rather easy.  The heavy listing is the <img> regex, but I suspect 15 min of googling will find some good ones.


PDO expecption error while adding class to the block with sql server "PDOException: SQLSTATE[42S22]: [Microsoft][ODBC Driver 11 for SQL
  Server][SQL Server]Invalid column name 'css_class'.: UPDATE block SET
  [css_class]=:db_update_placeholder_0 WHERE ([module] =
  :db_condition_placeholder_0) AND ([delta] =
  :db_condition_placeholder_1) ; Array ( ) in block_class_form_submit()
  (line 99 of .....\sites\all\modules\block_class\block_class.module)."

Adding class to the block using block class module. while adding class to the block throwing pdo exception error coming. Please any one resolve problem.

Instead of install one module for this, you can just use the ID for that block and create your custom css.

Example:

div#block-block-10{
    background-color: blue;
}

I think that could solve your problem


Change content of email verification email based on gender provided by user In my website when a user submits the registration form and email verification is sent to them. Is there a way to change the content of the verification email that is sent after the user submits the registration form based on the gender they have selected. I'm trying to make a separate emails for male and female users.

The default email provided by Drupal says

  [user:name],

  Your account at [site:name] is created. You may now log in by clicking
  this link or copying and pasting it to your browser:
       [user:one-time-login-url]

  This link can only be used once to log in and will lead you to a page
  where you can set your password.

  After setting your password, you will be able to log in at
  [site:login-url] in the future using: username: [user:name]
  password: Your password

  --  [site:name] team

I want to change this. For example if the user selects "Male" for gender in the registration form so instead of [user:name], it says "Hey Boy!" and if the user selects "Female" in the registration form the email says "Hey Girl!".

Is it possible to make that change?

Thank You.

You've got two options:

Create yourself a custom token and use that.
Use the hook_mail_alter function

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail_alter/7

The token approach is the more elegant approach, but needs a bit of head-wrapping to understand the concepts. The hook_mail_alter might be an easier quick hack.


how to render a node field of a referenced node on the node form I'm using Display Suite to show a referenced node inside another node in the default display. But when I edit this node that has the entity reference field on it, it shows me the reference field and I'd like that to show the rendered content of a field of the referenced node. Is there a way in Display Suite or do I have to write some code in a tpl file somewhere?

You can create using Views a view with "Entity Reference" where you can make the rendered content you wish to add to the node. Than add a new field of type "Entity Reference" to the node edit form of this node type and set up in section "Entity selection":

Mode -> 'Views: Filter by an entity reference view"
View used to select the entities -> choose the view machine name you have created for this purpose

Additionally, you can provide a comma separated list of arguments to pass to the view.

To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

Hope it helps


Translate untranslated words in Drupal I'm using calendar module and I noticed when browsing web that some words are not translated (e.g. "prev," "next," "day," "week," "month," "year"). Is it possible to write somewhere the translation for these words?

Content Translation module can help us using Translation Interface (example.com/admin/config/regional/translate/translate) in this regard to search the string and then define a translation against appropriate language.

The strings can only be translated if they are not hard coded and used with t() function.

t() always searches for appropriate translation with respect to currently selected language otherwise it returns the original string.


"&" displaying as "&" in Views exposed filter So I'm not sure where this happening, but would love to understand & fix it.

The same data is being displayed elsewhere on the website without the above issue, only in this exposed filter (& the content editor form) does it seem to happen.

In the configure filter window the ampersands appear as expected:

The filter is referring to a node reference field:

If I go to edit one of these content types, the ampersands DO NOT appear correctly either (in select list / drop-down box), only in the configure filter window do they appear correctly.

I checked the database & it's saved in "&" form, so somewhere Drupal is converting it...

I could write a javascript snippet to fix it, but I'd like to understand & fix it the "Drupal way"

So I used this jQuery search & replace to fix it client side, I still want to find & fix the issue the proper way & will update this when I do. Here is my resulting jQuery snippet:

(function ($) {
$(document).ready(function(){
    $("form#views-exposed-form-maps-page select#edit-destination option").each(function(){
        var text = $(this).text();
        text = text.replace("&amp;", "&");
        $(this).text(text);
    });
});
}(jQuery));


How can I use the Commerce Paypal module module without the Commerce module? I have a form, which has an amount and item detail values to pass to PayPal.

I have installed the Commerce Paypal module, but I don't find any clue on how to integrate it so that when the form is submitted, it should go to PayPal for transaction. On success, it should redirect to the success URL; likewise, it should happen on failure, where the users are redirected to  the failure URL. I haven't installed the Drupal Commerce module as there is no use of pages like catalogs and checkout in this system.

How can I use the Commerce Paypal module?

Commerce Paypal has the following dependencies:

commerce
commerce_ui
commerce_payment
commerce_order

Installing/using Commerce Paypal without Drupal Commerce isn't possible; it's a supplemental payment module, and requires Commerce's API to work.

You may instead be interested in something like Webform Paypal

  The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.


How To Add Button To Commerce POS Command Pane? My module needs to implement a custom payment workflow. I want to add a button to the Commerce POS command pane to perform a task, then modify the order entity according to the result of the task.

Implement the hook hook_commerce_pos_commands().


Making menu wrapped in nav tag I've got problem with making main-menu wrapped in  element.
I've tried:

Using hooks in template.php like:

function koko_menu_link_main_menu($variables) { /* For block override */
$output = '';
      foreach ($variables['links'] as $link) {
        $output .= l($link['title'], $link['href'], $link);
  }
  $output .= '';
  return $output;
}

function koko_links__system_main_menu($variables) {
  $output = '';
foreach ($variables['links'] as $link) {
  $output .= l($link['title'], $link['href'], $link);
}
  $output .= '';
    return $output;
}

Using preprocesss/block.preprocess.inc:

  switch ($variables['block']->module) {
    case 'system':
      switch ($variables['block']->delta) {
        case 'help':
        case 'powered-by':
          break;

      case 'main':
          // Use a template with no wrapper for the page's main content.
          $variables['theme_hook_suggestions'][] = 'block__minimal';
          break;

      default:
          // Any other "system" block is a menu block and should use
          // block--nav.tpl.php
          $variables['theme_hook_suggestions'][] = 'block__nav';
          break;
      }
      break;

      case 'menu':
      case 'menu_block':
      // Use block--nav.tpl.php template.
      $variables['theme_hook_suggestions'][] = 'block__nav';
      break;
  }

case 'main':
  // Use a template with no wrapper for the page's main content.
  $variables['theme_hook_suggestions'][] = 'block__minimal';
  break;

default:
  // Any other "system" block is a menu block and should use
  // block--nav.tpl.php
  $variables['theme_hook_suggestions'][] = 'block__nav';
  break;
 }
 break;

case 'menu':
case 'menu_block':
    // Use block--nav.tpl.php template.
     $variables['theme_hook_suggestions'][] = 'block__nav';
     break;
   }

That contains. block--nav.tpl.php

    <nav<?php print $attributes; ?>>
      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php print $content; ?>

Still nothing happends. Main-menu is not wrapped in anything different than:
.

Did you read this and this posts? I thinks it's not so difficult to achieve this:

function MYTHEME_links__system_main_menu($variables) {
  $html = "
\n";
  $html .= "  \n";
  foreach ($variables['links'] as $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "  \n";
  $html .= "
\n";
  return $html;
}


Invert shipping rate position with VAT field As described in this post I'd like to invert the row between shipping service and VAT calculation.

I don't know how to use that hook... Can someone tells me more?

Thanks!

EDIT:
I followed the example.
I created the module, it's active and running but I see that nothing happens.

I tell you what I did (it's all in italian):
 - Created posizione_iva.info file with this content

core = "7.x"
description = "Modulo che sposta la riga dell'IVA dopo tutti i valori imponibili."
name = "Posizione IVA"

Created posizione_iva.module and copied the function

I have a doubt about this condition  if (substr($name, 0, 3) == 'iva')
Where can I find the right component name? I tried vat, VAT, iva, tax...

I use the default Drupal Commerce Kickstart installation and the "tax" module.

I assume that you know how to create a module and what a hook is, you can use hook_commerce_price_component_type_info_alter like this:

<?php
function mymodule_checkout_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  if (isset($components['commerce_price_formatted_amount']['weight'])){

    // Get the row weight of total sum.
    $last_weight = $components['commerce_price_formatted_amount']['weight'];

    // Increase the row weight of the total row, so we can place the vat directly before.
    $last_weight = $last_weight + 100;
    $components['commerce_price_formatted_amount']['weight'] = $last_weight;
  }

  if (is_array($components) && count($components)>0){
    foreach ($components as $name => &$component){

      // Set the weight of the VAT row to the last position before the total sum.
      if (substr($name, 0, 3) == 'vat'){
        $component['weight'] = ($last_weight-1);
      }
    }
  }

  return;
}


Google can not connect to the server? Google Webmaster's tool tells me on a site that "Request timed out or site is blocking Google". On that site. I am wondering how to fix this.

Probably relevant info: I'm using Varnish in front of nginx and also user use iptables and DDoS deflate. The site is large but works pretty smoothly, with load less than 2 most of the times. The standard Pressflow 6 robots.txt is there and accessible through browser.

I am not quite sure how to figure out what blocks googlebots and how to fix the problem. So appreciate your hints.

Check the settings in the nodewords (or another meta tags) module look for noindex


How to grab $form_state value from text-format from drupal form I created a form for my module. I have a formatted text box

$form['message'] = array(
'#type' => 'text_format',
'#title' => 'Body',
'#format' => 'basic_html',
'#default_value' => '
The quick brown fox jumped over the lazy dog.
',
);

When I try to save the form message comes back as an array and I don't know how to pull the value out of it.

public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    \Drupal::logger('td')
      ->notice('text: @message', array('@message' => $form_state->getValue('message'),));
  }

Try with:

$message = $form_state->getValue('message')['value'];


How to I call a preprocess function for a view from a custom module? Lets say I have a view called widgets.

On a given page, /widgets/manage/ I want to add use a function that calls drupal_add_js and drupal_add_css to change the behaviour and appearance.

If I wanted to make a change to the widget view in a theme, I'd change this file:

views-view--widgets--page.tpl.php

But, I want to change this in a module, so I can easily switch a feature on when I enable a module.

I don't need to add any other template files, I just want to call a few functions in PHP.

What is the best way to do this, and what would be the relevant hook to use here?

A template preprocess hook would be the best place. The naming convention for those functions is standard so you should be able to use

function MYMODULE_preprocess_views_view__widgets__page(&$vars) {
  drupal_add_js('...');
  drupal_add_css('...');
}


How to integrate messaging into a custom module? I'm working on a custom module to handle time off requests for an intranet site and I'd like to be able to have the module fire off email notifications to a configurable list of users -- specifically, the requesting user's supervisor and also CC: an HR representative.

I've looked at Notify and Notifications and I assume that one or both of those expose an API but I can't find any documentation about how to integrate that into a custom module. I also looked at Rules, though I'm not sure that's the best solution.

I could always do a completely custom job but I'd hate to reinvent the wheel if there's a better Drupal-style solution like hooking into one of these existing notification modules.

Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.
If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its Answers Notification sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.


How to expose filter for entity reference as dropdown in the Search API view? In my Search API view, I'd like an Exposed filter > Entity reference to be a select box, not a text field.

Details

I have a view which I created like:

Views > Add new view > Show: default node index

So it uses the Search API index as a basis.

In the Search API I have ticked to index field_entity which is an Entity reference > Content_type: entity (confusing naming, I know).

I want the user to go to the views page & be able to filter the view results by field_entity (which is an exposed filter/entity reference).

The issue is the view shows the exposed filter as a text field. I have edited field_entity & checked the box Render Views filters as select list - this works fine for a normal view but not for a Search API view.

Question

Can I somehow convert this text field to a select box?

To clarify, I cannot use custom or contributed modules on this project, so it needs to be done without using hooks, or other modules, etc.

Try to use TYPE => String. This work for me.


Theming main menu with block--menu.tpl.php not working My template file block--menu.tpl.php is not catching my main menu block. It works for custom menus. Am I missing something on this? I don't have any other specific block overrides.

I'm running Drupal v7.10

main-menu comes from system module, so it should be block--system--main-menu.tpl.php

Cheers


Displaying non-empty fields in full node view Using drupal 7 I have imported an excel spreadsheet into a database and mapped about 20 fields into a Custom Content Type. Not every field contains data in every record. I've created a couple of Views - one based on the Glossary that gives me a searchable form for the entries, and a separate Block view, which gives me the ability to hide empty fields and show random nodes.

However, when I click on a record to view the full node, the display shows all the fields, including the empty ones. If I edit the node, and then save it, when viewed the empty fields are hidden.

Is there a simple way to hide those empty fields all the time in full node view. Can I do it from within Views(3)? I'm not a programmer so not sure that I could edit a page template if that is what is required.

If, when you edit the node, it displays correctly, this makes me think that the import may have added whitespace into the fields? Is that possible? I would recommend using Migrate for importing data. Even from files.

Either way, Views will not work for a node view ie, node/nid. You could use Views to create a landing/index page and hide empty fields pretty easily.

Rather than change the display, I would be more concerned with the quality of data in the fields (ie, whitespace) and would look at using something like VBO for cleaning the data. Are there many nodes? You could even just write a simple SQL update statement, something like;

UPDATE {field_data_field_blah} SET $value_col = NULL WHERE $value_col = '';

Note, pseudo query. :)


Setting up REST post request I am having issues sending a POST request to create a node with Drupal 8 Core REST. Here are the steps I have went through several times. Note that these steps are in effort to produce a working example, I am not worried about the security implications as of yet.

Install latest version of drupal 8
Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization)
Go to permissions page. Find RESTful Web Services permissions and allow delete, get, patch, and post for all users. Find Node Article permissions, allow create, delete and edit for all users.
Launch Dev HTTP Client in Chrome. Input the following request:

After hitting Send, I receive the following message which I believe should be a 201 and not a 200 if a node were to successfully be created. I think the REST part is working, its just I cant seem to figure out how to get POST to create a node.

I am having trouble finding any documentation on making post requests to Drupal 8 REST. Insight into how to construct these requests so that Drupal can parse them successfully would be very helpful.

As I still ran into a lot of 403 errors, I'll summarize my overall solution (Drupal 8.0.1).
Setup and configuration
Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization). Enable the relevant permissions of RESTful Web Services and for creating the relevant Nodes.
Get a CSRF token
GET http://your-drupal8/rest/session/token
POST to create a new node
POST http://your-drupal8/entity/node?_format=hal+json
Note that the URL for POST seems to be /entity/node rather than /node.
Headers
Authorization: Basic QWRt...
X-CSRF-Token: zCf...

Data
{
"title": [
  { "value": "atest2" }
],
"type": [
  { "target_id": "article" }
],
"_links": {
  "type": { "href": "http://your-drupal8/rest/type/node/article" }
}
}


How to create a GET-form For example a filter form on admin areas can best be GET forms, that way they are bookmarkable and can filters be maintained across pager-pages.

How can one best use form_api for such forms? Will the _validate hooks be submitted? Can the _submit hook be omitted?

For example views-exposed filters work this way; But the code in views handling this is convoluted and complex, too complex to be used as good example for when developing custom interfaces with simple filter forms.

Use the #method parameter of the form like this:

<?php
  $form['#method'] = 'get';
?>


when to use include (inc) files in module development I think I understand the structural differences of a .inc file (compared to a .module), but could someone describe the design differences?  I see drupal example modules calling an .inc file with hook_menu, or I see call .inc file for function defintions.

Under what circumstances does one put code in a .inc file?  Any general design guidlines that some adhere to?
Is there any advantage other than clarity as to why one would use an (or multiple) .inc file? performance? versioning?

thanks!

As general rule, I would put in the module file the code that is required more often (e.g. helper functions used from more than one function), and in .inc files the code that is not used so often, or that is used for specific pages.

Since Drupal 6, the code automatically loads the files containing the page callbacks, or the form builders used for the menu items. For that reason, page callbacks for administrative pages are normally put on .admin.inc files, while page callback for normal pages are put on .pages.inc files.

Since Drupal 7, files containing classes are automatically loaded when a class is instantiated. Drupal 7 allows modules to define in which files their hooks are defined (through hook_hook_info()). For example, system_hook_info() defines the .tokens.inc files as files where hook_token_info(), hook_token_info_alter(), hook_tokens(), and hook_tokens_alter() implementations can be found; in this way, those files are automatically loaded when one of those hooks are required.
This allows to further split the code in files that are loaded when necessary, and code that is always loaded from Drupal.


First things first with Ajax Somehow I can't get through the first Ajax lesson.

This is the code of a simple module that I put together:

function myajax_menu() {
  $items = array();

  $items['myajax/param/%'] = array(
    'page callback' => 'dynamic_products_ajax_callback',
    'page arguments' => array(1),
    'access arguments' => TRUE, // array('access dynamic_products content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function myajax_ajax_callback($type = 'ajax', $param){
   if ($type == 'ajax') {
    $commands[] = ajax_command_html('#myajax_wrapper', '[Content returned for argument ' . $param . ' will be here]');
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }  else {
    $output = t("This is some content delivered via a page load.");
    return $output;
  }
}

This is my markup.

drupal_add_library('system', 'drupal.ajax');

// Output a link
print l(t('AJAX 12'), 'myajax/param/12', array('attributes' => array('class' => array('use-ajax'))));
print l(t('AJAX 20'), 'myajax/param/20', array('attributes' => array('class' => array('use-ajax'))));
// Output a wrapper
print '

';
?>

All I'm getting is a JavaScript alert that informs me about AJAX error that occurred, and the result code is 200.

Is the example module missing anything?

Question revision:

After much googling I've come up with a very rudimentary working Ajax example that does what I want - it replaces HTML of a wrapper with a response obtained from a dynamic link. Hope it'll be of some help for newbies.

Module:

<?php
function myajax_menu() {
  $items = array();

  $items['myajax/param/nojs/%'] = array(
    'page callback' => 'myajax_ajax_callback',
    'page arguments' => array(2,3),
    'access arguments' => TRUE,
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  $items['myajax/param/ajax/%'] = array(
    'delivery callback' => 'ajax_deliver',
  ) + $items['myajax/param/nojs/%'];

  return $items;
}

function myajax_ajax_callback($ajax, $param){
    $is_ajax = $ajax === 'ajax';

    drupal_add_library('system', 'drupal.ajax');

    if ($is_ajax) {
      $commands = array();
      $commands[] = ajax_command_html('#myajax_wrapper', "This is some content delivered via a page load with param " . $param . ".");

      return array(
        '#type' => 'ajax',
        '#commands' => $commands,
      );
    } else {
      drupal_set_message(t('JavaScript should be enabled to avoid page reloads.'));
      drupal_goto();
    }
}

The markup:

<?php
print l(t('AJAX 12 '), 'myajax/param/nojs/12', array('attributes' => array('class' => array('use-ajax'))));
print l(t('AJAX 20 '), 'myajax/param/nojs/20', array('attributes' => array('class' => array('use-ajax'))));
?>

The problem with disappearing admin_menu persists. If anyone could tell me why...

The problems with your original (first) question are as follows:

Your callback function expects 2 parameters, but you are providing just one.
You are missing nojs in your url.
You are giving param as a parameter to your callback function, but you wanna % instead/

So it should look like something like this:

  $items['myajax/param/nojs/%'] = array(
    'page callback' => 'myajax_ajax_callback',
    'page arguments' => array(2,3), // drupal starts counting from 0 so nojs is 2nd and % is 3th arg
    'access arguments' => TRUE,
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

I hope this will help someone.

P.S.
sorry for my English


hierarcical select not apply parent restriction i want to add a  "category" field in my custom content type.category type is "terme refrence" with hierarcical select wideget . in settings of it i restrict it with set parrent term for it

but in my form not resriction happend !!!

but in $form['field_category']['und']['#config'] have this

what is the problem and what is the correct way to restrict HS to pick up only sub term of optional term?(i have a vocabulary with a lot of term,i don't want split it to some vocaublary)

eventually i found  this is a bug in hierarcical select module, and the
patch in here

i hope this  be useful.


Module for recommendations based on Solr I would like to ask if there is any module for recommendations (products,nodes etc)
based on Solr.

I have searched on Drupal.org, and I have found Content recommendation modules, which doesn't list any module using Solr.

Actually, if you go to Apache Solr's 'Pages/blocks' configuration page at admin/config/search/apachesolr/search-pages, you should see whether your "More like this" (which is like a "Related content") block is enabled.

If it's not, just click on the "Add search block "More Like This" as shown below:

That will take you to a page where you can configure your 'More Like This' block.

you can title it and call it something like "Similar Products",
you can define which content types it recommends (if you only want articles, or regular pages or just products to appear in this block) --> set that in the 'Filters' section which is collapsed by default
you can configure settings about the word matching it uses to pull up relevant content (how frequently words must appear or excluding words that are too short or too long from being matched on, etc)

Would this default block that comes with Sorl meet your needs?


Inserting div wrappers - changing hierarchy of the html I have placed a number of blocks in my Main Section of the site. I have finished all the standard styling for the site, but now that I've moved on to the mobile/phone layouts, I find that I need more control over this list of blocks - I need to wrap some of these blocks so as to position them properly.

Image: http://i720.photobucket.com/albums/ww203/Nongolf/divhierarchy.jpg

I have looked at CCS Injector (which would be more aptly named 'CSS Adder'), and moving blocks for mobile browsers, but far as I can tell I can only move all blocks or none at all.

I really do not want to change the default sections for the blocks now, as the styles are all in place and would be largely ruined by moving them to another section.

So now I'm about to use some jQuery magic to strong-arm the html. But before I do so I wanted to ask you good people if there's another way?

Completely forgot to return and give my solution. This is it:

jQuery(document).ready(function() {
    my_selection = [];
    my_selection.push(['#block-views-dyn-box-1-slider-block']);
    my_selection.push(['#block-views-dyn-box-2-slider-block']);
    my_selection.push(['#block-views-dyn-box-3-slider-block']);
    my_selection.push(['#block-views-dyn-box-4-slider-block']);
    my_selection.push(['#block-views-static-boxes-test-block']);
    jQuery( my_selection.join(',')).wrapAll('&ltdiv class="dyn-box-wrap"&gt&lt/div>');
});

I'm little more than a jquery novice, so I'm sure there are more efficient ways, but this worked just fine for me.


The 'drupal' way to implement delete button UI: part 2 I asked this question earlier The 'drupal' way to implement delete button UI
The answer worked perfectly. I would like to take it a step further and make sure my routing is done the best way for Drupal. (I'd hate to think there's some uber-powerful method out there I'm missing out on).

snippet from hook_menu():

$items['bluenose/rmlist/%'] = array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);
$items['bluenose/rmlistitem/%']=array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);
$items['bluenose/rmavailableprop/%']=array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);

The method those route to:

function bluenose_app_rmelement($type, $id)
{
  switch($type)
  {
  case 'rmlist':
    bluenose_app_remove_wishlist($id);
    drupal_goto('bluenose/wishlists');
    break;
  case 'rmlistitem':
    bluenose_app_remove_list_item($id);
    drupal_goto('');
    break;
  case 'rmavailableproperty':
    bluenose_app_remove_available_property($id);
    drupal_goto('');
    break;
  default:
    break;

  }
}

Just to clarify the flow:
There are three hook_menu items that route $type and $id to a common rm* method.
This method switches among possible $type params. When it hits the right one, it calls the appropriate remove method (which performs basic crud), then calls drupal_goto() with a url that makes sense to the end-user.

How's that method chain look to you guys?
Thanks a lot!

It does look good! But you could remove the repeating hook_menu items as well.

When I said the following,

  When the entity gets complicated, I often end up writing a single menu
  router to handle them all. The operation argument of a menu path
  (edit, delete, clone, disable, etc) can be a wildcard loader as well,
  and you can easily validate it using a method_exists() call.

I actually meant that you'd use one menu router item that passes extra variables to resolve the call to an actual function. Now that you have posted some real code, I'd go ahead and show an example for you. Note that this is not an official way to do this, but I practice this quite a lot and never had a problem.

The only menu router item we need.

$items['bluenose/%/%'] = array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_CALLBACK,
);

The page callback to handle 'em all.

function bluenose_app_rmelement($type, $id) {
  switch($type) {
    case 'rmlist':
      bluenose_app_remove_wishlist($id);
      drupal_goto('bluenose/wishlists');
      break;
    case 'rmlistitem':
      bluenose_app_remove_list_item($id);
      drupal_goto('');
      break;
    case 'rmavailableproperty':
      bluenose_app_remove_available_property($id);
      drupal_goto('');
      break;
    default:
      break;
  }
}

Now, you will notice that the menu router item is actually of type MENU_CALLBACK, and its not of type MENU_LOCAL_TASK. If you want to make it a local task, it has to be defined so in the hook_menu... But you can also do so in a hook_menu_local_tasks_alter() hook implementation.

If you absolutely need to make all the operation links to be MENU_LOCAL_TASKS, you can either go for the multiple router item way (from your original question's snippet) or implement hook_menu_local_tasks_alter(). With this hook, you are dynamically adding menu router items only when the current router item is what we are after.

Also, note that menu paths that immediately execute the functions are vulnerable to CSRF attacks. When you create the URLs, you should add a token to the link and validate it in the page callback. See drupal_get_token() and drupal_valid_token().


how to optimize setting theme suggestion for different languages? I've been trying to look for a way on how to optimize theme suggestions for different languages. The code below is a snippet of what I have been working on.

One is for english and one is for Spanish. Is there a way I can minimize this into a single code instead of breaking it down for multiple languages?

// Template based on current url
// News Press Room

if ($current_url == '/iom/news-press-room') {
    $suggestions[] = 'page__news_press_room';
}

// News Press Room(Spanish)

if ($current_url == '/iom/es/news-press-room') {
    $suggestions[] = 'page__news_press_room';
}

Check the example in hook_theme_suggestions_alter() for language (second one below)
You can add more specific suggestions by appending the content type.


how to retrieve refrencing parent id with EntityFieldQuery I am very new to EntityFieldQuery. I understand how you create a query with this class. However, I have a node which is referenced (with Entity Reference) by a parent node. I would like to use EntityFieldQuery to retrieve the parent id. Can this be done?

Without extending the class I'm pretty sure not. The reverse relationship isn't defined as a field, so EntityFieldQuery won't be able to help.

Don't forget entity reference doesn't define a parent/child relationship, it's literally just a relationship from one entity to another. A single entity can be referenced by any number of other entities, so the notion of a single 'parent' doesn't conceptually exist.

If you want more advanced relationships you might consider converting to the Relation module. It has a RelationQuery class which wraps around EntityFieldQuery to add relationship-specific functionality.


Redirect to PayPal site without payments pane in checkout On the checkout forms review pane when i select to pay with Paypal WPS and submit the form it get's redirected to an intermediary pane which is the payments pane.
And only after 10 seconds it redirects to the PayPal site, there's a button as well..

Could this step be left out? If so, what is the right configuration.

So when selecting PayPal WPS payment and submitting the form it should automatically redirect to the PayPal site.

Commerce Paypal WS already redirects automatically by using the "offsite_autoredirect" flag in hook_commerce_payment_method_info:

  $payment_methods['paypal_wps'] = array(
    'base' => 'commerce_paypal_wps',
    'title' => t('PayPal WPS'),
    'short_title' => t('PayPal'),
    'display_title' => $display_title,
    'description' => t('PayPal Website Payments Standard'),
    'terminal' => FALSE,
    'offsite' => TRUE,
    'offsite_autoredirect' => TRUE,
  );

The behaviour of this flag is to redirect automatically:

if (!empty($payment_method['offsite_autoredirect'])) {
  $form['#attached']['js'][] = drupal_get_path('module', 'commerce_payment') . '/commerce_payment.js';

And the js is the simplest it can be:

  Drupal.behaviors.commercePayment = {
    attach: function (context, settings) {
      $('div.payment-redirect-form form', context).submit();
    }
  }

So if you're experiencing a 10s delay on this operation, you need to debug what's happening in your payment page to cause this slowness. Check things like other panes you've put there (there should be just the payment one), cache, js compression and so on.


How can I add my Bootstrap classes to a custom menu? How can I add different Bootstrap menus to menu_tree_output()?

I know this is a very common question asked by a number of people earlier. I have found tons of answers, but none of them are working for me. However, I have tried a number snippets and here is the latest piece of code I am working on to get all menus and sub-menus.

<?php
  $menuTree = menu_tree_all_data('main-menu');
  $menu_tree_array = menu_tree_output($menuTree);
  print render($menu_tree_array);
?>

It works and prints all the submenus, however, It adds the same "menu" class to all parent ul. Rather I would like add sub-menu classes like the below output:

        Home

        Biography

        Services

What you want is theme_menu_link(). See the example here.


How to Split Regions Is there any way I can split a region into 2 different regions. For example, in Garland theme I want to split the HIGHLIGHT block region horizontally into two regions..
is it possible ?

Any help would be so much appreciate.

You should build your own theme and edit the tpl file to apply the layout you need

the easiest way is to build child theme and edit what you need in tpl files

create child theme


Get payment before users create a node When users create a node, they should be redirected to a payment page; if payment is successful, the user can see the node.

Is there any way to achieve this?

Although not open source, there is the paid for module called 'pay to publish'.

I've not used this exact module, but have used this companies products before and they worked 100% as advertised...

For some reason my phone will not allow me to paste the URL in here, so just Google 'moneyscripts Drupal pay to publish'.


How to set up subscription service with credits that visitors can use to buy products? I have a client that has a Drupal 7 site with Drupal Commerce already running to manage his store of products.

He wants to add a subscription service where users could pay a monthly subscription fee, and this fee would give them credits to buy products with.

Just wondering the best way to set this up/what recommendations people have to implement this.

The Drupal Commerce site builder's guide refers to modules named Commerce Credits and Commerce Credits Transactions for building sites with a "store credit" feature.

However, these modules seem to be unmaintained and aren't covered by Drupal.org security policies, so you would need to evaluate the value of using them in your integration vs the risk of having to support a site using them without much help.


Module for getting what is visible from user's webcam I need a module that allows users to show what is visible from their webcam.
Is there a module that can do this?

I don't think there is exactly what you want at the moment, but the following module might help you on your way:

Webcam field - This is still in development

  Webcam field provides dynamically updating webcam image fields. This
  module is compatible with Colorbox.

Videochat - Has no recommended release, although seems to have a full 3.6 version

  The Video Chat module adds a fully hosted free video chat to a Drupal
  website. The chat application and video hosting are courtesy of
  Camamba and ad-supported. We hope it provides an alternative to all
  the payware chat modules out there.

Media: Webcam - This is in beta

  This project (still under active development) will add a Webcam
  capture tool for video and images to FileField. Video requires a Red5
  or Flash Media server to also be available; documentation for this
  coming soon enough.

Video conference - This requires some further set up of server components, but if you want live video streaming I should imagine you're aware that you will most likely need a RTMP protocol set up.

  VideoWhisper Video Conference is a modern web based multiple way video
  chat and real time file sharing tool. It can be used stand alone or
  integrated as extra feature to existing sites. Internet based video
  conference software is great for bringing physically distant people
  together in meetings, trainings, conferences, live events, recruiting,
  consultations, coaching and of course casual community chat.

Paid solution

AVChat

This comes at a price of $285 plus $49 for the Drupal module


Require v8 only contrib module with v9 patch Given I have Drupal 9 composer installation with composer-patches plugin
and given a contrib module with a stable v8 release, but no v9 release (not even dev branch)
and given that contrib module has a working v9 patch in the issue queue

is there any method to install that module + patch in composer? Even if I manually add both, the package and patch, to my composer.json, I still can't require or update this module with composer due conflicting versions. I really want to avoid duplicating /contrib code into my project's /custom codebase. My current workaround is:

forking that module to my own, private git repo
applying patch there
creating a new composer.json in my private git, and changing the package vendor to my custom_private_vendor
adding my private git as VCS repo in the D9 project's composer.json
and then composer require custom_private_vendor/contrib_module

This fulfills my goal of not duplicating the contrib module in my project's custom codebase, but every time I do this I feel the urge to wash my dirty hands.
Is there something more elegant like composer require drupal/contrib_module --apply-patch-first or can I somehow target drupal.org's git with a specific patch included?

You've got the right idea but you don't need to fork Drupal's repository. You can set up composer to read Drupal's git repo instead of using packagist for the naughty modules like this:
    {
        "type": "package",
        "package": {
            "name": "drupal/cache_control_override",
            "type": "drupal-module",
            "version": "1.0.0",
            "source": {
                "type": "git",
                "url": "https://git.drupalcode.org/project/cache_control_override.git",
                "reference": "8db91684a427366d8f9c51f60cbac10c2d586d95"
            }
        },
        {
          "type": "composer",
          "url": "https://packages.drupal.org/8"
        }
    },

Note the 'reference' is a commit hash, though it looks like you can also use tags. Also note that the custom git type: package repo must be before Drupal's default type: composer repo in your composer file.
And then patch as normal using composer:
"drupal/cache_control_override": {
    "Drupal 9 Compatibility (3132036)": "https://www.drupal.org/files/issues/2020-04-29/Drupal-9-readiness-3132036-2.patch"
},

Thanks @miststudent2011 for pointing out that this doesn't automatically install dependencies which I can confirm. You will need to require those yourself!
(Shamelessly stolen from @acbramley on Drupal Slack because wider dissemination of this knowledge is worthwhile)


Avoid duplicated external links I would like to add a section on my website (Drupal 7) which consists of articles with external links (as source). To avoid spam and duplicated content, I would like to avoid that users may add a URL more than one time. Basically, I need something which checks if the external URL is unique and not being used more than once.

I've looked for modules on Drupal.org, and tried googling some information. But I couldn't really find a solution. The Link checker module seems fine for checking if the URL is still available, but it doesn't avoid the same URL is used more than once.

You should take a look at the Unique Field module:

  This module performs additional validation when a node is created or
  updated by a user to require that a node's title, author, language,
  and CCK fields are unique within a given context.


How to displayed fixed menus, extracted from the main menu? I am using a Bartik subtheme, and would like to split the main menu into 4 smaller menus, and display them in the four footer columns, side by side. I would like the same menus to be displayed on all pages.

How would I do this?

If you go to admin/structure/menu/add and add four menus (Footer 1, Footer 2 ...), four blocks of the same name will also be created. Then go to your Main Menu and move the links into the new menus you have created.

Place these blocks where you want them at admin/structure/block and modify your stylesheets to make sure they display the way you want.


Is the a module that will allow me to quickly switch from administrator to user? Is there a module that will allow me to quickly switch from the administrator view of my site to the user's view?

I currently use Firefox to login as admin and IE to login as a user. This arrangement works, but is very, very slow.

You can use masquerade module.
Part of description :

The Masquerade module allows site administrators (or anyone with
enough permissions) to switch users and surf the site as that user (no
password required). That person can switch back to their own user
account at any time.
This is helpful for site developers when trying to determine what a
client, logged in as themselves, might see when logged into the site.
The masquerade module is designed as a tool for site designers and
site administrators. While masquerading, a field is set on the $user
object, and a menu item appears allowing the user to switch back.
Database log (watchdog) entries are made any time a user masquerades
or stops masquerading as another user.


how to create two or more view with in a single view I want to create a view which outputs as page . Within that view ,i need to create two or more views they will react based on the arguments to their parent view

What you need is a views attachment to the main parent view. Fist you create a new Views Display, say a block. then on the parent view, attach that view to it. Now turn on inherit contextual filters so you can pass the arguments over to the other view. If you want finer control with the output and fields you can try: http://drupal.org/project/views_php


Drupal 7 - Array to string conversion in DatabaseStatementBase I have an error on a Drupal 7 site that I cannot solve.

Notice: Array to string conversion in DatabaseStatementBase->execute() (line 2168 of ...

I cannot use dpm, can't find a way to debug, and can't see what is the data that causes the problem.

Anyone would know how I could debug this? really appreciated

Webchick's Quick-and-dirty debugging is so useful in this type of situation that I've sometimes had a projects with it as a ready to apply patch.

Find drupal_set_message()

function drupal_set_message($message = NULL, $type = 'status') {

in bootstrap.inc, and add

// DEBUG: Go track down that stinkin' error...
if ($type == 'error') {
  $message .= '<pre>'. print_r(debug_backtrace(), 1) .'</pre>';
}
// END DEBUG

at the very top. This will give you a backtrace on the error, helping you to trace down it's source. It could be good to know that there are instances where this runs PHP out of memory, if you have a lot of errors, so you may need to add extra conditionals in there at times.


Authentication providers: no token_bearer I created a custom resource for a Drupal 8 REST call. For some reason, I can't see either basic_auth or token_bearer from the authentication providers. I installed simple_oauth and still can't see either basic_auth or token_bearer.

The code I am using is the following one.

config/install/rest.resource.sample_index_resource.yml

id: sample_index_resource
plugin_id: sample_index_resource
granularity: resource
configuration:
GET:
  supported_formats:
    - json
  supported_auth:
    - basic_auth
    - cookie
    - token_bearer

src/Plugin/rest/resource/SampleResource.php

/**
 * Provides a Sample Index Resource
 *
 * @RestResource(
 *   id = "sample_index_resource",
 *   label = @Translation("Sample Index Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/sample-response/{category}/{alias}"
 *   }
 * )
 */
class SampleResource extends ResourceBase {
/**
* Responds to entity GET requests.
* @return \Drupal\rest\ResourceResponse
*/
public function get($category, $alias) {
  // Return response
}

The HTTP Basic Authentication module needs to be enabled to be able to use basic_auth as authentication provider. I don't know which module I should enable to be able to use token_bearer.

What module do I need to install to get token_bearer as authentication provider?

I think your yml syntax is wrong (or out-dated) look at rest.resource.entity.node.yml for a correct example.
Or use the "REST UI" module to specify your resources.

It should look more like:

configuration:
  methods:
    - GET
    - POST
    - PATCH
    - DELETE
  formats:
    - hal_json
  authentication:
    - basic_auth


How to import nodes and their translations from a csv using Feeds? Is there a way to provide the original and translated values of the title and the body in a csv for example, and the Feeds module to produce the translated nodes automatically (and synced with the original nodes - [tnid])?

I have tried using "Feeds: Entity Translation" but with no success.I have set the fields to be translatable but i don't see the translation fields available in the node-importer.

Any advice on the best practice on this?

Should i better go with a Migrate implementation?
All ideas/implementations welcome!

Thanks.

While Feeds:entity translation should be awesome when finished you can try this Solution

  I created two feed imports.
      I forced the language field for each one.
      Two separated nodes were created for each content (one in each language) but it didn't links the translations.
      So I used a SQL query to finish the job, it's based on the feeds uuid :

I think he meant: based on guid not uuid


Creating threaded nodes I know with Drupal you can have threaded comments. I wish to create something similar using nodes.

Where a node can be replied to with a node of the same type. I would then like to try and create a view of this. Do you think this is possible or should I look at bending comments to be more like nodes.

Sounds like Node comments to me. With it you can use normal Contentypes as comments. There is already a view included in the module.


Drupal mobile theme doesn't display image I am working on a mobile version of a drupal  website and I am using mobile tools to switch theme between desktop version and mobile version based on url. I am using fusion mobile theme on the mobile side.
Now the matter is that no images are displayed in views in the mobile version. There is some kind of filtering that disables images on the theme but I can't find out where is that.

I have just found the solution: It was just a permission that wasn't given to the anonymous user.


How can I display/hide a div based on taxonomy term value on node.tpl.php file? I am not a dev, but am trying to show and hide a div for on a particular node type node.tpl.php file based on taxonomy term value.

can someone please let me know how to do this.

*I AM ADDING THE ANSWER HERE AS I AM NOT ELIGIBLE FOR ANSWERING *

I have a div which prints the taxonomy value of a node (where 30 is the vacabulary ID):

    <div class="node-r-status-tid-0 <?php print $term_css;?>">
        <?php print THEME_NAME_taxonomy_list($node, 30); ?>
    </div>

Below is the PHP code to make the dive show and hide:

    <?php
    if ($node->taxonomy[868])
      $tid = 868;  // This should be the taxonomy term id that you want to theme on
        foreach ( (array)$node->taxonomy as $term ) {
          if ( $term->tid == $tid ) {
            $term_css = " node-r-status-tid-" . $term->tid;
            break;
          }
        }

    if($node->taxonomy[869])
      $tid = 869;  // This should be the taxonomy term id that you want to theme on
        foreach ( (array)$node->taxonomy as $term ) {
          if ( $term->tid == $tid ) {
            $term_css = " node-r-status-tid-" . $term->tid;
            break;
          }
        }
    ?>

Using css classes I make the dive display:block or none.

Please let me know if the above code can be fine tuned further

Thanks,
Anand

In Drupal 6 add somthing like this to your template.

foreach ($node->taxonomy as $term ) {
  if ($term->tid == YOUR_TID) {
     print "<div>...</div>";
  }
}


Most efficient way to do simple Entity API queries by node id and content type? A very basic 8.x API question.

What is the approved/simplest methods of confirming a node matching a certain content type and ID exists, and then loading it as an object?

(Use case: a module which accepts a node ID in the URL, that needs to be checked.)

Currently I have:

$node = \Drupal::entityTypeManager()->getStorage('node')->load(123);

if ($node->getType() == 'application') {
  return $node;
} else {
  return false;
}

My first attempt was in reserve (longer/less efficient):

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'application')
  ->condition('nid', 123)
  ->execute();

// followed by entityTypeManager()->getStorage('node') etc.

But I was wondering if there was a way to make entityQueue() return a flat array of IDs rather than an associative [1=>1,2=>2,3=>3] which you then have to mess around with.

I don't know how your module URL/API is structured, but if your module route has something like myapi/foo/bar/(id) to return a node object, you could upcast it instead. Here is an example from the node module:

entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    node: \d+

{node} will be upcast to a node object and available in the incoming request to the receiving class.

See: https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

So when you pass that to the receiving method:

use Drupal\node\NodeInterface;

class ExampleController {
  public function foo(NodeInterface $node) {
    if ($node->getType() != 'application') {
      // do something, throw Exception, etc?
    }

    // Otherwise this node is an application type.
    return $node;
  }
}

There may be a way to expand on this in the route definition, so you can upcast the node and ensure it is a specific type before doing anything else, eliminating the checking in the method - but I am not sure.

Perhaps:

https://symfony.com/doc/3.4/routing/requirements.html
https://symfony.com/doc/3.4/routing/conditions.html


How to add back button for specific content? Just realised all my pages are now displaying a back button with this code I added to node.tpl.php <FORM><INPUT Type="button" VALUE="Back" onClick="history.go(-1);return true;"></FORM>

Is there a way to change the code to include only some node content types?

Duplicate your node.tpl.php file (in your theme's folder) and rename it to node--[content type].tpl.php. Use machine name of the content type, which can be found in Administer > Structure > Content Types
Replace content type with name of your content type. (i.e for page content type, node--page.tpl.php)

Don't forget to flush all caches when you have placed the new code in this new template.

Drupal will now use this custom template file for this node type, and the node.tpl.php base template for other types.


How to add attributes to a specific field's image subtheme/templates/image/image.html.twig

controls the style of every image at a website is there a way to overwrite the image.html.twig for a given field let's call it

field--profile--field-trainerfoto--trainer

The field template would be

field--profile--field-trainerfoto--trainer.html.twig

what would the templates name for the image.html.twig be that just overwrites the output of the img tag for the image in the field?

One quick way of achieving this is to preprocess the field before it reaches Twig (in MYTHEME.theme) like this:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_field(&$variables, $hook) {
  if ($variables['field_name'] == 'field_avatar') {
    if (!empty($variables['items'])) {
      foreach ($variables['items'] as $delta => &$item) {
        $item['content']['#item_attributes']['class'][] = 'foo';
      }
    }
  }
}

Core's template_preprocess_image_formatter() then takes care of putting #item_attributes and the class into the <img> tag for you.

The normal way of offering alternative template names based on context is
implementing hook_theme_suggestions_HOOK() or hook_theme_suggestions_HOOK_alter(). In this case the latter as MYMODULE_theme_suggestions_image_alter().

But the problem here is that there's not much context about the field which will eventually wrap this image at this point. template_preprocess_image_formatter() only carries through the attributes that will end up on the image element itself.

You could be a bit sneaky and use the fact that we have already put the class (or some other identifier) into #item_attributes when preprocessing the field and use that to generate a new template name for the image once it gets to be rendered:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(&$suggestions, $variables) {
  if (!empty($variables['attributes']['class'] && in_array('foo', $variables['attributes']['class'])) {
    $suggestions[] = 'image-foo';
  }
}

It has the side-effect of adding an extra class (or other attribute) in your tag by default, but since you could now create image-foo.html.twig you could probably compensate for that in the template by removing it there if absolutely needed.

Now just make sure your "field identifier" is fairly unique (and recognizable) so you can figure out where that template suggestion in your theme debug output comes from in the future.


It is it difficult/time consuming to set up a Drupal site that users pay to subscribe to? I have never implemented a payment system in Drupal but it looks like I will have to do it in the very near future. I have plenty of Drupal experience, including writing custom modules, but I know nothing about payment systems.

I know of the Ubercart and Drupal Commerce modules and presume this is the standard way to go when setting up payment system for a Drupal website.

Basically I need to let users pay for monthly subscriptions for the site, and then money will be automatically taken from users' accounts on a monthly basis, until they cancel the subscription or it runs out.

Is this difficult/time consuming to set up? Will it take a weeks to implement for someone like myself with no prior experience in this area? How long rougly would I be looking at to get this set up?

I've just finished writing a multi-tiered subscription system for an online business directory, using Commerce. Without going into too many details (the clients might be watching ;) it took a fair bit longer than a week to complete and sufficiently test the subscription/payment element of the system, and I'm pretty familiar with how payment processors and Drupal Commerce work under-the-hood.

FWIW I took most of my inspiration from the Commerce subscription products PayPal module, which:

  integrates the PayPal Recurring Billing functionality into the Commerce subscription product module.

It's a feature module so you can just chuck it into a site and see what it does (sets up a product type of 'subscription', adds fields to the user and order entities for tracking subscriptions, handles the recurring IPN notification from Paypal, etc.)

If you read through that module code you'll get a good idea of what's required to set up a subscription system using Commerce. If you also need to write a payment processor from scratch then it'd be a good idea to look at the Commerce Paypal module at the same time so you can get a good overview of what needs to be done.

I'm afraid I can't comment on the UC Recurring Payments options as I've never used it.


Changing the text displayed in an Entity Reference Autocomplete I have an entity reference autocomplete which is populated using an Entity Reference View.

I would like users to be able to type in this autocomplete and for the suggestions to look like this:

"[title of node] [value of custom field]"

However, it seems like there is no way to achieve this. If I add extra fields into the Entity Reference View, these do not display. If I override the output of the title field in the view, this is ignored. It seems like the Entity Reference Autocomplete simply uses the entity title and ignores the 'Fields' section of the view.

Does anyone have any experience with this? I'm sure it was possible in D7!

You need to implement your own selection plugin for this.

I thought I've already answered a similar question but can't find it anymore.

Assuming the target is a node, extend from \Drupal\node\Plugin\EntityReferenceSelection\NodeSelection, otherwise from its parent or appropriate other child class and override \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::getReferenceableEntities().

Make that available under its own plugin id (not default:something, just something) and select it in the entity reference field settings.


Rules for how Drush vset works I want to perform some admin configurations through drush using vset the way I've used it in the past, such as the following:

drush vset site_name Example;

drush vset site_offline 1;

drush vset preprocess_css;

If I wanted to turn off email varification on the following page, is there a variable I can use drush vset to set the variable to 0 or 1?

admin/config/people/accounts

If so, how would I find the variable names for admin configurations to know which ones can be set by drush?

On administration forms system_settings_form is normally used to return form,
so the element id is same as the variable name without the "#edit-" with underscores.

For example on: /admin/config/system/site-information

id="edit-site-mail" -> drush vset site_mail peter@email.com

To turn off the email verification:

"edit-user-email-verification" -> drush vset user_email_verification 1

Drush returns all variables that match with your variable name, so if you only know part of the name you can try:

drush vget email

returns all matches:

user_mail_status_canceled_notify: 0
user_mail_status_canceled_subject: "Account details for [user:name] at [site:name] (canceled)"
reroute_email_address: "debug@email.net"
reroute_email_enable: "TRUE"

Module devel (https://drupal.org/project/devel) let you check all drupal variables on this menu callback: /devel/variable


view shows as database overriding code I've created a simple feature to export my custom views. I've downloaded the view and enabled it on the manage features screen. When I look at the view in views it tells me that the database is overriding code. I don't know why as I haven't touched the view since creating the feature. Surely the view should be 'in code'?

Even if you don't change anything, it's enough to click the 'Save' button on the views configuration page to make it override the code. You can simply revert the view if you are sure that you didn't change anything.


How to add image to only front page of Drupal 7? How to add image to only front page of Drupal 7 website ?

So for now I have this code:

    <?php
    if (!drupal_is_front_page()) {
        echo render($page['content']);
    } else {
        echo render($page['reference']);
    }
    ?>

But this means that on everypage it will show my image.

Any idea how can i fix it ?

Here is another approach:

create "a" node (pick whatever content type you want), say it's node id is 123 (generated automatically by Drupal when you save it). Or add a "path" to it like my_page_with_image.
include that image in that node and make sure your input filter that you use (i.e if you use "filtered HTML", which is what I'd recommend) accepts "images".
set node/123 as your frontpage (or my_page_with_image instead, if you added a path for it).

Next question? Maybe "How do I set that page as my frontpage"? ... Ask (via a new question, only 1 question per 'question' here ...) and pretty sure you'll get the answer to that question to ...

PS: What is so special about all your pages where you are considering using PHP for it's actual content? You are aware that using PHP for those things is in general NOT recommended, right? And that you have to be very carefull in which user "roles" will be allowed to create such pages ...