Drupal Commerce Multiple Prices I'm trying to get a two tiered pricing structure into my store. Essentially I need every product to have two prices. There's the main price but there's also a secondary price that get's triggered if the customer has more than 14 products in their cart. I can't do an across the board discount, it has to be specific prices per product.

Say product one has a main price of $20 but a hidden secondary price of $15 and product two has a main price of $50 but a hidden secondary price of $30. This will be defined on the product itself. It's all arbitrary pricing set for every product.

I figured out how to set a rule where 14 products will trigger it but I can't work out how to add a secondary price to a product then activate that price.

Luckily you have figured the harder part, counting the 14 products on user's cart. Second part is easily done, and it's called 'dynamic price calculation' or similar terms if you would like to find further information on google.

Create a rule
Event: Calculating the sell price of a product
Condition 0: (which is very important) Entity is of bundle or Entity has field or else you wont see the second price field added to the product type. It's rules assertion internal stuff and is needed, but somehow it's name is confusing.
Condition 1: If there are 14 or more products in cart
Action: Set the unit price to a specific amount
The value you pass to the action above is simply the price value in the second field!

This page could be useful, Sell Price Calculation / The life of a Price Calculation


Passing node parameters into views block I am on Drupal 7.

I have two content types. Content type 1 is called Bulletin and content type 2 is called Bulletin Text. I have a node reference field in Bulletin Text content type that allows me to link it to a certain Bulletin object.

Now, when my user is on a Bulletin Text node I want him/her to:

see all the other texts associated with that same Bulletin on a block to the side of the page;
remove the current Bulletin Text node from the list of bulletin texts, as it wouldn't make much sense, as the block would be something like "other texts from in this Bulletin".

Is there a pure Views solution for receiving the nodereference value from the current node being displayed on the page (passing that parameter into the Views block) and showing the list of nodes associated with it (also removing the current nid from the list), or do I have to play around with Contexts, Panels or custom code? What do you consider the best approach for me to solve this?

I can't give you the complete Views-based solution off the top of my head (although I think it must be possible) but the key to the solution is using 'Contextual filters' (they used to be called 'Arguments' in D6/Views2) and relationships.

Contextual filters are filters that take their value from the url, so you can narrow down the results to the current node currently. By adding a relationship for the node reference field, you can retrieve information from the nodes referenced by that field.

If I'm not mistaken, you can add a second contextual filter that makes use of the relationship, to exclude the current node from the related nodes.

Sorry this is not a complete how-to, but I hope it gets you started.


Views block doesn't appear on page if only media-type content is selected I've created a view block that has a contextual filter with a Content ID from URL. The view is only to appear on my content types if the field_aside_content has any data in it.
This field is just a paragraph reference type to a selected number of custom paragraphs that are to appear in the aside region of my page.

My problem is if I only select a media paragraph type in this content, the block doesn't display on the page. If I then select a paragraph type that is text-based, then the block displays both the media and text content. If I remove the image, the text shows fine on its own.

What I've noticed is that the only time this block doesn't seem to show up on the page is when I select a media-type of paragraph.
My image, video, map and slider paragraph types won't show up on their own unless they're accompanied by some sort of text-based paragraph type or if a menu or some other block is already in the aside that this block shows up in.

It's weird too because if I check the preview of the page when I'm editing the view, it shows the media content showing up, it just doesn't seem to actually show on the published page.

Does anyone have any idea as to what is happening here?

I've also attached a screenshot of my view settings below to show what I've done in case something needs to be tweaked here:

EDIT:

My page.html.twig file has the following code for the aside:

{% set has_aside = page.sidebar|render|striptags|trim %}
  {% if has_aside %}
  {% block sidebar %}
    <div{{ aside_attributes.addClass(aside_classes).setAttribute('id', aside_id) }}>
      {{ page.sidebar }}
    </div>
  {% endblock %}
  {% endif %}

I've noticed that if I remove the |trim filter, then the images will show up but the issue that then occurs is that even if my aside doesn't have any content in it, it will still show up on a page that doesn't need it.

The |trim twig filter in my page.html.twig was my problem as to why those blocks weren't appearing. Also, the reason that my aside always shows when that filter is removed was that in dev, it has twig debug on spitting code in that section. When twig debug is off on my production server, the aside won't appear unless content is in it and all my blocks now appear as well.


Display content during site maintenance Is it possible to display a static version of a Drupal 6 website while it's in maintenance mode? Could something similar to Boost help?

Yes, Boost can do this actually. Here's a video that explains it: http://www.drupalove.com/drupal-video/how-can-boost-help-my-site

Pages which are set to static cache will remain running while in maintenance mode.


In Drupal 7, do database queries need to be enclosed by double quotes? I am migrating custom modules from Drupal 6 to 7. Since the database API changed it's quite a lot to do. During this I stumbled upon a problem regarding quotes. I am used to enclose strings in PHP with single quotes, so in Drupal 6 I wrote

$q = 'SELECT * FROM {node} WHERE type = "page"';

However, without any pattern (as far as I could detect) some of these queries fail in Drupal 7. When changing the above line to

$q = "SELECT * FROM {node} WHERE type = 'page'";

it suddenly works. But I couldn't find any information if this quoting style is required by the new DAL. Anybody got further information on that or can confirm my observation?

Some SQL database engines are not supporting double quotes inside the query, that's why it didn't work out for you. Read more here: db_query#comment-11959.


how to get the value from a field in hook_node_load($nodes, types) I have a hook_node_load(), when I dsm($nodes), it returns an array, I need to get the value from field_tt_status (contains 1 or 0). I know I have to do something like

$status = $nodes['field_tt_status']['und']['0']['value'];

but it that doesnt work. Can someone help me?

The $nodes variable is an array of node objects. You either need to loop through the array and extract the field values, or get the first item off the array and use that. For example:

foreach ($nodes as $node) {
  if ($node->type == 'content_type') {
    $field_items = field_get_items('node', $node, 'field_tt_status');
    $status = $field_items[0]['value'];
  }
}


is_flagged with Views Is it possible to to check is_flagged in views ?

If I send POST request to this URL it works fine http://website/rest/flag/is_flagged but I want do it in Views ?

I am creating REST API using Services Module and what I am trying to check is that whether a Node is flagged by current user or not. /rest/flag/is_flagged this URL works fine but I want to do it in Views.

If its possible please tell me how I can do it ?

You could Create a Custom Service Resource for this, but IMO it's easier to do this:

Enable the Views JSON module (which is a sub module of the Views datasource module). This will allow you to get JSON output from a View.
Build a JSON data document page display for a View
Add a contextual filter for a node id, this value will be grabbed from the URL path
Add a contextual filter for a user id, this value could be grabbed from the URL path, or default to the current logged in user, that's up to you
Add a relationship to the flag in the View
Add your desired field output and watch the results preview to see your JSON assembled
Add the necessary filter(s) to limit the results to a certain user/flag/etc.

You then can consume this "resource" by doing a GET on the page path to your View.


Drupal compress (gzip) files attached to pages. How to turn it off? Drupal compress (with gzip) on the fly all files attached to pages during sending them to browser.
It takes too much time especially with PDF.

How to turn it off?

Drupal 6

edit:
Drupal do not compress pages on its own (option turned off), but apache does (output coming from php). And I want to stay it that way with exception of application/pdf (also output of php)

Is it possible?

edit2:
I couldn't change apache gzipping settings in .htaccess, but I was planning changing hosting. I've speeded it up a little and problem is gone now.

The question here is one of Apache configuration, rather than Drupal.

I'd suggest checking out the Apache mod_deflate documentation, which contains sample configurations to disable/enable compression in a variety of circumstances.


How do I create a 'page' that creates and downloads a file from within a module I have mymodule.php which contains all the logic for my site.

I need to create something like this.

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$array = array(
    array("data11", "data12", "data13"),
    array("data21", "data22", "data23"),
    array("data31", "data32", "data23"));
outputCSV($array);

function outputCSV($data) {
    $outstream = fopen("php://output", "w");
    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals); // add parameters if you want
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
}

Generally I've been adding items to mymodule_menu(), mymodule_theme(), and directing it to a mymodule_mypage() function, and oftentimes a mypage.tpl.php.

This setup doesn't really make sense for what I need to do here, though.

I need a linke like mysite.com/mypage to generate/download the csv.

I don't think that headers will work in a mymodule_mypage() function, and the template files are not appropriate because they load headers/footers etc.

I could just create the php files separately and create links to them, but I'm trying to keep things within the module and with tidy URLs.

Don't forget anything you can do with PHP you can do with Drupal, so headers work in exactly the same way.

Adding a page callback which sets headers and exits the script (with drupal_exit()) is definitely the right way to do this:

function MYMODULE_MENU() {
  $items['mypage'] = array(
    'title' => 'CSV',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_deliver_csv'
  );

  return $items;
}

function MYMODULE_deliver_csv() {
  // Full complement of headers so IE behaves
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"filename.csv\";" );
  header("Content-Transfer-Encoding: binary");

  // Print your CSV data here

  // Exit the script
  drupal_exit();
}


How to get the value of an item from a list field to add it to a computed field I am on Drupal 7 and I have issue. I want to set a token system that will make people buy token from their user account settings in order to be able to do some particular actions on the site.

So I've created three fields in the user's form with the help of Display Suite:

field_buy_tickets (Yes/No) : Yes if the user wants to add more tickets. If "Yes", field "field_nb_of_tickets" appears.
field_nb_of_tickets : is a list of numbers from 1 to 9 that the user choose one item.
field_avoir : When the user Save the changes, the number in the item chosen in "field_nb_of_tickets" should be added to the this field_avoir. I chose this field to be "computed" because I want the new value to be added to the old one, not to override it.

I was sure that it would work well, but I get an error. After a few time trying to make it work, I am still at the same point.

Can somebody help ?

Here are some pictures to illustration the case:

1. The first 2 fields

2. The third field

3. The field_avoir settings

4. The error

Thank you.

Definitely I found out what to do.
Maybe this will help somebody else.

I wrote this before :

$entity_field[0]["value"] = field_get_items($entity_type, $entity, "field_nb_of_tickets");

This is what's new :

I did put the foreign field's value in a variable before adding it to the current field :

$nb_of_tickets= field_get_items($entity_type, $entity, "field_nb_of_tickets");

$entity_field[0]["value"] = $entity_field[0]["value"] + $nb_of_tickets;

Now it works.


Save FileField file to an external server When using FileField or ImageField, files are saved to a local folder in the Drupal install. This works great and all, but up till now the media files on my website are served from a discrete server (a CDN), and I'd really like to keep them separate.

Is there a module that extends File/ImageField to allow you to specify an external server (FTP and credentials) to use as a file server?

Any advice or pointers with this is appreciated.

(Ps I've seen the CDN module, but that requires the use of a server daemon or modifying the CDN's origin... and I'm not particularly fond of either implementation.)

<3

As far as I know, there is no other way to do this in Drupal 6 than what CDN does.

In Drupal 7, this is a completely different story, however. Drupal 7 uses stream wrappers when dealing with files and it is a) possible to implement custom stream wrappers with PHP code and b) the stream wrapper can be chosen per file/imagefield.

So if it is possible to access X with PHP (FTP, Flickr, Amazon S3, ..) then it should be possible to write a stream wrapper for it and therefore allowing Drupal to write the files to that place.

This probably doesn't help you in your situation, but maybe it will help someone else, when deciding to use Drupal 6 or 7 for a new project for example :)


How to use helper/private methods with a .module file? Let's say I use a hook with a lot of code inside. To improve readability and reusability I'd like to use helper/private methods. However, a Drupal .module file is not a class.

The idea is to split big methods from this file into more readable and reusable smaller methods.

What is the correct way to call helper/private methods from a Drupal .module file?

I always follow Symfony standards when it comes to helper functions. I normally have one module for developer-central stuff where I add a class under src/Utils for that and then call it everywhere I need it. Also in *.module or *.theme files.

web/modules/custom/my_module/src/Utils/MyHelperFunctions.php

namespace Drupal\my_module\Utils;

/**
 * Class MyHelperFunctions.
 */
class MyHelperFunctions {

  /**
   * Get current multisite directory name.
   *
   * @return string
   *   The basename of the matching multisite directory.
   */
  public function getMultisiteAlias() {

    $site_path = \Drupal::service('site.path');
    $site      = explode('/', $site_path);

    return $site[1];
  }

}

web/modules/themes/custom/my_theme/my_theme.theme

use Drupal\my_module\Utils\MyHelperFunctions;

/**
 * Implements template_preprocess_html().
 */
function my_theme_preprocess_html(&$variables) {

  // Add multisite body class.
  $site = MyHelperFunctions::getMultisiteAlias();

  $variables['attributes']['class'][] = 'site-' . $site;
}

@NoSssweat suggested that the more Drupalitically correct way to do this would be to create a service to let that method be called by other modules via dependency injection as well.

web/modules/custom/my_module/my_module.services.yml

services:
  my_module.helper_functions:
    class: Drupal\my_module\Utils\MyHelperFunctions

And then you wouldn't need to use the namespace anymore, but just can call the service wherever you want:

\Drupal::service('my_module.helper_functions')->getMultisiteAlias();

Read more: When should I create a service or a utility function?


Open Field Collection in Colorbox We have a field collection containing an image and three different Text fields. How can we open the whole field collection (= all four fields (= image + texts)) within the colorbox??? The module colorbox-node does not help because we don't have separate nodes (and no URL-pathes to the content).

You can have a look at the Entity popup module, it allows you to define a separate view mode for the popup content and includes an example on how to integrate with colorbox.


list all used & unused views in site or panels, as a site audit Is there a way to list all used & unused views in site? or in panels? (as fields are listed in /admin/reports/fields). I have some complex sites with a lot of views (pages, blocks, entityreference, panes, etc.) and panels pages. While building a site we all make views to test something, then clone view, etc. at the end i may have a lot of unused views, i'm trying to delete unused views to clean site, all my views are rendered inside a panel page. I run D7, but i think this will be helpfull also in D8

I think this module might help you.

https://www.drupal.org/project/views_maintenance

Module provides administrative page with detailed information about each display use cases and its status for each enabled view. It helps you to detect unused and broken displays to modify them or completely remove from your site.

Regards,

Oleg


hook form alter with hidden field, throw an error I try to alter taxonomy edit form.

This is my hook:

function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    // hide the desciption field and relations group field
    $form['description']['#type'] = 'hidden';
    $form['relations']['#type'] = 'hidden';

    // set the default value
    $form['description']['#value'] = ' ';
    $form['relations']['weight']['#value'] = 0;
    $form['relations']['parent']['#value'] = array('value' => '13');

}

But When I submit, It throw me an error:

Warning: Illegal string offset 'value' in taxonomy_form_term_submit_build_taxonomy_term() (line 862 in /Users/tangmonk/MyGit/Drupal/daxuebao/modules/taxonomy/taxonomy.admin.inc).

The problem causing the error is that you are setting your hidden description field value is a string, but the taxonomy module is expecting a text area type array with a 'value' and a 'format', which you cannot replicate with a hidden field.

Unfortunately the term description field is a special property of the term, not a proper field, so you can't remove the field (the taxonomy module relies on it being there).

If you don't want people to see it and you always want it to have an empty value a good option is to restrict it from the user like this:

$form['description']['#access'] = FALSE;

but that doesn't allow you to change the value if you want to.

Another option is to use 'value' instead of 'hidden' as the type, like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  // Hide the desciption field and relations group field
  $form['description'] = array(
    '#type' => 'value',
    '#value' => array(
      'value' => '',
      'format' => 'filtered_html',
    ),
  );
  // Unset the existing relations fieldset.
  unset($form['relations']);
  // Set hidden values for all the sub-fields of the relations fieldset.
  $form['weight'] = array(
    '#type' => 'value',
    '#value' => 0,
  );
  $form['parent'] = array(
    '#type' => 'value',
    '#value' => 13,
  );
}

Note the changes to the relations fieldset too:

Since you only want to pass hidden values from the children of the fieldset just remove the fieldset altogether and then set the hidden values (be careful if using other add on modules that add fields to the 'relations' fieldset).

Because the fieldset wasn't using #tree the values passed through in $form_state will just be ['weight'] and ['parent'], not ['relations']['weight'] and ['relations']['parent'] so you can leave the ['relations'] part out when adding the values back in.


How restrict Anonymous users from creating accounts I am building my first site in Drupal(7), and I would like to restrict unloged users from creating user accounts, so how can I disable new account creating from {mysiteName}/user?

Thanks a lot

Go to sitename.com/admin/config/people/accounts

Scroll down to find REGISTRATION AND CANCELLATION

Select appropriate option in Who can register accounts? field


How do I add a template suggestion for a Views block? I am very much so new to Drupal and have moved to this platform after working with Magento for 5 years.
I am trying to create a template for a view. I have created the twig template under /templates/views/ called views-view--partners--partners--sales.html.twig but do not know how to hook the theme into using this twig template.

You need to name your template based on the rules for Views templates.
For example, "views-view--partners--partners--sales.html.twig" would mean:

viewid: partners
view-display-id: partners
fieldid: sales

If this is correct, then all you need to do is clear the cache and reload; the template should be picked up automatically.


how to see which user has assigned a content_profile content type? I´m using the module
http://drupal.org/project/content_profile
for drupal 6

I want to make a view where I show all the users and a link to their content profile,
or even display some views from their profile..

Can´t seem to be able to do that, I don´t know where to pick the relation between the users and the content type

Currently my view is of the Usuer type..not Node..
I can handle PHP with customfield if I have to..don´t know where to start

According to the code of the content profile module (I didn't test this) you can use views relations between profile nodes (ordinary cck node types) and users.

I'm not sure whether you have to base your view on the cck node type for the profile or users. But with one of these you should get an option to add the other side as a relation and then use fields of the user and the profile in the same view.


User relationship module - error strict warning: Only variables should be passed by reference module name: User Relationships.

module version is: 7.x-1.0-alpha5

whenever i try to add relationship type or edit it give me this error:

Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 103 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).
Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 104 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).
Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 105 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).

the code in user_relationship_implications.module is as follows:

function theme_user_relationship_implications_form_table($variables) {
$form = $variables['form'];
$headers = array(t('Relationship Type'), t('Strict'), t('Reverse'));
$rows = array();

foreach ($form['opts'] as $rtid => $elements) {
if (!is_numeric($rtid)) {
  continue;
}
$rows[$rtid] = array(
  drupal_render(array_shift($elements)),
  drupal_render(array_shift($elements)),
  drupal_render(array_shift($elements)),
);
}
return theme('table', array('header' => $headers, 'rows' => $rows));
}

in the above code line 103-105 is:

drupal_render(array_shift($elements)),
drupal_render(array_shift($elements)),
drupal_render(array_shift($elements)),

Can you please help me solve the error and also bring to my knowledge why does this occur?

IMHO, this is a bug in the User Relationships module, and should be reported to that module's issue queue.

If you look at the documentation, you see that the template  for drupal_render is:

drupal_render(&$elements)

Passing a function call by reference not good coding practice (but it will not have adverse effects if you never use the return value passed by reference).

The following will do the same thing and not produce the warning:

$_shift1 = array_shift($elements);
$_shift2 = array_shift($elements);
$_shift3 = array_shift($elements);
$rows[$rtid] = array(
  drupal_render($_shift1),
  drupal_render($_shift2),
  drupal_render($_shift3),
);

The module author probably doesn't have PHP-warnings enabled, and never saw the warning.


Search results - Show custom fields Is it possible to change the output created with the Search module? I want to show custom fields, and I want to hide the description, user and date...

You have two options:

You can use Display Suite module. A sub-module Display Suite Search allows you to change the way nodes are displayed for search results.
You can use template_preprocess_search_result() together with a copy of modules/search/search-result.tpl.php in your theme. Read thoroughly the comments in the search-result.tpl.php as they will help you understand what is going on and what is available to you.
You can define variables this way: $variables['your_value'] = $variables['result']['node']->field_sample[LANGUAGE_NONE][0]['value']; and use it in the .tpl file like this: print $your_value;.


Administrator settings vanished for sheetnode content type nodes I installed the sheetnode module. It was working ok and then the next time I clicked on "Edit" on the node, the following happened:

I don't know how the links for Publishing options, URL Path settings etc got disabled. I run as an administrator and I edited my permissions too (grant everything under sheetnode module to admin) but to no avail. Please help me get back to those links.

I run drupal 6.

I got the answer myself. I had my CKEditor module disabled while the "Sheetnode CKEditor" module was enabled. So there was some conflict which led to the disappearance of links.


Module webform2pdf modify template I have sereval webforms et each webform send a mail with a pdf. I would like to do a template for each webform.
I use webform2pdf in Drupal 7 to send pdf by email.
How can i do that ?

I'm working with this module right now too.

Once the module is enabled (and the required tcpdf library is intalled), you will see a new "Generate PDF" tab when editing each of your webforms. This is where you can add your PDF template under "Content of the PDF Document"

If you enter stuff here, it overrides anything you may have set globally (under /admin/config/content/webform2pdf).

You can use html and tokens here, for example...

INTERN NAME: [submission:values:intern_name]

I hope this helps.

If you get this working, maybe you (or somebody reading this) can help me with a problem I'm having: I want to add conditional logic for some of my fields so they only show up in the PDF if a value is entered.

I tried this via the interface (I have PHP filter module installed), but it resulted in a completely blank PDF, so now I'm going to try doing a template override instead.


Using hook_node_presave to auto-select a reference field from a field list selection I'm trying to use hook_node_presave to select a value in a term reference field based on a selection a user makes in a field list field. The term reference field is hidden from the user. The code I'm working with is problemmatic in at least two ways:

1) I'm not sure I'm referencing the correct theme in my function header because the dpm() is not outputting anything. But it's in the administrative theme 'seven' that this form is running so I assume that's right.

2) I'm getting errors when I run this code saying 'syntax error, unexpected ||' wherever I have those. Am I not using the correct syntax for OR operators? It seems fine to me. I tried OR in place of || and got the same errors.

Here's the code I'm working with:

function seven_node_presave($node) {
    $field_type = $form['field_type']['und']['#options'];
    dpm($field_type);
    if (($field_type == 4) || ($field_type == 5)) || ($field_type == 7) ||
($field_type == 6)) {
        $form['field_icon']['und']['#options'][]= '2';
    }
    elseif (($field_type == '9') || ($field_type == '98')) || ($field_type == '8')) {
        $form['field_icon']['und']['#options'][]= '6';
    }
    elseif (($field_type == '3') || ($field_type == '1')) || ($field_type == '2')) {
        $form['field_icon']['und']['#options'][]= '1';
    }
}

Note 1: the numbers being compared to (ex: $field_type == 4) are the 'keys' for those fields, not the actual text the user would select.

Note 2: I'm running this from a module called grouphideandselect, not from template.php...maybe that's my problem?

As Darvanen said above, the function name is wrong, replace HOOK by the module's name in HOOK_node_presave().
About the || operators, you could use in_array instead or a single associative array:

function grouphideandselect_node_presave($node) {
    $field_type = $form['field_type']['und']['#options'];
    dpm($field_type);

    $field_type_to_icon = array(
      1 => 1,
      2 => 1,
      3 => 1,
      4 => 2,
      5 => 2,
      7 => 2,
      8 => 6,
      9 => 6,
      98 => 6,
    );

    if (isset($field_type_to_icon[$field_type])) {
      $form['field_icon']['und']['#options'][] = $field_type_to_icon[$field_type];
    }
}

EDIT: from another question of yours I see that you already tried renaming the function to grouphideandselect_node_presave. You need to make sure that:
- the function's name is right
- the module is enabled
- you cleared Drupal's cache afterwards


Lightest setup to sell only digital content with no physical products? I'm looking for recommendations on how to setup Drupal 7 with the fewest modules so I can charge users to Buy Digital Content (Book Pages) on my site.

I will eventually have several books, and users will need to pay for each one to read (view) them. There are no files to be downloaded here, I will actually try to prevent users from copying the content; they should only have access to the Book.

I looked at the recommended Drupal Commerce, but it seems very much like overkill (many unused features like shipping, packing, inventory) for what I want to do. Not sure it can (easily) handle Digital Content.

If there is no simple solution, can this be easily done in Drupal Commerce?

You could get by using Drupal Commerce with just the core modules, some custom Rules, and your preferred payment gateway module. The modules and features you pointed to (shipping, inventory, etc.) and the ones you didn't point out have nothing to do with Drupal Commerce itself. They're all optional contributed modules and don't have to be added if you don't need them.

It's possible you saw a demo site running Commerce Kickstart 2.x. That is a distribution of Drupal that includes Drupal Commerce and a wide variety of contributed modules to make it function more like a robust eCommerce application out of the box. At its core, Drupal Commerce is much lighter weight, and I think you'll find its compatibility with Rules combined with the Content Access / Access Control List modules to be very helpful in selling access to digital content on your site.


Coding a Load and delete Field Collection with Entity API I'm trying to delete all values of a multivalued field containing a field collection. I want access with Entity API wrappers. I use this in a custom rule with hook_rules_action_info()

I'm using drupal 7.39 and field collection modules 7.x-1.0-beta8 and

I'm testing this code but doesn't work for me, this node has 2 values in field_collection

$node_wrapper = entity_metadata_wrapper('node', $node);
dpm($facWrapper->field_collection,"Field Collection");
//Prints a EntityListWrapper object
dpm($facWrapper->field_collection->count(),"Field Collection count");
//Prints zero, it should be 2
dpm($facWrapper->field_collection->value(),"Field Collection value");
//Prints array() 0 elements, it should be 2 elements
//And obviously doesn't enter into this foreach, it should enter
foreach ($facWrapper->field_collection as $fc) {
  dpm($fc,"Field collection item");
}

The questions are:

How to load or access to the field_collection in the entity wrapper way ?
When I have access, How can I delete ? I want to delete the field_collection_item and its reference in the node.

Please look into this links it will give your answers:

Example: Programmatically create and update field collection with Entity API

How to properly delete a field collection

Delete field content using entity metadata wrapper


Select only if row not exists in joined table I have a db_select that selects row from t_project_proposal_writer table only if in joined t_project_milestone table row with milestone_id 10 is found:

$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->innerJoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->condition('p.initiative_nid', $node->nid)->condition('m.milestone_id', 10);

One project row can have 10 milestone rows. Now I need to do another query that selects only the rows from t_project_proposal_writer where milestone_id 10 not exists in joined t_project_milestone.

Is there any other possiblity to do that, instead of query all the projects and iterate throught them while checking if milestone 10 exists?

You can use isNull() method :

$query = db_select('scald_atoms', 'a');
$query->fields('a', array('sid','title'));
$query->leftjoin('table_name','table_alias','table_alias.entity_id = a.sid');
$query->isNull('table_alias.mon_field_value');
$query->execute();
$query->fetchAllAssoc('nid');

with your example something like that should do it :

$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->leftjoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->isNull('m.milestone_id');


Load video to youtube when node save I have search but not found so I need to ask.

I need a module that permit to my users to load a video into the node add form and this video need to be loaded into my youtube/vimeo page.

Is there? Please...

M.

A combination of following modules would do what you want

Media

  The Media module provides an extensible framework for managing files
  and multimedia assets, regardless of whether they are hosted on your
  own site or a 3rd party site - it is commonly referred to as a 'file
  browser to the internet'.

  Media is a drop-in replacement for the Drupal core upload field with a
  unified User Interface where editors and administrators can upload,
  manage, and reuse files and multimedia assets. Any files uploaded
  before Media was enabled will automatically take advantage of the many
  of the features it comes with.

Media: YouTube

  Media: Youtube integrates with the Media module to make Youtube videos
  available as file entities.

  Users can add Youtube videos to their site in a file field or insert
  them into a WYSIWYG area by pasting the video's URL into the media
  browser web tab. Formatter options are available to customize the
  Youtube player's appearance, show the video preview image, and enable
  the Javascript API. The 2x branch is under active development and uses
  the Youtube iframe embed that can serve HTML5 videos to mobile
  devices.

Media Mover

This is the module that would do what you have asked. I have highlighted the point you have asked

  Media Mover is a set of modules which allows website administrators to
  easily create complex file conversion processes. The core of Media
  Mover is the media_mover_api module which creates a set of rules
  allowing multiple modules to interact with a file. Media Mover can
  take a file emailed to an email account, turn a file attachment into
  an FLV file, create a new node with the file data, and then save the
  file on an external file storage system like Amazon's S3 all at once.
  And that's just the start.

  What you can do The core set of Media Mover modules offers lots of
  options for someone manipulating rich media.

  get attachments from an email account
  get attached files from nodes of a specified type
  get files from previously harvested files
  get files from CCK filefield and imagefield fields
  get files from a FTP server, provide file tokens for user authentication as well
  create a thumbnail from a video file with ffmpeg
  transcode video files into web friendly (and other) formats
  compress a file with zip
  move a file to Amazon's S3 service
  attach file back to node
  save file and related data as a node
  add a file to a CCK filefield or imagefield
  save a file to YouTube


Displaying node fields in a view I have a content type called Snippet. Snippet will have one image field and unlimited text fields.

I want to output fields in Views as:

image field (image.png)
text field (Text1)
text field (Text2)
text field (Text3)
text field (Text4)

The image field is always first, and the different text fields follow it. I want to put this into a slideshow format with fade transitions.

Right now, the image field keeps reproducing itself after every text field.

Do you have any idea? Do I need to use grouping?

First, you should use Views Slideshow to do this.

On Drupal 7, add 2 more text fields in your content type; then add them to the view using Content: [your text field name].


Remove all added classes to body tag How do I remove all the classes that are being added to the body tag? Currently my body tag is :

<body>

This however is rendered as

<body class="lightbox-processed admin-nw admin-vertical admin-df">

Those are added there via Javascript of the Lightbox and Admin Menu modules. You can either disable those modules or modify/override their Javascript. You could also use custom Javascript to remove the classes from the body element. Anyway, the question is, why would you want to remove the classes?


Drupal module upgrade via Composer not being recognized A Drupal 8 site started pestering me to upgrade Twig Tweak from 8.x-2.8 to 8.x-2.9. I went to the directory and ran composer require 'drupal/twig_tweak:^2.9' which seemed to work. I also did drush cr. When I go back into the Drupal web interface it still thinks I'm on the older version of Twig Tweak and wants me to upgrade. If I run the composer command again, it thinks I'm already upgraded. How do I get these two things to play nice with each other?
(You might be wondering why I didn't just use the web interface to upgrade. If I do that I have even bigger problems so I'm sticking to composer for now.)
Update: output of composer show
descrip. : A Twig extension with some useful functions and filters for Drupal development.
keywords : Drupal, Twig
versions : * 2.9.0
type     : drupal-module
license  : GNU General Public License v2.0 or later (GPL-2.0+) (OSI approved) https://spdx.org/licenses/GPL-2.0+.html#licenseText
homepage : https://www.drupal.org/project/twig_tweak
source   : [git] https://git.drupalcode.org/project/twig_tweak.git 8.x-2.9
dist     : [zip] https://ftp.drupal.org/files/projects/twig_tweak-8.x-2.9.zip 8.x-2.9
path     : /var/www/html/ycfld/modules/contrib/twig_tweak
names    : drupal/twig_tweak

support
source : https://git.drupalcode.org/project/twig_tweak
issues : https://www.drupal.org/project/issues/twig_tweak

requires
drupal/core ^8.7 || ^9.0
twig/twig ^1.41 || ^2.12

suggests
symfony/var-dumper Better dump() function for debugging Twig variables```

Do you have more than 1 copy of twig_tweak.info.yml located anywhere under Drupal root? Composer will install the module in <drupalroot>/modules/contrib. Installation through the UI will put modules in <drupalroot>/modules.
Did you originally install Twig Tweak with composer? If you originally installed the module manually/through the UI and then did a composer require, you will have two copies of the module. That won't work. You have to ensure you have one and only one copy of the module's code on your site.
The cleanest way to fix this is to uninstall the module from the UI, then remove both versions of the module code - remove both the <drupalroot>/modules/contrib version and the <drupalroot>/modules version. Then you can re-install the module using composer and re-enable it.


How Can I send full content body field by simplenews_content_selection? I use the drupal 7 and simple news content selection module for simplenews.

When select an existing content for send by simplenews only the title of its content add to simplenews sent mail.

I want to send whole content (the full body field) of selected content by simplenews.have any idea?

thanks before hand

I have found my solution.

In content type manage display setting , for simplenews content selection view mode the body field must be visible .


Php in "regions" without php filter I've heard that using the php filter is dangerous. Something about having php in databases being a bad practice. I use it in blocks quite a bit and want to move away from that.

I have a lot of page template files so I need a replacement for regions/module_invoke blocks. I tried using an include but dealing with paths was tedious. Is that the only option or is there something easier?

Includes or requires is likely your best bet here, why are they tedious? If the includes are within the same theme/template files directory you needn't use absolute paths.

If you cannot use relative paths then you can use getcwd() to get the current path/working directory of a file, or use drupal_get_path() to get the path to a theme or module file.


Modify Drupal pagination to restrict shown page numbers on Drupal 8 On Drupal 8:

I have a pagination for list of articles within a Drupal site  e.g.:

<<first <previous ... 3 4 5 6 7 8 9 10 11 ... next> last>>

So at the moment there are always nine page links shown. Basically I want to find out how to modify this so there are (for example) only five links and the text for labels for the controls in the pager like this:

<< < ... 6 7 8 9 10 ... > >>

I wrote this code with not result:

/**
 * Implements template_preprocess_pager().
 */
function MYTHEME_preprocess_pager(&$variables) {
  $variables['quantity'] = 5;
  $variables['tags'] = ["«", "‹", "›", "»"];
}

It would seem that at the point you're trying to modify the quantity, the pager items have already been generated so your quantity value doesn't have any effect.

Similar to Drupal 7, I believe you're going to need to implement the full pager function, just copying the core pager function to your theme and changing the quantity.

function MYTHEME_preprocess_pager(&$variables) {
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = 5; // hardcode your quantity here
  global $pager_page_array, $pager_total;

  // Nothing to do if there is only one page.
  if ($pager_total[$element] <= 1) {
    return;
  }

  $tags = $variables['tags'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  // Create the "first" and "previous" links if we are not on the first page.
  if ($pager_page_array[$element] > 0) {
    $items['first'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, 0),
    );
    $items['first']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[0])) {
      $items['first']['text'] = $tags[0];
    }

    $items['previous'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
    );
    $items['previous']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[1])) {
      $items['previous']['text'] = $tags[1];
    }
  }

  if ($i != $pager_max) {
    // Add an ellipsis if there are further previous pages.
    if ($i > 1) {
      $variables['ellipses']['previous'] = TRUE;
    }
    // Now generate the actual pager piece.
    for (; $i <= $pager_last && $i <= $pager_max; $i++) {
      $options = array(
        'query' => pager_query_add_page($parameters, $element, $i - 1),
      );
      $items['pages'][$i]['href'] = \Drupal::url('<current>', [], $options);
      if ($i == $pager_current) {
        $variables['current'] = $i;
      }
    }
    // Add an ellipsis if there are further next pages.
    if ($i < $pager_max) {
      $variables['ellipses']['next'] = TRUE;
    }
  }

  // Create the "next" and "last" links if we are not on the last page.
  if ($pager_page_array[$element] < ($pager_max - 1)) {
    $items['next'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
    );
    $items['next']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[3])) {
      $items['next']['text'] = $tags[3];
    }

    $items['last'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_max - 1),
    );
    $items['last']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[4])) {
      $items['last']['text'] = $tags[4];
    }
  }

  $variables['items'] = $items;
}


Redirect to an external site when accessing the page of a node meeting a set of condition I need to redirect users to an external website when they access the node view page at node/%node of a node meeting some conditions.

What would the proper/best way to achieve this (using code) be?

I would use hook_node_view.

Remember to check the view mode along with the conditions, so you don't redirect on pages where only the teaser is shown.

It should look something like this:

module_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && "Conditions") {
    drupal_goto('http://example.com');
  }
}


Migrate doesn't update destination files if source files have changed content I'm using Migrate 7.x-2.5 to keep Commerce products synchronized between a legacy system and a Drupal ecommerce website.

I setup two migration methods, one for Commerce Products entities and one to generate nodes for product display. Migration tasks are supposed to be run every night, because people during the day add new products, update some, and delete others. So both migration tasks are run with the "update" checkbox checked. I take care to delete obsolete content at postImport() and all is good.

Everything is working for me, except for product images. When source files are updated with different pictures, filename doesn't change (that's a legacy system behaviour). Migrate doesn't seem to notice that the file has changed, so it doesn't migrate it and pictures don't get updated.

Anyone can help dealing with this file updating issue?

Here's the relevant migration part where files are handled.

$this->addFieldMapping('field_image', 'immagine'); //this field gets populated in prepareRow()
$this->addFieldMapping('field_image:file_class')
        ->defaultValue('MigrateFileUri');
$this->addFieldMapping('field_image:source_dir')
        ->defaultValue(SRC_IMG_PATH);
$this->addFieldMapping('field_image:file_replace')
        ->defaultValue(FILE_EXISTS_REPLACE);

It turns out that files are actually updated. So there's nothing to edit in my migration code.

Problem is that a flush on image styles is required.

I was triggering flush manually, but I could not see updated images in webpages.

Flushing was not working due to file permissions on resized images, so I still see the old "styled" images.


Adding a widget to CKEditor 4.3.5 I've installed CKEditor 4.3.5 on my Drupal 7 by simply copying it into the sites/all/libraries folder as described here: http://mtt.desk.com/customer/portal/articles/973377-how-to-install-the-ckeditor-on-drupal-7

I've done this successfully with CK Editor 4.3 and as of May 2014 it works fine with Wysiwyg 7.x-2.2.

I'm wondering if anyone has successfully installed CK Editor's widgets using the installation as in this method. There seems to be plenty of documentation for installing widgets if using the Drupal CK Editor module, which is an alternative installation route. However, I can't find any for this route.

Specifically, in the CK Editor widget tutorial, http://docs.ckeditor.com/#!/guide/widget_sdk_tutorial_1,
we are asked to register the widget in the extra plugins list, config.extraPlugins.
This seems to be placed wherever CK Editor is first called. So in Drupal, where do I place this code??
I tried the config.js file in sites/all/libraries/ckeditor but it doesn't seem to work.

I'd be grateful for any ideas.

Thanks and best wishes.

First off, you should create a basic custom module, containing an .info file and a .module file.

Call it for example "custom_wysiwyg"

[custom_wysiwyg.info]

name = My Custom Wysiwyg
core = 7.x
package = Custom
version = 7.x-1.0

[custom_wysiwyg.module]

/**
 * Implements hook_editor_settings_alter().
 */
function custom_wysiwyg_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
    $settings['allowedContent'] = TRUE;
    $settings['extraPlugins'] = 'lineutils,widget,quote_box';
    $settings['extraAllowedContent'] = array(
      'img[src,title,alt,style,width,height,class,hspace,vspace,view_mode,format,fid]',
      'a[type,length,href]',
    );
  }
}

/**
 * Register a directory containing Wysiwyg plugins.
 *
 * @param $type
 *   The type of objects being collected: either 'plugins' or 'editors'.
 * @return
 *   A sub-directory of the implementing module that contains the corresponding
 *   plugin files. This directory must only contain integration files for
 *   Wysiwyg module.
 */
function custom_wysiwyg_wysiwyg_include_directory($type) {
  switch ($type) {
    case 'plugins':
      // You can just return $type, if you place your Wysiwyg plugins into a
      // sub-directory named 'plugins'.
      return $type;
  }
}

function custom_wysiwyg_wysiwyg_plugin($editor, $version) {
  switch ($editor) {
    case 'ckeditor':
      $module_path = drupal_get_path('module', 'custom_wysiwyg');
      $plugins = array(
        'lineutils' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/lineutils',
          'load' => TRUE,
        ),
        'widget' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/widget',
          'buttons' => array(
            'widget' => 'widget'
          ),
          'load' => TRUE,
        ),
        // Quote box is an example widget based on the Samples Simplebox widget.
        'quote_box' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/quote_box',
          'buttons' => array(
            'quote_box' => 'quote_box'
          ),
          'load' => TRUE,
        ),
      );

      return $plugins;
      break;
  }
}

The function "custom_wysiwyg_wysiwyg_editor_settings_alter" alters the wysiwyg profiles' settings when rendering a wysiwyg textfield. We add some extra allowed elements and their attributes (bugfix for media module), and we define our custom plugins.
The function "custom_wysiwyg_wysiwyg_include_directory" describes our custom module's CKeditor plugins path subfolder "plugins".

You can than place any custom plugin folders in your module's "plugins" directory as follows:

/
/custom_wysiwyg.info
/custom_wysiwyg.module
/plugins
/plugins/lineutils/plugin.js etc...
/plugins/widget/plugin.js etc...
/plugins/quote_box/plugin.js etc...

The function "custom_wysiwyg_wysiwyg_plugin" defines a list of our custom plugins which we have placed in our module's subfolder "plugins".

Note: The plugin "lineutils" is a dependency for the "widget" plugin and is not included in the Ckeditor Full download.

I hope this points you in the right direction.

greets,
Kim


How to ask for user confirmation when submitting a form using FAPI What I want is suppose a user enters same data twice in two rows then I want to show her an error/warning and now if she chooses to press submit again then I'd process and accept the form.

How to do it?

use the confirm_form function. See Here and Here for examples

  This function returns a complete form array for confirming an action.
  The form contains a confirm button as well as a cancellation link that
  allows a user to abort the action.


Migrate users from a table with non-unique email column I'm using the Migrate module to migrate users from a non-Drupal PHP/MySQL site to Drupal 7.  The users are spread across two tables, the second of which has a non-unique email column, many values of which are present in the first table.

Generally, how do I import the second table, inserting users with new email addresses, and updating a couple fields whenever the email address is already present among the users created from the first table and avoiding duplication errors from the second?

The users from the first table are administrators.  The users in the second table are clients.  There are other tables that references administrators and clients by ID.  The ID columns for the two types of users are unique only within its respective table.

I made all the client uid's globally unique by adding 10,000 to all their uid's and updating their references in the other tables accordingly.

It depends on what kind of method, modules, tools you'd like to use to migrate the data as each of them might have their own settings for the kind of situation you had described.

If it's just a custom script migrating data between databases, then I would treat all users the same and import any of the tables first and then import the second one ignoring the error message - Drupal won't be importing users with the existing e-mail twice. After the migration you could go over each admin to assign appropriate role.


Multilingual settings form using i18n variable I'm using a settings form for my module and I'm trying to make some of the fields multilingual.

I've declared the multilingual variables with hook_variable_variable_info (and with hook_variable_group_info for my custom group):

function MYMODULE_variable_info() {
  $variable['my_variable_name'] = array(
    'type' => 'string',
    'title' => t('My title'),
    'default' => MY_DEFAULT_VALUE,
    'description' => t('My description.'),
    'localize' => TRUE,
    'group' => 'my_group'
  );

  return $variable;
}

I've added my settings form (one field for example)

function MYMODULE_settings_form() {
  $form = array();

  $form['my_variable_name'] = array(
    '#type' => 'textfield',
    '#title' => t('My title'),
    '#title_display' => 'before',
    '#default_value' => variable_get_value('my_variable_name'),
  );

  return system_settings_form($form);
}

And as you can see I've used system_settings_form($form) to save my form fields as variables.
I've checked my new variable at 'admin/config/regional/i18n/variable' and the form shows that it's a multilingual form and multilingual field, but when I'm switching to another language the value isn't saved. (Only the English version saves and changes the value for all languages)

Thanks.

I was in a need to create translatable strings for text entered using Page title module and I used the following code to create variable

function module_variable_info($options) {
    $variables['page_title_type_news_and_event'] = array(
    'type' => 'text',
    'title' => t('Page title CT New Events', array(), $options),
    'default' => '',
    'description' => t('Module : Page title', array(), $options),
  );

  return $variables;
}

Now I can see them in others tab at admin/config/regional/i18n/variable and I enabled the check box there

Then I can translate my string at admin/config/system/variable and at others tab


Blog monthly archive block - list of posts grouped by year then month See the implementation on this guy's blog: http://deglos.com/blog

YEAR
-- Month
-- Month
YEAR
-- Month
-- Month

Anyone know how this was accomplished?

It's normally done using Views and a good tutorial on the process has been explained by Chris Shattuck on his blog - see How to create a monthly archive block for a Drupal blog with Views

A little sleuthing on how the blog you mention was generated leads me to believe that the author wrote the wp_blog module on Drupal.org which provides a view that ultimately generates the year -> month -> post hierarchy.  You can see an exported view for the blog archive block here: http://cgit.drupalcode.org/wp_blog/tree/views/wp_blog.view?id=47246da29d176c028a749632807d207dfe0461e1


Is it a good idea to load the css files from page.tpl file instead of .info file I am just curious, because i am trying to get my site working for both IE and chrome, and I want it to load only a specific css file. Conditional stylesheets arent working for me, as I cannot see the change in the browser when I check it's html file.

It is bad idea, on so many levels I'm sure I can't list all.

Conditionally included stylesheets will get cached by various proxies and served with no respect for original conditions.
Modules like CDN will not be able to work on your CSS files to speed things up.
Aggregation and cache modules will stop working as well.
Search engine bots will get confused and may think you are trying to trick them by serving different version of a page to bot, and other one to bot disguised for an user - risk of google ban.
If, in future, someone will redefine page.tpl.php for certain content types, you will have the same file described in many places - easy way for inconsistency and styling bugs.
CSS provided by modules might end up in other position to your own than they are now, this can cause hard to diagnose display bugs.


Infinite Redirect Loop with PURL and spaces_og I created a calendar feature for organic groups, and tried to enable it in a group with spaces_og.  The page refreshes saying changes have been saved but the feature is still disabled.  In the logs, there is a message that purl prevented a redirect loop.

I realize spaces is still in dev with d7.  Is this a known issue?  Did I do something wrong when creating my feature, or is there a better way to create features for use in organic groups?

This issue occurred because I didn't have a path prefix set for purl.  I created the group prior to enabling purl and spaces.  After adding the path in the group node edit form, the redirect loop was no longer present.


Migrate process plugin to skip values I'm working with Migrate. On my json source file I've the alias of the node to import. There are nodes that does not have an alias, so in the json I've things like "/node/1234". So I want to skip this alias (not the entire node).

Is there a way to do this?

I'm already using custom process but I don't know how to skip a single value.

Use skip_on_value plugin in Migrate Plus module.

Sample code:

id: custom_menu
label: Menu
migration_group: custom
migration_tags:
  - Drupal 7
source:
  plugin: menu
process:
  id:
    -
      plugin: skip_on_value
      equals: true
      source: menu_name
      method: row
      value:
        - devel
        - features
    -
      plugin: static_map
      bypass: true
      source: menu_name
      map:
        main-menu: main
        management: admin
        navigation: tools
        user-menu: account
  label: title
  description: description
destination:
  plugin: entity:menu


Is there a way to place the "Add new comment" link where I want? Is there a way to place the "Add new comment" link where I want in my content type? I'd like the link to be between two already existing fields in the content type. Is there some type of way to add this link via a field? Please help. This issue has been killing me.

You can use hide and render to hide/show individual fields.
http://tjegz.wordpress.com/2012/03/02/132/

This will allow you to place things in any order in the tpl file


Display suite removing class id I split 2 columns my contetnt node with Display Suite and add custom class to the columns. (with Bootsrap responsive class col-sm-3) But display suite still render column with old style: group-left and group right. How can i remove old style?

The classes are only added to the existing ones, they don't replace them. If you want to remove the old styling, you can create a new layout and either add different default classes, or no classes at all.

Adding custom layouts to your theme (Display Suite)

You also might want to consider using Display Suite Bootstrap Layouts. Bootstrap 3.0 layouts are still in dev, but it's worth taking a look.


Passing extra image data (EXIF date) to the browser upon adding an image in a form I am currently using EXIF module to import the DateTimeOriginal tags but it does not display the tag in the form right after uploading the image and I would really prefer to see that info while still filling the form as it affects what I should fill in manually.

I noticed that the image size is displayed next to the image file name after the image has been uploaded, found the code in core/modules/image/image.field.inc that basically hard codes what will be rendered to be sent back to the client in an ajax response. I added a call to exif_read_data() right there and appended my DateTimeOriginal tag after the file size and it works fine!

But surely editing core files is not the right way to do that - there must be some hook to use but I can't seem to figure out which one. Besides I would prefer my tag (and maybe other info like image width and height etc) to be neatly accessible via js on the client to update other fields in the form dependent on it.

I would appreciate any advice on what is the right place to put that code.

hook_preprocess_image_widget() worked for me.


Block taxonomy list count with filter by search term? Currently I have setup a view to display custom search results based on search terms (exposed filter):

/blog/search?keys=user+entered+term

On the page I am looking to show a list of tags with counts based on that search term, for example:

Code (x)
Tutorial (x)
Help (x)

A block has already been created in the view with the following:

CONTEXTUAL FILTERS
(term) Taxonomy term: Name (-> display summary with count)
RELATIONSHIPS
Content: Taxonomy terms on node
FIELDS
(term) Taxonomy term: Name

While the above does output the taxonomy terms, it displays the counts for all of the taxonomy, rather than filtering it based on the search term.

Seems like I am most of the way there, but would appreciate any thoughts/suggestions anyone could offer.

Contextual Filter Wont do here. Please follow these steps:

Add another field "Taxonomy:term name".
Under the advanced settings tab, turn on SQL Aggregation.
Edit the sql aggregation settings against the newly added field "taxonomy term" to make it "COUNT". Not "COUNT DISTINCT" remember.
If there is any sort option, please remove it for this to work. Let the filter remain as it is.
Now you will have taxonomy tags, with the number of nodes against each.


How do I create custom user tabs? I am trying to create a new custom tab that appears on all routes that are descendants of entity.{entity_type}.canonical. I have tried extending the DeriverBase class, specifically overriding the getDerivativeDefinitions method. I created the tab itself by extending LocalTaskDefault and overriding the getRouteParameters method. The tab appears when you visit a standard Drupal user path such as www.mysite.com/user/1/ or www.mysite.com/user/1/edit. However, when we add our new custom user routes such as www.mysite.com/user/1/subscribe, no tabs appear. Is there a special way to define local menu tasks on custom routes? A sample of the code:

 $this->derivatives['recurly.subscription_tab'] = [
  'title' => $this->t('Subscription'),
  'weight' => 5,
  'route_name' => 'recurly.subscription_list',
  'base_route' => "entity.$entity_type.canonical",
];

foreach ($this->derivatives as &$entry) {
  $entry += $base_plugin_definition;
}

Thanks in advance of any help.

As suggested by Berdir you can look at Devel module and at how it's implementing that. The following code was "extracted" from Devel

1) Create the routes

Create the file mymodule.routing.yml in and inside define a route callback (which is used for create the dynamic routes)

route_callbacks:
  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'

Create the class MyModuleRoutes for generate yours dynamic routes in src/Routing

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class MyModuleRoutes implements ContainerInjectionInterface {

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function routes() {
    $collection = new RouteCollection();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $route = new Route("/mymodule/$entity_type_id/{{$entity_type_id}}");
        $route
          ->addDefaults([
            '_controller' => '\Drupal\mymodule\Controller\MyModuleController::doStuff',
            '_title' => 'My module route title',
          ])
          ->addRequirements([
            '_permission' => 'access mymodule permission',
          ])
          ->setOption('_mymodule_entity_type_id', $entity_type_id)
          ->setOption('parameters', [
            $entity_type_id => ['type' => 'entity:' . $entity_type_id],
          ]);

        $collection->add("entity.$entity_type_id.mymodule", $route);
      }
    }

    return $collection;
  }

}

2) Create the dynamic local tasks

Create the file mymodule.links.task.yml and inside define a deriver

mymodule.tasks:
  class: \Drupal\Core\Menu\LocalTaskDefault
  deriver: \Drupal\mymodule\Plugin\Derivative\MyModuleLocalTasks

Create the class MyModuleLocalTasks for generate yours dynamic routes in src/Plugin/Derivative

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModuleLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $this->derivatives["$entity_type_id.mymodule_tab"] = [
          'route_name' => "entity.$entity_type_id.mymodule",
          'title' => t('Mymodule title'),
          'base_route' => "entity.$entity_type_id.canonical",
          'weight' => 100,
        ] + $base_plugin_definition;
      }
    }

    return $this->derivatives;
  }

}

3) Create the controller

Create the class MyModuleController in src/Controller

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class MyModuleController extends ControllerBase {

  public function doStuff(RouteMatchInterface $route_match) {
    $output = [];

    $parameter_name = $route_match->getRouteObject()->getOption('_mymodule_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = ['#markup' => $entity->label()];
    }

    return $output;
  }

}


How to add crumb for each search result item? I want to add crumb/breadcrumb on each of search result item.

For example, if I search keyword "dog", the search result should return results as follow.

Dog's Life ($title)
Dog is life. Dog is love... ($snippet)
Home > Article > Dog's Life (the crumb)

Dog Dog Who's There ($title)
Who's there dog? Dog dog dog... ($snippet)
Home > Tips Trick > Dog dog Who's There (the crumb)

Usually I construct the crumb using variable $url from search_result.tpl.php via function mytemplate_preprocess_search_result(), implemented in template.php.

I create a new variable, $breadcrumb, based on variable $url and then I call it on search_result.tpl.php. Then I copy search_result.tpl.php into my theme folder.

The problem arises when it is no longer achievable to construct crumb from $url due to circumstances, mostly because of custom breadcrumb that is not related with URL.

Please guide me to achieve that goal, a different approach is welcome. Thanks.

If you already have a function to get breadcrumb from URL and assuming breadcrumb is, when is it, customize by hook_menu_breadcrumb_alter hooks, you just have to call this hook :

// Allow modules to alter the breadcrumb, if possible, as that is much
// faster than rebuilding an entirely new active trail.
drupal_alter('menu_breadcrumb', $active_trail, $item);

If this isn't enough to fix your problem, you can also see this contribution on github which seems great regarding the default breadcrumb construction in Drupal : https://gist.github.com/arshad/5490042#file-gistfile1-php-L12

Hope that helps :)


Feed importer: field collection processor settings I'm trying to import field collection to profile2.

I do not understand where to get in the Field Collection Processor information for the "Field/property name of Host entity GUID" and "Identifier field name" settings to fill in the text box?

Please see the image below.

Thanks!

Finally got it to work!

Settings for Field collection processor

Do not update existing field collection item

Field name: (The machine-readable name of the field collection)

Host entity type: Profile

Is field: unchecked (FALSE)

Field/property name of Host entity GUID: pid

Identifier field name: pid

Mapping for Field collection processor

pid => Host Entity GUID

(and my other fields of course)

Note:

pid is the Profile ID.


How can I add custom field validation for one of the fields "within" an addressfield? I'm attempting to implement one of the answers to this question on validating whether there no double-byte characters present.

Here is what I've done so far in my custom module:

function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'profile_gen_node_form') {
    $form['#validate'] = 'CUSTOMMODULE_location_doublebyte_validation_handler';
  }
}

And then:

function CUSTOMMODULE_location_doublebyte_validation_handler($form, $form_state) {

This is where I'm stuck.  Addressfields include much more information than normal fields; they seem to be like a collection of fields.  Here is a screenshot of the output of dpm($form):

I want to check strlen() and drupal_strlen() of the value of the "locality" piece of my addressfield but I can't figure out how to do that.

I tried something like this:

if(strlen("field_gen_loc_current['und']['0']['locality_block']['locality']") !== '0') {
    form_set_error('locality', t('No double-byte input.'));
}
}

But, while this doesn't produce an error, it also never causes the validation to fail.

I've just chucked a validation function into a dev site with an addressfield and you're right, it's a bit strange. It might be that the address field is marked as #tree => TRUE, and that's what's causing the long element key string.

Either way, it looks like you're checking the $form variable in your validate function, when the submitted data will actually be inside $form_state['values']. A couple of other minor alterations and you should be able to get it working:

function validation_function(&$form, &$form_state) {
  // Let's at least TRY to keep lines to 80 chars...
  $key = 'commerce_customer_profile|billing|commerce_customer_address|und|0';

  // Get the length of the
  $length = strlen($form_state['values']['addressfield'][$key]['locality']);

  if ($length != 0) {
    form_set_error('addressfield', t('No double-byte input.'));
  }
}

That example is based on the Commerce add customer form, so you'll need to inspect the $form_state['values'] array in your own form to find out exactly what the $key variable should be but hopefully that'll give you somewhere to start.

Just a note on your use of !== above...be careful with that, it will force PHP to make sure the types of the variables are equal, as well as the value.

strlen() returns an integer, and '0' is a string, so strlen('string') !== '0' will always return TRUE, regardless of whether the values are the same.


Breadcrumbs stopped going to third level I'm still learning Drupal, so have a basic understanding, and have been assigned to fix our breadcrumbs.  Apparently it used to go to the 3rd level on this page (https://ccom.unh.edu/theme/auvs), but it no longer does, only to the 2nd level.  It should say Home>Research>AUVs, but it only says Home>Research.

The Crumbs module wasn't installed.  I've been looking through our modules to try to figure out what is doing the breadcrumbs, but I don't see anything.  If I install the Crumbs module I can't even find instructions on how to implement it.  Can someone give me some guidance here please?  Thanks!

You can search for theme_breadcrumb(), they may develop it with this function ( search in template.php )


Drupal 7 how to programmatically display resent comment from all article with author image and comment content? I'm just use built in function comment_get_recent($number); but its only fetch resent comment's subject and author name, is any built in function available which display resent comment with author image comment subject and comment content?

comment_load($cid) should load the entire comment object based on the comment id ($cid).

What you do with it then is up to you.


How can I encrypt the login process without using SSL? My webhost doesn't allow SSL certificates for my webhosting product since it is a shared IP server. (I would have to upgrade the product and pay a lot more money, which I don't want to at the moment) I don't really need all of the website encrypted, I only want to give the password (and username) submission on login a bit more protection. Is there a module that just does some asymmetric encryption on the password on submission, e.g. with JavaScript?

Note: I know about the possibility of Man-in-the-Middle attacks with this setup.

So far, the only way that I've found to encrypt user login without SSL is the Encrypt Submissions Module (https://www.drupal.org/project/encrypt_submissions)

It uses the jCryption library (http://www.jcryption.org/) to encrypt the username and password that drupal offers up in clear text otherwise. Fairly straightforward to set up. The only server requirement is bcmath php module which most servers have anyway.

I use Encrypt Submissions whenever I can't use SSL, not as a replacement. You may want to consider switching hosts if they don't allow SSL certs, they sound pretty backwards.


how to link a select field options with the database records i am doing some experiments within my custom form and that is to display a table record from database only corresponding to the product code (i.e sku) is selected from the select list. The database has following structure:

nid | sku | orderin | orderout | created

I want to link the sku in select list and the sku in database table so that when i select a sku then data corresponding to that sku should only display. Below is what I have done so far.

Query for the select list

function formModule_display($form, &$form_state)
{

  // The form we are building
  $form = array();

 $result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->sku;

    }

Query for record display

 $query = db_select('formmodule_order', 'h')
   ->fields('h',array('nid','sku','orderIn','orderOut','created'))
   ->orderBy('h.nid', 'ASC')
   ->condition('$options[$row->nid]', array('pen-11'));

    $result = $query->execute();

Check out the Form API reference, especially the part about select lists:

<?php
   $form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
          0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );
?>

You can also consult the examples module for more information.


Embed one entity form into another and save both I have a custom entity, that is depending on the user entity. In fact, it is even so depending that I felt it made sense to display my entity form within the user profile form:

The problem I am now having is the following; there are 2 save buttons. And if it is not bad enough, the save button for the user (the lower one) does not even function anymore and white label save button only saves the white label entity.

The form is altered into the user form like this:

function whitelabel_form_user_form_alter(&$form, FormStateInterface $form_state) {

  $whitelabel = WhiteLabel::load(1);

  $whitelabel_form = \Drupal::service('entity.manager')
    ->getFormObject('whitelabel', 'default')
    ->setEntity($whitelabel);

  $form['whitelabel'] = array(
    '#type' => 'details',
    '#title' => t('White label settings'),
    '#open' => TRUE,
    'form' => \Drupal::formBuilder()->getForm($whitelabel_form),
  );
}

I was hoping to shuffle some parameters in the $whitelabel_form array (that used to work in Drupal 7), but that array is enormous and I could not find the submit buttons and handler that I needed.

So the question is, can this be done? And what would be the recommended way of doing it?

Instead of trying to do your own thing, you should try Inline Entity Form module. This module is made for this specific case (creating / editing entities within entity forms).

I know a lot of work has been put in to this to improve workflow in Drupal Commerce, which means this should be working well. I haven't tested it out myself, but since Drupal Commerce depend on it in Drupal 8 as well, it should be quite stable already.

The module works by adding a widget to the entity reference field that creates the form, so it should be pretty much plug and play. The only requirement is that the user has a reference to your custom entity.


Regex field validation producing false (?) negative I've also asked this question in the module issues, since I'm not sure if it is a bug or something I'm doing wrong.

I'm trying to use the Field Validation module to apply a regex control to ensure that a Philippines cell phone number is correct, and I'm getting what seems to me to be a false negative.

These numbers are 63, followed by 8 or 9, then followed by 9 digits.
I've created a control using the Regex (PCRE) rule, with the following format:

 ^63[8-9]\d{9}$

and yet it persistently gives me false negatives, for example on this: 639121129374

I can't see anything wrong with the regex, and I've tried testing my numbers on regex101.com (cool tool) and they work fine. Is this a bug, or am I doing something wrong?

When using the PCRE validator you need to add delimiters to your regular expression. For example:

/^63[8-9]\d{9}$/


Find if the drupal node is published or not published in node_save() I am trying to find if the user has set the node to be published when creating a node. Upon hitting save, the call to node_save() is done; I tried to call print_r($node), but nothing seems to show up in the data which relates to the publishing status of the node.

How would I find out if the node is set to be published? Is there a way I can find out if an alias is set?

You are looking for $node->status. The Node module defines two constants which you can use instead of 0/1 to make your code more readable:

/**
 * Node is not published.
 */
define('NODE_NOT_PUBLISHED', 0);

/**
 * Node is published.
 */
define('NODE_PUBLISHED', 1);

Example:

if ($node->status == NODE_PUBLISHED) {
  // Node is published.
}

Note that you should not alter node_save(). Instead, implement hook_nodeapi() to do something either before ($op is "presave") or after ($op is "insert"/"update") the node is saved.


How to get rid of "Designed by" in the theme? I am using the business theme in Drupal 7. I was wondering how do I get rid of the "Designed by Devsaran." in the bottom right corner?

You need to edit the page.tpl.php file and remove the line in the footer:

http://cgit.drupalcode.org/business/tree/templates/page.tpl.php?h=7.x-1.x

Its at the bottom.

    <?php if ($footer_copyright): ?>
      <?php print $footer_copyright; ?>
    <?php endif; ?>
    <?php if (theme_get_setting('footer_credits')): ?>
      <?php print t('Designed by'); ?>  Devsaran.
    <?php endif; ?>

However, it seems like there is a theme setting you can just uncheck as well, under Admin > Appearance > Business > Settings called 'Footer Credit'.


How to change the order of the payment methods in Commerce? How can I change the order of the payments methods in the last step before placing an order in Drupal Commerce?

Changing the weight of the Rules for payment methods will change the order on order review page.


Replace tables with divs in pages generated by views How can I replace the page layout generated by views with the grid format into something  tableless? I need those columns displayed in css stylished divs.

The short answer is to edit the View and change the Style Settings from table to unformatted.


Pass variables from controller to existing node template file In the Drupal 8 documentation I have found a way how to pass variable from controller to custom twig template

https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

test_twig.module

function test_twig_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
    ],
  ];
}

TestTwigController

class TestTwigController extends ControllerBase {
  public function content() {

    return [
      '#theme' => 'my_template',
      '#test_var' => $this->t('Test Value'),
    ];

  }
}

But is there a way to pass variables from controller to already existing node template, for example to node--custom_content_type.html.twig

I believe that node--custom_content_type.html.twig is referring to template overriding.  In template overriding, you are still using the default theme with it's defined variables.  If you are generating the render block in your controller, you can set the variables defined in the default theme. These are generally listed in the default template.

An alternative to passing variables into templates is to use the specific theme preprocess hook.

Finally, if you set up your local site to deal with debugging twig, you will see information about the template and available hooks for various parts of the output.  See the docs for how to set this up.


Drupal 7 Views filter between start and end date I try to accomplish the following:

I want to create a View, which is automatically listing the newest terms.

There a two terms a year (summer term 01.04.-30.09) and (winter term 01.10-31.03).

Those terms have several Events in it. So i tried to filter them automatically with a reference of "now"

So i set the filters as the following:

start-date is greater than or equal to "now"

end-date is less than of equal to "now"

I also tried to switch the arguments,

just as explained in this article: Drupal 7 Views filter between two dates?

but it didn't do anything.

I made some screenshots, to show you how i configured the view and the event.

(And yes, the other filter criteria s are met.^^)

I hope you can help me with this problem, or tell me another trick to accomplish my goal.

This module should do exactly what you need: https://www.drupal.org/project/views_between_dates_filter


Drupal 8 Contextual Filter Exclude option I have a case where I want to list all taxonomy terms but exclude the term that is filled in the url. In D7, in contextual filters you could expand 'More' and check that option. I cannot find this option in D8. Am I looking in the wrong place or just not seeing it, or is this option not (yet) in Drupal 8.

If the latter, is there any other option to become this? I searched around but without any succes.

Thanks in advance

I ran into the same problem, and I got it working because in D8 I didnt have Search API installed(still beta in D8 at time of this post).  Not sure if you have this extension installed.

Also I had to enable Search API term handlers.  Then you should be able to see the Exclude option in the Views contextual filters.


Block display using wildcard, non-greedy I have a block that I have configured to display "Only on the listed pages"

commerce_store/store/*

The problem is, it displays not only on the view link, which I want it to, but on the edit and other menu tabs

commerce_store/store/1        <-- good
commerce_store/store/1/edit   <-- bad
commerce_store/store/1/sales  <-- bad

I've tried switching to PHP code, but this doesn't seem to have any effect whatsoever. I've even changed the code to var_dump($path); exit; and it doesn't exit.

Edit: This code works, just enclose it in <?php and ?>

$path = current_path();
$url_parts = explode('/', $path);
if( $url_parts[0] == 'commerce_store' && $url_parts[1] == 'store' && count($url_parts) == 3 ) {
  return TRUE;
}

Note that you can use arg(x) where x is the position in the path starting from 0, so you could do something like this as well:

<?php
if (arg(0) . arg(1) == 'commerce_storestore' && !arg(3)) {
  return TRUE;
}
?>

You could also use drupal_match_path() like so:

<?php
if (drupal_match_path(current_path(), "commerce_store/store/*") && !arg(3)) {
  return TRUE;
}
?>

Cheers,


Can Features package its dependencies? I have just created a Feature that has about 10 module dependencies.
I installed the feature on the target Drupal instance, and discovered that the dependencies were not included in the feature tarball. Is there a way to tell features to package dependency modules into the feature so that they will get installed along with the feature?
Or am I misunderstanding what the features module is supposed to do?

I think the latter is true, and you're misunderstanding what Features does.

Features takes any database-stored configuration (Views for example), and exports it to code.  The generated module is essentially just a package that then contains the code version of your configuration.

For example, if you create a Feature containing a Blog content type, and a View that show all Blog articles in a list - the generated Feature is simply a module with that configuration stored in code, and exposed to Drupal.

If you want all of the modules packaged, you are looking more towards a distribution - which is a completely different kettle of fish.

To cut a long answer short, Features is a module builder - so as with any other module, dependencies must be retrieved seperately.


Adding an entity reference field to entity I'm looking for a way to add an EntityReference field to an Entity, but haven't found an answer to this.  Is it possible?  Can someone point me in the right direction?

Thank you

You need to go to the admin section for your entity / entity types, and add fields with the Manage Fields tab (just like you would for content types).


Views - currently logged in user problem There's a taxonomy list labeled games-list that's used in both the content type named game and user field subscribed. Each game has exactly one of the terms from games-list selected, but a user can select an unlimited amount of items within subscribed.

To be clear, both the user field subscribed and the content type field game are a term reference field that's linked to games-list.

My goal is to create a view that shows a list of content from game that is unique to each user, and that only shows the values of game that has been selected by the user from subscribed.

Whenever I try to filter by "currently logged in user," it only shows content that was authored by that user. Specifically, how do I configure the view to show only content that the user wants, regardless of who authored that content?

I figured it out.

The key was to create a "user" view from the beginning, and not a "content" view. Then, the view provided me with all the necessary relationships/filters that I could use. I got this idea from Views - Filtering nodes by current user profile field.


Flag lists alternative Is there any good way to let users create custom node lists? I'm using Drupal 6.

I've found the Flag Lists module, but it has not been fully released, yet.

Any idea would be helpful.

I think you need the Node Queue module with the Smartqueue Per User.

Although it's not listed on the front page, you can now get the 6.x-2.x-dev version which does the multiple lists (or queues) per user.

I've also got a patch to make it work with the latest version of Node Queue.

This module might appear flaky because few sites use it and the issue queue is stale, but it really does work the way it's supposed to. We're using that 6.x-2.x-dev on a production site with premium content and it gives us NO problems whatsoever.


Hierarchy between terms from different vocabularies in Drupal 7? Is there a way to have a hierarchy of terms by reusing the same terms that reside in different vocabularies? There seem to be so many different options for dealing with taxonomies in Drupal 7 that it feels very daunting to figure out...

For example, let's say I want to make a directory of athletes for different sports. I've created 3 vocabularies, each with several terms:

Vocabulary: Sports
* Soccer
* Basketball
* Baseball

Vocabulary: Divisions
* Division 1
* Division 2

Vocabulary: Teams
* Team 1
* Team 2

Each type of sport will be divided into Divisions and then into different teams per Division.

The hierarchy looks like:

Soccer
* Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
    --Team 2

Basketball
*Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
... and so on for each sport.

Since the terms for vocabularies Divisions and Teams are always the same, I'm thinking it would make more sense to be able to reuse the same terms under those two vocabularies instead of creating the same terms over and over again for each sport, each division...etc.?

Is that even possible and if so, what would be the best way to go about implementing it?

You can make a term reference field on a vocabulary.
So on a the team vocab one of the fields would be "division".
So when you create a new team you would enter the team name and "tag" the division it is in using auto complete or a dropdown.


Is there a token for the body of a content type? Is there a token for the body of a content type? I'm using the Integrated Metatags module. I want to include some of the body text inside of the Meta Description tag.

There is a feature request opened for the Token module: Token for body of node.   Essentially, the reason it has not been implemented is performance issues, as modules are queried for the values of the tokens they implement, independently from the fact those tokens have been requested. This means the content for, e.g., [body] would be generated even if the string passed to Token doesn't contain that tag.
The Drupal 7 code that handles tokens is changed, and the modules that implement tokens gets the list of tokens that need to be replaced; the content of tokens that are expensive to generate is generated only when required.

In short, the only module that could implement that kind of token is the Token module, but so far it doesn't implement it for implementation issues. Any other module that implements it would have the same performance issues.


AJAX event and disable select form element I have a little problem:

/**
 * Form callback
 */
function ajax_disable_test_form($form, &$form_state) {
  $form['select'] = array(
    '#type' => 'select',
    '#required' => FALSE,
    '#title' => t('Change me!'),
    '#empty_option' => t('- Select -'),
    '#options' => drupal_map_assoc(range(1, 3)),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['change'] = array(
    '#type' => 'submit',
    '#value' => t('Change!'),
    '#ajax' => array(
      'callback' => 'ajax_disable_test_form_submit_ajax',
      'wrapper' => 'select_box_wrapper',
    ),
  );
  return $form;
}

/**
 * Ajax callback
 */
function ajax_disable_test_form_submit_ajax($form, $form_state) {
  $form['select']['#title'] = t('Changed!'); // It's work!
  $form['select']['#disabled'] = TRUE; // It's not work!
  return $form['select'];
}

Link: https://gist.github.com/nevergone/23f0a50bee01acc34ed2

If clicked the button, select box title changed, but select box not disabled. Why?
Version: Drupal 7.41

try:

$form['select']['#attributes']['disabled'] = 'disabled';

Ok, a detailed explanation can be found on this article https://www.drupal.org/node/357328

But pretty much resumes to:

  we cannot simple set the $element['#disabled'] attribute of the
  element. The reason is this attribute is transformed into
  $element['#attributes']['disabled'] by
  _form_builder_handle_input_element executes()...


Using jquery-match-height to set two blocks to equal height I'm new to jquery and adding it to Drupal. I'm trying however to add this library to my Drupal site so I can set two of the blocks on my home page to equal heights. But it's not working and I'm not sure why.

Here's the library:

https://github.com/liabru/jquery-match-height

The items on the home page to make equal are in two different regions in the zen subtheme. They are separated by a third region in the middle. Here's how the regions look in the tpl:

  <?php print render($page['featured_resource']); ?>
  <?php print render($page['hp_video']); ?>
  <?php print render($page['whats_new']); ?>

Note: because I'm using Zen I've used Zen grids to make all these items be on the same 'row' (the same zen_clear()). Not sure if this might cause problems with the way the jquery is coded.

I want to set the blocks within the 'featured_resource' and 'whats_new' to the same height. The blocks contained within those regions I've given the same class as each other: 'feat-res'.

I've added my jquery library and code file to my pages using drupal_add_js in my template file like so:

function mytheme_preprocess_page(&$vars) {
    drupal_add_js(drupal_get_path('theme', 'my_theme') . '/js/jquery.matchHeight.js');
    drupal_add_js(drupal_get_path('theme', 'my_theme') . '/js/matchHeightHP.js');
}

I think it's calling it correctly because when I firebug the page those .js files are showing up in  tags.

The code I've put in the file matchHeightHP is simply this:

(function() {
    $('.feat-res').matchHeight();
})();

So that's where I get especially unsure. I tried to model it after the examples given on the link I referenced at the top, but as a jQuery newbie I really don't know if this is correct or not. Any help would be appreciated.

The blocks on my home page continue to look very uneven as the content on one is much great than the content on the other. I want them to both be equal to the height of the block that has more content.

Have you already tried out the Equal Heights jQuery module? This module does exactly what you want, without having to create custom code and works fine with Zen.


How do I get a contextual filter argument in a template file? I use contextual filters for a view whose path is /path/langcode, where langcode is a contextual filter. How can I get langcode in a template file?

You can get the contextual filter argument from the route match:

  $variables['arg_0'] = \Drupal::routeMatch()->getParameter('arg_0');

Usually the route parameters of contextual filters are named arg_0, arg_1 etc. If it doesn't work, check the route definition of this View page with Devel (/devel/routes) or Drupal Console.

Dependent on the Twig template you might need to add a cache context as well:

  $variables['#cache']['contexts'][] = 'route';


Substitute "Your Name" field for anonymous shown on posted comments I am using the 'Corporate Clean' theme.  I have allowed anonymous posting of comments for basic pages. When a person posts, there is a an input field called 'Your Name'.  However when the comment is posted, Anonymous is showed instead.  I would like to know how to substitute the Anonymous for the 'Your Name' field or if not, have the 'Your Name' show in the title line of comment.

thanks in advance.

Update : ok I have loaded a test site with bare minimum modules and tested comments again.  It works this time - no issues.  I can only assume one of the modules I have installed is causing this as I have not edited any files by hand.  What is the best way to troubleshoot this?

I found it was the antispam module and created a bug + patch