When should I use user_load($user->uid) when do we need to load user using  user_load($user->uid) after global $user. Why do we need to load a user because we can access user data after declaring it global. I am adding a commerce customer to his billing and shipping profiles, should I use user_load?

The global $user object is just the bare data received from the users table for the associated user. It doesn't have any field, or other module-added data, attached to it by default.

For example, if you have a field attached to your user accounts called 'field_nickname', and you want to inspect the value of that field for the current user in code, you would need to call user_load() for the data to be available.

// Might work, but it's not guaranteed - depends on the modules
// you have installed and what's happened in the page build so far
$account = $GLOBALS['user'];
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

// Will always work.
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

There are situations when other modules will load the field and other module data onto the global $user object, so depending on what modules you have installed you call to user_load() might not strictly be necessary.

However, it's good practice to make sure you load the object yourself; if another module has already run it for the current user then that data is statically cached, so you don't get a performance hit.


How to programmatically print all comments from a given node? I need to print comments belonging to a given node. So basically, get a node id then choose all the comments from a given node and print them. I know that I can print one comment (for example with id=12) using the following code:

<?php
$comment = _comment_load(12);
return theme('comment',$comment);
?>

Can anyone tell me how to do this?

If you are looking for a ready to use function, take a look at comment_render().

Example use (say the node you want comments for has nid = 5):

<?php
  $node = node_load(5);
 print comment_render($node);
?>

Or else you can manually query the database (comments table) to get all comments that have a matching nid.

<?php
  $nid = 5;
  db_query('SELECT * FROM {comments} WHERE nid = %d', $nid);
?>


Use a Custom Field in page.tpl.php I have a custom field called site_category that I am using in a few different content types.  The field site_category is an entity reference to a content type which has only one field defined:  Title.  For the purposes of this example, I have three instances of that content:  Things, Widgets, Places

I have another content type called content that has a number of fields including site_category

(Think of this like taxonomy, but using content types rather than terms)

I would like to add in the site_category field to my page.tpl.php so that it not only displays the title of the page, it also displays the site category that it is related to.

So, as an example, if I had a "Super Duper Widget De-Duper" that fell under the widgets category...

example URI:

.com/widgets/super-duper-widget-deduper

Page would render (styled of course):

Header
**Widgets**
**Super Duper Widget De-Duper**
Content
Footer

I have found a number of similar posts here on stackoverflow like this one:  Access custom node field in page.tpl.php  However, it dosen't work and I don't know what I am doing wrong.  There is a lot of php code provided, but I don't know where to put said php code because it is never really referenced.

I have added the output from the Devel module.  It appears that the field is being loaded as it is "there."  Shouldn't I be able to access it?

I have added the following code with a reference to the field that is displaying in Devel:

if (isset($variables['id'])) {
// Get the node ID and load it.
$n = node_load($variables['id']);

$variables['site_category'] = "Breakpoint 1";

//If "Breakpoint 1" shows up on the page output, we know that (isset($variables['id']))
//evaluates as  "true"

// Check if the node exists
if ($n) {
  $variables['site_category'] = "Breakpoint 2";

  //if "Breakpoint 2" shows up on the page output, we know that the ($n) evaluates
  //evaluates as true.

I only added the two breakpoints - no other changes were made.  When I view the output, only Breakpoint 1 shows up meaning the node doesn't exist.

Since you want to function on a "page level" (outside the content area) what you can do is:

Use hook_preprocess_page
Get the node id being viewed
Query the node using node_load or just your "term field" alone using EntityFieldQuery

This would somehow look like:

Your theme or custom module

// This function is inside my template.php
function YOURTHEME_preprocess_page(&$variables) {
  // This array key is only present when a page is a node page(node/<nid>).
  // If this is set, this contains the node object already.
  if (isset($variables['node'])) {
    $n = $variables['node'];

    // Don't forget to change this also to check if the reference field
    // has at least one reference/target node.
    if (isset($n->body['und'][0])) {
      $variables['site_category'] = 'PARTY! This displays the field we need';
      /**
       * The above line is just an example.
       *
       * You would replace it with the codes to load the target node:
       *   $target_node = node_load($n->field_site_category[......]);
       *
       * Display the title of the target node
       *   $variables['site_category'] = $target_node->title;
       */
    }
  }
}

page.tpl.php

<?php if (isset($site_category)): ?>
  <?php print $site_category; ?>
<?php endif; ?>

I added some screenshots of the outputs:

When viewing a node page

When not viewing a node page

Also to get the array keys inside variables, there is a module called Devel. Install it like any module and use its helper function dsm($your_var). This displays the contents of the variable in a pleasant manner.


How to implement challenges with prizes in a Drupal site? I've been working on a Drupal Commerce site where you can buy goods with points. Users gain those points with a system I already implemented. Everything is fine, but now I have to implement challenges.

Basically, the users will need to "follow" the challenge, then every point they gain from that moment will fill their point meter of the challenge. Every user who reaches the point limit (specified when the challenge is created) will win a prize.

How can I do this? I was told that I could use the Flag module for the following part, but I'm really clueless.

Your question seems like a perfect usecase for the Goals module (disclosure: I'm its maintainer). It can be used in combination with the User Points module, though you'd use that combination by granting user points "after a goal is completed".
Read on for a possible configuration for your specific case.

Configure the goals

Define some goals, with a description (say) like so:

Challenge 1
Challenge 2
Challenge 3

For each goal you may optionally associated some image with it, which are typically used to visualize the goals completed by a user.

And after a goal is completed, you can (optionally) automatically grant a predefined amount of user points to the user who completed the goal.

Configure the tasks

To achieve goal "Challenge 1", define the Task(s) to be completed. E.g.:

Publish 1 (or some other amount of) articles.
Post 1 (or some other amount of) comments.

To achieve goal "Challenge 2", define the Task(s) to be completed. E.g. publish 10 articles and post 20 comments.
To achieve goal "Challenge 3", define the Task(s) to be completed. E.g. publish 25 articles and post 50 comments.

Advanced task configuration

A more advanced way to use (configure) Goals, is to configure tasks like so:

there could be multiple tasks to be completed for a single goal.
some tasks might have to be repeated multiple times.
some tasks might have to happen within a given timeframe.
some tasks may require some amount of time to expire in between any 2 similar tasks.

Track progress while performing tasks

To track the progress made by a single user to complete some task, you only have to write the appropriate rules, using the Rules module, to record relevant events happening in your site, which are related to the completion of the various tasks.

For the goals/tasks described above as an example, you'd only need 2 (extremely basic) rules, which would be triggered like so:

After publishing an article.
After posting a comment.

Note that these 2 rules can be re-used to measure progress on each of the 3 goals.

Moreover, the above challenges are pretty straight forward (basic) as examples of Challenges. But you can do this for virtually any entity for which you can think of a way to track them via the rules module.

Process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. And the user points related to completing that goal will be rewarded.

If you want, you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user.

More info

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).


is there any way to make the webform components labels translatable? Just wondering how to make the webform components labels translatable.
I found this post with a link to a sandbox project but I don't where to download the module: Make Webform multilingual (i18n) aware through contributed modules

I also find this function to just make what I need but it doesn't work, maybe with a few change it will work: Source: work around

function module_name_form_webform_client_form_xx_alter(&$form, &$form_state) {
  foreach (element_children($form['submitted']) as $element) {
    // Pass each webform component title through the t() function.
    $form['submitted'][$element]['#title'] = t($form['submitted'][$element]['#title']);
  }
}

The function provided  by @lenni does the job but I get these error messages.

  Warning: strlen() expects parameter 1 to be string, array given en
  drupal_validate_utf8() (línea 1600
  de/Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).

  Notice: Array to string conversion en filter_xss() (línea 1366 de
  /Applications/MAMP/htdocs/tonisacristan.com/includes/common.inc).

  Notice: Array to string conversion en format_string() (línea 1552 de
  /Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).

The source of the problem is a Markup component. This function is working fine.

function webform_extras_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      //to skip Markup components
      if($key != 'my_markup_component'){
        $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
      }
    }
  }
}

Similar (a litte bit more generic) solution but still not a clean one:

function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
    }
  }
}


What's the use of the new Star button in the project pages? If you go to a Drupal project page (example Views) you will see a new button with a Start like this:

And you can Star and Unstar a project, but what is the real use of this button?

I can't find all the users that have starred a project.

Consider this "Star"-facility as a way to "bookmark" specific contributed modules as your "favorites". Some more details about it (from What’s new on Drupal.org? - April 2017):

  Users on Drupal.org may now star their favorite projects - making it easier to find favorite modules and themes for future projects, and giving maintainers a new dimension of feedback to judge their project's popularity. Users can find a list of the projects they've starred on the user profile. Over time we'll begin to factor the number of star's into a project's ranking in search results.

Notes:

Projects that you star-ed are shown to others also. E.g here are your current star-ed projects.
When I look at the views page (without being logged in to D.O), I don't see that "star" (as in your image), I only see the star itself, and the "35". After I log in, I do get a similar Star-image like your question here.


How to enable maintenance mode only when there are no active users? When there are updates available for Drupal, I enable the maintenance mode, update, and disable the maintenance mode again.

As far as I understand it, users that were right in the middle of editing a node or checking out their shopping cart would lose their content/progress because of the maintenance break.

One solution could be to notify all online users that they should save their content, however, this would not work for users that are checking out right now (e.g., filling in the shipping data or being in the payment process).

Ideally, when trying to enable the maintenance mode, Drupal should warn me that users are currently active on the site.

Is this possible? Can Drupal detect that someone (be it a registered or an anonymous user) is "active", even if the user might have been afk/inactive for some time (e.g., searching for the credit card)? Possible indications could be: opened a node edit form but no submission or further request detected; started but not finished the checkout; added products to the cart without checking out; etc.

If yes, how could I achieve this? I’m not experienced enough to write this from scratch, so hopefully this doesn’t involve creating a totally new module. Does there exist a module for this purpose?

Solution 1 - Going Down:

Using the Going Down module (credits: J. Reynolds) could be a valid compromise (and maybe help to create a custom work around). Some more details about this module (from its project page):

  ... warns site visitors that the web site will be going down for maintenance at a specified time. The default configuration displays a fixed position red overlay message at the bottom of the browser window with text in the format 'Drupal is going offline for maintenance at Tue Feb 21 14:41:08 2012 -0800'. Module configuration is added to the Site Maintenance administration page (admin/settings/site-maintenance).

Here is a screenprint about it (also from its project page):

Only using this module will only reduce the risk of active users when you want to enable maintenance mode (though not completely reduce it).

However, by using that module, you may be able to use the Rules module to build some custom rule(s), in which you add your own custom Rules Conditions to go check if the time left for scheduled maintenance date/time is still sufficient.

Such Rules Condition would be to perform some custom PHP code, to retrieve the date/time set via the Going Down module. And then add this Rules Condition when visiting pages where you want to avoid your issue.

Solution 2 - Rules (and Message) is your friend:

Use the Rules module to create a custom rule that uses Rules Event "Drupal is initializing". Add whatever Rules Conditions you want, if any (eg: not for users with role admin). And add the appropriate Rules Action(s) to perform some type of special logging, e.g. using the Message module to create custom log data. Such log data should include things like timestamp, user id, current path, etc. If you'd use the Message module, you could create a (rather basic) view (using the Views module) to list the relevant log records that got created by this custom rule.

Enable this custom rule only X minutes (pick whatever value that fits for X) before you plan to enable maintenance mode. From then on just browse the views results to get an idea about how long ago which user/visitor has been visiting which path. For any events (log records) longer then Y minutes ago, just assume that user/session is not really doing anything on the site anymore at the moment you're browsing your Views result.


What may cause my fatal error Call to undefined function _menu_target_edit_form_extra_elements_submit()? I'm running Drupal 7.53 and all my modules are up to date. I suddenly started having this error on my Drupal site.

  Fatal error: Call to undefined function _menu_target_edit_form_extra_elements_submit() in /home/portal/public_html/includes/form.inc on line 1520

This error happens when I try to add a new content type or edit a content type that includes a media or image field. It doesn't matter if the field is empty or contains content.  However, if I remove the field from the content type, it saves just fine.

Since my site is very event driven, I am unable to edit events until the problem is fixed.  I've run registry update, flushed caches, run cron...  you name it. I did not update any modules since it was working on Tuesday to when it stopped working this morning. I did update the media module on Tuesday but I am pretty sure I did this before I added a few events.

Any ideas?

Hey I just had this issue this morning too. In my case it was being caused by the module menu_target I disabled it and the issue disappeared.


Removing external CSS files with hook? My theme is adding the following CSS below. How can I remove it? I know that with Drupal 6 you can do stylesheets[all][] = in the .info file but what about Drupal 7? Can hook_css_alter() be used on an external file?

<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" media="all" />

Yes, hook_css_alter can be used with external CSS.


Why can anonymous users see my block, whose visibility is set to hide it for anonymous users? I have a block on one of my sites, in which all content is private.  Anonymous users don't see any of my content types, any of my views, blocks, etc.

The problem is one single block.  The problem block is the only one not created by a view or a module.  I created it simply by adding it via the block page interface.  I have set its visibility settings to be restricted to a certain role (not 'Anonymous', of course :-)).

However, this is the one piece of content that is still showing up on my site for anonymous users (before one logs in).  I've cleared cache multiple times, so that isn't the issue.

Has anyone else run into this issue?  Why would the block not respect the visibility settings?  I'm wondering if there are some modules that may be interfering with this or if there's another explanation I'm not seeing....

The strangest thing fixed my issue.  I'm still not sure why.

I was placing the block in a certain region with the 'Context' module.  When I removed the block placement from that context and set it directly in the block's configuration page, the block stopped being visible to anonymous users.

Not sure why that would matter!  Placing blocks generated by views with the 'Context' module is not interfering with their visibility settings, but for some reason it was interfering with this one.  It's just a regular block with text, nothing funky.

In any case, that's what solved my problem...


Modify price components from Commerce Shipping without altering the module itself I use Drupal Commerce with Commerce Shipping and Commerce Flat Rate.

I have a client who wants the shipping line item in the commerce summary cart to come before the tax line item. My problem lies in that Commerce Shipping doesn't expose the weight of each shipping service when it implements the hook_commerce_price_component_type_info as seen below.

I have tried to use the mentioned hook in one of my own modules and with a lower value for the weight. This produces an error in the Commerce Price module where it tries to do the addition array(20, -50) + 1. Somehow, the Commerce Price module creates an array of the values instead of overwriting.

The weight I'm trying to overwrite is the one in the foreach loop.

Once I have solved this, I'll need to subtract the tax component on the shipping line item, but that's another problem which I can probably figure out by myself.

Line 110 to 135 in commerce_shipping.module.

/**
 * Implements hook_commerce_price_component_type_info().
 */
function commerce_shipping_commerce_price_component_type_info() {
  $components = array();

  // Define a generic shipping price component type.
  $components['shipping'] = array(
    'title' => t('Shipping'),
    'weight' => 20,
  );

  // Add a price component type for each shipping service that specifies it.
  foreach (commerce_shipping_services() as $name => $shipping_service) {
    if ($shipping_service['price_component'] && empty($components[$shipping_service['price_component']])) {
      $components[$shipping_service['price_component']] = array(
        'title' => $shipping_service['title'],
        'display_title' => $shipping_service['display_title'],
        'shipping_service' => $name,
        'weight' => 20,
      );
    }
  }

  return $components;
}

PS. Tax rate on shipping price is not the same as my problem. DS.

If I get you correctly, you want to alter the order in where this components are displayed in the checkout process.

What I've done for minor tweaks on this area is using a preprocess of the components theme function, for example:

function mymodule_preprocess_commerce_price_formatted_components(&$variables) {
}

There you've got $variables and all the components, including the shipping ones so you can tweak some things of the display.


When offloading a hook implementation to another function, which function should be documented as "Implements..."? This is a (probably super simple) document standards-related question.

Example:

_menu_block_block_configure - DrupalContrib

Note the docs: "Implements hook_block_configure()."

It initially threw me off to see an internal function (with underscore prefix) documented as a hook implementation, but if the actual work is being done here then there is some sense to it.

My question: is this the proper way to document it?

TL;DR: Yes, it's fine and widespread too!

It might look kinda unorthodox but it's just offloading the bulk of the hook implementation to an include to keep the main .module file smaller.  Here's where it's happening: menu_block.module (view source at the bottom).

A lot of other contribs do this too, for example: Display Suite (see line 48 onwards) and I'm pretty sure Views and a bunch of others too.


Sending Contact Form Emails I am trying to configure a site to send emails using the Contact Us form. At the moment, my understanding is that some PHP modules are required for that. I have already created the Contact Us forms and entered the 'recepient' addresses.

Could someone tell me how I should configure the PHP to do that? The site is running PHP 7.0.12

If you're running on localhost there is a great chance your emails will not be sent.

I would recommend using webform for your form modules as this is a very good tool for this.

And test the email part on an actual server. If you want to send emails locally you will need to set up your php.ini file:

See more info on that here: explanation here


Users cannot login. The username field is highlighted red, but there are no error messages. There is no password reset link I've inherited a Drupal site and uploaded it to a new server but retained the existing domain name. The site is working, but when I try to log in as admin (or any other user) the login page just reloads with the username field highlighted red. There are no error messages and the username is definitely correct. I have tried to re-set the password manually in the database. I have also tried to add a new user directly into the database with admin privileges. Neither works. Also, there is no forgot password link on the login page. I have tried to change the base url and cookie url in the settings.php file but that did not work. I have tried repairing the sessions table but to no avail. I'm new to Drupal so not sure what to try next.

Perhaps User 1 (if that's the admin login you're using) is blocked somehow. There could be a module, or custom code somewhere that is blocking this account's login.

I'd try looking through the list of contrib (contributed/non-core) modules for any who's name looks like it might be responsible for limiting login access.

Also, look for any custom modules and look through their code for any hints that it may be limiting logins also.

If you find a suspect then try disabling the module to see if this resolves the issue.

Another place to look for possible culprit code is in the active theme's template.php file (usually located in /sites/all/themes/THEME_NAME/template.php)


Multi language Poll output I am developing a multilingual site, where the front page outputs the poll block with the following code.

    $block = module_invoke('poll', 'block_view');
    print render($block['content']);

The output does not change when the language changes. How do I translate that output with the i18n module?

You need to do the following steps in order to achieve what you need:

Download Poll aggregate patch file from here
Apply the patch file the way you want. Good Drupal reference here.
Goto Modules list page admin/modules and install/enable the following modules:

Multilingual content module
Multilingual select module
Field Translation
Synchronize translations module
Poll aggregate

Then goto Poll content type settings page admin/structure/types/manage/poll and enable Multilingual support by choosing Enabled, with translation
Create a new poll content with its options and select default language from the Language dropdown list and save the node.
Create translation Poll content for the same node by clicking on translate tab.
Replace default language content with the second language.

I hope this will solve your issue.


Update form attributes with javascript and get them on submit Hi i have a textfield form with attribute of "data-updated" the default is 0
If user clicks on textfield and fill it, "data-updated" changes to 1 with jQuery.
On form submit the attribute remains 0 even if it changed to 1, how can i fix it?

Here is the code:

    $form['name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#attributes' => array('data-updated' => 0, 'onclick' => array('jQuery(this).attr("data-updated", 1);')),
    );

And here is the submit

print_r($form_state['complete form']['name']['#attributes']['data-updated']);
die();

I always get 0 even if the jQuery update the attribute to 1 :/

As Clive said in the comment, you can't fix it. To do such things in the background of a form, use a hidden element:

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#hidden


Why does adding a relationship change the display of my view? I have a simple view based on my commerce_product? When I add a relationship to Flags, the display changes from 12 per page, to 2. I'm confused why adding the relationship changes the markup?

It does not alter the markup, it just potentially reduces the result set, depending on whether the flag is set as required or not.

It depends on how you add the flag. If you add it and tick Include only flagged content, then you make the relationship required and the relevant SQL has this form:

INNER JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

whereas if you add it and don't tick Include only flagged content, then the relationship is not required and the relevant SQL has this form:

LEFT JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

So views alters the type of join depending on whether the relationship is required or not - INNER JOIN vs LEFT JOIN.

Look at A Visual Explanation of SQL Joins and Visual Representation of SQL Joins


How do I show webform component labels in a chart using Views chart format? Drupal 7.50, Webform 4.12, Webform Chart 2.0, Views 3.13, Charts 2.0, with Google Charts as the charting engine, so not Highcharts.

I have a webform that collects simple drop down list values for each question. The values are 1, 2, 3, 4 and 5. There are around 10 questions.

The labels for each component are not displayed on the chart. It seems the Label of the very last field added to the list is used for all fields, and they are only shown when the bar is hovered over.

I created a view and added the webform submission data fields then enabled aggregation and set the format to Chart. Limited the number of records in the pager settings to 1 (So we get just one Webform instance). Example below shows how the first series is called "Governance Framework" but when hovered over, the bar shows the last label "Organisational Structure1".

Can anyone advise how I can get the Webform Component Field labels to show up on the left of each of the bars, or fix the hover over issue? Many thanks!

P.s. not sure which module page I should log an issue, so any pointers on how to patch the relevant project would be appreciated.

Module involved

About your PS:

  ... not sure which module page I should log an issue, so any pointers on how to patch the relevant project would be appreciated.

No doubt possible: Charts.

Using tooltips

It sounds to me that you should have a look at Pass library-specific options via existing #raw_options, which already provides a solution (using #raw_options) to what you're trying to get to work (ie: "tooltips"). For charting engine Highcharts it's already supported (and committed to the most recent dev version, which is the version I recommend), while for charting engine Google Charts (which you are using) you'd need to apply the RTBC-patch attached to comment nr 9. Obviously, after that patch is committed, using the #raw_options will continue to work (for either charting engine). And rest assured, this patch will (not might ...) make it.

With this #raw_options solution, Charts has a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Notes:

Apart from Webform Chart (without s), there is also Webform Charts (with s). The results you'd get are probably going to be similar, because both modules use Charts.
Drupal 7.50, which you are using, is the most recent Drupal version, but still your screenprint includes that (red) error msg with "There is a security update available for your version of Drupal"... bizarre ...

Disclosure: I'm a co-maintainer of the Charts module.


Not able to install a module via drush I am trying to install
Vote Up/Down module via drush. But even if it is not already installed and it has been downloaded, it is not being installed.

[root@localhost custom]# drush dl vote_up_down
Install location /var/www/html/d7/sites/all/modules/contrib/vote_up_down already exists. Do you want to overwrite it? (y/n): y
Project vote_up_down (7.x-1.0-alpha1) downloaded to /var/www/html/d7/sites/all/modules/contrib/vote_up_down.                [success]
Project vote_up_down contains 5 modules: vud_term, vud_field, vud_node, vud_comment, vud.
[root@localhost custom]# drush en vote_up_down
vote_up_down was not found and will not be enabled.                                                                         [warning]
There were no extensions that could be enabled.                                                                             [ok]
[root@localhost custom]#

Can anybody help me with this?

Project contains 5 modules. Neither of them is named exactly like the project. See the names you were given in first message.

You probably meant

drush en vud


How to use d3 word cloud in Drupal? I am using D3 word Cloud locally on my computer. It works fine. It gets the data from the database and displays it as word cloud on webpage. I want to place the output from it in Drupal website. How do I place it as a block?
EDIT: I have 2 JavaScript file, a JSON file and a HTML file. All these files I want to include. I just realised that the HTML file has this code,
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="../lib/d3/d3.js"></script>
<script src="../d3.layout.cloud.js"></script>
<script>
  var fill = d3.scale.category20();

  d3.layout.cloud().size([800, 300])
      .words(["This", "is", "some", "random", "text"].map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      }))
      .padding(5)
      .rotate(function() { return ~~(Math.random() * 2) * 90; })
      .font("Impact")
      .fontSize(function(d) { return d.size; })
      .on("end", draw)
      .start()
      ;

  function draw(words) {
    d3.select("body").append("svg")
        .attr("width", 800)
        .attr("height", 300)
      .append("g")
        .attr("transform", "translate(150,150)")
      .selectAll("text")
        .data(words)
      .enter().append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return fill(i); })
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; })
        .on("click", function(d) {
          var string_url = "http://etraining-dev/search/node/" + d.text;
          window.location = string_url;

  });;
  }
</script>

which is just script. I am not sure how to include these files and make it work. Can anyone help?
Thanks.
Background
D3.js is a JavaScript library for manipulating documents based on data. I will need to add the d3 javascript library to the page, as well as the D3 word Cloud script. I then need some way of inserting the HTML5 canvas element in my content so that it can be manipulated by d3.

Option 1 - simple

Generate a block using a custom module

Making a simple block module with drupal is really easy. The examples project includes a block_example, this is a good starting point. The following is roughly what your module (d3wordcloud.module) should look like:

  d3wordcloud

  d3wordcloud.info
  d3wordcloud.module

d3wordcloud.info:

name = "D3 Word Cloud"
description = "Provides a block with awesome word cloud generated by D3."
package = custom
core = 7.x
dependencies[] = block

d3wordcloud.module:

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function d3wordcloud_block_info() {
  $blocks['word_cloud'] = array(
    // info: The name of the block.
    'info' => t('Display a pretty word cloud generated by D3'),
    'status' => TRUE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks
 */
function d3wordcloud_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'word_cloud':
      $block['subject'] = t("wordcloud");
      $block['content'] = '

';
      break;
  }
  return $block;
}

Within the code that generates the block you can use drupal_add_js to include both the D3 js and the word cloud js. If you then copy the script you have in your html into a .js file as well you can put a drupal_add_js in for that as well. Wrap everything but the draw function as follows

jQuery(document).ready(function($) {
  // code that initialises drawing
});

function draw() {...

More drupal javascript
 info here

The actual block content then just has to return a placeholder for your wordcloud, eg

. Your script looks like it draws straight into the body tag, so replace d3.select("body") with d3.select("#d3-wordcloud") so that the cloud ends up in your block.

Option 2 - bit more drupally and extensible?

Install the D3 module, which supplies d3 via the libraries api
Create custom module (using parts of the d3_example module as a template):

expose the D3 word cloud project as a library
make use of the word cloud in your block

Option 3 - re-usable module

As option 2 but also create a fork or patch for the tagcloud module which uses your D3 word cloud library in place of its own display. This solution will give you a block for each taxonomy vocabulary tailored to the terms associated with the viewed node.


How to remove Field Group module label length limit? How to remove Field Group module label length limit (which is 128 characters). Is there any module to change the default length?

Try this module remove field length limit

  Removes field label length limit (which is 128 characters).
  The module supports entity field labels and views field labels.

Or you could also write a custom module

function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}


Why the template_preprocess_field hook is not called for a custom template? I'm working in a site that has implemented the template_preprocess_field() hook. I want to change the content of a field but the code works for all the nodes except for the nodes of a content type that have a custom template (node--emploi.tpl.php) It's strange because I have another template for the nodes of the content type named tarif (node--tarif.tpl.php) and in this case the hook is called.

Here the piece of code inside the template node--emploi.tpl.php file:

<div class="editor">
  <?php
  /* At this point the body's h2 do not know what the nid is, so a quick and dirty replace will set it right. */
  print preg_replace('/NO-NID[a-z0-9]*--/', $nid . '--', check_markup($field_stm_emploi_temoignage_body[0]['value'], $field_stm_emploi_temoignage_body[0]['format']));
 ?>
</div>

As @Clive says the problem was that the code didn't use the render() function for the field output, and in this case the template_preprocess_field() hook is not called.

For the moment I have 2 solutions:

Use the render() function in the template file (node--emploi.tpl.php) to create the output of the field. In this case the template_preprocess_field() hook is called.
Use the template_preprocess_node() hook and check $vars['type'] for my content type. In this case the template file remains equal.


How do I display a block on the checkout page based on the product type? I have created some custom blocks in code that are shown on the Drupal Commerce checkout page. I would like the block to have differ content basing on which items are in the cart. How can I achieve this in code?

Around the time some Item1 (or Item2) is added to your cart, grant that user access to a role like "HasItem1InCart" (or "HasItem2InCart"). Use the Rules module to grant such access, using a Rules Action like "Add user role".

Within the block visibility settings for Block1 (which you want to show if Item1 is in the cart), only show that block to users with roles ... you probably guessed it .... HasItem1InCart (same for Block2 and HasItem2InCart).


Using Cron and CURL in a custom module I am using a hook_cron (mymodule_cron) in my custom module, but would like to know whether the cron run is successful or not and has sent the data using CURL, and from there, update a specific column value in my sql table. How to get this status?

Part of my codes:

$options=array(
    CURLOPT_URL            => $urlCron,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => false
);

$CURL=curl_init();
curl_setopt_array($CURL,$options);
$content=curl_exec($CURL);
curl_close($CURL);

You can utilise watchdog at the end of your hook_cron implementation, then implement db_update to update your desired table.


Restrict a users node posting total dependent on a paid subscription role I am interested in how one would restrict a users node posting total dependent on a paid subscription role.

For example, there maybe 3 subscription roles which allow different Node posting for a user dependent on which Role they have chosen on site registration. Using UberCart for example, 3 packages (Low, Mid, High) offer 10,25, 50 respectively to a user. The total posting per month cannot exceed that amount at anyone time in that they can either add/edit/delete an applicable Node (only of their own posting), but not exceed that subscription's total given amount for that role. I would be interested in the best easiest and best approach to this using Rules/Views/UberCart framework. Or possibly knock up a custom table in the backend to tally up the number of said posts per user if that need be the case.

Alternatively, the restriction or limitation of Node  content 'viewing' per subscription role. ie Pay to read more of the said Node content. Which appears nowadays to be an emerging trend for online content access as I see it.

Any comments and ideas greatly appreciated for a learning developer.

In my opinion the best solution would be Ubercart for selling roles to users
 and Node Limit module to set a block on how many nodes can be created by certain roles (in a given period, optionally).

You should set up different roles, one for every different amount of nodes a user can create. Then with Ubercart you have configure a product for every role to be sold.

Then with Node Limit module you can configure the restrictions for every role.


Can't get Drush to function I have a local site but drush doesn't seem to be functioning correctly:

$drush status=

PHP executable         :  /usr/local/bin/php
PHP configuration      :  /usr/local/etc/php/5.6/php.ini
PHP OS                 :  Darwin
Drush script           :  /Users/myuser/vendor/drush/drush/drush.php
Drush version          :  8.1.5
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :  /Users/myuser/.drush/sitename.aliases.drushrc.php

It's not listing anything about the drupal site, so I can't run any drush commands on the local.

Does anyone know how to set this up correctly?

I'm reporting back to provide my solution.

The site itself was Drupal v 7.51. As you can see, I was using Drush v. 8.1.5.

Reverting back to 7 corrected the issue and was done fairly easily following the modules unraveled tutorial here: https://modulesunraveled.com/blog/install-drush-7-and-8-and-automatically-switch-versions-based-project.

Regards


How do I define a separate form template for a multistep form? I have a multistep webform in Drupal 8. I want to define spearate page template for each page in the webform.

I'm trying to define it using hook_theme_suggestions_hook() like below. But how can I identify the current webform page currently viewing from $variables.

function custom_module_theme_suggestions_webform(array $variables) {
  $suggestions = array();

  $suggestions[] = 'webform__'.$current_page;

  return $suggestions;
}

I have fixed the issue using D8 temp storage functionality. I was able to get the current step in my form_alter() hook, and I stored it in to a temp variable and accessed it in theme_hook_suggestions() hook().

/**
 * Implements hook_form_alter().
 */
function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == 'mywebform_id') {

    $current_page = $form_state->get('current_page');

    $tempstore = \Drupal::service('user.private_tempstore')->get('custom_module');
    $tempstore->set('current_page', $current_page);
  }
}

function custom_module_theme_suggestions_webform(array $variables) {
  $tempstore = \Drupal::service('user.private_tempstore')->get('custom_module');
  $current_page = $tempstore->get('current_page');

  $suggestions = array();

  $suggestions[] = 'webform__'.$current_page;

  return $suggestions;
}


$form_state->set(), $form_state->setValue() doesn't save new value Below you could find my code. It works fine until below the comment. I also tried countless combination of $form_state->saveValue(), but nothing works. Any ideas?
    function myforms_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if ($form_id == 'commerce_product_default_edit_form' || $form_id == 'commerce_product_default_add_form') {
        $form['#submit'][] = 'myforms_extra_submit_handler';
      }
    }

    function myforms_extra_submit_handler($form, FormStateInterface $form_state) {
      $events_dates = $form_state->getFormObject()->getEntity()->get('event_date')->getValue();
      $count = count($events_dates);
      if (empty($events_dates[$count-1])){
        $count = $count - 1;
      }
      if ($count > 0) {
        $start_date = date("j/n/y", strtotime($events_dates[0]['value']));
        $end_date = date("j/n/y", strtotime($events_dates[$count-1]['end_value']));
        if ($count == 1) {
          $count_suffix = "zjazd";
        } else if ($count == 2 || $count == 3) {
          $count_suffix = "zjazdy";
        } else {
          $count_suffix = "zjazdów";
        }
        $date = $start_date.' - '.$end_date.' ('.$count.' '.$count_suffix.')';

        $title = $form_state->getFormObject()->getEntity()->get('title')->getValue()[0]['value'];
        /* code above works, below is the code which doesn't */
        $form_state->set('title', $title.$date);
        $form['elements']['title']['#value'] = $title.$date;
        $form['elements']['title']['#default_value'] = $title.$date;
        $form_state->setRebuild();
      }
    }

I assume with code works you mean you get the updated title value. Then another submit handler has already transferred the values to the entity and your changes to $form_state are too late.
So you can try to position your submit handler first:
array_unshift($form['#submit'], 'myforms_extra_submit_handler');

or update the entity instead of $form_state:
$entity = $form_state->getFormObject()->getEntity();
$title = $entity->get('title')->value;
$entity->set('title', $title . $date);

Caveat: Normally submit handlers in entity forms are attached to submit buttons. So you might want to check first all submit handlers which are active in the form before you decide where to place your submit handler.

Different approach
You are asking why your submit handler is not working and there is definitely a solution for that, but there is probably a much easier solution outside of the form when the form is trying to save the entity. See  Programmatically update a field's value


Show all taxonomy terms on taxonomy term page Though I saw a lot of posts on views & terms, this is new it seems.

I have a set of 1-level vocabularies. When user is on term page

mysite.com/vocabulary1/term1/

He should see also 'menu' - list of all terms of this vocabulary.

How can it be achieved?

P.S. I think that it's about context filters but I can't figure out how!

There are couple of modules to solve this purpose

Taxonomy Block
Taxonomy Menu Block

Here is the config page of taxonomy menu block module


Disable caching for custom entity I have set up access to some custom data by creating ContentEntity classes in my module, so I can query and display that data through Drupal entities. However, that data is also updated by a non-Drupal service, that changes some columns in the database directly. After the data is changed by that service I have to use "Clear all caches"  in order to see any changes in Drupal.

How can I stop Drupal 8 from caching an entity type at all - so it always queries the fields fresh from the database?

I have tried annotating my Entity class with

render_cache = FALSE,
field_cache = FALSE

as these are the cache related options listed in the documentation (Structure of an Entity annotation) and suggested in How to avoid caching of fields in Entity View?
However, this didn't have any noticeable effect in my scenario.

The flag you are looking for is persistent_cache, field_cache is no longer used, that documentation is a bit out of date. You're welcome to update it :)

See the API documentation of the EntityType class for a up to date list, maybe that documentation page should just link to that instead of trying to maintain a duplicate list.

That said, unless you have almost as many or more writes/changes to your entity type as loads, I'd considering changing your architecture and either update the entity type through the API or invalidate the changed entities. But there can be cases where that doesn't make sense, e.g. because of mass updates and if those entities aren't very frequently. But for example displaying them in views can be quite slow if they need to be loaded all the time.

Also, speaking of views, while render_cache disables the caching of viewing an entity, I don't think it disables views row-level caching. Maybe it should, you should consider opening a core issue for that if you need that, otherwise your rows will still return cached output even if the entity is changed.


Updating author name in preprocessnode The kpr line in the function works – It outputs the author of the node's full name. But setting the author_name variable does not. Why isn't that replacing the author_name variable in my template? (It's just blank.)

If i remove this, it will display the username.

function theme_preprocess_node(&$variables) {
  // die(kpr($variables['node']->getOwner()->get('field_full_name')->getValue()));
  $variables['author_name'] = $variables['node']->getOwner()->get('field_full_name')->getValue();
}

getValue() is probably returning an array, which cannot be interpreted by twig. try:

$variables['author_name'] = $variables['node']->getOwner()->get('field_full_name')->getValue()['value'];

Or search for the right key in there ..


Is there a way to determine what is powering the content behind a URL? I have a relative URL in a large site that I inherited: /my-url.

For the life of me I can't find the View, Module, or other content that shows how to edit this URL. I've grepped the code base, and searched the database, but can't find it.

How can I tell how this URL gets edited? Is there some kind of search modules/views/blocks by URL?

You could try looking in the menu_router table, where the path column contains values like node/%/revisions/view. Also, the url_alias table has a source column (to check against the menu_router table) and the alias defining a path like /my-url.

I also use TextWrangler and PHPStorm to inspect my code. You could try to search.


How does one diplay only the referenced entities associated with specific node in a view block? I have two content types that are related to one another with and entity reference field, Research project and Profile. In my block display view, I would like to display only the entities that are referenced by a specific Research project.

If you use Drupal 7, you must go to: Structure > Views > (Choose the view you want to customize).
There you will find a section "Filter Criteria" if nothing exists press add on the right and add your criteria. You select it and continue with the customization, each element has different customization.

On the bottom you usually see the result, if nothing is shown, then this does not necessarily mean that you made a mistake (I had that problem once). Don't forget to save.


Passing global variables to alter hooks The problem I have is that it seems that I can use global variable created inside another module, only if I use it inside callback function. I successfully tested it by inserting code inside existing modules.

The global variable is $subtotal.

function uc_checkout_pane_simple_quote($op, &$arg1, $arg2) {
    global $subtotal;
drupal_set_message($subtotal);

function uc_webform_pane_checkout_pane_callback($nid, $op, &$arg1, $arg2) {
  global $subtotal;
  drupal_set_message($subtotal);
}

In both cases the message shows the correct value.

However, inside other functions it is does not work.

function uc_webform_pane_checkout_pane_alter(&$panes) {
  global $subtotal;
  drupal_set_message($subtotal);
}

function uc_cartdetails_checkout_pane_alter(&$panes) {
  global $user;
  global $subtotal;
  drupal_set_message($subtotal);
}

What am I missing here?
What I am trrying to do: to show or hide checkout pane based on $subtotal value.

function uc_cartdetails_checkout_pane_alter(&$panes) {
global $subtotal;
  foreach ($panes as &$pane) {

    if (($pane['id'] == 'webform_nid780') && ((40 - $subtotal) > 0) ) {
      $pane['enabled'] = FALSE;
      }

    }
 }

The problem is not the global variable, but the fact you are using a function like drupal_set_message() inside a alter hook, which is not necessarily invoked when Drupal is outputting a page.
If you want to debug a hook, it's better you go with watchdog() and check in admin/reports/dblog if there is any message. You need to enable the Database Logging or the Syslog module to see any output; in the latter case, you will see the output on the syslog of your computer, instead of admin/reports/dblog.


Content Pane on Landing Page not getting Context I thought that would be fairly easy: I am working with Panopoly and I have multiple Landing Pages, a Vocabulary, Content Items and a View with a Content Pane.

The user can select one term per Landing Page (term reference) on creating the lp. Also the content items have one of the terms from the vocabulary attached (as well via term reference).

The View lists all the content items with a contextual filter by term. By default the content pane is part of a newly created Landing Page. So, in this simple case, I want the user to pick a term from the vocabulary and subsequently let the content tagged with this term appear on that landing page via the content pane.

What I get working is the contextual filter "Has taxonomy term ID" with "Argument Input: Input on pane config" Now I can pick a term through the IPE.

However for more complex applications I would like to hand the term selected by the user on creation of the Landing Page (in the edit form) to the content pane, so that the user doesn't have to set it on each content pane seperatly.

Any ideas?

Ok, the solution is pretty easy, but due to Views complexity it took my some time to figure it out. In my setup, there is no filter available. My mistake was, that I thought there IS a fitler available which is why I did not fill in the upper section. Since my filter is not in the url, I had to select "Load default filter from node page, that's good for related taxonomy terms".

That's all the magic ;)


How to cache a custom rest resource when using Url::fromUri I have a custom rest resource that is returning data using new ResourceResponse():
$node = Node::load($nid);
$data = load_data('node', $node);
$response = new ResourceResponse($data);
$response->addCacheableDependency($node);
return $response;

This works fine, but if I use the function Url::fromUri into the load_data function I get the error:
LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.

I can get it to work if I use ModifiedResourceResponse instead of ResourceResponse, but as far as I understand this will disable all caching. As this resource might end up getting intensive I want to make sure it is cached - how can I do this?
Many thanks in advance!

This is the answer:
Url::fromUri($var)->toString(TRUE)->getGeneratedUrl();

Found here: https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8


How to open a node form in popup after click on edit from front end? I added a edit link using hook_form_alter in my node form..When I clicked on this link it goes edit content page. But I need to open this form on popup and change the form value from here.

My question: How to open a node form in popup after click on edit from front end?

If you want to go through custom module you need to follow instructions given here. If you are looking for contrib module colorbox or modal forms to edit your content on modal popup(using Ctool).


Is there any danger in caching forms, such as node edit, add, etc? I am playing with authenticated caching modules to speed up performance while logged in.  Currently I am using authcache.  However, authcache and other caching modules often have node add, node edit, and other (CRUD) forms excluded from the pages the module will cache.

Why? What is it about a form that it should not be cached? Is there any potential danger in allowing these modules to cache forms found in the authenticated areas?

Forms have unique build ids that identify a particular submission. Caching would defeat that and thus defeat Drupal's ability to detect duplicate or invalid form submissions.


No install link for sub theme of sub theme In my D8 site I have Magazine Lite, a sub theme of Classy. Magazine Lite is installed.

In web/themes/custom I have a theme installed that in its .info.yml file names Magazine Lite as its base theme.

On the Appearance tab, instead of an install link is the message:

  This theme requires the base theme Magazine Lite to operate correctly

In what way does it require the base theme beyond the base theme being present and installed?

Copied the base theme's info file and changed 'name' to 'base theme'. But the base theme entry needs to be the machine name of the theme, whereas the name is a descriptive name.


The styled image is not displaying I have created a thumbnail like image style in Drupal 7 (glossy_footer_sublogo).Also i have coded a module that has a block to display the 'logo.png' file that comes with my theme and converted by 'glossy_footer_sublogo' style. after enabling the block and clearing cache no image is displayed although the 'sites/all/themes/glossy/' path created in my style directory.
Following are the codes that i used to display the block:

/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  switch ($delta) {
    case 'glossy_footer_sublogo':
            $img_url = 'public://sites/all/themes/glossy/logo.png';
            $style = 'footer_sublogo';

            return array(
                'subject' => '',
                'content' => "<img src=" . image_style_url($style, $img_url) . ">",
            );
      break;
  }
}

Can anyone point me to what is the problem?
Thanks!

If you go to admin/config/media/file-system what is your public path set as?

If your public path is set as sites/default/files then I think your code is generating the following link:

  http://yourdomain/sites/default/files/sites/all/themes/glossy/logo.png

Try changing your $img_url to the following

  $img_url = drupal_get_path('theme', 'glossy') . '/logo.png';

On another note, is the block rendering at all (just without the image)?  Your implementation of hook_block_view looks incorrect.

I think it should be more like the following:

/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  $block = array();

    switch ($delta) {
      case 'glossy_footer_sublogo':
              $img_url = 'public://sites/all/themes/glossy/logo.png';
              $style = 'footer_sublogo';

              $block['subject'] = ''
              $block['content'] = "",

              );
       break;
    }

  return $block
}

Edit

Change $img_url as I previously mentioned, but rewrite your block content as follows:

$block['content'] = '';

There aren't any quote marks around the image URL that is being returned by the function.


How to remove id="node-[nid]" with Display Suite? How I can remove the node id when I override a node layout with Display Suite?

In some (old) how-to I noticed that the id node is not present when a node layout is overridden with DS.

i.e.: from this

to this

Thanks

Below code is quoted from template.php of Tao.

/**
 * Implementation of preprocess_node().
 */
function tao_preprocess_node(&$vars) {
  $vars['hook'] = 'node';

  $vars['classes_array'][] = 'clearfix';

  $vars['attributes_array']['id'] = "node-{$vars['node']->nid}";

  ...

The ID is added by this line.

$vars['attributes_array']['id'] = "node-{$vars['node']->nid}";

You can override it by implementing the same hook function in template.php of your custom child theme.

/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$vars) {
  unset($vars['attributes_array']['id']);
}


How many times drupal calls hook_node_presave for a node? During debugging my code I noticed that hook_node_presave() is called 3 times when I edit a node. Why?

I use the following code to count how many times the function is called:

function mymodule_node_presave($node) {
  static $counter = 0;

  // Some code...

  $counter++;
  watchdog('mymodule', "hook has been called $counter");
}

Once.

If it's called multiple times then you your node is saved multiple times.

This might be because you have some rules or other code that e.g. resaves the node in a hook_node_insert()/update().

To find out what and where, enable devel.module if you haven't already and add a ddebug_backtrace() call to your hook. That will give you the backtrace on how your function was called and you can identify who is calling node_save().


Is every image style I have for each image upload auto-created? I believe I understand this about Drupal 8: every image uploaded will automatically be created in each of the image styles I have set up (or the default 3 that come with core).

This incentivizes me NOT to create very many image styles, because then I'll end up with a bunch of different copies of my original image, whether they will ever be used in that particular style or not.

Is that correct?

On the other hand, Molot's answer over here mentions that "styled image files are supposed to be created on first access". That gives me hope that if I upload an image, it will only be created in an image style the first time it is requested in that image style. That means I could have as many custom image styles as I need and not worry that an image will be created for each one of those every time.

For example, if I have 12 custom image styles, but I only call a certain image in one style, will I end up with only 2 copies of the image, one as the original upload and one in the only style I called? This is what I would love to be true.

Thanks for any insight.

The styled images will be created on first request, creating a new file with the styled image. This will not only save space if you have tons of image styles but also CPU power - because if you attach 10 images to a node and want to create 12 (as you mention the number) different image styles, that will put quite a load to generate all the styled images in one go. Doing this when needed is far better management of resources.


How do I add custom CSS to individual pages? Im trying to create pages with a search bar in a specific non block area in Drupal 7. If I edit using Live CSS (or another module), it edits all my pages, and offsets the content I created. I need a way to edit the CSS styles for each individual page; in that way, I can edit the search form area, and have also a way to add my own button images.

I can disable Drupal regions/blocks, but that doesn't really help. May someone name some modules that could help, or suggest me some code?

Well the absolute simplest way is to look at the body class using firebug or developer tools with chrome.

You will see something like this:

<body class="html not-front logged-in no-sidebars page-node page-node- page-node-19 node-type-log-node admin-menu">

Which as you can see even has the node id for the page. Then its just a simple case of using

.page-node-19 {
background: #000000;
}

Or whatever!

And, if you want to get super in detail with adding stuff to certain pages, themes, regions, dependencies on which users etc etc then look into the context module and all its related modules.


How to customize registration process in Drupal 7? I want to customize default registration process in Drupal 7. The registration process includes 3 steps:

Show some account types (in a page or form?). For example "personal", "business", "organization"... And users will choose their own account type.
Fill information into registration form. Each account type which users choose in step 1 has some corresponding fields.
Finish registration with an confirmation email or something else.

The registration process is similar to https://secure.payza.com/signup

Thank you for helping.

You can create three roles named:

Personal
Business
Organization

Now you can use profile2 Registration Path module. This module will give you three separate profile for each roles. You can add separate fields for each profile. And from the configuration of profile pages you can enable separate registration path also.

Thus you can have three registration path for three roles and three registration forms also.

Now to create multistep form for profile2 module you can follow this question from this site.


find out object properties passed to a function which is the best way of debugging codes in drupal?
for instance in election module there is a submodule called conditions, and there is a function:

function election_example_conditions_access_gmail($post, $account) {
  if ($account->uid == 0) {
    return FALSE;
  }
  return (bool) preg_match('/g(oogle)?mail\.com$/i', $account->mail);
}

in the above code, what is the easiest and fastest way to find out what is the $account object passed to function?

You can make use of the devel module for debugging.

Download and install the latest version of the Devel module.

dpm()
Prints a variable to the ‘message’ area of the page using

dvm()
Uses var_dump() to print a variable to the ‘message’ area of the page

So in your situation in your function use dpm($account)

function election_example_conditions_access_gmail($post, $account) {
   dpm($account)
  if ($account->uid == 0) {
    return FALSE;
  }
  return (bool) preg_match('/g(oogle)?mail\.com$/i', $account->mail);
}

and go to the page normally and you should see the debug backtrace appear in the message area


Creating custom field with Display Suite and Profile 2 I am trying to use Display Suite (newest version) to format the profile page for users. I am using the Profile2 module and the default main-profile type. I have the user's full name (not username) split into the fields for first, middle, and last. I am trying to create a custom field to combine these three fields as the full name.

I am trying to create a code field but I don't know what variable or replacement pattern to use. There is nothing in the list of available tokens. I have tried php using $content and $entity and get undefined variable errors.

How can I create a custom field in Display Suite to combine these three fields from a Profile2 entity?

Enough trial and error and I finally figured it out. I ended up using Display Suite Code as the text format, but writing php code in the field code box.

And to grab the first name the code was: $entity->field_first_name['und'][0]['safe_value'].


Print image field path in views-view-fields--key-projects.html.twig I am working with Drupal 8 and trying to print some fields through a twig file.

Created:

A view (format:grid)
A content type (fields: title, body image)
Contents

File working on:

views-view-fields--[machine-name].html.twig

To Do:

How can I print the path of the image in the content?
How can I print the path of the node/content on a Read More link?

To get the path of an image in a view, use the image format 'URL to Image' in the field setup. I have not found a really good way to get the site absolute, rather than relative url, but prefixing the returned value in a rewrite block with {{ url'(<front>') }} is almost there:

{{ url'(<front>') }}{{ field_image }}

To use that in a different field (content), mark it 'Excluded from display' and then reference that field using a rewrite in another field, or using a twig field template.


Add class to any element with CKEditor Is there a way to add class to any element through CKEditor?

Here is an example: I create a list with CKEditor and I want to add a class to the ul tag. Or maybe on one of the li.

Everything without opening the source of course.

Is there any way to achieve that? (with CKEditor or with another WYSIWYG)

You can configure custom styles in 'Text formats and editors':

Visit /admin/config/content/formats, and click Configure for any
format using CKEditor
Ensure the 'Styles' button is in your active toolbar
Click 'Styles dropdown' under CKEditor plugin settings
Add class|style values per the instructions

Using your example, you could add entries like:

ul.myListClass|Special List
li.myItemClass|Special List Item

This would make the styles 'Special List' and 'Special List Item' appear in the styles dropdown anytime the user's cursor is anywhere in an ul or li. If they choose 'Special List', the class 'myListClass' would be added to the nearest ul. If they choose 'Special List Item', 'myItemClass' gets added to the current li.

This assumes current versions of Drupal 8. I'm not sure about Drupal 7, but I assume up-to-date versions would have similar functionality.


How to make Username as non mandatory on Drupal 7 registration form? I am working on a project where i want to remove the Username form registration from. Is it possible? How?

Yes it's possible, there are couple of modules out there that will auto-generate the username and just require an email address on the registration form (and there are probably a few more as well)

Email registration

  Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.

  A username is generated and assigned based on the user name part of the email address. Subsequent users who have the same name (email prefix) are numbered sequentially. For example, "johndoe@a.example.com" would be assigned username "johndoe", "johndoe@b.example.com" would be assigned "johndoe_1" and so forth. Sites that want to create usernames in their own way can do so by implementing hook_email_registration_name.

Login Toboggan

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

  Allow users to login using either their username OR their e-mail address.

Out of those two Email Registration is a bit more lightweight, so if you don't need the features from LoginToboggan it would make more sense to use that one.


how to change login destination to front page I have disabled user login block. I use Menu link to user/login for login. I also used CAPTCHA for login page. But now when I log in to site it stays on user/login page not redirect to front page and gives me an error The webpage cannot be found. Then after refreshing page it shows Access denied
You are not authorized to access this page. Any one has idea to set login destination after login.

I think the Login Destination-module is what you're looking for! Easy to configure and works perfect!


Enabling a custom module after uninstalling it I have simple question concerning enabling a custom module after having disinstalled it.
The module provides a simple creation of a new content type based on node content.
It implements a hook_install() function that first time i enabled the module worked perfectly. For debugging reasons i had to disable and unistall the module, then when i tried to enable again the module the system checks it as enabled but the new content type that is the result of the hook_install() function does not appear anymore.

It seems to me that when i try to re-activate the module the installation script doesn't work anymore, and this although i cleared the cache after unistallind the module the first time.

Any ideas?

Here's the install code:

function bachecanews_install() {
  $t = get_t();
  $node_bachecanews = array(
    'type' => 'node_bachecanews',
    'name' => $t('Bacheca News'),
    'base' => 'node_content',
    'description' => $t('Usa Bacheca News per inserire le notizio sul sito.'),
    'body_label' => $t('Contenuto della News')
  );
  $content_type = node_type_set_defaults($node_bachecanews);
  node_add_body_field($content_type);
  node_add_date_field($content_type);
  $status = node_type_save($content_type);
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // in caso di modifica
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato modificato.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // in caso di creazione
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato creato.', $t_args));
    watchdog('node', 'Creato il nuovo tipo di contenuto %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}

function bachecanews_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'node_bachecanews'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }
  node_delete_multiple($nids);
  node_type_delete('node_bachecanews');
}

I found out that you have 2 issues with your hook_install code.

You're adding body field first then saving the node type. It should be the opposite.
There's no such function called node_add_date_field in Drupal package, unless you've created it yourself in your custom module.

Your hook_install should be as the following code:

function bachecanews_install() {
  $t = get_t();
  $node_bachecanews = array(
    'type' => 'node_bachecanews',
    'name' => $t('Bacheca News'),
    'base' => 'node_content',
    'description' => $t('Usa Bacheca News per inserire le notizio sul sito.'),
    'body_label' => $t('Contenuto della News')
  );
  $content_type = node_type_set_defaults($node_bachecanews);
  $status = node_type_save($content_type);
  node_add_body_field($content_type);
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // in caso di modifica
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato modificato.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // in caso di creazione
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato creato.', $t_args));
    watchdog('node', 'Creato il nuovo tipo di contenuto %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}

If you want to add additional field to your custom content type and this field is not body field, you use field_create_field()

As an example, you can look at standard_install().


Can a Event Service be coupled to a route I have created a custom service and have hooked into the "event_subscriber"  via tags in my custom service.yml

  demo_api.exception_handler_subscriber:
      class: Drupal\demo_api\Response\Handler
      tags:
          - { name: 'event_subscriber' }

With in this custom service I'm listening into KernelEvents::RESPONSE

public static function getSubscribedEvents()
{
    // For this example I am using KernelEvents constants (see below a full list).
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
}

The problem is I have some API request and I'm modifying the response for these request and returning a modified json format.

public function onResponse(FilterResponseEvent $event)
{
    $response = $event->getResponse();
    $apiFormatter = new ApiFormatter();
    $response->setContent(
        json_encode(
            $apiFormatter
            ->wrapResult(
                json_decode(
                    $response->getContent()
                )
            )
        )
    );
}

This is causing any web pages to respond as json.

I would like to limit this service to these API calls only and not be called on each request.

Any advice would be grateful.

If you want to restrict the event subscriber to a route then check for the route name:

public function onResponse(FilterResponseEvent $event) {

  $route_name = $event->getRequest()->attributes->get('_route');
  if ($route_name !== 'my.route.name') {
    return;
  }

  ...

}

Although in Drupal it might be best practice to get the route name from the current_route_match service:

$route_name = $this->routeMatch->getRouteName();

which you then need to inject in the event subscriber.


Move php in views to module now and then i use php in views. Now i do this only when it's the only option. I often use this for specific action links (action links are links like: edit delete).

Now i don't want to save php in my database, it doesn't belong there. So i was wondering if their was an other option to add those action links i generate with php to each row. The action links need data from the current row.

Thx
Nuctorn

You definitely want to create a views handler with your custom php code. This is the standard way to do custom php stuff on views module.

Here you have an example:

mymodule.info

...
files[] = views/handlers/views_handler_field_node_link_custom_stuff.inc
...

mymodule.module

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/views',
  );
}

In MYMODULE/views/mymodule.views.inc:

function mymodule_views_data() {
  $data['node']['custom_stuff'] = array(
    'field' => array(
      'title' => t('Custom link'),
      'help' => t('Provide a custom content link.'),
      'handler' => 'views_handler_field_node_custom_stuff',
    ),
  );
  return $data;
}

MYMODULE/views/handlers/'views_handler_field_node_link_custom_stuff.inc

/**
 * Field handler to present some custom HTML.
 */
class views_handler_field_node_custom_stuff extends views_handler_field_node {
  function construct() {
    parent::construct();
    $this->additional_fields['type'] = 'type';
  }
  function query() {
  $this->ensure_my_table();
  $this->add_additional_fields();
  }
  function render($values) {
    $type = $this->get_value($values, 'type');
    $nid = $this->get_value($values, 'nid');
    return mymodule_print_my_link($nid, $type);
  }
};


What do I put in the drupal 7 commerce Checkout Completed Rules: Send Email field to display all of the order data? Currently I have the following below in my completed checkout send email settings. But when i receive the emails on a completed order, I'm still missing some data even though I have it set there. Would someone please paste their completed order send email setup?

See below as it only shows the SKU reference #'s.

One main issue I'm having is for these tokens:

[commerce-order:commerce-line-items] -- Only gives the Product ID number and nothing else

[commerce-order:commerce_line_items] -- Displays "No line items found".

I think this is a permissions issue related to line items and anonymous users. See https://drupal.org/node/1811972, and https://drupal.org/node/1333174.

This does not answer your exact question, but what I've done recently is install Commerce Invoice Receipt (https://drupal.org/project/commerce_invoice_receipt) as a solution. Here's the basic checklist I followed:

install commerce invoice receipt (dev version has support for logo)
set visibility of fields at admin/commerce/config/order/display/invoice
disable SQL query rewriting on on Line items view - needed for line
items to appear when emailed to customer (security issue, but I'm not sure how serious)
create a new rule with Send Invoice Receipt action - for customers
create a new rule with Send Invoice Receipt action - for admins
disable rule: Send an order notification e-mail


Alter field items before render I'd like to add an item to a multivalued image field rendered by the Field Slideshow module.
I need to display an image coming from field image B of entity B in the slideshow of field image A of entity A.
The Field Slideshow module implements hook_field_formatter_view.
I'd like to be able to add an item at the end of the $items variable of this function.
How can I do that ?

If someone comes here, use template_preprocess_field

In template.php :

function MYTHEME_preprocess_field(&$variables) {
  $element = $variables['element'];

  if ($element['#field_name'] == 'field_myfield') {
    //Load the related node, I let you do this step ...
    //$nid = ...

    $nodeB = node_load($nid);
    $variables['items'][0]['#items'][] = $nodeB->field_another_image_field[LANGUAGE_NONE][0];
    //If you have a pager
    $variables['items'][0]['#pager']['#items'][] = $nodeB->field_another_image_field[LANGUAGE_NONE][0];
  }
}


Risks of developping your own theme from scratch? I read several answers about "Is it better to develop your own theme from scratch or extend a existing one?".

Here is my situation: I just got an existing project and I have to debug it and evolve it. I'm in the audit phase and I was wondering if, in a theme developed from scratch, you forgot to provide the code for render some elements, are they going to stay hidden?

The specific case in this project is the absence of drupal status messages. They never appear. I guess there are plenty of them that are generated by the core, like when you fail at login or something. But they just don't happen.

It is very problematic and I want to fix that.

Is that because developers forgot to render them manually somewhere?

Thanks in advance

if, in a theme developed from scratch, you forgot to provide the code for render some elements, are they going to stay hidden?

Yes, of course - if you develop a theme and override core templates, anything that's left out will remain left out. There's no magic in Drupal, it's just PHP at  the end of the day. Think of it from the other side of the equation - if you were building a theme from scratch, and Drupal kept injecting markup into your templates without your say-so, wouldn't that be a crazy state of affairs?

  Is that because developers forgot to render them manually somewhere?

That's impossible to say from here. Could be that, could be some rogue CSS hiding them, could be a theme override of status messages nulling the output, and a bunch of others besides. The only way to know is to have a look and see what's there.

If the theme follows any sort of convention at all you should be able to look for a variable called $messages for the status messages. Usually it's located in page.tpl.php.

What you're essentially asking is akin to "I've built a car from scratch, if I leave out the brakes with someone else put them in for me?". The answer is "Only if someone intervenes manually; the assembly line won't do it automatically".


How can I present a screen that asks users to confirm their account details upon registration? I have a site for which I would like to display a "confirm details" screen when users create an account.  Basically, I would like something similar to the "required preview" option for adding a node-- just for user registration instead.

I was unable to find a module to do this.  Any ideas?

you have a function for that "function confirm_form"

see this link https://api.drupal.org/api/drupal/modules!system!system.module/function/confirm_form/7

2. add through js

<?php
    drupal_add_js('(function($){ $(function(){$("#edit-xxxxxx").click(function(){return confirm("confirm do that ?")});}); })(jQuery);', array('type' => 'inline'));
?>

refer the above link you will get three different ideas


How can I load a block's subject and body, programmatically, for use in a module? I need to create an array in my custom module that contains data from multiple blocks.  something like this:

array(
  'block_1' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),

  'custom_module_block' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),

  'another_block_machinename' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),
);

In order to do this, i need to be able to programmatically load block content, being able to access and handle each block's subject and body in order to populate my array.

Imagine the node equivalent being a simple node_load(); where you can easily access $node->title and $node->body from within the loaded node.

I'm not able to find any functions that make loading this block data possible.  Neither block_load() nor module_invoke() get me all the data I need (specifically the block subject).

So, how do I load a block's subject and body programmatically so I can use it in my custom module?

/**
 * Implements hook_block_view().
 */
function hook_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'block_1':

      $block['subject'] = NULL;
      $block['content'] = 'Full block body html here';
      break;

    case 'block_2':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

    case 'block_3':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

  }
  return $block;
}

Based on https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view/7


In Drupal Commerce how can you turn product select box options into images? As seen in the image below, how can I turn the product dropdown options into selectable images instead? Is there a module for this or does this have to be done via js/css?

ok seems that this module does the trick:

https://drupal.org/project/commerce_fancy_attributes

  This module provides a "Rendered term" attribute mode, that shows the
  rendered term instead of a radio button (degrades to a normal radio
  button when JS is off) on the add to cart form.

  Example usage: 0) Enable this module. 1) Create a Color vocabulary,
  add a text field called "Color" that will hold hex values. Go to the
  "Manage Display" screen of that vocabulary, click the tab called "Add
  to Cart form - Attribute", enable only the color field (with the label
  hidden, and using the "Color" formatter). 2) Create several terms with
  matching hex colors (Black: #000000, White: #ffffff, etc). 3) Add a
  Color taxonomy_term_reference field to a product type. 4) When you add
  the color field on the product type, tick the checkbox "Enable this
  field to function as an attribute field on Add to Cart forms." and
  select "rendered term" as option of the "Attribute selection widget".

  The Add To Cart form will now show the colors. Of course, imagefields
  can be used instead of "textfields holding hex values" rendered as
  images.


How to override text field widget form in Drupal 8 In my project I am using maxlength module to display the message like
'Content limited to 100 characters, remaining: 20'. The module using the hook 'hook_field_widget_third_party_settings_form' and provide textboxes to add length size and count down message.

I want to alter this count down message for all the fields by using my own custom module. Please help on this ?

You can create you own widget for textfield you will use in your forms each time you need :

<?php

namespace Drupal\your_module\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'your_widget_widget' widget.
 *
 * @FieldWidget(
 *   id = "your_module",
 *   label = @Translation("Your widget name"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class YourWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => $items[$delta]->value,
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
      '#attributes' => [
        'class' => ['js-text-full', 'text-full'],
      ],
    ];

    return $element;
  }

}

You probably have to override settingsForm() with your maxlength settings.
You can do this for each widget type (textarea...)

Note that you can generate skeleton with this drupal command :

$ drupal generate:plugin:fieldwidget
$ drupal gpfw


Print the WHOLE menu? Is there a way to print out an array of the entirety of a menu in Drupal 7?

For example, I have access controls in place so that a user gets a role after they take a quiz, which then allows them to see the next quiz. So until they pass quiz #1, their menu will not show them any evidence of quiz #2's existence.

What I want to do is print out the titles of ALL menu items, regardless of whether the user has access to the associated nodes or not. I plan to rewrite the menu to make the permitted items links, while the others appear greyed out until the user gains access to them.

I have not been able to find any modules, and simply doing this:

print_r(menu_navigation_links('menu-program-menu'));

only shows the items that the user has permission to view.

Is there a module already that does this, that I just haven't been able to find? Does a query have to be made directly to the database or is there a way to do this with more finesse?

What you can do is to select corresponding titles from the database directly:

$sql = "SELECT l.link_title FROM {menu_links} l WHERE l.menu_name = :menu_name ";
$result = db_query($sql, array(':menu_name' => 'menu-program-menu'));
foreach($result as $object) {
    print $object->link_title;
}


Optionally add image/icon after node title based on boolean content type field? Using Drupal 7.10 with a Zen sub-theme.  I have a custom content type, say Product.  The products have titles such as "Wrench", "Hammer", "TV".  I want to designate certain products as being a recommended product by having a little star icon appear inline after the title.

So for example:

Wrench
Hammer *
TV
Scooter
Piano *

Whether the star appears or not should be based on a boolean field I added to the product content type.  I want the star to appear when viewing the node directly or when the node appears as part of a list in a view.

My thought was to put an if statement in the node template for my content type, e.g. node--product.tpl.php.  However, what has me stuck is that in Zen it appears, if you are viewing a node as a page then the title is rendered in the page template, and if you're not viewing the node as a page then the title is rendered in the node template.  I'm not sure how to reconcile this.  Furthermore, I'm not sure if my field variable would even be available directly from the page template.

UPDATE

It appears I can successfully create a boolean preprocess variable in the function mytheme_preprocess_page whose value is based on field from the node:

function mytheme_preprocess_page(&$variables, $hook) {

  //$variables['sample_variable'] = t('Lorem ipsum.');

  if (isset($variables['node'])
      && $variables['node']->type == 'mycontent_type') {

    if($variables['node']->field_is_recommended
       && $variables['node']->field_is_recommended[LANGUAGE_NONE][0]['value'] == 1) {
      $variables['is_recommended'] = TRUE;
    }
    else {
      $variables['is_recommended'] = FALSE;
    }

  }
}

So now that I know this is possible, what's the best way for me to do this?

While this can be on in the page preprocess, and the node template, and probably several other places as well, I would discourage that. It is putting to much logic in the theme, that doesn't belong there. The main advantage of my solution is that the field can look right regardless of where you display it. On a page, in a block, in the header, or essentially anywhere that properly integrates with the Field API.

My solution is as follows

Add a text field, with the boolean Yes/No options

Implement two hooks, hook_field_formatter_info() and hook_field_formatter_view()

function product_field_formatter_info() {
  return array(
    'product_star' => array(
    'label' => t('Recommended product'),
    'field types' => array('text'),
  );
}

function project_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  if ($field['type'] == 'text' && $display['type'] == 'product_star') {
    return array(0 => array('#markup' => '<img src="star.png">'));
  }
}

Clear the cache

Go to the fields display settings, and set it to "Recommended product"

Profit!


Webform custom composite Could someone advise on how to adopt the working composite example that comes with Webform in Drupal 8?

https://www.drupal.org/node/2824714 suggests it can be done.

I've copied the example from modules/webform/modules/webform_example_composite folder. Does this need to go into the webform root folder with other example or root module folder?

I realise that the functions and iterations of webform_example_composite need to be renamed.

I also tried altering the pr-existing example that comes with Webform, without success.

Someone very kindly posted an example https://www.drupal.org/node/2883734.
Module creator also suggested here https://www.drupal.org/node/2824714 that documentation is being updated.


How to categorically theme views? I have a site that has several pages that are just views (a blog page, calendar page, and similar).  I want about 50% of my views to collapse the right column.  Do I have to create a template for each individual view?  Is there any way I can give views 1,2 & 3 a 3-column layout and give 4,5 & 6 a 2-column layout?

Idea: is it possible to add my own custom displays for views and theme those?  Right now I have Page, Block, etc - could I have Page2column and Page3column?  Then I could make my changes in views-view--page2column.tpl.php and views-view--page3column.tpl.php, right?

You could do this with Context. Set the Context condition to be either path or view based (depending on what suits your site structure) and then have the Context reaction take care of block placement (presuming your sidebar will collapse if empty).


Customize Search Terms search criteria of the view I am having a weird problem. I have made a exposed Filter "Search" field which allows a user to Search the results. It's a Search Term.

The problem is that it is not searching the results effectively.

Example: If I have a title XYZ-0123 and I search for XYZ, it would not give this result.

Any idea how I can customize the Search Term?

I'd greatly appreciate if you can assist here.

Here is a screenshot of the pop up in view. You can see there's no indication.

Select Containg any word operator in expose filter settings of Title field.


Best practice for language key for "und" in hook_form_alter I'm modifying in a form in my custom module. Code looks like:

function my_module_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == "someID") {

        $form['field_charity_author']['und'][0]['value']['#value'] = arg(3);
        //$form['field_charity_author']['#type'] = 'hidden';

    }

}

However, I think hard-coding und is bad. What should be the proper way to modify form fields properly in this case?

Unfortunately, your self-answer is not so universal. Field language and node language are not the same things.
Field language is needed only if you are using Field Translation API (for example Entity translation). When you start using it, some fields are converted to translatable.

Translatable fields have language code, which really makes sense. But if the field is not translatable, the language code will always be (and for all content types, entities, etc) — LANGUAGE_NONE (best to use the constant LANGUAGE_NONE and not the string 'und').
So with your solution you can get a situation when a node is Russian, but a field of the node uses LANGUAGE_NONE.
Happily, fields are attached to the form with '#language' key, which always contains the correct language code.

$lang = $form['FIELDNAME']['#language'];
$form['FIELDNAME'][$lang][0]['value']['#value'] = $value;

If you have no access to attached form, Field Language API functions can be useful.


Problem with getting number of nodes created by a user in a View I know this question is already asked, here is a few links How to count the node a user has created in a View? or How can I count the number of nodes submitted by the current user?

This is a very simple task but I am facing a problem.
I'm trying to get the number of nodes of a certain content type created by a user. This is the configuration of the view:

setting Author uid as contextual filter
setting the content type in filter criteria and selecting Node ID as field
setting aggregation to yes and set the nid to use the Count Distinct aggregation
Setting the Pager to Display all items

If I don't use the aggregation this is the result:

2158
2151
2152
2153
2154
2155
2156
2157
2142
2143
2144
2145
2146
2147
2148
2149
2150
2141
2140
2139
2138
2137
2136
2127
2126
2125
2124
2123
2128
2129
2130
2131
2132
2133
2134
2135
2122

But if I use it, the result is :

8
15
14

which 8+15+14 = 37 and number of the nodes is also 37 but I wonder why it displays the 37 this way?

You should make sure that you have no sort criteria set in your view that splits your aggregation.


Listing module under one custom module heading I have created Menu type called Form submission. Under this I want to list all the Form submitted values. There are two forms one is Contact form and help form. I want to display these two as Contact and help form under the menu type Form submission.

Example: When I click Contact it has to show the contact list.

How to list the Contact and help form under the Form submission in admin page. I build it as custom module.

You can print any form using drupal_get_form

drupal_get_form($form_id)

And to print a form

<?php print drupal_render(drupal_get_form($form_id)); ?>

You can find form id using hook_form_alter

Eg :

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  echo $form_id;
}

To redirect users after submission you can use drupal_redirect_form

  Redirects the user to a URL after a form has been processed.

To get all modules list you can use module_list

  Returns a list of currently active modules.