How can I resend the commerce email from the admin orders screen? Is there any way of allowing site admins to resend the default order email that commerce provides to the user after a completed order?

Since I was using the commerce email module, it was a pretty easy setup to use a rules component and then add it to my /admin/commerce/orders vbo view.

{ "rules_resend_order_email_to_customer" : {
    "LABEL" : "Resend order email to customer",
    "PLUGIN" : "action set",
    "REQUIRES" : [ "variable_email" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" } },
    "ACTION SET" : [
      { "variable_email_mail" : {
          "to" : [ "commerce-order:mail" ],
          "variable" : "commerce_email_order_[mail_part]",
          "language" : "default"
        }
      }
    ]
  }
}


Subscribe/unsubscribe user from mailchimp list after purchase I am using mailchimp 7.x 3.3 Module and ubercart is integrated for role selling,
also I have rules module installed.

I have users subscribed to the mailchimp list, my requirement is when a user from my list purchase any order he should be unsubscribed from one list and subscribed to other mailchimp list, so that I can track the users from the list who did not purchase any order.

I am thinking of doing it using rules, In rules I have an event "when the user completes checkout", I want to add the action on same event, the action should be "unsubscribe from one list and subscribe to other list" but unfortunately I dont have any way to select the list there.

Please find the screenshot of rules interface below, help would be greatly appreciated.

This is event interface

This is Action Interface

Because MailChimp doesn't want you to just subscribe people without their permission, it makes you put this into a field.

We have clients, however, who put the subscription opt-in into their Terms of Use agreement. A way around this is to create your own rule:

/**
 * @file
 * Rules integration for the mailchimp lists module.
 */

/**
 * Implements hook_rules_action_info().
 */
function mymodule_rules_action_info() {
  $items = array();
  $items['mailchimp_lists_id_user_subscribe'] = array(
    'label' => t('Subscribe or unsubscribe entity from a MailChimp list ID'),
    'parameter' => array(
      'entity' => array(
        'type' => '*',
        'label' => t('Email Address'),
        'description' => t('The email to subscribe.'),
        'wrapped' => TRUE,
        'allow null' => FALSE,
      ),
      'list_id' => array(
        'type' => 'text',
        'label' => t('MailChimp List ID'),
        'description' => t('The list ID found in the mailchimp dashboard.'),
        'allow null' => FALSE,
      ),
      'subscribe' => array(
        'type' => 'boolean',
        'label' => t('Subscribe'),
        'description' => t('True to subscribe, False to unsubscribe'),
      ),
    ),
    'group' => t('MailChimp'),
    'access callback' => 'mailchimp_lists_rules_access_callback',
    'base' => 'mymodule_rules_action_entity_subscribe',
  );
  return $items;
}

/**
 * Action callback: Subscribe an entity to a list.
 */
function mymodule_rules_action_entity_subscribe($entity, $list_id, $subscribe) {
    $email = $entity->value();

    $choices = reset($field_info['instance']['default_value']);
    $choices['subscribe'] = $subscribe;

    if ($subscribe == 1) {
        mailchimp_subscribe($list_id, $email);
    } else {
        mailchimp_unsubscribe($list_id, $email);
    }
}

Where mymodule is the name of your custom module. This will provide the rule integration you're actually looking for.

Be careful, though: This method could get you banned from Mailchimp. It's best to combine it with a double opt-in process to prevent people from reporting subscription abuse.


How do I set up a view to filter on URL path? Can views show me all menu items with paths that match a particular pattern?

I have a documentation section which is mostly basic pages, but there's some views that belong here, too. I have set the views' paths to doc/some-view-name.

I would like to use a View to find all documentation pages (including pages created by Views) identified by the path doc/*

Is this possible?

To be able to filter nodes by their path you will have to use menu_link. (i havent used it though).

As far as i know there is no simple way of displaying content of the menu related tables, which is what you would have to do to include the views in the result. Some discussion and a direction of coding is here : http://groups.drupal.org/node/22731 Unfortunately the module suggested there wouls help you neither - it is again just for nodes.


Adding variables to page--taxonomy.tpl.php How do I add preprocess variables to page--taxonomy.tpl.php which will be available only to the vocabulary Project Type? I know my code below is wrong.

function themename_preprocess_taxonomy(&$vars, $hook){
    $vars['testing'] = 'It works!'; // This doesn't work :p

    // If that checks out, how to limit it only to a specific vocabulary (e.g. Shoes)?
}

You can limit variables to certain conditions. Obviously only when the variables to measure these conditions are available.

function themename_preprocess_taxonomy(&$vars, $hook){
  var_dump($vars);
}

This will show you all the available variables, for example the $vid, which contains the vocabulary-ID. The simple version would be:

function themename_preprocess_taxonomy(&$vars, $hook){
  if($vars['vid'] == 12) {
    $vars['example'] = "Foo";
  }
}

A clean, and much better solution would then be:

function themename_preprocess_taxonomy(&$vars, $hook){
  $vars['example'] = ''; # Always instantiate a variable, and make sure
                          # it has a constant type
                          # e.g. always return a string.
  if($vars['vid'] == variable_get('themename_vid_for_example', 123)) { # Avoid Magic Numbers [1]
    $vars['example'] = "Foo";
  }
}

[1] http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants

EDIT: updated variable_get. tss.


How one can get a field auto loaded with node title by passing nid How one can get a field auto loaded with node title by passing nid. I mean instead of getting the selectllist of all available title i want it to be auto loaded with corresponding node title.

NOTE: I have passed nid to that content type. Now have to fetch the corresponding node title into a field.

Thanks in advance ,
Manju

Prepopulate might solve your problem.

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.
For example, the following URL,
http://www.example.com/node/add/blog?edit[title]=this is the title
will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.


How do i remove main menu title once it's in sidebar, Why is so dang difficult to style the main menu once you put in the sidebar in Drupal 7?!?

i also want to remove those annoying leaf classes!  first leaf, leaf, last leaf etc.

on the page template file i see the main nav code and where it spits out title, but in the same file,
all the side bar code is in one variable. how do i access that?,

i don't mind  php coding. can someone please advise how to do this?

big thanks in advance

Welcome to the wild world of theme functions, friend. You're going to need to do some overriding of the main menu in a file called "template.php" which should be included in whatever base theme you're using. Create a function in that file that looks something like this:

function MYTHEMENAME_menu_link($variables){ // Code here }

Use this link as reference to understand how to change what's there: https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

And for a real brain buster on everything you want to know about how to theme menus, check out this answer by Sheena, who's basically a genius: Advanced menu theming in Drupal 7


Dynamically changing the href on a link with data-dialog-type = modal does not work For reference I am working on this issue for the Focal Point module...

I have a link whose href is updated dynamically using js based on a particular user interaction (moving the focal point on an image). The link may start as /admin/focal_point/preview/10/21x68 but after a user moves the focal point to another part of the image it is changed to /admin/focal_point/preview/10/75x28. In attempting to open this preview page open in a modal (as opposed to a new window) I'm finding that clicking the link loads the preview as though the link had not been changed. Any idea how to tell the ajax logic that loads modals to acknowledge the changed href?

Presumably, the JS used to generate the dynamic href is on the page that the modal opens?  If I'm not mistaken, iframes do not run their attached scripts by default.  So this page may be helpful:

https://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Since your requested iframe is on the same domain as your parent page, there shouldn't be any CORS issue.


Entity Reference field fails when choosing from more than 1000 items I've set up my Drupal system to allow users to select from a list of locations, which are registered as nodes.

However, after importing my ~6000 locations the field lookup no longer works with the following error:

  PDOException: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log,
  revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky,
  base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed,
  base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp,
  revision.uid AS revision_uid
  FROM {node} base INNER JOIN {node_revision} revision ON revision.vid = base.vid
  WHERE (base.nid IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, ... (trimmed) ...
   :db_condition_placeholder_5915, :db_condition_placeholder_5916))
  ...

  SQLSTATE[HY000]: General error: 1795 OCIStmtExecute: ORA-01795: maximum number of expressions in a list is 1000 (ext\pdo_oci\oci_statement.c:148)

I am using an Oracle backend, so it's possible this error is a quirk of Oracle. But in general, is the Entity Reference module intended to allow lookups on large lists of nodes? Or should I move to another module such as the References module?

I haven't tested whether Oracle's performance with Entity Reference is substantively worse than another backend such as MySQL.

However, implementing the workaround detailed here and converting a Drupal user.module query to a dynamic form to also implement partitioning worked, albeit with a 50 second execution time and a hugely increased PHP memory requirement. This is because of multiple complex queries across the whole node set.

Switching to use of the references module and the node_reference content type has vastly improved performance.


hook_preprocess_page for mobile detection I am attempting to set a variable $is_mobile that I can use in my page.tpl.php function.

function mytheme_preprocess_page(&$vars)
{
    require_once(libraries_get_path('mobile_detect').'/Mobile_Detect.php');
    $detect = new Mobile_Detect();
    $is_mobile = $detect->isMobile() or $detect->isTablet();
    $vars['is_mobile'] = $is_mobile;
}

It seems the result is cached and whatever the first hit will be used.

My overall goal is to create a dynamic menu for mobile and desktop. (One for each)

What is the best way to approach to this?

You could use panels and create a variant for mobile and other for non mobile.

the mobile detect module provide a selection rule for that by using
mobile_detect_ctools


Add captcha to registration form I'm quite familiar with PHP but do not a clue of Drupal.
All I have to do is to add a captcha to the registration form. How do I do this and btw. where is this registration form module located.

I know that this a beginner's question, but nevertheless any help would be appreciated. :)

Cheers

Chris

You can use CAPTCHA module. To add captcha in in drupal registration form there is no need to edit any single line of code. First you download and install the module then go to module settings page (/admin/user/captcha/captcha/settings) and enable the captcha for user registration form.


Rules - event stopped triggering itself I have two questions, both related to rules

1) It seems, all of a sudden and no idea why, 'When an order is first paid in full' is not triggering anything. I have a custom payment method, which worked fine till today. I can confirm that commerce_payment_transaction_save works and updates the order with payment information and status changes to 1. So I don't know why 'paid in full' event stopped working.
I am still able to trigger 'Completing the checkout process' event without problem.

2) Is there any module or perhaps an existing devel configuration that would allow to see rules log? Or debug by rules/events/actions?

Rules has its own set of debugging options. Using Drupal 7? Try /admin/config/workflow/rules/settings and then check your recent log messages at /admin/reports/dblog. As a last resort, it might help to print some manual code just so you know that the rule is being triggered.

More info on debugging Rules: https://drupal.org/node/1593278


allow only the author of the comment node I want to make an option to subscribe to news within the node, node - it's maintenance team that adds news. I decided to do with the comments as flag in this case does not fit. Everything seemed to be fine, I can add the required fields in the form of comments and install the Node notify that and give the ability to subscribe to a node. But then the question I give the ability to add comments to the author node and not the whole role, and I need to limit the addition of the comment and make only the author can add nodes. anonymous and everyone else can only view and subscribe.
Sorry for my English. Thanks for any help!

In the permissions of  Comment you can allow Post comments for your author role alone.For anonymous user you can give permission of view comment alone. Hope this helps you :)


Diff of module version releases I'm trying to debug an error I'm encountering in the latest version of the Custom Formatters module and I'm encountering a common problem I have in debugging.  There's no easy way to do a project-wide diff of project from release to release.  I'd like to easily diff https://www.drupal.org/project/custom_formatters 7.x-2.4 with 7.x-2.3.  I can use software locally to do that, but github has spoiled me I guess.  Am I missing a hidden function of drupal.org that shows diffs between releases?

You can clone down the project via

git clone --branch 7.x-2.x http://git.drupal.org/project/custom_formatters.git

When in the directory do a git diff 7.x-2.4..7.x-2.3 and review the output.

If you don't want to scroll through your terminal, try git diff 7.x-2.4..7.x-2.3 > version-change.diff and pop the output into a diff viewer.

I wish cgit had this built it, but the diff viewer in it only supports per commit (as far as I know)


Change order of fields per node So i know how to order fields when creating/editing a content type. But say i have three fields in a content type:

name
last name
nick

and want these to be draggable when a user creates a new node.

Any suggestions?

Thx!

For Drupal 7, you can use the Field Weight module to change the field order per node.
http://drupal.org/project/field_weight

I've used it with no trouble.


Form data not being entered into the SQL statement I have created a form which is not entering the data I enter in the fields into the sql statement. I just got the error:

  user warning: Duplicate entry '' for key 'PRIMARY' query: INSERT INTO subscription_info (first, last, email, phone) VALUES ('','','','') in C:\EasyPHP-5.3.8.1\modules\drupal620x120318224310\sites\all\modules\email_form\email_form.module on line 124.

Here is the code:

function email_form_my_form($form_state) {
  $form['info'] = array(
    '#type' => 'fieldset',
    '#title' => t('Personal Information'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['info']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    //'#default_value' => $form_state['values']['first'], // changed
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
   );

   $form['info']['last'] = array(
     '#type' => 'textfield',
     '#title' => t('Last name'),
     '#size' => 20,
     '#maxlength' => 20
     //'#default_value' => $form_state['values']['last'], // added
   );

   $form['info']['email'] = array(
     '#type' => 'textfield',
     '#title' => t('Email address'),
     '#size' => 30
   );

  $form['info']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#description' => "Format: 555-555-5555",
    '#size' => 10,
    '#maxsize' => 10
  );

  $form['subscription'] = array(
    '#type' => 'fieldset',
    '#title' => t('Subscription Information'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['subscription']['content'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Events'),
    '#description' => t('Please chose which events you would like to follow'),
    '#options' => array(
      'Baseball' => t('Baseball'),
      'Basketball' => t('Basketball'),
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  $form['clear'] = array(
    '#type' => 'submit',
    '#value' => 'Reset form',
    '#validate' => array('email_form_my_form_clear'),
  );

  return $form;
}

function email_form_my_form_submit($form, &$form_state) {
  //unset($form_state['storage']);
if (db_query("INSERT INTO {subscription_info} (first, last, email, phone) VALUES ('%s','%s','%s','%s')", $form_state['values']['info']['first'], $form_state['values']['info']['last'], $form_state['values']['info']['email'], $form_state['values']['info']['phone'])) {
      //$form_state['values']['subscription']['content'] use this later...
      drupal_set_message(t('The form has been submitted.'));
}
else {
      drupal_set_message(t('The form had an error in it.'));
    }
  }
}

Drupal flattens the form values array so the element set at $form['info']['first'] will be available in $form_state['values']['first'].

If you want it to be available in $form_state['values']['info']['first'] you need to set the #tree attribute on the parent element:

$form['info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Personal Information'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#tree' => TRUE
);

There's more info available on the #tree and #parents documentation page if you're interested.

The alternative is to change your db_query() call to use the "default" method:

db_query("INSERT INTO {subscription_info} (first, last, email, phone) VALUES ('%s','%s','%s','%s')",
  $form_state['values']['first'],
  $form_state['values']['last'],
  $form_state['values']['email'],
  $form_state['values']['phone']
);


Drush remote sql-dump starts with "stdin: is not a tty" When I run drush @SITEALIAS.live sql-dump > db.sql on some servers or in fact any remote drush command I get:

stdin: is not a tty as part of the return.

This is difficult when doing sql dumps as then you have to edit a multi megayte file to remove that from the head.

I'm reading from here: https://stackoverflow.com/questions/7062521/rsync-exits-with-the-message-stdin-is-not-a-tty

You need to add:
[ -z "$PS1" ] && return
to the beginig of .bashrc that is located in your home dir. That command checks to see if the shell is running interactively. If so, it exits immediately. This makes sense since stuff in the bash configuration file isn't needed for non interactive processes, like rsync

"in your home dir" meaning the user used to login on your @SITEALIAS.live server. So you need to SSH into your server as that user, and add the above line to the beginning of your ~/.bashrc on that server.
An explanation from another answer:

The error message "stdin: is not a tty" is due to something in the startup script on your server attempting to process an action that should only happen for interactive logins (when you connect with ssh direct to the server, etc).


How can I list all the IP address and referrers of visitors of a specific node? The tracker module is active on the website and I want to get all the Track statistics of a node created.

www.example.com/node/3/track lists all the redirection etc. But what I want to do, is to get all IP addresses that visited this node:

In Track Tab I can see the logs but the IP address and the referrer details are not listed here, to see this info I have to visit the link (www.example.com/admin/reports/access/24488 etc.) for per log listed in Track page.

How can I list all the IP address and referrers of visitors of a specific node via Drupal interface, Views or via PHPMyAdmin etc.?

Have a look at the Visitors module. It comes with various reports, such as reports about pages that have recently been visited, or that have been hit frequently, or about pages count per month, day of month, day of week, hour. And it also includes a Referrers report (for referrer type either internal, external, or both).

One of the included reports is the Recent hits report, a table with columns Date of visit, Title, Path and User ID of the visitor. If you follow any of the "details" links in that report, you'll get something that looks as in this example:

The demo site contains some sample reports (charts) available to anonymous users also.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case the delivered reports are not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


How to perform views date calculations using global math? Is it possible to calculate date in Views like to calculate two cell using global math for this case?

Example:

Nick's birth of date was 20/10/2005
Only 20 years old can join the club
So before 31/10/2025 Nick cannot join the club,
its mean Nick needs to wait for 10 years 10 days (date 31/10/2025) to join the club.

Can anyone assist me to solve this?

You can try Views PHP which allows you to add a php code field to a View.

Otherwise, for a less "dangerous" solution, you can add a field to your content type for which you are creating the View, hide the field from the node creation form with css, hook_form_alter() or Display Suite, and create a Rule that calculates the new date when a user save new content. This field could be a Date field, or an Interval field if you want to store the interval between two dates.


How to debug a variable in a controller class (var_dump) I am trying to do a var dump from a Drupal 8 Controller class. This is not working because controllers need to send a response. I just need to see the contents of a variable and I have not idea how to do this since I've tried all response combinations and can't seem to get it working.

This is my variable.

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

I am trying to var_dump($node) to see what's in it. Can anyone help?

OK, I'm going to be that guy. Do yourself a favour and set up Xdebug, hacks like var_dump() or var_export() are very bad practice and sooner or later you will forget to remove some of those statements and it will end up in production. Also it takes one single click to set up a breakpoint, as opposed to writing a var_dump()  or var_export() statement. Not to mention that the amount of information you can get by using a debugger is vastly more comprehensive.


How do I remove the appended string from image and Javascript URLs? I have a Drupal 8 website. I have installed the Advagg module. The URL for the JavaScript file has a string appended.

https://example.com/libraries/superfish/superfish.js?pzw4cp
https://example.com/libraries/superfish/superfish.js?pzy2r8
https://example.com/libraries/superfish/superfish.js?pzzsmo
https://example.com/sites/default/files/js/optimized/js_rKIkMy4-wmUaGP59iZKW9XJMLcVwjsfB0SXmAPmdK1I.sEln9qPOr9xw2O4-sGx2Wja5YU2bXXCG59CPiBDxwUY.js?q0emwu

The same happens for the URLs of the uploaded images. Sometimes, the browser doesn't display the image, when its URL has that string. If I remove the string, the image is displayed. Google search console reports such files as malware.

How do I remove those strings from the end of the URL?

The strings are to ensure that the files are not cached by proxies or intermediary caches when Drupal rebuilds its own caches. Whenever Drupal's cache is cleared and regenerated these strings will change. These are 'cache buster' strings.

Check this for an explanation of what is cache busting - https://www.adopsinsider.com/ad-ops-basics/what-is-a-cache-buster-and-how-does-it-work/


How do I create a tax calculation rule that runs by default before the customers address has been set? With Drupal Commerce and the Australian GST calculation module, I have been trying to calculate taxes as early as possible.

Most of the customers to the site are Australian and will have to pay the taxes. Rather than give them a nasty surprise I'd like to add GST by default and then get rid of it if the person's shipping address isn't Australian.

I created a secondary OR condition in the GST rule as below:

If the country component of the order address is AU or if it is not set, then calculate GST.

The current effect is that GST never get calculated.

It looks like your problem might be caused by the incorrect usage of the "OR" (within your Rules Conditions). The logic you have in your "conditions" is like so:

Order address component comparison.
AND one of the next conditions in the OR group must be true:

Data value is empty.

Here is an attempt to translate your current Rules Conditions:

  "Order address component comparison must be TRUE" AND "Data value is empty".

I doubt that is what you wanted to implement as Rules Conditions, but that is how Rules actually interprets them ...

I'm not sure which (at least 2!) set of Rules Conditions you wanted to combine with the "OR"-operator, but what is shown in your question for sure cannot be right. Maybe you want to try to see what happens if you adapt your Rules Conditions like so:

OR one of the next conditions in the OR group must be true:

Order address component comparison.
Data value is empty.

That is: move the "Order address"-condition below the OR, and also indent it (same indent as for "Data value is empty).

So if either (or both) of those 2 Rules Conditions are satisfied, then the Rules Actions will be performed. That should be pretty close to "*If the country component of the order address is AU OR (repeat: OR !!!) if it is not set, then calculate GST*" (as in your question).

For an interesting video tutorial about this, refer to "Combining conditions". Somewhere around '9:00' (near the end), it has a similar OR condition. Here is a summary of that tutorial:

How to be confused over the positioning of the AND and OR statements
How to combine conditions with AND requirements
How to combine conditions with OR requirements
How to combine AND and OR groups to create complex conditions
Some advice about the order of conditions
How to delete reaction rules
Why you shouldn't use the "send e-mail to all users in a role" action
Why it might be useful to have messages printed out when configuring complex rules


It's possible to pass a variable on attach_library in a template on Drupal 8? I need to pass a variable to a library called on a Twig template, is this possible?

{{ attach_library('theme/some-library') }}

.module

/**
 * Implements hook_ENTITY_TYPE_load()
 */

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks.
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name');
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;
    }
  }
}

.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);


Drupal Advanced Analytics I need to do some advanced analytics for my site. I need the basics Google Analytics stats (nb visits, bouncing rate, etc) and how many times each particular users came back in a specific period of time.

For example, I need to answer these specific questions:

How many users came back more that 2 times during the last week?
How many users added two nodes or more in the last month?
Graphs showing users repartition between fans, average users, first time users, etc

Is there any module implementing that kind of funneling in Drupal? Ideally, it should interface with Google Analytics (with Google Analytics events tracker) and/or Mixpanel.

Any thoughts or ideas?

You might be able to use custom variables within Google Analytics. That way you can get all your sexy graphs in one easy place.

You would have to use existing tokens or create some new ones and attach them to your users report to Google.

You can then install : https://chrome.google.com/webstore/detail/jnkmfdileelhofjcijamephohjechhna?hl=en

This shows you what variables are being tracked. For example I track my users on what content type they are viewing, what taxonomy, tags, roles etc.

What you are asking for is very specific, so I think you would end up creating custom tokens.

As an example you could show all first time users by attaching the token [user-created-date] then filter in GA to only show today's date for that custom variable.


Search API ItemType missing Node I am using Search API and search views to add facet blocks into my views page. It works perfect on my test site with only search/facet/views related modules.

But on my working site, when I add Search Index, the ItemType is missing "Node" selection, instead, it is showing "Content". I have updated all modules, but can't figure out why "Node" option is missing.

Anyone has ideas on this?

You do not need the "Node" Item type. Using the "Content" is going to index all your nodes.


Use views to produce list of terms with descriptions I have a Tags taxonomy which includes a couple of terms with descriptions.

Tags are rendered in a simple inline list under the content, and this is fine for most of them.

But some terms are acting as flags, e.g. "needs update", "stub". For these, just being listed at the bottom is not enough.

I would like to make a view block that lists all terms that have descriptions (and not ones that don't). I plan to then stick this at the top of the Content section and use a contextual filter so that if a page is tagged "needs update" you get a warning at the top of the page explaining what this tag means. Just like wikipedia does for "This page is a stub - it needs more info...".

Problem: views 3 (on Drupal 7) does not appear to be able to add term:description as a filter.

A easy workaround could be to attach a regular text-field to the terms, instead of using the hardcoded description.

Update: After taking a quick peek in the code, it does look like filtering on descriptions are not supported. This could just be a simple oversight.
There's an issue here, which claims this functionality has been added. I can't seem to find it, so I attached a new patch and reopened the issue.

Update 2: Dereine has commited my patch to D7. You should now be able to filter on term descriptions with the dev version.


Security model and menu access Drupal 8.6.1

I have some menu items  I would like to hide from some users: An administration menu with documentation about site admin; A contributors menu with documentation for contributors. etc.

It appears that Drupal prefers every menu entry to link to something. I have these menus pointing to route:<nolink> and have the content hanging from them, tagged as required to implement https://www.drupal.org/project/permissions_by_term.

The result of this is that the top level menu items are visible to everyone.

Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?

Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?

Obviously there is no hard and fast rule about this, but generally speaking your hunch is correct. Drupal menus expect every link (even a parent) to link to some content. As an example, the "add content" link goes to a page that lists the available content types even though the content types are usually listed under "add content" in the menu anyway.

I do not believe there is an example in core where a menu link is there only as a parent and does not link anywhere.


Why is the Media module ignoring view_mode display settings? I'm using the Media module 7.x-2.

I've added an image field to a content type, and I've enabled the Media CKEditor/Wysiwyg plug in and filter.
I've added fields to the image media/file type and set these up to display for the 'large' view mode setting.
When using the field, the image is displayed along with the other fields, as normal, but when I've inserted the image via Wysiwyg, only the image comes through; the fields are not displayed.

Why is this happening?

This is currently not supported in Media module. There is work being done though. Checkout this issue. https://drupal.org/node/1792738


Module design question I need to create a module that when visited with some get parameters in the url to be able to create user with specific roles in the database.

So if someone visits mydomain.com/my_custom_module/create/john/smith/role_id/filename_that_includes_hidden_token_for_validation

Will create the user John Smith with a role specified by the id passed and in order not to allow anyone to create users I have a temp txt file with a random generated name where I keep a token

Is that possible? Is there a better way?

Thanks in advance

EDIT

Why I want a module like this:

I have a site written in cakePHP and the need for a forum came up. The client heard that drupal's advanced forum is the best solution (I've tried to persuade him to use phpbb with no luck...) but he wants the forum to be private and to give access and roles to existing members from the cakePHP's site admin. So I'll provide him an "give forum access to member" button which will redirect to the url described above after I've created a temp file with a hidden token somewhere in the server for security issues. I don't know if it is the best way to do this.

That is no problem. user_save an hook_menu will be you're friends.

The file with the random is a good id for security. You could also have a look into the IP Login module.


current_timestamp in date field How can I add current_timestamp or now for date feild in drupal database schema.

        'created' => array(
            'description' => t('Timestamp when the fee schedule was added.'),
            'type' => 'int',
            'not null' => TRUE,
            'unsigned' => TRUE,
        ),

You can specify a driver-specific column type for MySQL using the mysql_type attribute:

function MYMODULE_schema (){
  $schema['table_name'] = array(
    'fields' => array(
      'created' => array(
        'mysql_type' => 'timestamp',
        'not null' => TRUE
      )
    )
  );

  return $schema;
}

Then, on enabling your module, you can simply modify the column to add the default/on-update behaviour:

function MYMODULE_enable() {
  db_query('
    ALTER TABLE {table_name}
    MODIFY created TIMESTAMP NOT NULL
    DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP'
  );
}

I've just tested that on Drupal 7 and it works a treat.

NOTE: If you don't want the timestamp to update every time the record is updated then just remove the ON UPDATE CURRENT_TIMESTAMP part of the query.


Same SKU but different product - Drupal Commerce I am facing a problem with the Products in a website made with Drupal 7 and Drupal Commerce.

As per the requirement, two admin can create products in the website with Same SKU and same name. But the difference will be the Stock number and the color etc.

As an example,
Product A has SKU: 0001

The 1st admin Creates Product A with Price $10 and stock 10.
The 2nd admin Creates the Same product with Same SKU with Price $20 and stock 5.

Is it possible to do? Or it's better to create new SKU each time? Please suggest.

Short Answer: No, SKUs must be unique.

Longer answer:
SKU is acronym for Stock Keeping Unit. It is a specific produkt that you have have on stock, like a gray medium sized T-shirt with V-neck for men. Had it had a different size, color ... it would have been an entirely different product.

SKU's were create to be able to keep track of these different products, even if there only is a slight change. This also means that SKUs must be unique, since a SKU is the code for a specific product.

The above is general for e-commerce and originates from physical stores with stock keeping etc. Drupal Commerce conforms to these standards, and so it is impossible to create two products with the same SKU.


Email a Whole Node (Including template contents) I have created my own custom node.tpl.php file.
I now want to email the entire node, each time the user creates a new node of that content type (I have made sure that all the HTML in my node.tpl.php file is email friendly).

How can I do this?
Ideally I would like the email to go to a specific email address automatically when the node is saved.

I have found that a combination of Rules and HTML Mail can achieve what I want. Except... When creating a rule action, there isn't the option to email the entire node (including the node.tpl.php theming). Rules only gives the option to email out specific node fields (without theming).

Any suggestions would be most appreciated!

Here's another approach. (The code is available in this sandbox.)

nodemail.info

name = Nodemail
description = Sends node e-mails.
core = 7.x

nodemail.install'

<?php
function nodemail_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('nodemail' => 'NodemailMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function nodemail_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['nodemail']);
  variable_set('mail_system', $mail_system);
}

nodemail.module

<?php
class NodemailMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

function nodemail_mail($key, &$message, $params) {
  switch ($key) {
    case 'node_mail':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}

function nodemail_node_insert($node) {
  if ($node->type == 'mycontenttype') {
    $params['subject'] = 'Node "' . $node->title . '" was created';
    $params['body'] = render(node_view($node));
    $to = variable_get('site_mail', '');
    $from = 'noreply@example.com';
    $lang = language_default();
    drupal_mail('nodemail', 'node_mail', $to, $lang, $params, $from);
  }
}

The install file contents and NodemailMailSystem class are used to allow this module to send html e-mails. The 2 other functions are implementations of hook_mail() and hook_node_insert() that deal with sending the e-mails when a node of mycontenttype is created. One thing you'll have to note is that Drupal will use the node template file of the theme that is being used for node creation pages (or the core node.tpl.php if the theme doesn't have it) for the node view. You may also want to check out the node_view() and drupal_mail() functions that are used here. This whole thing should work with Drupal 7 core functionality (no contributed modules are needed).


Writing a custom Rules Action for VBO- do I need to use Entity? I have a list of email addresses displayed in a view. I'd like to parse those email addresses using a rules action, via VBO.

I'm trying to pass the email address to my rules action as a parameter, but it seems the only way I can do this is if I declare the email address as an entity first. Is that right or am I missing something? If there's an easier way, please let me know.

[I'm assuming you have a custom table to store these email addresses and are not related to any other entity]
With the latest version of VBO, yes, you have to define an Entity.
See this issue in the VBO queue for more information.

FYI, the below steps worked for me.

function module_entity_info() {
  return array(
    'MY_NEW_ENTITY_TYPE' => array(
      'label' => t('MY_NEW_ENTITY_TYPE'),
      'base table' => 'MY_NEW_TABLE',
      'entity keys' => array(
        'id' => 'your_tables_primary_key',
      ),
    ),
  );
}

Note that in entity keys array, set the table's column as the key, and VBO will pick it up and will pass as an object to the action. See below:

function module_action_info() {
  return array(
    'module_remove_something' => array(
      'type' => 'MY_NEW_ENTITY_TYPE',
      'label' => 'Remove URL',
      'configurable' => FALSE,
      'behavior' => array('deletes_property'),
    ),
  );
}

In your views integration file, you will probably need to define the tables as an entity too.

function mymodule_views_data() {
  $data['mymodule_emails'] = array(
    'table' => array(
      'base' => array(
        'field' => 'eeid',
        'title' => 'Extracted E-mails',
        'help' => 'Email addresses collected by parsing the remote URL',
      ),
      'group' => 'E-mail',
      'defaults' => array(
        'field' => 'email',
      ),
      'entity type' => 'MY_NEW_ENTITY_TYPE', // attention here!
    ),
   // Rest of the table definition...


How can I link a text field to a user profile such that I can display nodes on the user profile based on that text field I'm trying to create a relationship from thin air, at least that's how it feels.

I have two account roles.  Producers and Instructors.  I want to be able to reference nodes (events) created by Producers on the related instructors profile page and vice versa.  The caveat is that the 'referenced' accounts may not yet exist.

For example:

Producer A creates an event and lists Instructor B (who has an acct and profile) and C (who does not have an account) as the instructors via a multivalue text field (reference field is not possible here).
Once the node is saved, the system checks for a relationship between the text field data and user profiles.  A relationship exists for Instructor B, so the nodes are displayed on her profile.  No relationship exists for instructor C yet, so nothing happens.
instructor C comes a long and makes an account, when the account is saved the system checks for relationship again and finds a relatioship between previous nodes and this new account, the nodes are displayed on the profile.

I am thinking this field could be an email address or something.
Is this possible and does anyone have advice on where to get started?

I can see how you'd want the Producer to be able to create an event and assign instructors to it before the instructor has an account. So in that case, have a node type which represents the instructor. This would be like a bio page or CV or some-such.

Then use nodereference and/or entityreference fields, Views, and viewreferences to connect the dots. The Event type would have Instructor fields which would refer to the bio pages for the instructors. As the instructors created accounts, a viewfield on the user profiles would show the bio page, keyed by an email acct field which you'd be sure and add.

Complex but not hard. :-)


Ckeditor toolbar not entirely showing up I have just moved my site from local machine to production, the wysiwyg editor based on ckeditor no longer show the complete toolbar. I have a minimal list of element.
Can someone help, am trying everything, edit profile, check if all files are uploaded, i don't see any problem !

Updated answer:

Go to "Home › Administer › Site configuration › CKEditor".

Then select an individual profile in the upper section (not the Global settings).

You'll be on the "Edit CKEditor profile" page, where there is an "Editor appearance" section. The 6th item down (just below the color picker) is the toolbar selector.

There are 5 options, if none of the selections meet your needs, you can easily create a custom toolbar with exactly the buttons that you want to have available.

The module author included a note below the toolbar selector, you can open the "ckeditor.config.js" located in "sites/all/modules/ckeditor" and create your custom toolbar there. It will appear in the selector after you create it.

I've included all of the buttons available for the normal CKEditor, but the module author has added some that are specific to Drupal. You can take a look at them in the config.js file.

Here are the standard plugin buttons, you can pick and choose which ones you want:

[ 'Source','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ]
[ 'Link','Unlink' ]
[ 'Image','Table','HorizontalRule','SpecialChar','-','SpellChecker' ]
[ 'Source','About','InsertSnippet','BGColor','SimpleLink', 'Select', 'SelectToText', 'SelectorUpdateSelector','SimpleLink' ]
[ 'About','BGColor' ]
[ 'Format','Font','FontSize' ]
[ 'TextColor' ]
[ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ]
[ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ]

Be Well,
Joe


How can I add player parameters to a core oembed field for a youtube video? For example, if I enter this url that contains the player parameters to remove controls and autoplay, oembed field on my media type does not allow it ("The given URL does not match any known oEmbed providers.".
https://youtu.be/9ot0rIlhbNE?autoplay=1&fs=0&controls=0&modestbranding=1

If I paste just the base url, then it works.
Any thoughts?
Edit: Based on Yuseferi answer, I have isolated the Youtube section if the providers.json.
{
    "provider_name": "YouTube",
    "provider_url": "https:\/\/www.youtube.com\/",
    "endpoints": [
        {
            "schemes": [
                "https:\/\/*.youtube.com\/watch*",
                "https:\/\/*.youtube.com\/v\/*",
                "https:\/\/youtu.be\/*"
            ],
            "url": "https:\/\/www.youtube.com\/oembed",
            "discovery": true
        }
    ]
}

I had the same problem before with a local provider. So I share the solution I used and hope it works for you too.
The Drupal core, fetch providers form https://oembed.com/providers.json automatically. So you need to change the provider to what you want.
Oembed Providers module helps to add custom providers too.

Add custom oEmbed providers via an admin user interface (providers are
stored in configuration)
Global enable/disable of providers
Modify the provider list URL (which is > defaulted to
https://oembed.com/providers.json)
Disable the fetching of the
provider list (useful in an instance where only custom providers are
used)
Provides hook_oembed_providers_alter() to alter provider
definitions

So, all you need is to add a new provider for your custom provider "youtu.be" with your parameters too.
try it and let me know if you need more details.;)
Screenshots that shows it's working without any validation error:

what I did, was just add "oembed_providers" module and enabled it


Prev/Next on field group horizontal tabs I'm using entityform and Field group to create a multi-step form, using Horizontal tabs.

I'd like the Prev/Next buttons, that show when you use Multipage, to show when using horizontal tabs.  i.e tabs + Prev/Next

I'd like pointers on how to go about coding it myself (if it's not currently configurable) as I don't know where to start.

OK, well before this is closed, I will post what I did in the hope it might help someone.

I added a #tab_back/#tab_next buttons to the form, and used a bit of jquery to handle the UI.

  var current_tab = 0;
  jQuery("#tab_back").hide();
  jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();

  function click_tab(inc)  {

    newtab = current_tab + inc;
    if (newtab >= 0 && newtab <= 4 )  {
      jQuery('.horizontal-tab-button-'+newtab).find("a").click();
      current_tab = newtab;
      jQuery("html, body").animate({ scrollTop: 0 }, "slow");
    }
    return false;
  }

  jQuery("#tab_back").click(function () {
    click_tab(-1);
    return false;
  });

  jQuery("#tab_next").click(function () {
    click_tab(1);
    return false;
  });

  jQuery('.horizontal-tab-button-0').find("a").click(function () {
    current_tab = 0;
    jQuery("#tab_back").hide();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-1').find("a").click(function () {
    current_tab = 1;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-2').find("a").click(function () {
    current_tab = 2;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-3').find("a").click(function () {
    current_tab = 3;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-4').find("a").click(function () {
    current_tab = 4;
    jQuery("#tab_back").show();
    jQuery("#tab_next").hide();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').show();
  });

For what it's worth, I didn't really need tutoring, just help knowing which avenue to explore as it could have been done many different ways.  Anyway, hope this helps someone.  feel free to pick at my javascript... It's not my forte.


How to attach css to bean preprocess? So we define the function with this hook...

/**
 * Implements hook_preprocess_bean().
 */
function MODULE_preprocess_bean(&$variables) {

  // Attach css...

  return $variables;
}

What can this be attached to please?

$variables['SOMETHING']['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';

It can be attached to whatever you like - the important thing is that you render it.

So you could quite simply use:

$foo['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';
drupal_render($foo);

Or stick it in a var like you're already doing:

$variables['SOMETHING']['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';

And in the template:

drupal_render($SOMETHING);

It works because drupal_render() unconditionally calls drupal_process_attached() on any element it finds with an #attached property, regardless of what you're doing with the result of the render (or if there's even anything to render).


How can I use Rules to 'Set a Data Value' on a node's field WITHOUT updating that node's 'updated' timestamp? I am using rules to set a data value of a field on a node. Works great!

BUT, when the rule is triggered, the node's 'updated' timestamp is changed. In my particular application, I do NOT want this to happen. I totally understand why this behavior might be desired by some (most), but in my case I don't.

Is there any way to prevent the 'updated' timestamp from being updated when rules is used to set/change the value of a field on that node?

Here are the nitty gritty details of my application:
I have two node types: Parent & Child
The child node includes an entity reference field to relate it to its parent node.
When a child node is created or updated, I use rules to change a field value of it's parent node.
I got that all to work great, but, when the rule is triggered, the parent node's 'updated' timestamp is changed to the current time, which I do not want.

I also posted this question to the Rules issue queue on d.o:
https://www.drupal.org/node/2796899

If it is not necessary for you to use rules, you can also try to invoke the hooks node_update and node_insert.
There you can load the parent, change the fields value and save it with the field_attach_update function.

You can find an interesting article about this at https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself


How to add User edit link in main menu Site  link

here, in this 9 is the user id.it is different according to register users.

When add link in main menu there is an option Path textbox
in that text box if i add "user/9/edit" then link is created but here 9 is login user id. then it is accessible only whose user id 9. but other not access.
I want to add link dynamic which user are login then that user access that user edit page.user/*/edit

Install me aliases module.

  Provides shortcut paths to current user's pages, eg user/me, blog/me,
  user/me/edit, tracker/me etc.


Can I use AddressBook values to populate a webform field? I am currently trying to make lots of things work together. I'll try to put it simple without annoying details.

I work on a lawyer's site with drupal commerce installed, as well as AddressBook, Webform and FillPDF.

Outside the commerce functionalities (selling legal templates), my client wants her users to share loads of necessary informations with her (about the case she needs to work on).
Among these information are… you guessed it: name and address.
These informations might be used (many times) in pdf generated from forms (like mandates etc.)

Do any of you know a way…
to pick an address already stored in AddressBook to re-use it in a WebForm, (let's say, via a token)?
---OR---
to fill The AddressBook values as well as user informations from data typed in a WebForm which I could grab later on (the other way round suits me fine).

The aim being to provide a unique place to register all the necessary infos,  in order to keep the site super-simple for middle aged people.

I was able, lately, to use a list of existing profiles in a node field. As these profiles are entities, an 'entity reference' field can do the job. But I can't offer the possibility to choose from a list of entities in a webform though.
Now, I get a token related to this newly created field but not to the current user.


restrict a field's content based on a selected taxonomy term I have a content type with a number field and a field for a taxonomy. I'd like that, when the user creates a node of this particular content type, the value that appears in the number field changes to a preset depending on the taxonomy term chosen.

For example, The taxonomy term is a restaurant and the number field is a price, if the user chooses an specific restaurant the price changes depending on the restaurant chosen.

option 1:
use a hook_form_FORM_ID_alter MYMODULE_form_node_form_alter(&$form, $form_state) to add an ajax functionality on the taxonomy change event and populates the number field default value depending on the form_state taxonomy value.

option 2:
Add your own javascript with taxonomy terms mapped to number values and when the taxonomy term changes, change the number values to the mapped value. This is pretty much same as above without requiring ajax.


Solving performance issue DrupalDatabaseCache::clear I am facing a performance issue when I open some of the pages.  It is taking too long time. After checking the queries and the time for each query I found that these two functions are taking a long time:

DrupalDatabaseCache::clear
DrupalDatabaseCache::set

What to do?

If you are facing performance problems using database as cache backend you should consider moving the caches to a better performing cache backend. Suitable backends for general caching are for example Memcached and Redis. For both of these you can find proper contrib modules (Redis & Memcache) and a lot of help in using them. If you want to have high performance page cache you could use Varnish for that. Also setting up APC to improve general PHP performance is a wise thing to do. Some basic information on using APC can be found from here.

Whatever caching methods you choose to use you should remember that form-cache must use non-volatile storage. This means that you should simply remember to keep form-cache in database. This can be achieved by inserting the following to your sites settings.php file.

$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';


Fatal error after enabling backup and migrate module I just enabled back up and migrate module. Then I backed up my site and tried to restore the site using the back up file and it did not allow me to do it.

Then when I go to admin > config > I get this error:

"One or more problems were detected with your Drupal installation. Check the status report for more information."

Then I go to admin > reports > status reports > click run cron manually > I get this error:

"
Fatal error: Class CToolsCssCache contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (DrupalCacheInterface::__construct) in /home/content/65/11722765/html/sites/all/modules/ctools/includes/css-cache.inc on line 52
"

Chaos tools 7.x-1.7

Drupal 7.22, 2013-04-03

Please advise,
 D

Go to this link and install the ctools-cache-handler.patch patch


How to perform x = x + y in Rules How can I add this action in Rules? This is my pseudocode:

1 total=0;
2 //loop through each line item {
3 //get quantity of each product
4 total = total + line_item_quantity;}
5 if total =< 2 then total = 0;
6 total_cost = total * $1.50

I think I can get everything working with the Conditional Rules module. but I cannot get

x = x + y

to work on Rules because they say that the variable already exists.

Also, how do I use conditions on entities like calculated shipping cost? What's the variable name?

Have a look at my answer to the question about "How to add up all items of a field collection field using Rules?". Your question is, IMO, a minor variation of it. Just replace article-details-item:field-price by line_item_quantity (as in your pseudocode) and it is close to identical.

The custom rule to do the calculation, looks like so:

{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

Enough to get you going and get it to work (or should I say "How good are you in reading/digesting the Rules-export-language)?


View field with link to excecute action plugin How can one add a field in views with a link to a custom Action plugin?

With bulk operations it's possible to create a checkbox to perform an action to a set of results. My actions have an access check that may be different per result so using the checkbox would result in a lot of warnings when the user tries to perform the action and doesn't have access.

I'd prefer to show the action as a link and only show the link when the user has access.

I'm thinking about setting up a route with a csrf token and an access check on a controller that manually performs the action:

my_module.my_action_callback:
  path: '/node/{node}/my_action_callback'
  defaults:
    _controller: '\Drupal\my_module\Controller\ActionController::my_action'
    _title: 'My action'
  requirements:
    _permission: 'perform my action'
    _csrf_token: 'TRUE'
    _custom_access: '\Drupal\my_module\Controller\ActionController::my_action_access'

In ActionController::my_action I could perform the action programmatically:

\Drupal\system\Entity\Action::load('foo')->execute($data);

I had hoped there was a less complex and more elegant way using an existing view plugin.


Custom Editor for a node based on type Using Drupal 7, I'm working on a module and want to have it so when the module is installed it will set a new node type called "project" When a user is adding/editing a $note->type="project" I want to bring up a custom editor for my module that is for that node type. I have been looking for tutorials for nodes and editors for nodes but I wasn't able to find any good examples of making a custom node type and making and assigning a custom editor for a node type.

I also don't know what hooks I need to use to target the node editor. As of right now I'm following the steps from the following tutorial. http://www.sitepoint.com/creating-a-new-drupal-node-type/

The WYSIWYG module allows embedding any supported WYSIWYG editor to a field via a hook_form_alter()/hook_form_FORM_ID_alter() invocation. Here's a link to its documentation page. You can alter your custom node type form by altering the its body field #type & #format elements.

Note: To do this it also requires:

The WYSIWYG libraries pre-installed to the sites/all/libraries directory.
A pre-existing WYSIWYG profile created.

As such, you'll need to have add a wysiwyg dependency in your module's .info file and some how do the above work in #1/#2 inside your  hook_install invocation.


What would be a comprehensive but safe set of html tags to use with the HTML Filter but compatible Markdown? I want to use the Markdown filter on my pages, but using the HTML filter messes it up. However I still want to use it. Does anyone have an idea what other tags should be allowed beside these and what the safety issues are?

This the list I currently use - what else should be added?

 <src>

But you don't need enable all of it, just simple reorder the filters, and put the markdown filter under the html filter. So the html filter will drop the unavailable tags, before the markdown process the text, and build own html.

Edit:
Checked the OpenAtrium's dedicated Markdown filter, it has the following in HTML

Markdown PHP Version: 1.0.1n
Markdown Extra Version: 1.2.4

And own filter weights:


field_info_field: how to define the content type name? I defined several content type. In a module, I need to get the list of fields for this content type. I did the following:

 $fields = array();
  $content_type = 'indicatorsheet_page';
  $instances = field_info_instances('node', $content_type);

Variable $instances is empty. How should I defined $content_type? Isn't it a string set to the type machine name?

What you're doing here seems correct to me, bear in mind that you can leave the bundle parameter empty and then you'll get an array of results keyed by bundle so you can evaluate if there's a problem with the machine name of the bundle you're using:

  $instances = field_info_instances('node');

You can also access admin/reports/fields and take a look to fields and content types available in your site.


Facebook Canvas-friendly Theme I'm very new to Drupal and web dev in general (J2SE C/ObjC background). I've just installed Drupal For Facebook. With its help I'm able to get my FB App to get its content from my Drupal site. However, none of the standard Drupal themes seem to format nicely for facebook.

My criteria are:

formats pages to < 520 pixels wide (main criteria)
shows the page contents but very little else (no breadcrumbs or menus)

I thought about writing my own theme to achieve this end. But I thought I'd ask if there's anything readily available out there that I can use, since I can't be the first guy that wants this. Or if there's a way to constraint the page width and hide the menus and breadcrumbs using only CSS trickery, I'd love to know about it too (mind you I'm an HTML noob here)

Gracias

My thoughts in a nutshell:

Start with the Zen base theme
Sub theme this with your custom theme (there are instruction in the Zen theme on how to do this)
Use a fixed width option, and resize the main column to 520px
Add CSS to spice it up and give it colours etc (out of the box it is fairly boring colour wise)

In order to hide breadcrumbs you can override the page.tpl.php to not display them.


CKEditor adds inline nonsense I'm hoping someone else has run into this and has a solution:

I have the CKEditor module (v. 7.x-1.13) installed using ckeditor.js version 4.01 (due to compatibility with Media module). The problem I run into is after I've added content into a field and publish it. After I return to edit the content, CKEditor has added all kinds of "stuff", a ton of inline CSS inside of a paragraph and span, and the letters "BESs" See sample below. Hoping someone can make some sense of this and offer a solution.

BESsBESsBESs

Thanks in advance.

I guess it's a bug in WebKit/Blink http://dev.ckeditor.com/ticket/9998. I don't know what you did with your text so I can't help more. But if it does not happen within Firefox or IE, then it is definitely that bug.


How to specify Views page as parent for menu link? I have a module with a menu link which I want to appear as a child of another link in the admin menu. The would-be-parent link is to a Views page if that matters.

This is the contents of mymodule.links.menu.yml:

mymodule.add_location:
  route_name: mymodule.add_form
  parent: views.branch_locations.page
  description: 'Add a foo.'
  title: Add new
  menu_name: admin

I got the views.branch_locations.page machine name for the desired parent link from ViewsMenuLink::getDerivativeDefinitions(), the class responsible for dynamically providing menu links for the Views module.

With the current setup the "Add new" item doesn't appear under "Branch Locations" in the admin menu. The route_name definitely exists, and no error is thrown when clearing cache or rebuilding menus, which suggests Drupal is accepting views.branch_locations.page as a valid parent link somewhere along the line.

But how do I get this item to show up in the menu, as a sub-item of the specified parent? I guess I could use the API to programatically create the link, although I haven't tried it so it might have the same problem, but I want this one in config.

Is the problem maybe that because the Views module declares its links dynamically, I need to do the same for that dynamically created parent to even be available?

Views generates menu link id's with a prefix views_view: and the first page display normally has the id page_1, so the parent should be something like this:

  parent: views_view:views.branch_locations.page_1

There is no error thrown, if parent: doesn't match an existing menu link. It's ignored and the menu link appears in the top level of the menu.

It doesn't matter from which provider the menu links are from, all discovered menu links are treated equally in the menu tree table.


Fetch feed from a given URL I have a URL like www.example.com/test/rss.xml, and I want to import this XML automatically in Drupal 6. I created the content type as in rss.xml, but I am not able to import automatically. I tried the Feed module for this, but I am able to upload manually, not automatically, when I need it to update all the feeds from rss.xml automatically.

Does anybody have an idea about this?

Have you tried the Feeds module?

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files


Video conference module I have some doubts about the Video Conference module.

Can we integrate the video conference module in Drupal 6?
Can we use Dokeos for video conference?

It looks like that module is in the very early stages of development and is not widely deployed.

There is an abandon dokeos module as well, but I think that you may be out of luck with this particular feature?


Shutdown functions not working on php-fpm setup? I have a problem with drupal_register_shutdown_function(): my callback is not being called =| Here's example code:

<?php
/**
 * Implements hook_node_update().
 */
function example_node_update($node) {
  if ($node->type == 'test') {

    drupal_register_shutdown_function('_example_shutdown');
    dpm(drupal_register_shutdown_function()); // This outputs callbacks array showing that '_example_shutdown' really gets registered.
  }
}

function _example_shutdown() {
  dpm('Shutdown callback executed'); // This is not shown
}

I use php-fpm, and php.net register_shutdown_function discussion suggests to use fastcgi_finish_request() instead of register_shutdown_function() with php-fpm. Also, see this D8 issue: "Ensure register_shutdown_function() works with php-fpm". Is there any D7 workaround?

I think there could be two different approaches:

Global: Fix drupal_register_shutdown_function() to check for php-fpm environment and use fastcgi_finish_request() in that case.
Local: Use some hook to force _drupal_shutdown_function(). Maybe hook_exit() would be ok for some cases, but in my case it is too late (as my callback updates nodes, and by the time hook_exit() runs the response is already sent to the browser, so user would get an "old" node, I'm afraid).

Maybe there is something simpler that I'm missing?

Example shutdown is getting called ; you can't use dpm in a shutdown function though, because at that point the session already got written to the database and there's just no way to add a new message to it.

In PHP-FPM, the connection also could have already been closed, so print or var_dump is not really a good test to check if you're shutdown function is getting called in general ; it should work in D7 though if you're not using a module that's specifically closing the request, so you should be able to use print "Hello world"; and get it to show on screen (that's what the core "Shutdown functions tests" is doing in D7).

If you want something realiable to use in a shutdown function to check if it got invoked, try something like file_put_contents('/tmp/drupal-debug.txt', 'Shutdown function called');


Pagination Not Tied to database queries I would really like to:

to create a paginated table of nodes, displaying only those that the user has 'update' permission to; displaying title, content type, and path alias
the path for nodes may be different depending on the content type. More specifically, I have created a content type 'file' to wrap an uploaded file; I would like to display the url alias associated to the actual file, rather than the url alias of node that wraps it.

There are a few approaches that I have considered,

Creating views. However, the above behavior seems to require merging two views --- one for nodes of type file, one for node of content type not equal to file. I have no idea how to merge two views. Also, this method seems to create a dependency of the output of the view on the content type 'file'.
Use database query + pagination. In many of the examples that I have seen, if I want to add pagination to a table, I can do the following (see this very excellent tutorial):

run a database query using either pager_query or the extend method for the SelectQuery object
theme the query results, and use theme to generate the pager based on the query

The problem with this approach is making theme('pager') play well with filtering the database entries by node_access. For example, for an user with relatively few nodes that she can edit, the table displays many empty pages.
Database query, filter into array, then use pagination on array as suggested by this post. This does get the table to work correctly. However, it is really expensive, because the entire query is run at this point, and the pager is purely for aesthetic purposes; seems a bit wasteful.

Now (thank you for bearing with me so far), is there a some way to create this table this without using views, but faster than method 3? I can also accept 'no' for an answer; in this case, it would be nice to know why not.

I realise the question is more than a year old...

Create a view with no content type filter.  Add fields for Title, Type, Link, and File field in that order.  In the Link field settings, check the Exclude from Display box.  In the File field settings, under No Results Behavior, use the token of the Link field in the Rewrite Output space.  The available tokens will be listed in an expandable space below the text field.  Tokens include all fields listed before the current field, which is why the order matters.  Set display to a table and turn on paging.

Views will automatically check access permissions, so this should do what you want.  This will pull in all nodes, filter by access, look for the file and use that link if it finds it, and then in the cases where that field is empty (content of another type) it will use the node link instead.


When using drupal_get_query_parameters(), should I still run values through filter_var() or check_plain()? When absolutely needing to take in query string values, I'm using drupal_get_query_parameters(). However, is it still a good idea to run values through check_plain() or filter_var(). Or does this drupal function automatically take care of data sanitization for me?

For example, is the filter_var with FILTER_SANITIZE_NUMBER_INT a good idea, necessary, or redundant?

<?php
$params = drupal_get_query_parameters();

// get dept name if exists in query string
if (array_key_exists('exposed_filter_a', $params['field_department_tid'] = filter_var($params['exposed_filter_a'], FILTER_SANITIZE_NUMBER_INT);
    $expfilter_value = taxonomy_term_load($params['exposed_filter_a'] )
}

drupal_get_query_parameters() doesn't perform any sanitisation of vars at all.

If you need to validate the incoming value, or filter it for XSS before it is outputted, etc., you'll need to do that as normal.


How to import and merge existing site from svn to git? I'm working with a site that has been using Subversion for version control and we'd like to swtich to using git instead. It seems like it would make the most sense to clone the Drupal project git respository from drupal.org, checkout the branch that represents the version closest to the existing site, create a new branch from that point and then somehow merge the existing svn repository into that branch. Is it possible to do that last step, to avoid losing the svn history?

For what it's worth, in one of the Pantheon demo screencasts they're doing something similar (around the 3 minute mark). It looks like they are starting with a backup of the site though, rather than importing a repository and its associated history.

Is there a better way to handle this scenario?

I don't see any advantages to being "in sync" with drupal git repo unless you're "chasing head."

I would just convert your current SVN repo to git. You can create a new branch that tracks drupal git and merge that branch in occasionally (if your directory structures match) or just download the final release packages and copy them into your directory and commit the changes.


Site maintenance/merge changes I set up an account at BlueHost and my unfinished site is now live at columbiablooms.org.

My understanding is that when I make modifications, such as enhancements, that changes are made not only to the file structure, but also the database meaning that from this point forward I need to make all my changes and content additions to this live site. Also, I want to be very careful to backup both the file structure and the database before I make changes in case I mess things up.

At this point my Acquia Dev Desktop is not very useful since there appears to be no way to merge what I've done on my local machine with what's live out there on the web.

You aren't required to make changes directly to your live site, it is bad practice to do this for things other than minor content additions/changes.

You should have at a minimum a dev and production environment.  Your local environment would be dev obviously and there are many ways to sync the changes between dev and live.

If you have ssh access to your server, the best way would probably be to use drush to sync your changes between environments.  There is a good explanation of this method here.

If you don't go the drush route, you could always do it manually by dumping your local db / files and updating the live site.

There is a lot of information on the subject on this site, a good bit of info can be found here.


Block with search box in header I need to create a block with a search box in header in order to allow users to search for a the specific content type that is shown in that block, but I don't know how to do this.

I've attached one photo to show what I need.

All you would need to do is create a block in views with an exposed search function. A walk through on how to do something like this is available at http://summapro.com/drupal-tutorials/learning-exposed-filter-views-search-and-filter


HTML tags in a block body are not rendred I'm using Drupal 8. I have created a custom installation profile. Inside the profile profileName.install file, I created the following function:

function setupCustomBlocks() {
  $blockContent = BlockContent::create([
        'type' => 'basic',
        'info' => 'Why choose us?',
  ]);
  $blockContent->set('body', '
&nbsp;

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
'
  );
  $blockContent->save();

  $block = Block::create([
        'id' => 'why_choose_us',
        'plugin' => 'block_content:' . $blockContent->uuid(),
        'region' => 'topwidget_first',
        'provider' => 'block_content',
        'weight' => 0,
        'theme' => \Drupal::config('system.theme')->get('default'),
        'visibility' => array(),
        'settings' => [
          'label' => 'Why choose us?',
          'label_display' => TRUE,
        ],
  ]);
  $block->save();
}

The bellow function, allows me to create a custom block when I install the profile. Here is the result:

As you can see, the HTML tags are not rendering. How can fix that?

It's rendering the block's content a plain text, not HTML, because you aren't setting the body field's format property when creating the BlockContent entity.

$blockContent = \Drupal\block_content\Entity\BlockContent::create([ 'type' => 'basic', 'info' => 'Why choose us?' ]);
$blockContent->body->value = '
&nbsp;

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
';
$blockContent->body->format = 'full_html';
$blockContent->save();


Drupal Slow loading times I'm currently having a Drupal 6 (because some modules are not available in Drupal 7) site running. But the loading time is very slow(www.hard-dance.org)

Here's what I've tried so far to eliminate possible reasons:

I have looked in my admin panel for problems, and did a cron job manually
I have checked to see if Clean-URLs was causing the site to slow down, it was not.
I've disabled some modules, but no change.

I also noticed that my website is going slow, once logged in.

Does anyone have an idea of what the cause of it could be?

Check size of files folder, heavy images may increase site loading time.


Change the Default " - Choose -" text in Ctools Jump menu? I've created a Ctools jump menu in a block in a module. The default text which Ctools provides for their jump menu is "- Choose -". Is there a way to change this in the module? I'm guessing it should happen somewhere in this line of code but not quite sure how to do it;

$form = ctools_jump_menu(array(), $form_state, array($url => t('Classified Ad'),$url2 => t('Places'),$url3 => t('Facility')), array());

Just had a look at the ctools_jump_menu function's code here.
I would try the following:

$options = array( 'choose' => 'CUSTOM TEXT' );
$form = ctools_jump_menu(array(), $form_state, array($url => t('Classified Ad'),$url2 => t('Places'),$url3 => t('Facility')), $options);

Hope this helps!


How to override default cardinality for the field widget? I've custom widget which consist multiple input elements in hook_field_widget_form() as part of one field (like address field).

The problem is that Drupal complains about:

  this field cannot hold more than @count values

which happens in field_default_validate(), when I've multiple input filled, so it doesn't recognise that this is one single field.

I've tried to change my cardinality in every possible place as below, but without success:

/**
 * Implements hook_field_info().
 */
function my_address_field_field_info() {
  return [
    'my_address_field' => [
      'label' => t('My Address Field'),
      'settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'instance_settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'default_widget' => 'my_address_field_widget',
      'default_formatter' => 'my_address_field_default',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_info().
 */
function my_address_field_field_widget_info() {
  return [
    'my_address_field_widget' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'settings' => array(
        'size' => 60,
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_NONE,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_properties_alter().
 */
function my_address_field_field_widget_properties_alter(&$widget, $context) {
  $widget['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
}

/**
 * Implements hook_field_formatter_info().
 */
function my_address_field_field_formatter_info() {
  return [
    'my_address_field_default' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ],
  ];
}

/**
 * Implements hook_field_widget_form().
 */
function my_address_field_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $widget = array();
  $widget['label'] = array(
    '#title' => $instance['label'],
    '#theme' => 'form_element_label',
  );
  $widget['address_line_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 1'),
  );
  $widget['address_line_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 2'),
  );
  // more text fields here ...

  return $widget;
}

Including defining hook_field_validate which I thought it'll override default field validation handler, but this was not the case.

What's the right way of assigning unlimited cardinality for my widget?

You can use Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

This module allows the cardinality of specific instances of fields to be overridden.
This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.


How to display default value of disabled form elements after failed validation? I have a form with some disabled form elements. When the form fails validation and is sent back to the user, the disabled fields are empty. How can I make the disabled fields display the default values that were originally defined in the form?

function foo_form(&$form_state) {
  return array(
    'foo' => array(
      '#type' => 'textfield',
      '#default_value' => 'foo',
      '#disabled' => true,
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => 'Submit',
    )
  );
}

function foo_form_validate($form, &$form_state) {
  form_set_error('submit', 'You cannot submit this form');
}

In this example, when the user presses the Submit button, the expected warning is displayed, but the text field is empty. This is most disturbing for the user, he does not know that all relevant information to process the form are still present.

$form_state['values']['foo'] is empty, but that's expected because disabled HTML elements are not included in the HTTP request that submits the form. Setting $form_state['values']['foo'] to the desired value in the validation function does not help.

The function that builds the form array isn't expecting any params unless you set a param in your hook_menu for instance. Instead you could try to grab the $form variable in the validation handler by reference and setting the value.

function foo_form() {
  return array(
    'foo' => array(
      '#type' => 'textfield',
      '#default_value' => 'foo',
      '#disabled' => true,
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => 'Submit',
    )
  );
}

function foo_form_validate(&$form, &$form_state) {
  $form['foo']['#value'] = 'bar';
  form_set_error('submit', 'You cannot submit this form');
}

This is untested as I have no running Drupal 6 instance at the moment. But I was able to do so using Drupal 7.

Another approach would be to use #value instead of #default_value since you already got your custom validation handler to put some extra logic in (get rid of the form_state value).


Hide block on specific page through custom contextual link We usually require to hide some blocks on specific pages for which we need to goto configure block page and add the URL of the page where we do not want to display a block.

Instead of going to configure block page, I want to add a contextual link " Don't display on this page"

which should add the path of the current page in the list on which the block should not appear.

You can use context module which has good number of contextual filters that can be used dynamically to display/hide a block.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.


file_usage_add: custom type for my module I have a custom calendar module I've created. When a user creates an event they have the ability to attach a thumbnail image to it. I'm trying to make it use the managed_file type. In the documentation it appears I need to use file_usage_add to keep it from throwing an error. The problem is I'm not sure what to put in the 'type' and 'id' parameters. The documentation lists these required parameters:

$file: A file object.
$module: The name of the module using the file.
$type: The type of the object that contains the referenced file.
$id: The unique, numeric ID of the object containing the referenced file.

$file and $module are easy. However, this module doesn't create a node or anything else. I have my own table structure for this information. Is there a way to define my table that events get stored in as a 'type' and pass that with the unique id from that table?

Yes, type just needs to be something unique within your module's types of file usage. The value of the string itself is arbitrary.

So if you have a module which stores pictures of cats and dogs, and you want to address those two different types of usage separately, you might use (contrived examples obviously):

$cat = MYMODULE_load_cat('whiskers');
file_usage_add($file, 'MYMODULE', 'cat_pictures', $cat->id);

$dog = MYMODULE_load_dog('fido');
file_usage_add($file, 'MYMODULE', 'dog_pictures', $dog->id);

But the type for those could just as easily be cat_foo and dog_foo, all that matters is that you (the module developer) know what they are, so they can be used appropriately with file_usage_delete().


No release history was found for the requested project When I try to download registry_autoload via drush dl registry_autoload I get this error:

  No release history was found for the requested project

Is this an issue with the module's .info file, or something I'm doing wrong? How can I get this module using Drush, and if that is impossible can I just download and install the latest release? I don't want to install it if there's an error with the code.

According to release updates.drupal.org, the module has release candidates for Drupal 7.x as per:

https://updates.drupal.org/release-history/registry_autoload/7.x

So try the following suggestions:

Make sure your IP is not blocked by going to https://updates.drupal.org/
Make sure your Drush recognise your Drupal root as 7.x (check drush status) and whether Drush can access the above endpoint by:

drush ev 'echo file_get_contents("https://updates.drupal.org/release-history/registry_autoload/7.x");

There could be a case that you are behind the firewall or corporate proxy, therefore the certificate could be not valid, so you'll have to configure your PHP's curl library either by importing the right certificate and mark it as trusted, ignoring it (not recommended) or use the non-secured connection to check for the new releases.


sql error when installing a module after enabling raydash module the message appear
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned NOT NULL COMMENT 'The session id foreign key',tokenVARCHAR(32) NOT' at line 4: CREATE TABLE {raydash_stream} (nidINT unsigned NOT NULL auto_increment COMMENT 'The table for the stream',entity_idINT unsigned NOT NULL auto_increment COMMENT 'The entity in the video stream that\ncoresponds to the token',session_idVARCHAR(128) unsigned NOT NULL COMMENT 'The session id foreign key',tokenVARCHAR(32) NOT NULL,connected_tokenVARCHAR(32) NOT NULL COMMENT 'The token this video-stream is connected', PRIMARY KEY (nid,entity_id,session_id) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'The table stores video stream'; Array ( ) in db_create_table() (line 2684 of C:\xampp\htdocs\drupal\includes\database\database.inc).
How to fix it?

The Raydash module (if it's this one) appears to be a sandbox project that isn't even hosted on Drupal.org.

Sandbox projects are not suitable for production use and usually have a number of bugs; this is what makes them sandbox projects rather than real modules on Drupal.org.

Also, the Raydash module I linked to only had one commit a year ago.  Drupal 7 has changed some since then so it's unlikely that this module would still work "out of the box" if it ever did.

I would disable the module for now and either:

Consider forking the module and fixing it yourself (giving back the patches if you succeed) or

or

Looking for a different solution.


Building a simple render array and rendering it I'm trying to render a render array. This render array will be configurable through a UI.

For some reason, I'm unable to render it.

I've isolated the issue so we can replicate it quickly.

Here's the render array:

$render_array = array(
  '#type' => 'html_tag',
  '#tag' => 'h1',
  '#attributes' => array('class' => 'title'),
  'children' => array(
    array(
      '#type' => 'link',
      '#title' => 'Link title',
      '#href' => 'Link URL',
      '#attributes' => array('class' => 'inner'),
    )
  )
);

$html = render($render_array);

debug($html);

The result of this is:

<h1 class="title" />

I tried many possibilities, tested multiple things... but it won't work.

I also searched the API and found this comment and the example in the comment is pretty much the same as mine... but it won't work either.

Is there an easy why to build a complete HTML structure with a render array ?

I could use '#theme' => 'link' but it's not advised, see this thread.

Anyone got a clue ?

Thanks!

Edit1: I opened an issue on Drupal.org which is a workaround to get this fixed.

I believe "children" needs to have a "#" ... You could also try using #value instead of children


8.4 - Use entity browser in a module block from in same way as I would in a custom block I am having trouble adding an image picker to a block form defined in a custom module.

If I create a custom block type I can define an image field as entity_reference and in the block's form view tell it to use entity_browser and media_entity_browser.  This provides me with an picker with which I can select my image:

I am trying to recreate this in a block provided by my custom module, without much success

// /src/Plugin/Block/MyCustomBlock.php

function blockForm($form, FormStateInterface $form_state)
{
    ...

    $form['image'] = [
      '#type' => 'entity_browser',
      '#entity_browser' => 'media_entity_browser',
      '#title' => $this->t('Image'),
      '#default_value' => $this->configuration['image'] ?? null,
      '#weight' => '0',
    ];

    ...
}

This gives me the following.  Note the lack of the bounding box, title and option to edit remove items:

Exporting the configuration files for the working form view gets me this:

// core.entity_form_display.block_content.lead_block.default.yml

...

field_image:
    weight: 1
    settings:
      entity_browser: media_entity_browser
      field_widget_display: rendered_entity
      field_widget_edit: true
      field_widget_remove: true
      selection_mode: selection_append
      field_widget_display_settings:
        view_mode: default
      open: false
    third_party_settings: {  }
    type: entity_browser_entity_reference
    region: content

 ...

But if I try and use 'type' => 'entity_browser_entity_reference' in my blockForm function the field disappears altogether.

Looking into various core files I can see that entity_browser is a @FormElement and entity_browser_entity_reference is a @FieldWidget but I don't really understand the difference.

As you might guess I am fairly new to Drupal and I feel like I am missing something fundamental.  I (think I) understand that custom block types are actually nodes internally and that they are subject to different rules to blocks which I define in my custom modules, but I don't fully grasp what the differences here are.

Is is it possible to use the entity browser in my custom module block form in the same way as it is used in the form which I build through the admin's custom block type builder?

Thank you.

No, this is not possible. Block forms in a block plugin are configuration forms and here you can only use Form API fields.

  I (think I) understand that custom block types are actually nodes
  internally and that they are subject to different rules to blocks
  which I define in my custom modules, but I don't fully grasp what the
  differences here are.

Custom blocks are not exactly nodes internally, it's very similar, custom blocks and nodes are both content entities. This doesn't change the rest of what you found out correctly. You can use entity fields and their form elements, widget and formatters only for content entities.