Drupal cannot write to /tmp folder My Drupal 7 website has no layout (CSS and JS is messed up) and is getting the following error message:

  The specified file /tmp/filestW97L could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

The /tmp/ directory at the root level has 777 permissions. I think the directory the error message is referring to, as there are files with similar names in it. I'm puzzled as to why Drupal cannot access that directory.

It does have 80,000 files in it. Could it be too full?

I'm assuming that /tmp/ is the "destination directory". Am I correct?

I'm on a VPS running Centos. The VPS has plenty of resources and I tried rebooting it in case that might help.

I don't think I did anything to cause this error, as it happened when I was not working on the website. Is it possible that a CPanel update from the past several days did it?

I cannot read the system log, as the admin user cannot log in (I get blocked by an anti-spam module that requires JavaScript enabled). Is the system log the same thing as the watchdog table?

I fixed the problem.  I did several things.  I think flushing the drupal cache was the solution that worked, but I am not 100% certain.

CSS and JS are stored in files/ folder. This folder must writable in order for Drupal to store the aggregated files.


TemporaryStreamWrapper error during installation In continuation to my previous question https://drupal.stackexchange.com/questions/208245/openatrium-installation-profile-error

I have another problem in the very next step i.e. during Site Configuration.

Firstly the theme seems to have broken because CSS is not being applied.
Secondly, I'm getting the error message.

"Warning: file_put_contents(temporary://fil3BF3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1936 of \includes\file.inc).

•The file could not be created."

I understand from some other posts that this is due to missing permissions on "sites/default/files" folder. But this folder is created on the fly during installation how do we give access to it.
In addition, I believe another possible cause can be due to permissions to "tmp" folder. Most of the other posts mention changing that path in "Admin -> configuration" somewhere, but for that OpenAtrium needs to be completely installed. Where can I change the path for "tmp" file through file system.

Appreciate a reply.

Where can I change the path for "tmp" file through file system.

You can set the tmp path by appending the following line in the site settings.php

$conf['file_temporary_path'] = '/tmp';

In Addition, all item stored in variable table in Drupal site's database can be set with $conf array in the same way.


Why AJAX does not change field's value? I wrote simple code:

function rah_cc_generate_form($form,$form_state){
    $form=array();

    $form['gen']=array(
        '#type' => 'fieldset',
        '#name' =>t('generate gift card code'),
        '#collapsible' => TRUE,
        '#collapsed' => false,
//        '#weight' => 5,

    );
    $form['gen']['code']=array(
            '#type' => 'textfield',
            '#title' => t('gift code'),
            //'#default_value' => '',
            '#prefix' => '
',
            '#suffix' => '
',
            '#size' => variable_get('rah_gc_code_size', 8),
            '#maxlength' => 20,
            //'#required' => TRUE,
    );
    $form['gen']['price']=array(
            '#type' => 'textfield',
            '#title' => t('price'),
            '#default_value' => 10000,
            '#size' => 10,
            '#maxlength' => 20,
            '#required' => TRUE,
    );

    $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      ),
   );

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

    return $form;

}
function rah_cc_generate_ajax(&$form,&$form_state){

    $form['gen']['code']['#value']=33;
  return $form['gen']['code'];

}

but it doesn't work: textfield is not replaced by the one that has value 33.

There is no JS error and AJAX request returns HTTP code 200.

There are several problems with your code:

Your AJAX callback should return a form element. Now it returns plain 33.
All changes should be made inside form building function, in your case rah_cc_generate_form. Simply add condition to test $form_state['triggering_element'] and perform action if it was your AJAX trigger. Do not alter things in AJAX handler, it's not what it is for. I know it's counter-intuitive, but that's the way it is.
Changing default value once there is some user input will have no effect. Maybe you should try to change appropriate entry in $form_state['input']? But that depends on your intentions.


Adding create, edit, delete link of referenced entity in same content type How could we interconnect referenced entity in one content type so that we can search, create, edit, delete the referenced entity on the same content page.
In drupal 7 "references_dialog" module was fulfilling the requirement but now in drupal 8 what is alternative of that module.I think references_dialog is now no more maintained by developer for Drupal 8. I already know that inline_entity_form is there but i want some module which open every thing in modal window pope up like reference dialog does.

Any module or code suggestion will be great.

You want a combination of inline_entity_form and Entity browser.

It's possible to create different browsers that consist of one or multiple views, dropzonejs upload forms (with the dropzonejs module), you could also integrate it with a create form I guess but there's no integration for that yet I think (within the entity browser, which is why you can use Inline Entity Form for that part directly in the widget9.

Entity browser doesn't have a UI yet to create browsers, but you can look at the provided demo module and adjust it to your neeeds.

Another example is the File Browser project. That uses an inline iframe, and not a dialog. And it's specifically for managing files/images.


sending query results via email if this is my function:

<?php
//dsm($query);

function customstatsB_menu() {
  $items['customstatsB'] = array(
    'title' => 'Maestros Inactivos + email',
    'page callback' => 'customstatsB_all',
    'access arguments' => array('access customstatsB content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}
/**
* Valid permissions for this module
* @return array An array of valid permissions for the customstats module
 * No repetir permisos, este es únicamente un modulo, y cada query NO necesita permisos. PERMISOS A NIVEL MODULE x ROL.
 */

function customstatsB_perm() {
  return array('access customstatsB content');
} // function customstats_perm()

//return array('access customstats content', 'administer customstats');

function customstatsB_all() {

/**
 * MAESTROS INACTIVOS
 */

$query = "
SELECT name, status, rid, mail
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@hotmail.com'
AND users_roles.rid =6
AND users.status =0
";

  // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    //$page_content .= l($links->name, 'node/'.$links->mail) . '
';
    $page_content .=
    l($links->name, 'mailto:'.$links->mail) . '
';
  }

  // check to see if there was any content before
  // returning the page
  if ($page_content == '') {
    // let the user know there is no content to show
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}

return array('access customstatsB content', 'administer customstatsB');

/**
 * Email configs
 */

function customstatsB_mail($key, &$message, $params)
  {
     $params = array(
        'subject' => t('SQL Results Tester'),
        'body' => t("Body of the email goes here"),
      );

      drupal_mail("customstatsB", "customstatsB_normal_mail", "my@mail.net", language_default(), $params, "admin@mysite.com");
      drupal_mail("customstatsB", "customstatsB_html_mail", "my@mail.net", language_default(), $params, "admin@mysite.com");
  }
      $language = $message['language'];
      switch ($key)
      {
           case 'customstats_normal_mail':
              $message['subject'] = t($params['subject'], $var, $language->language);
              $message['body'][] = $params['body'];
              break;
          case 'customstats_html_mail':

              $message['subject'] = t($params['subject'], $var, $language->language);

               $body = "

HTML Email Sample with Drupal

                  {$params['body']}
                  ";
              $message['body'][] = $body;
              $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
              break;
      }
  }

and I am using hook_mail and drupal_mail to send an email, how should I insert the query results into the body of the mail?

Also, I have created pagecallbacks customstats1 to customstats15 via hook_menu and I need to send indivual mails when users visit each page independently. I have read a few tutorials but I haven't been able to do this.

Thanks in advance for your help.

You need to invoke hook_mail() to specify a 'body' parameter. It is a little confusing since it is two steps but well documented: http://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal_mail/6

See 'example_notify()' and 'example_mail()' from the above link.

In your case yo need to call drupal_mail outside of your invocation of hook_mail. See below for an example. You can pass the body as in the $param when you call drupal_mail or you can edit it when you invoke hook_mail.

Be advised that this is not the best example since it would fire off an email any time somone visited that page, but I'm not sure where you are trying to call drupal_mail from:

$query = "
SELECT uid
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@mail.com'
AND users_roles.rid =6
AND users.status =0
";

 // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    $account = user_load($links->uid);
    $body = t('Message for %name', array('%name' => $links->name));
    $subject = t('New email!');
    $params = array('body' => $body, 'subject' => $subject);
    drupal_mail('customstats', 'html_mail', $account->mail, user_preferred_language($account), $params);
    $page_content .= l($account->name, 'mailto:'.$account->mail) . '<br />';
   }

  if ($page_content == '') {
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}


Order Status is Pending after Paypal Payment I created an order with weekly or monthly subscription. User can purchase the subscription only through paypal.

If a user purchase the subscription he redirected to paypal site. After successfully payment the order is created. But the order status showing pending. It should be completed.

Recurring Module : UC Recurring Payments and Subscriptions

Payment Method - Paypal

(Edit) Problem was in Sandbox paypal Account. Api Credential (Password and Signature) was not there. I changed the merchant account Api Credential.

After changed the api credential same problem occured with changed account. What to do?

Ubercart does not make orders completed on it's own. It seems to be a well known problem, already discussed on stackoverflow and on ubercart.org. It seems manually setting up Conditional Actions is a must in most cases.


How do I specify the debug_mail_directory for the devel maillog? In settings.local.php, I have set my local dev environment to use the Devel module's mail logging function:

 $config['system.mail']['interface']['default'] = 'devel_mail_log';
 $config['devel']['settings']['debug_mail_directory'] = "???";

The DevelMailLog documentation says that:

  Filename pattern controlled by 'debug_mail_file_format' config setting.

What do I put for the filename pattern?  I have tried several patterns:

public://devel_mail
private://emails
sites/default/files/devel

But none of these work.  I checked watchdog, but apparently devel mail doesn't leave any logs.

NOTE 1: There is a note in the docs that config settings are broken, but the linked issue is already fixed.

NOTE 2: By default, when I enable devel and export the config, the value for debug_mail_directory is temporary://devel-mails, but I don't want to store them in the temporary directory; I want to store them in the Drupal files directory if possible.

You should use

$config['devel.settings']['debug_mail_directory'] = 'private://mydirectory';
$config['devel.settings']['debug_mail_file_format'] = 'mypattern-%to-%subject-%datetime.mail.txt';


How do I iterate over values of a multivalued field with entity_metadata_wrapper? For instance, I have a taxonomy_term_reference field with cardinality -1. If one or more terms are selected, I can use this code:

  foreach ($wrapper->field_myterms as $t) {
    $terms[] = $t->name->value();
  }

But if the field has zero values selected, this code throws:

EntityMetadataWrapperException: Unable to get the data property name as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 442 of sites/all/modules/entity/includes/entity.wrapper.inc).

This happens in a preview form step while creating a custom entity. The entity has not yet been saved but I am showing a preview of the properties and field data by creating a temporary entity with this code:

$entity = entity_get_controller('ams_survey')->create($form_state['values']);
$wrapper = entity_metadata_wrapper('ams_survey', $entity);

The problem is in this file: /sites/all/modules/entity/includes/entity.wrapper.inc

Whenever a field_foobar->value() is called, and the field isn't set, then the class throws an Exception.  That is just silly, because having an empty field isn't an error.

Inside that field, when checking to see if a field is empty, it uses this code:

$data = $this->dataAvailable() ? $this->value() : NULL;

But using "if ($wrapper->field->foobar->dataAvailable())" before each echo of the value is aggravating.  Sigh, why can't things in Drupal ever be simple?


Varnish has no SSL support; then what to use? As the developer of Varnish, Poul Henning, wrote back in 2011 on https://www.varnish-cache.org/docs/trunk/phk/ssl.html and again this year on https://www.varnish-cache.org/docs/trunk/phk/ssl_again.html Varnish has and will have no SSL support.

If this is true for Apache servers (note  https://www.digitalocean.com/community/tutorials/how-to-configure-varnish-cache-4-0-with-ssl-termination-on-ubuntu-14-04 has instructions on how to configure both on Nginx), then I wonder what are Varnish alternatives for Drupal sites that need to be running through HTTPS (like, for example, Drupal Commerce sites)?

Content delivery platforms like CloudFlare and Fastly offer a wide range of SSL/TLS options. The question is, what are you trying to accomplish? Note that Varnish really won't do you any good for high transaction-volume sites because you're dealing with authenticated traffic. However, services like the ones listed above can be useful for delivering assets or for serving anonymous traffic.


Create a menu that expands on click I want to create a menu that expands on click . ( For example, facebook, gmail, twitter all have menus at the top right where onl click the we get account settings , log out etc.)

What is the best way to do this in drupal? Is there any module for this or do I need to do it in theme?

Also, is there any special name for such menus?
Thanks!

Which drupal 6/7 ?
See here http://www.pixelclever.com/custom-drupal-themes-drupal-5-and-drupal-6
and this JQuery menu module.

Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.

Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don’t use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.


Apply condition on particular template I have a template name page--catalogue.tpl.php, I need to add style sheet only for this template. Below is my snippet in my html.tpl.php which only adds class to a particular node whereas I need to add to a whole template. Is there any way?

<?php
if (strtolower ($_GET['q']) == "node/287")
{
?>
<link rel="stylesheet" type="text/css" href="sites/default/files/engine1/style.css" />
<?php
}
?>

OPTION 1:

If it's a small amount of CSS, maybe considering making your CSS selectors based on the node and including the css in your theme's CSS? Drupal 7 provides the body.page-node-NODEID selector.

OPTION 2:

You could have a look at the Code per Node module. It is also featured in this blog post.

  Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

OPTION 3:

For adding css file to specific content type, you may use this snippet;

function MYTHEME_preprocess_node(&$variables) {
  if(!empty($variables['node'])) {
    if($variables['node']->type == 'my_custom_content_type')
      {
       drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
      }
  }

}

OPTION 4:

If you want to add css to specific node then you may use this;

MYTHEME_preprocess_node(&$variables) {
  if ($variables['node']->nid == 3) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
   }
}


Module for creating "entity edit" form? Is there a module that will take an entity machine name and optionally id as input, and generate a suitable edit form as output?

If you want to create or edit a reference entity in a node add/edit form then you can use Entity Connect module.

If you want to have a separate page which will take an entity machine name and optionally id as input then you can have a look at the code in this module and build on that.

You may also take a look at Inline entity Form


Show relationship summary using Entity Reference First question, hope I can get some answers. I have this information schema:

Books: Title and Author (Entity Reference field to Books content type)

Author: Name and Books (Entity Reference field to Author content type)

I created a view to show the authors with their ID's. I want to also show in the Books field the ID's for the books that reference them. I already created the relationship and turned aggregation on and asigned it to the books field. The view looks like it's working and aggregation also seems to be working, however, no results are showing in the books field. Any ideas?

I'll appreciate any answer. Thanks!

First off, you only need an entity reference field on the content type Books that points to Author in your example. It would be a pain in the long run to manually maintain the two relationships and all data needed to describe your relationship is given in the Book->Author field.

Now let's create a View that lists books.

(I've removed the second column in the screenshot from Views as no settings were done there)

Add the entity reference relationship under Relationships.
Add Content: title and use your relationship.
Under Format and Settings, set group by to the Content: Title field you created in the step before.

Now all books are listed and grouped by their author.

In my example I also sort by the authors name. If you rather show the Nid of the content, just switch from Content: Title to Content: Nid.


Multiple Date Argument Values with One Contextual Filter I have a pretty simple view in D7:

Fields

nid
title

Contextual Filters

nid
date (from date, monthly granularity)

Now I'd like to fetch some results for a specific node, but across multiple months. I was hoping to be able to pass in the contextual filter arguments via the url like so:

123/201302+201303

This isn't working for me though. Is this even possible with Date fields in Views ? I heard it was only possible with term ids right now.

Are there other techniques to accomplish this? Perhaps hook_views_query_alter() is in order here.

Try with the following method using views_embed_view():

views_embed_view('viewname', 'display_name', array(123,'201302+201303'));

Or by using a hook_views_query_alter and modifying the where condition to span across both months.


hook_form_FORMID_alter select list default value I created a custom module to override some fields in an exposed form created by views. One of the filters is the between filter on a number field. The between filter produces min and max fields for every field in the form. What I want to do is replace the min and max text fields with lists of integers that the user can select from. Where I am stuck at is the default value of the lists. I keep getting the following message:
"An illegal choice has been detected. Please contact the site administrator."
Below is a snippet from my module file:

$sale_price_min_options=array(
  'All'=>t('-Any'),
  10000=>'10000',
  20000=>'20000',
  30000=>'30000',
  40000=>'40000',
  50000=>'50000',
  60000=>'60000',
  70000=>'70000'
);

$form['field_sale_price_value']['min']=array(
          '#type' => 'select',
          '#options' => $sale_price_min_options,
          '#default_value' => "",
      );
      $form['field_sale_price_value']['max']=array(
                '#type' => 'select',
                '#options' => $sale_price_min_options,
                '#default_value' => 70000,
            );

Please let me know where did I go wrong. Many thanks in advance

Change 'All' to ''. The key should be blank. The default value is not matching the option list.


Config webform for read It is posible config webform for read but not submmit?
I need that anonymous user see webform but only authenticated user can send.

If you customize your submit buttons, you can set up access controls that only allow authenticated users to see the submit buttons.

@see https://www.drupal.org/project/webform/issues/2983024


Searching for a user details (including custom fields) in People Administration Page I want to search people on my people page in admin. I searched around and found this great plugin :-

User search to People Admin - This helps me search user through their email, usernames perfectly.

The only problem is that I want to search users through additional User fields I added later into the admin. As an example, each person has a Full Name as a custom field but this module is unable to search through it.

Any idea how I can achieve that?

Thanks

I recommend using Views.  With this you can create a searchable, sortable and filterable display using any format you desire, and including any fields you want.

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.


Send mail to email addresses from webform when a content is saved I want exactly like this Send notification e-mail after new content was added but the answer is not seems to be question specific. I have a webform where I get email id of the anonymous users and I want to send email to those ids when I save a new content.

I have combined Rules and webform rules for it. I created an

event
-After saving new content

Condition
-Content is of type

Actions
-Fetch webform submissions of node ID n

Loop
-fetched submissions

loop action
-Send mail.

But i am stuck to move forward as I am not able to configure 'TO' field with email fields from fetched submissions.

Enabled the PHP filter module and the list item is available in the PHP evaluation area. So fetch the email is as <?php print $list_item->data['component_id']['value'][0]; ?>. Works pretty well :)


Custom Module Separate Settings for Each User I am working on a custom module. I am currently using system_settings_form to enter an API key and it works fine. However, I need users to be able to enter different api keys. What is the best way to do this?

You need to create module with .install file that would help you to create custom table where you can store individual user API key. I am sharing with you some code to achieve this. It should be something like that. Rest your code will be same you just need to make some minor changes like use return $form instead of return system_settings_form(). You also need to write hook_form_submit() function.

Module Name: custom
1. custom.install

/**
 * Implements hook_install().
 */
function custom_install() {
    // Create tables.
    drupal_install_schema('custom_table');
}

/**
 * Implements hook_uninstall().
 */
function custom_uninstall() {
    // Drop tables.
    drupal_uninstall_schema('custom_table');
}

/**
 * Implements hook_schema().
 */
function custom_schema() {
  $schema = array();
    $schema['custom_table'] = array(
        'description' => 'Stored user api key',
        'fields' => array(
          'id' => array(
            'type' => 'serial',
            'not null' => TRUE,
            'description' => 'Primary Key: Unique ID.',
          ),
          'api_key' => array(
            'type' => 'varchar',
            'length' => 256,
            'default' => '',
            'not null' => TRUE,
            'description' => 'Store api key',
          ),
        ),
    'primary key' => array('id'),
  );
  return $schema;
}

custom.module

/* Submit hook function for submission form. */
function custom_form_submit($form, &$form_state) {
  // insert your api key in your custom table using db_insert() function or you can use db_merge() for both insert/update operation.
}


Internal/External JS don't work with Drupal, but works fine in static HTML/JSFiddle Continued from here Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal

Working JSFiddle: http://jsfiddle.net/tbq8eo8b/10/ (it calculates total, in Drupal it calculates zeros - why?)

Raw:

$(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});

Drupal:

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

/*Add your js code here */
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);

2nd attempt with internal Drupal:

  <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
  <script>
  $(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/^\$(\d+)$/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});
  </script>

As you see the code is identical (except Drupal wrappings), so why it's not working on Drupal? Why it prints zeros in .total field, but in JSFiddle it works fine?

I've rebuilt the scenario and my guess now is that you don't want the value of the select field but the option text for your parsing purpose. Thus, the script should probably be something like this:

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

    /*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
          var val = $("#"+this.id+"  option[value='"+this.value+"']").text().match(/\$(\d+)/);
          total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);

This is how it looks like working:

This is how the first select's options are setup as a webform component

To retrieve prices, one would need to change the regex line to

var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d+(\.\d{2})?)/);

Working example:

To have the total always be display with trailing zeros, replace the last script line with

$(".total").val(total.toFixed(2));

To make the script also work with thousands separator, change the script into

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

/*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
                var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d{1,3}(,\d{3})*(\.\d{2})?)/);
                        total += val ? +parseFloat(val[1].replace(/,/g,'')) : 0;
        });
        $(".total").val('$'+total.toFixed(2));
    });
}
};
})(jQuery);


How to order a database query In Drupal v7.22 I'm trying to order the query below for a custom module but I cannot seem to find documentation that fits this query.

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));
$num = $result->rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}

I've found details on 'orderBy' but only with examples as below which are not in the same format as my query. Any help would be appreciated.

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();

Something like:

$query = db_select('tablename');
$query->fields('tablename', array('field1', 'field2'));
$query->condition('field3', $var1);
$query->condition('field4', $var2);
$query->orderBy('field1', 'DESC');

$result = $query->execute();

foreach($result as $row){
  // Debug
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

More info:

https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7
https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AorderBy/7


hook_views_data Join by multiple value field I need retrive data from a custom table in drupal db by a colum that match with a drupal field in a content type.

I have this table:
equipages
id_equipage|description|price|status

The id_equipage is a varchar and is unique.records example:
cliowave123abs|ABS of my Renault Clio|150|1
cliowave123oth|Some other option of my Renault Clio|10|1
cliowave123air|Air cond of my Renault Clio|250|1
meganeliveabs|ABS of my Renault Megane|310|1

Now I have a content type called car whit a text field equipages (table field_data_equipages) with unlimited values.
In this field I add all the id_equipage of the car.
So for example I have a node (nid: 5) like this:
Title: Clio Wave 2013
equipages:
1. cliowave123abs
2. cliowave123air

Now, When I read the node (nid: 5), I want retrive the 2 records from my custom table
cliowave123abs|ABS of my Renault Clio|150|1
cliowave123air|Air cond of my Renault Clio|250|1

Can I do this whit the hook_views_data()??

Can you help me?!

Thanks!

I believe this https://www.drupal.org/node/810932#comment-3020000 comment describes exactly what you need which is the extra field in a join description:

$data['node']['table']['join'] = array(
  // this explains how the 'node' table (named in the line above)
  // links toward the node_revision table.
  'node_revision' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'extra' => array(array('field' => 'fieldname', 'value' => 'value', 'operator' => '='))
 ),

);


How do I programmatically export all webform submissions into a single csv? (multiple webforms) I have hundreds of webforms created from a single webform template. How do I programmatically export all webform submissions into a single csv? Note that this is not possible via views out of the box. One would have to create [webform_mysql_views.] (Combine Webforms to export multiple form results in a single CSV) This doesn't seem efficient.

As per your comment that you are interested in "an alternative to creating such CSV file programmatically": have a look at the Forena module (without using Views. Forena can do exactly what you're asking for (so no need for "programmatically").

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example that I sometimes use for some testing:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Then create a Forena "report" that uses this data block, and make sure that within "document types" you enable the "CSV" option. Here is the (basic) layout of such report to illustrate the idea:

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

After you saved the report and browse it, you'll have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for.

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

Disclosure: I'm a co-maintainer of Forena.


Configuring View output with multiple related nodes Real world: Our not-for-profit holds monthly meetings. At each meeting, zero, one, or two people can present.

My site has:

Content type Presenter with fields Name and Description
Content type Meeting with field Date, Topic, and Node Reference (which will allow a maximum of two entries)

I created a View to show the meeting information. What I would like to see is this:

Meeting Date
Meeting Topic
Presenter 1 Name
Presenter 1 Description
Presenter 2 Name
Presenter 2 Description

What I am currently seeing is this:

Meeting Date
Meeting Topic
Presenter 1 Name
Presenter 1 Description
Meeting Date
Meeting Topic
Presenter 2 Name
Presenter 2 Description

I have tried several things to fixed this: Grouping, SQL Distinct (via Advanced->Other->Query Settings), and others, but so far, nothing has worked. This seems like something which should be easy to do - but I have yet to find the proper incantation.

Please help.

Have you tried grouping by the node id (the same node id used in the node reference)?


Drupal Webform is sending emails but there are no values The email that my webform is sending only has this... no actual values as entered into the form?

Submitted values are:
[submission:values]

Please help!

In the Webform configuration under advanced settings to configure the general Webform settings go to admin/config/content/webform

Advanced settings : Check off Allow tokens to be used in Webforms


Weird problem in calculating sum of two computed field values as another sum I have created one content type having fields like A,B,C,D,E,F,G. I have used computed filed module to compute these fields like the following. (Used filed group module to group some A&B in first group, C&D in second group , E,F,G are in third group.
Here are the computations

A*C=E

B*D=F

E+F=G WHERE E,F AND G are computed fields .

The problem is when I submit the content type first time I am able to get E and F values but not G and if I edit the node and submit the result of G(E+F) is displaying correctly.

Here is the code snippet used to computed fields

$entity_field[0]['value'] = $entity->field_a['und'][0]['value'] * $entity->field_c['und'][0]['value'];

$entity_field[0]['value'] = $entity->field_b['und'][0]['value'] * $entity->field_d['und'][0]['value'];

$entity_field[0]['value'] = $entity->field_e['und'][0]['value']+ $entity->field_f['und'][0]['value'];

Display Output

$display_output= $entity_field_item['value'];

We tested the same scenario in Articles content type with field groups which shows all the results at a time i.e E,F and G.

I am getting errors on first submit.

Notice: Undefined property: stdClass::$field_e in eval()

Notice: Undefined property: stdClass::$field_f in eval()

What would be the problem?

I think this suggestion works

Go to the computed filed settings of G. Uncheck "Store value in the database" option might solves your problem. (If not necessary to store)


Why isn't Drupal aggregator configurable? I am trying to display the RSS feed of this page: http://groups.yahoo.com/group/actventurers/, on a drupal website.

I have the aggregator module enabled, but when I go to /admin/config/services, only RSS Publishing is available.

Any ideas as to why it won't allow me to add any feeds?

Use Feeds, it's import or aggregate RSS/Atom feeds to Drupal.


Retain CKEditor styling I am using CKEditor for client side text editing.
All works fine. I see the content styled correctly
when node is saved.

The problem begins when the node content is added
to a view. The text styling font boldness is retained but the spacing options like indents are overridden
by the view settings.

What I wish to do is to retain the CKEditor styling
for the entire view display.
Is there are option in Views to achieve this?

By default the text format filter "Limit HTML tags" will strip out "style" attributes in your HTML.  You can't configure this via the admin but you can replace the filter with WYSIWYG Filter and configure that to allow specific styles whilst still filtering out dangerous HTML.  The settings are found at /admin/config/content/formats/filtered_html (or replace "filtered_html" with the name of any other text format you need to alter).  See this issue for pointer as to how best to set this up.

Please note though that if you're not sure what you are doing here then you may compromise the security of your site by setting up WYSIWYG Filter in a less than ideal way.


Enable field inside Manage Display from a .yml file When I create a field field.field.node.custom.body.yml in my custom module with the following code:

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.customblog
  module:
    - text
id: node.customblog.body
field_name: body
entity_type: node
bundle: customblog
label: Body
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

The Body field is created and added to the appropriate CT when installed, but is set as disabled in the manage display. This seems to be default behavior. I would like the field to be enabled as the module is installed through the use of .yml files, is this possible?

There is a single config entity per entity_type, bundle and view/form mode. If you fully control that, then you can provide those config entities, if you just add a single field to something existing, you need to use the API to add your fields configuration to it.

See core.entity_form_display.node.article.default.yml in standard.profile and various others for examples.


Store field values in a JSON file? I'm building a booking calendar module, and want to get back arrival & departure datefields values to highlight reservations on the calendar, passing to a library the variables.

public function showCalendarAction() {
        return [
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.popperjs']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap_year_calendar']],
            '#markup'=>$this->t('

')
        ];
    }

I intended to store all the dates(linked to one hotel/house) in a json file, that I would call in ajax.

If it's a good Drupal 8 practice, how to do this ?

Else, what would be the good way to store and pass the variables to my module library ?

You could use the routing system and create a custom route and output your json within the controller.

After that you can load the url in your ajax call.

module.routing.yml (path_to_module/):

  module.content:
  path: '/json-output'
  defaults:
    _controller: '\Drupal\module\Controller\ModuleController::content'

  requirements:
    _permission: 'access content'

ModuleController.php (path_to_module/src/Controller/):

<?php

namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class ModuleController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function content() {
    // Load your json content here.
    $json = module_get_json();

    $response = new Response();
    $response->setContent($json);
    $response->headers->set('Content-Type', 'application/json');
    return $response;

  }

}

Now you can load your json via /json-output. It is also possible to pass variables to the controller via the url.


How do I theme the "The website encountered an unexpected error" page? How do I set the theme to use for the error page showing an unhandled exception like the one shown in this screenshot?

The errors in Drupal 7 handled by includes/errors.inc file, and the The website encountered an unexpected error. Please try again later. error use the maintenance_page theme see from includes/errors.inc

print theme('maintenance_page', array(
        'content' => t('The website encountered an unexpected error. Please try again later.'),
      ));
      exit;

So if you want to theme the error page, you theme the maintenance_page to do so take a look at Theming the Drupal maintenance page.


Drupal 7 website with landing page and two sections with different templates I need a Drupal 7 website with 2 sections..

for eg. www.example.com

One is Civil and the other is MEP.

Landing page with navigation to the below two sections:

section 1: www.example.com/Civil

section 2: www.example.com/MEP

Screen shots of the design:

Landing page:

Site -a

Site-b

The exact requirement is as follows:

/ = intro page

/site-a/ = menu and templates for site a

/site-b/ = menu and templates for site b

Separate layout and menu for these two sections.
How can we keep two layout for the two sections?
Is it a multisite? or just two sections?

Please suggest me a solution.

These sites look almost identical. In fact, I would say that given the pictures, the layouts are close enough to use the following templating strategy:

In Drupal, it's very easy to create a front page that will be your landing page. You will simply create a template file called page--front.tpl.php and put whatever html you want in here, exactly like you want to lay it out. This will be what people see when they come to example.com/

I know we keep calling these 'sites' but they are pages instead. Indeed 'site-a' and 'site-b' will be two 'Basic Pages titled 'Civil' and 'MEP'. In my mind these are so close I would simply have have one layout template (page.tpl.php) with the same regions, etc.  It looks like the only difference is in the content. So, to handle that I would use blocks and Drupal's default functionality to force blocks to appear on one page and not others.

So far you would have to templates - page--front.tpl.php for the home page and page.tpl.php for all other pages. In the event you indeed wanted to have a different layout for pages Civic and MEP you could even have templates for these. If Civic had a node ID of 3, for example, and MEP of 4, the template names would be page--node--3.tpl.php and page--node--4.tpl.php.  Please see the Drupal theming guide for more details.

Site-a menu and site-b menus:

You will have two menus created for site-a and site-b. There will be blocks for each in the Blocks section under structure. You will put both blocks in the same region (say, 'menu-region' if that's what you decide to call it). Then, edit one block to 'appear only on the following pages' and type in:

site-a
site-a/*

Then, edit the other block to 'appear only on the following pages' and type in:

site-b
site-b/*

Drupal will automatically know which menu to load. Also, each of these blocks will have their own css tags in the markup, so it will be easy to style them.

For the other sections, you would repeat the process - add all the blocks you need to appear in one regions, but edit them to show or not show based on what site (page) you are on.


Commerce Paypal WPP Sandbox: cURL error: SSL connect error EDIT: Appears it is related to this issue: https://www.drupal.org/node/2616730#comment-10782646 . Still awaiting a fix though, as the patch in the issue doesn't fix it for me.

Our staging site was successfully using the Paypal sandbox with WPP for taking payments. As of three days ago, with seemingly no changes it is no longer working. The front end returns the error: "We encountered an error processing your payment. Please verify your credit card details or try a different card." Under reports all it says is cURL error: SSL connect error. Any idea how to fix this?

EDIT: I've tried to add CA certificate as per these instructions:

  // Commerce PayPal requires SSL peer verification, which may prevent out of
  // date servers from successfully processing API requests. If you get an error
  // related to peer verification, you may need to download the CA certificate
  // bundle file from http://curl.haxx.se/docs/caextract.html, place it in a
  // safe location on your web server, and update your settings.php to set the
  // commerce_paypal_cacert variable to contain the absolute path of the file.
  // Alternately, you may be able to update your php.ini to point to the file
  // with the curl.cainfo setting.

But now I get the error cURL error: Problem with the SSL CA cert (path? access rights?). I've tried restarting Apache with no effect. Please help!

More info on the request below:

Message PayPal API request to https://api-3t.sandbox.paypal.com/nvp:

Array
(
    [METHOD] => DoDirectPayment
    [PAYMENTACTION] => Sale
    [NOTIFYURL] => http://website.com/commerce_paypal/ipn/paypal_wpp%7Ccommerce_payment_paypal_wpp
    [BUTTONSOURCE] => CommerceGuys_Cart_PPP
    [CREDITCARDTYPE] => Visa
    [ACCT] => XXXXXXXXXXXX0331
    [EXPDATE] => 032016
    [AMT] => 126.00
    [CURRENCYCODE] => USD
    [CVV2] => XXX
    [INVNUM] => 5355-1453684794
    [CUSTOM] => Order 5355
    [DESC] => 1x product
    [EMAIL] => test@test.com
    [IPADDRESS] => [IPADDRESS]
    [FIRSTNAME] => test
    [LASTNAME] => test
    [STREET] => test
    [STREET2] => test
    [CITY] => test
    [STATE] =>
    [COUNTRYCODE] => HK
    [ZIP] =>  -
    [USER] => pro_api1.website.hk
    [PWD] => XXXXXXXXXXXXXXXX
    [SIGNATURE] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    [VERSION] => 76.0
)

Ran this past some Paypal support personnel. They echoed both the author of the question and Nick in the comments.

Paypal reviewed the error and offered a link to this resource, which I will quote in part:

  PayPal is upgrading the protocols used to secure all external connections made to our systems. Transport Layer Security version 1.2 (TLS 1.2) and Hypertext Transfer Protocol version 1.1 (HTTP/1.1) will become mandatory for communication with PayPal in 2016. You will need to verify that your environment supports TLS 1.2 and HTTP/1.1, and if necessary make appropriate updates.

  PayPal is in the process of upgrading the SSL certificates used to secure our web sites and API endpoints. These new certificates will be signed using the SHA-256 algorithm and VeriSign's 2048-bit G5 Root Certificate. You will need to ensure that your environment supports the use of the SHA-256 signing algorithm and discontinue the use of SSL connections that rely on the VeriSign G2 Root Certificate.

  If you are using PayPal’s Instant Payment Notification (IPN) service, you will need to ensure that HTTPS is used when posting the message back to PayPal for verification. HTTP postbacks will no longer be supported.

Related Drupal.org Issue: https://www.drupal.org/node/2616730#comment-10782646

So, it seems, Paypal is upgrading lots of their security requirements for 2016. I highly recommend you investigate deeper with Paypal's support service to see if they can make a recommendation on next steps for you.


How do I apply an OR condition? I've got the below code

$query = \Drupal::database()
  ->select("excel", "e")->fields("e");
$group = $query->orConditionGroup()
  ->condition("grupindex", 1)
  ->condition("grupkodu", NULL);
$query->condition($group);
$excel_products = $query->execute()->fetchAll();

When I run SELECT * FROM excel WHERE grupkodu = 1 OR grupkodu IS NULL, I get 1594 records, however the above code gives only 638 records, which means only grupkodu condition is taken into account. What is the proper way to apply OR?

After a bit of dabbling, I got the answer. ->condition("grupkodu", NULL); is not sufficient, it needs to be ->condition("grupkodu", NULL, "IS NULL");


Assign Node To Other Menus Besides Main Menu Is there a module or technique which will allow us to assign a node to a menu -besides- the Main Menu. Users find it annoying that the only menu they can assign a new page to has to be based on the Main Menu. We have many custom menu blocks and it would be nice if the user could set up the page menu in one step rather than having to save the page, then go to the Admin/Structure/Menus and assign the page to the link.

BTW: We're using Kickstart 2 Omega theme if that makes any difference.

Can this be done?

Restricting the menus to which a Content Type can be added is configured on the Content Type itself (Structure -> Content Types -> Edit or admin/structure/types/manage/[content-type]) within the "Menu settings" tab:

By default, only the Main menu is selected. Simply check off additional menus to make them available on the node add/edit page for that Content Type.


Issue a Conditional Redirect in Drupal 7 I have a custom payment form that redirects to a 'Thank You' page on success. The page is just a Page type node, so someone can control the content of the page.

What I wanted to do was add a little extra, and prevent the page from being seen unless they had just come from the form.

I tried using 3 functions. hook_node_view, hook_node_view_alter, and hook_init.

I thought the first two would allow me to check the node path or nid, and redirect if I needed to, but they did not seem to be called. Additionally, I tried

mymodule_init() {
  global $user;
  krumo($user);exit;
}

That was not being hit, either. The rest of the module works fine, custom menu item, custom form, validate/submit/mail hooks. I am stumped.

How can I check a node value when loading, take action, and furthermore, why is hook_init() not dumping/exiting?

You should not use hook_init, but hook_boot as you want to perform the check when caching is turned on. That would also be the best explanation as to why your exit doesn't work. That or you forgot to clear cache after implementing the hook. (All hooks are cached in D7)


Toggle text field depending on checkbox value in drupal 6 I need to toggle a textbox depending upon the checkbox value.

Basically i need to take email entries for updates.

Here is the form elements I used.

$form['chkupdates'] = array(
        '#type' => 'checkbox',
        '#title' => t('Sign up to receive email updates about Green Apple'),
        '#options' => array(
        '1' => t('Yes'),
        '0' => t('No')
        ),
        '#default_value' => FALSE,
        '#attributes' => Array('class'=>'sub-form-element',
        'id'=>'chkbox'),
);

$form['chkmail'] = array(
'#type' => 'textfield',
'#title' => t(''),
'#attributes' => Array('class'=>'field','id'=>'chktext'),
);

Please guide.I am rendering elements in tpl files so jQuery is acceptable.
Thanks

You could do something along these lines:

$('#CHKBOX').click( function() {

  if ($('#CHKBOX').is(':checked')) {
    $('#CHKTEXT').display();
  } else {
    $('#CHKTEXT').hide();
  }

});

where CHKBOX and CHKTEXT are the CSS ids of the form elements in the resulting HTML.  If you know it will be hidden at the start, this can be simplified further into:

$('#CHKBOX').click( function() {
  $('#CHKTEXT').toggle();
});


How to handle with broken module installation I prepared a module that has some issues. I tried to install it, but while installing it crashed. I'd like to make some tiny changes and reinstall it, but the module is set as installed. When I go to uninstall this page is no longer available, because while module was installing it provided some changes, so uninstall page crashes. I know how to uninstall a broken module, but this procedure is pure evil and it takes a wile. Is there, so the changes are rolled back if the module has some issues?

Before the module installation you export your site configuration with drush cex. You install your module and if it crash you import the saved configuration with drush cim.


How *.drupal.org single sign-on works I believe there are many ways to achieve single sign-on within drupal. I would like to know the approach that *.drupal.org sites have been using. If I visit any drupalconf sites http://chicago2011.drupal.org/user or http://london2011.drupal.org/user it authenticates me with the user credentials given in drupal.org site. I would appreciate if anyone can point me to the modules or handbook pages on achieving this. Thanks in advance.

You might have a look at Bakery Single Sign-On System.

It mentions "This module started at the 2009 Drupal.org redesign sprint in San Francisco as a way to manage single sign-ons across *.drupal.org infrastructure."

For more details about how it work, you can see this article that has great explanation: Single Sign-on across Sub-Domains in Drupal with No Extra Modules.


How to get instance of referenced entity? I have a node object with image field named field_image. When I do

$node
  ->get('field_image')
  ->first()
  ->getValue()

I get array with some properties instead of entity object. The array looks like this:

'target_id' => string '8' (length=1)
'alt' => string '' (length=0)
'title' => string '' (length=0)
'width' => string '587' (length=3)
'height' => string '458' (length=3)
'_loaded' => boolean true
  '_accessCacheability' =>
    object(Drupal\Core\Cache\CacheableMetadata)[1092]
      protected 'cacheContexts' =>
        array (size=0)
          ...
      protected 'cacheTags' =>
        array (size=0)
          ...
      protected 'cacheMaxAge' => int -1

Do I have to manullay load the file entity using target_id or there is a way to automatically get referenced entity object from instance of Drupal\image\Plugin\Field\FieldType\ImageItem?

Why the referenced entity is not accessible via getter? It could be lazy loaded if it's not available immediately.

The path to referenced entity is very long:
// $id = some node ID
// $field = field name for entity reference field
$node = Node::load($id);

/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $referenceItem */
$referenceItem = $node->get($field)->first();

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $referenceItem->get('entity');

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();

/** @var \Drupal\Core\Entity\EntityInterface $referencedEntity */
$referencedEntity = $entityAdapter->getValue();

// At this point $referencedEntity is the referenced entity object.

Of course one can still get it via one liner call, but still, it is cumbersome and I wonder why EntityReferenceItem does not provide method that would return the reference entity object.
$referencedEntity = $node
  ->get($field)
  ->first()
  ->get('entity')
  ->getTarget()
  ->getValue()
;

Note: if you have php 8, you can use the nullsafe operator:
$referencedEntity = $node
  ?->get($field)
  ?->first()
  ?->get('entity')
  ?->getTarget()
  ?->getValue()
;

It's also worth noting that it's quite easy to get array of all referenced entities:
$node->get($field)->referencedEntities();

It works because for entity reference fields $node->get($field) returns instance of EntityReferenceFieldItemList which implements referencedEntities() method.


bulk node translation We have a lot of languages on the site and a node needs to be translated in every one of them.
We create the node in English and then some people translate the content to their language. So when there is no translation available the content remains in English. The translators only have edit permissions for the nodes in there language.
To not have to give them more access we create the nodes that should be translated.

Now when creating a node we have to click translate several times to create a node for every language.  I'm looking for a way to do this in one click.

One way i was thinking of this is by selecting the node to be translated and do something like the existing bulk operations to translate them.

Or by using rules to create a translation for every language when the node is created.

Anyone with experience in this field?

Try the Entity translation actions module.
https://www.drupal.org/project/entity_translation_actions


Is it possible to disable CSS and Javascript aggregation by role? Is it possible to disable CSS and Javascript aggregation by role?

That way during content editiong or administration stages the user is not affected and can check the CSS alright, while end users received cache values as usual. If the cache lifetimes are long enough the editing can be completed before it any changes interfere with the other users.

To do exactly what you want; using hook_css_alter & hook_js_alter is how to do it. Set the preprocess key to FALSE for everything.

For an out of the box solution that is fairly close to what you want https://www.drupal.org/project/advagg/ can do it. Give that role the "bypass advanced aggregation" permission and then they can add ?advagg=-1 to the end of the URL to see the change.

Will also mention that using a dev environment when altering css/js is ideal.


Change the number of entries depending on a theme setting I have a theme setting that allows the administrator users to specify how many teasers should be shown on the home page by selecting a number from 1 to 4 (through a <select> field). Is it possible to reference this variable so I can use it in Views? In that way, I can let Views check that value in the theme settings, then display the number of entries accordingly.

You could do this, but it will require that you know a bit about views exports.

You would have to create the view in code, by exporting it, this could be done with features or the views alone and use hook_default_views.

Once views read the view from code instead of the database you could insert a dynamic value for the number of items shown by the view, gotten from the theme setting. You would need to make sure that the value is formatted the way views expects it.

One important note. You can't make any changes to the way, as it will stop reading from the code and use the database instead. When this happens the dynamic value will be replace with a static one.


Which is the cache I have to clear to refresh list of view blocks? I created a new block (a view block) but it is not available to use in other modules (like panels). If I clear all cache then it shows up.

I don't want to clear all caches but only the right one to get the same.

If you use Drush you can clearly see there are cache for block and views. Clear both these cache and you will get the required result


How do I display a history of messages between two users using the Privatemsg module? Anyone knows how to display a list of all messages that two users had shared using the Privatemsg module for Drupal 7? Sort of a history of the conversation between the two users in a block or in a template.tpl.php?

Any help please.

The OP succeeded in doing this by creating a helper function in a custom module.

The function accepts two arguments, the sender uid and the recipient uid.  It returns the list of messages.

Then one can call this function from anywhere to get the required list of messages.

Here is the function the OP created:

function get_message_history($sender_uid, $recipient_uid) {
  $query = db_query("SELECT * FROM pm_index, pm_message
    WHERE ((pm_index.recipient = $sender_uid AND pm_message.author = $recipient_uid)
      OR (pm_index.recipient = $recipient_uid AND pm_message.author = $sender_uid))
      AND pm_index.mid = pm_message.mid
    ORDER BY pm_message.timestamp DESC");
  $messages = $query->fetchAll();
  return $messages;
}


Is it possible to get user uid in login form submit in DrupalGap? I have altered the login form like

if (form_id == 'user_login_form') {
    form.submit.push('my_module_user_login_submit');
  }

In submit I need the uid.

function my_module_user_login_submit(form, form_state) {
   //I need the uid of login user here;
  if(form_state.values.name){
   form.action = 'user-dashboard/'+ uid;
   }
}

Tried

var uid = Drupal.user.uid; but not working.

More info

function my_module_menu() {
var items = {};
items['user-dashboard/%'] = {
    title: 'User dashboard',
    page_callback: 'my_module_user_dashboard_page',
    page_arguments: [1],
    pageshow: 'my_module_user_dashboard_pageshow'
  };
return items;
}

**
 * The user dashboard page callback.
 * @param uid
 * @returns {{}}
 */
function my_module_user_dashboard_page(uid) {
  var content = {};

  // Build an empty container where the user dashboard will go.
  var attributes = {
    id: my_module_user_dashboard_container_id(uid),
    class: 'user-dashboard'
  };
  content['my_widget_container'] = {
    markup: '
' +
      'Loading dashboard...' +
    '
'
  };

  return content;
}

/**
 * The user dashboard pageshow event handler.
 * @param uid
 */
function my_module_user_dashboard_pageshow(uid) {
alert(Drupal.user.uid);
  // Load the user account...
  user_load(uid, {
    success: function(account) {
    var content = {};
    content['txt'] = {
        markup: '
' + account.name + '

' + account.uid + '
'
    };

      // Inject it into the container.
      var container_id = my_module_user_dashboard_container_id(uid);
      $('#' + container_id).html(drupalgap_render(content)).trigger('create');

    }
  });
}

function my_module_user_dashboard_container_id(uid) {
  return 'user-dashboard-' + uid;
}

Try using this hook in your app: http://api.drupalgap.org/7/global.html#hook_services_postprocess

/**
 * Implements hook_services_postprocess().
 */
function my_module_services_postprocess(options, result) {
  if (options.service == 'user' && options.resource == 'login') {
    drupalgap_goto('user-dashboard/'+ Drupal.user.uid);
  }
}

You may also need to set the action on the form object to null so that DrupalGap core doesn't try to redirect the page to the path indicated by the form's action variable:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(form, form_state, form_id) {
  if (form_id == 'user_login_form') {
    form.action = null;
  }
}


What's the meaning of "theme()"? I am new to drupal, I read some introductory tutorial.

I notice there is some theme() function in template files.

Like this:

<?php print theme('uc_price',array('price'=>$price)); ?>

It will generate some html source code:

$59.85

Is it theme() function is only to generate the html source? If this is the case, why I need use theme() function? I Think just only write html source manually.

I use Zen base-theme, Does theme() is one of zen's native function?

Please tell me the real usage of "theme()".

Your understanding about theme is right. It is for wrapping data with html elements. Advantage is that you can seperate view part and logic part. There are also default theme which you can use out of box


How to insert/update data in database I want to save data in a mysql table database using drupal 7 (costume module), but my question is that depends if the value exists I have to use the UPDATE command and if not INSERT command but I don't know how to write this code with the db api.

Use db_merge

  In the general sense, a Merge query is a combination of an Insert
  query and an Update query. If a given condition is met, such as a row
  with a given primary key already existing, then an Update query is
  run. If not, an Insert query is run.

Thus, db_merge adds it, if it doesn't exist yet. OR updates it, if it already exists.

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute();

  by: dzutaro, tlyngej, stewart.adam, AndreyMaximov


How can I embed a node in a block? I need to embed each node I have in a different block. How can I achieve it?

If it makes any difference, I am using Drupal 7.

create a block and use the below code to get the node body field content.

$node = node_load(YOUR_NODE_ID);
$body_content = $node->body[$node->language][0]['value'];
print $body_content;

If you are using a field other than body field, then you should print_r that $node variable and you will get all content type field relate with particular node.From this array you can get the all values created by content types.


I can't filter the child view based on a value from the parent view I have read many of the questions asked on this site, but none of them suited my problem. What is the need to make a Users view that shows below its created contents.
I have a website with 3 roles. Each role has the permission to create a content type. Users of the "Truckers" role can create nodes whose type is Trucks. The Username value is automatically added to a field, in order to identify which truck driver that truck belongs to. That field is an entity reference.
I need to create a view that shows users of the Truckers role and the trucks which belong to them. I created 2 views. One of them, based on the Trucks content type, lists the trucks, and among other fields, shows the Username of the truck driver who created it; the other one, based on Users, lists the users who have the Truckers role.
Using Views field view, I added the Trucks view as a field inside the Truckers view. However, I didn't find any combination of contextual filters, relationships, etc. that gives the desired result.
In the second image, you can see that the Trucks view is shown below each user of the Truckers role, but it shows all trucks, not just those created by the trucker.

I am not a programmer. How could I achieve the result I need? Is there a contextual filter, relationship, that I need to set? They have many options and I do not understand all of them correctly and in depth.
I am using Drupal 8.9.13 and Views field view 8.x-1.0-beta3.

You should be able to accomplish this with one view.  I don't think views field view is necessary.
Add a view that shows Users
In the Filter Criteria section filter it by role (trucker).
Under Advanced use the Relationships dropdown to add the relationship Content Authored.
In the Fields section add a field to show whatever field of the trucks content type you want to show for each trucker (e.g. truck name).  You could also use title.  This field setting will use the "node" relationship which is available as a result of adding Content Authored in the relationships dropdown in the advanced section.
If you do use title instead of something like truck name, or any field that appears in multiple content types, in the Filter Criteria section be sure to add a "content type" filter in order to restrict results to the trucks content type.
Format the results as you like (e.g. table, etc.).


Separate domain for specific content type I haven't worked with multi-domain setups in the past so I did some research regarding the options for altering my website to accommodate for specific multi-domain needs.

My immediate need is to have a specific content type appear in links like:

http://my-content-type.my-website.com

According to what I've found so far, the Subdomain module fits my use case exactly however, there are 4 things that keep me from installing it:

Very small user base (272 sites using it according to drupal.org)
It's a beta version since 2011 and the latest dev seems to be 4 months old
It does not work with Global Redirect module (which I happen to use in my site)
I will most likely need full sub-domain support in my website in the near future (different theme, custom user paths in separate domains etc).

Based on that, I came across the Domain Access module which seems to be the way to go for my future needs having the added benefit of a large user base, frequent maintenance releases and a stable version.

My question is the following:

Is there a way to minimally setup the Domain Access module to suit my needs for now (give me the option to setup a custom content type as a separate domain) and configure any advanced settings later? Is there any other solution that my research did not reveal?

I had the exact same choice to make 1 year ago and Domain Access was the best way to go.

To answer your questions:

You can always configure what content is available on each domain (basically you will set the new subdomain and set your specific content type to be available only there)
You can worry about advanced settings later; keep in mind now that almost all setting throughout the whole site can be differently set for each subdomain
A good recommendation would be a multi site install like Karel suggested
Another approach would be to just put some rewrite rules in your server, and have multiple themes set on each path which can contain a view that serves your content (this is pretty limited depending on what you want)


Changing blocks based on visitor's country On a Drupal 6 site I am trying to display blocks on my site based on user's country.

To do this I had to install  'IP to Country' module
Updated IP to Country
Created a new block and added the following code into the block body to print the user's country code:

<?php
$co=module_invoke('ip2cc','get_country',$_SERVER['REMOTE_ADDR'];);
print($co->country_code);
?>

Then, under 'Show block on specific pages' selected 'Show if the following PHP code returns TRUE (PHP-mode, experts only).' and then added the below mentioned code, so that the block is displayed based on the country ID.

<?php $co->country_code == "IN" ?>

After doing all these the block is getting disabled for the ID mentioned, eg: If 'IN' is mentioned the block should only be displayed for Indian visitors, but the block is actually being disabled.

Your code seems to be right. You've mis-spelled the module name in the module_invoke function at #3 and misplaced the semicolon ;

Try this:

<?php

$detectedcountry = module_invoke('ip2country','get_country',$_SERVER['REMOTE_ADDR']);
$us_canada = array(
  'US','CA'
);

//return true in block visibility when the country appears to be in detected country
if(in_array($detectedcountry,$us_canada)){
  return true;
}

?>


Calendar: How to limit the range of hours in Days display? I´m using the calendar module in d7.

In the  Day display it shows 01.00 to 23.00 in the hour column. How do I set it to be: 08.00 to 18.00?

I´m sure this is setteable in somewhere but I can´t find it...

I upload a picture which shows the hours to change:

Change the Settings of the Calendar format in the View and set the time grouping to custom.  In the box, specify the intervals/start times that you want to show up starting at the hour you want to start at.  See illustration below:


How do I get JSON data from a custom entity I would like to GET JSON data from drupal 8 custom entity.
I am using ubuntu 14.04 and vagrant.
For that i have done these steps.

I have taken reference to Create drupal 8 custom entity from this link.

Enable this modules:

HAL - Core module
HTTP Basic Authentication -Core module
RESTful Web Services - Core module
Serialization  - Core module
Restui - Contributed module

RESTui Configuration:

redirect to admin/config/services/rest
Enable content_entity_example_contact entity
GET Settings done for custom entity

Save.

Permissions given for Rest full web services

Postman Plugin is integrated in to chrome.
below settings is done for postman.

Above steps i have done to GET JSON from custom entity but getting error in postman. Any suggestion or starting point will help for me.

Interestingly when i perform similar steps for drupal 8 node entity i am able to GET JSON data.

Thanks

Dou you have an access control handler or an admin permission to control view/create/update/delete access to your entities?

You need to have that, in addition to the rest specific permissions. In fact, those will go away in 8.2, only the generic entity access will matter then.


Menu links not working in IE When I click on certain links in menu in IE a page with error message "Internet Explorer cannot display this page" appears. Other browsers are OK.

Problem is with these two links
"http://localhost/?q=calendar"
"http://localhost/?q=user/login"

Do you know what is wrong?

thank you

To give any meaningful answer you need to describe your problem better. I did notice that your urls seem to lack your site name

http://localhost/?q=calendar vs http://localhost/drupal?q=calendar

This can happen if you don't create the urls with the l/url function regardless of browser being used.


How do I use Url::setUnrouted() in a custom module? How do I use Url::setUnrouted() in a custom module?

If I call this method I get the following error:

  Call to protected method Drupal\\Core\\Url::setUnrouted()

Url::setUnrouted() is really an internal method used by the URL class.  It is used by the static constructor Url::fromUri() when the URI passed as argument isn't a route.

In general, you should create URL from one of the static constructor functions, and then use the public methods to change anything that you need.  And, paths in your own code should be set up as routes, whenever possible.

If you really need to create an unrouted URL to a static resource that can't be handled through other method (eg, JS and CSS should be handled using #attached), then you would do something like the following:

$url = Url::fromUri('base:some/path/foo.txt');


Referencing another node's field values I have created a "Customer" node-type. In that, I have a multi-valued field "Addresses" for taking customer's address.

I have another node-type "Order". While creating a new "Order", I want to select the customer from my existing customers. I can do this using entity or node reference. Now, while selecting the customer, I also want to select the customer's address which is present in the "Customer" node-type.

So, how do I do this? How do I reference another node's field values?

Or, is there any other way for this use-case?

Entity Reference Autofill does exactly what you want.

    The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


What are the problems with merging DB dumps? A strategy I've used with ExpressionEngine for managing the CMS in different environments is to use Git to merge the DBs of my dev and live environments when I need to deploy something new to live. This is working really well for me, my users are creating content but I can code without fear at the same time.

I see comments here and here that make it seem like the same is not true for Drupal 6. Is this just a question of the size of the database (which I think I could cater for by ignoring certain tables), or are there other concerns?

If you use Git to version DB dumps and merge dumps from dev. and live, you can also do that with Drupal. But the Drupal DB schema is dynamic, new modules add new tables and some configuration (mainly CCK) changes can add or remove columns or rename tables. Because of this, handling (configuration) changes with DB dumps merge is hard and error prone. That's why alternative methods like Features-driven workflow are recommended to manage (configuration) changes management between multiple environments.

See also The Development -> Staging -> Production Workflow Problem in Drupal and the Code driven development: using Features effectively in Drupal 6 and 7 presentations.


How to 'SELECT FROM {entity_bundle} WHERE field_A + field_B <= given_number_X' with EntityFieldQuery $query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MYCONTENTTYPE')

// Now say for instance I would like to grab the value of
// field_A and field_B, sum them up ( or subtract | divide | multiply them ).
// Then compare the result of that ( is greater than, equals to, smaller than )
// with a given number X. Is it possible with EntityFieldQuery?

$query_result = $query->execute();

I know I could do that by looping through the query result. Nontheless, if EntityFieldQuery allows me to do that at query time, I would like to know how.

I dont believe you can do this with the core methods provided by the EFQ api.

But, you may always extend the default EFQ class with a version of your own. Or, you may implement a function such as hook_entity_query_alter() or the addTag() method of EFQ.

Using addTag for instance on the EFQ you could then also implement hook_query_TAG_alter() and alter the SelectQuery that is ultimately called from the original EFQ and alter the base query to include your additional (non-standard) logic.

This could look like this short example, we additionally use the SelectQuery::where() method:

// Within some function of yours, you execute your query; giving it a Tag.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MYCONTENTTYPE')
  // Must call the method fieldCondition on field_A and field_B so
  // they get included in the SQL INNER JOIN statement.
  ->fieldCondition('field_A')
  ->fieldCondition('field_B')
  ->addTag('DoFunkyFieldLogic');
$query_result = $query->execute();

// ... elsewhere in your custom module ...

// Implements hook_query_TAG_alter
function mymodule_query_DoFunkyFieldLogic_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('DoFunkyFieldLogic')) {
    // You will likely need to install Devel and call dpm($query) here.
    // Or else you wont know what the field names are in the raw SQL ...
    // you might be able to cheat and use full database table names and
    // column names, eg:
    //dpm($query);
    $query->where("field_data_field_A1.field_A_value + field_data_field_B2.field_B_value <= :my_quantity", array(':my_quantity' => variable_get('my_quantity', 5));
  }
}

There may be cleaner ways to do this -- but this approach is relatively straight forward. This code is untested; but should work.


Move "Log in or Register to post comments" to the bottom of the page For some reason any time a new post is made at the top of the post a module shows up saying

Log In or Register to post comments

The problem is that it shows up way at the top of the post, instead of down in the comments area, as well as at the top of every post. Meaning it will show up several times on the front page.

I was unable to see anything that seemed related in the Block Layout for my theme or anywhere else

Does anyone know if there's a way to change this?

You need to change the fields order in Manage display /admin/structure/types/manage/page/display (replace page with your content type machine name e.g. article). Change Links after Comments.

If you don't want to show this information in lists, then in teaser view mode drag links under Disabled. Note that this will also disable the default read more link. If you don't have teaser tab available, then you need to enable it under Custom display settings.


Create a blog from a separate menu item I want to create a menu link that says blog, and have blog posts show up there (this blog is only for a single user).

I can't find any documentation, and so far everything seems to be posting on the homepage and I can't find a way to redirect blog posts to a different page.

What version of Drupal are you using? If you are using 6x you will have to create a "blog" content type and fields using the CCK module. In D7 Content types and custom fields are built into core. Make sure you uncheck the "promoted to front page" option in the content type settings so that your posts won't default to the front page. If you want your blog to go to a link other then the homepage (blog for example). You will need to install the views module, and create a "blog" view page, and configure that view to display your "blog" content types as either teasers (that will further link to the full node) or to full nodes themselves if you don't prefer teasers. Then go over to menus and create a "blog" menu link that leads to the new blog view that you created. Now every blog post will post to the blog view.


How to get an export option as a pdf for views? I am using views on my Drupal site I can able to export my view in csv, but I am not able export my views as pdf I need to export my view as pdf. Any suggestions on this it will be very helpful, Thanks in advance.

Try Views Pdf module

Descriptoin about viewspdf module:

  With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.

  There are already some PDF solutions such as Print. But these solutions use the HTML output and converts this to PDF. The downsides
  of such an integration are:

  No control over page flow (e.g. page break).
  Little or no control over page header and footer.
  You need HTML skills to change the layout.
  The rendering is slow and need a lot of memory, because it needs to render the HTML.
  Complex tables make troubles.
  Vector graphics can not be implemented, therefore the printing of the document can be problematic.
  You are limited by HTML's capabilities.
  No hyphenation.

  You can also specify a background PDF document. This enables you to put unlimited static content to the dynamic PDF. This static PDF
  can be exchanged dynamically by using a File Field. The PDF can be
  created by any PDF creator such as Adobe Acrobat Professional or Open
  Office.


Custom entity datetime field definition I created an entity in a module, using code. I generated skeletons with drupal console generate:entity:content (without bundles), and then added a datetime field to my TestFieldEntityItem.php, in baseFieldDefinitions().

$fields['test_date_incode'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Test date'))
  ->setDescription(t('Test.'))
  ->setRevisionable(TRUE)
  ->setSettings([
    'datetime_type' => 'date'
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'datetime_default',
    'settings' => [
      'format_type' => 'medium',
    ],
    'weight' => 14,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime',
    'weight' => 14,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I can add data to my entity, without problem, but if I want to add another field (a simple text field) through the UI, I get this error:

  Un problème est survenu à la création du champ test_text : The "datetime" plugin does not exist.

(In English, the error message is A problem occurred creating field test_text: The "datetime" plugin does not exist.)

The field is created, but I don't like this error. It seems my code to create the datetime field is not the right one.
I use the Calendar module, if this could have any incidence.

Hard to tell which plugin is missing. A guess would be it is a missing field widget plugin which causes the error when you try to add a new field to the default form mode. Then change the plugin name to something like this:

  ->setDisplayOptions('form', [
    'type' => 'datetime_default',

If this is not the error, then provide a full error message with a backtrace.


Connecting different content types/tables in Drupal with primary/foreign keys I am using Drupal 7 and I want to create tables which have primary key and foreign keys using content types. Each table would be created using content types. Let's say, when I create Fruit content type, it should create a table for it, right? Then, I may have Price table, hence, I create a Price content type. Now, the Fruit id(primary key) should be connected with Fruit id in the Price table (content type). How's this possible? I don't know how to code the tables/content type schema.

Thanks for your help.

Following link has a long discussion about foreign key in Groups.Drupal

=>
 Add join/foreign key info to schema


(How) can I Create products by the square foot? I have a product that I need to sell by the square foot, where the customer would enter the length and width, and the number of sq ft would be the unit amount on the product line. That unit number should then only be changed by updating the length/width fields (not by direct customer entry). Is there a commerce module or combination of mods for that. I've tried commerce custom product, and tinkered with rules, but can't make it work.
Maybe I need a custom module?
Any advice appreciated.

There isn't a complete solution, but there's a start and an open issue to make it do exactly what you need. I wrote a Physical Fields module that defines a dimensions field you can use to collect the length and width via a line item field exposed to the Add to Cart form. The issue is the dimensions field right now only supports collecting all three dimensions: length, width, and height. It needs to be updated to support using a subset of the dimensions, and I've just updated the appropriate issue that you can follow here.

Once you have that field on your line item type and have exposed it to the Add to Cart form, customers will be able to specify their dimensions when they add the product to the cart. With this data in fields on the line item, you can then make calculations based on the value of the field using Rules (or a custom Rules action). You can create a new data value by multiplying the length times the width (should be possible in Rules) and then set the product price accordingly. In such a case, I'd probably make the price of the product be the "sq. ft." price and then just multiply that times the square footage I calculate.


How to change default message from user relationships module? I am using User Relationships module. Its working fine. But I want to change a default message which get displayed on user site after getting request.

The message is like

  "John has requested to be your Friend. View your pending relationship requests to approve or decline."

I want same message to be displayed as

  "John has requested to be your Friend. View your pending friend requests to approve or decline."

Just want to replace the word relationship with friend. How can I do that?

User Relationship module allows you to set your own message, you can override the default message by settting a variable using variable_set("user_relationships_msg_{$key}", "Custom Message"), check the functions user_relationships_get_message() and _user_relationships_default_messages().


How to make Rules ignore case sensitivity when comparing strings I have an issue where I want to use Text Comparison in the Drupal Rules module but sometimes the case doesn't match (one is provided by user input and the other is provided by user data).  It's comparing 2 emails.

The rule fires as expected if the text matches exactly, but if the text doesn't match case (ie example@example.com != Example@example.com) it doesn't fire.

Is there a way to get rules to ignore case?

The data that I'm getting to compare is as follows in text comparison:
user-data:mail
person-email

The user-data:mail is the email of the user who is submitting the webform, the person-email is the provided data to a ruleset coming from the webform that the user entered.

Make a custom module called 'email_lowercase' and place this code inside it, before runnin this new action, do on both emails 'convert a data type' to 'text', then run the new action this custom module provides with Example@example.com TEXT-token-value you have just converted. After running custom action it will return a TEXT in lowercase, then comapre your email1-text-converted with the TEXT returned from custom module.

Note: you will nedd rules conditional module to compare (add conditional, add an IF) your variables AFTER this custom action is triggered.
Done.

<?php
/**
* Implement hook_rules_action_info()
* Declare any meta data about actions for Rules
*/

function email_lowercase_rules_action_info() {
 $actions = array(
  'email_lowercase_action' => array(
    'label' => t('Convert to lowercase a TEXT email'),
    'group' => t('custom'),

    'parameter' => array(

        'email' => array(
                'type' => 'text',
                'label' => t('$text-variable-token-Email to be lowercase'),
                ),
    ),

    'provides' => array(
      'email_lower_case' => array(
        'type' => 'text',
        'label' => t('email in lower case'),
      ),
    ),
  ),
);
  return $actions;
}

// rules function numero a texto
function email_lowercase_action($email) {
  $email_lower_case = array();
  $email_lower_case = strtolower($email);

  return array (
  'email_lower_case' => $email_lower_case,
 );
}

NOTE: there are no EMAIL data types for rules, thats way i suggested to firts convert an email field to text. It may work if you don't, i did not tryed that.


Can Display Suite render content without my theme around it? I'm just getting familiar with Display Suite and I want to know if I can use it to display only the content - not my header/footer/etc from my theme.

My goal is to display this content in a modal popup so I don't want anything around it.

aDisplay suite should allow you to modify the output for the fields and even choose some layouts but AFAIK it won't let you completely omit the site theme (i.e. create a page without header or footer).

You can use js/ajax to grab just the portion of the page you want to appear in the modal pop-up so that it doesn't pull in the header/footer. Depending on the JS library(ies) you are using this could be easy or challenging.


Image output when using scald module I'm using the scald module for image management.
It's working 99% as I'd want it to - but when used with WYSIWYG (ckeditor) I'm having an annoying issue.

The images in this context need captions so I've hooked into the scald templating and changed the output to use  and  tags.

All fine - except when saved the WYSIWYG / scald seem to add lots of empty  tags between the figure and the figcaption.

Attempting to use the empty paragraph tag module or create my own input filter have failed as they run before scald replaces the atom reference with the actual image output.

Any suggestions on where to hook into scald to be able to influence this markup?

I've been able to resolve this without using Scald templating.

The Scald plugin for CKeditor automatically inserts the image Title as the caption just below the image.  This text is editable in WYSIWYG if you want to replace the image Title with your own caption.

Below is how it looks at my site. Notice the caption just below the image.  (This is without any additional CSS - it can look nicer if you add some some CSS.)

And this is the markup inserted by the Scald plugin.  The caption is in the
 with the class dnd-legend-wrapper:

Fred Espen Benth. Foto: Gunhild M. Haugnes.


Theme inner field collection field(s) I'm looking for a way to theme the inner fields of field collection. Does anyone know, how to do that?

Currently the template output is like this:

        ... the field collection ...

but as you can see, there are now two ids with the same name

What you're experiencing is a bug. It happens quite often with contributed code, since it usually moves faster than it is tested. But don't worry, being contributed also means there are lots of people using, and probably someone else will bump into the same issue as you are experiencing.

When you face an issue that looks like a bug, you should ask yourself whether you've configured everything properly. Check first, but if there's nothing obviously wrong, give the issue queue a visit. Every module, theme or profile has an issue queue where people report bugs, suggest features and ask for support.

Search the issue queue and you may find a patch to your issue. If there is no report of your bug, file a new issue and provide a step-by-step guide to reproduce the error. That means you will have to try installing and configuring the module again on a fresh Drupal install. When the module mantainer sees the bug report, the steps to reproduce will make it a lot easier to debug and provide you with a fresh patch.

Mantaining modules/themes are usually voluntary work, and if you don't provide the steps to reproduce nor reply to mantainer questions, your issue will probably be postponed. Get involved with the community, it pays off.


What replaced the ContentFormControllerSubscriber class? In the past, there was a ContentFormControllerSubscriber class in Drupal, but there is no track of it anymore; the change records don't report anything about that class too.

The reason I am looking for that class replacement is that I noticed the Chaos tools module using a similar class to alter the requests passed to Drupal, and I was wondering if the priority (29) used in the getSubscribedEvents() method of those classes is still sufficient to alter the request before it is too late, and not doing it too early.
I guess the Chaos tools module used that value because it was used from Drupal core too; I am assuming there was a good reason to do so.

It was renamed once or twice, but https://www.drupal.org/node/2613034 moved the actual code from an event subscriber to a route enhancer. See \Drupal\Core\Routing\Enhancer\FormRouteEnhancer for the current approach.

Good event subscribers will document how they determined what priority to use, it could have been random or very carefully picked.

See CTools' \Drupal\ctools\EventSubscriber\WizardControllerSubscriber which still uses 29.


How to display list of nodes by number in views I want to put my custom list of ids to views filter but is seems to work only for one id. How can I do it for this list for example (1, 5, 9, 12, 455)

You can use the filter operator for regular expressions and this regex:

1|5|9|12|455


creating lists of nodes in a list is there currently a module that allows a user to bookmark a bunch of nodes and name them? E.g. create a bookmark of each movie and name the list, "comedy".

I'm guessing using the flag module would be the best bet but i'm not sure how to store attributes to flags and how to create separate flags.

You might want to look at the Flag Page module which expands on the Flag API, or the Bookmark module.

For the Flag API, look at the Flag Lists module which will allow your user to create multiple private lists of nodes.


How to add Organic Groups after Site has been created My site allows people from a certain class to upload their pictures on the website. It has various content types and views made but and I would like to install the Organic Groups module to allow multiple classes from my school to upload images.
Can I do that now or do I need to re-create the site from scratch?

It should not be necessary to re-create the whole site from scratch. After installing Organic Groups, you can mark an existing content type as "Group Content" if you want the nodes of that type to belong to a group:

Go to admin/structure/types.
Click on the "Edit" link next to the type you want to modify.
In the Organic groups tab, check the Group content checkbox. It will create a Groups audience field in your content type.

After that, you will need to assign each node to the appropriate group, in the Groups audience field.