Is it possible to use different versions of same language with different prefixes? I am building a multi language website. I would like to use 2 instances of same language (maybe with slightly different translations).

So is it somehow possible to use different versions of same language with different prefixes?

Yes you can.

Go to the languages settings page (admin/config/regional/language) and click on the Add Language link.

There you can select a preexisting language, but below of that list is a Custom Language option.

Fill that form with your new language settings and there you have your new language.

To start, I'd suggest to export (admin/config/regional/translate/export) your main language and import it (admin/config/regional/translate/import) in your new language. It will give you a translated new language. Then, you can go to the translate interface and update the texts that must be different.


prevent drupal from redirecting to created nodes as you know after publishing a node Drupal redirects to that node. How Can I change this functionality ? I want to force it to stay on the same page or maybe redirect it admin page instead of nodes.

You can use rules to achieve this easily, here:

Add a new rule and give it a name.

Event:

After saving new content

Conditions:

Content is of type - and chose your content type you want this rule to react on.

Actions:

Page redirect - and enter your destination.

here is an export of a rule that will redirect to homepage after insert a new node of type article.

{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "\u003Cfront\u003E" } } ]
  }
}


Installed a module, broke my site. And now I have no way to turn it off I'm still wrapping my head around Drupal 8 and installing modules during my learning process. Now I installed this module: https://github.com/iwhitcomb/foobar and it totally broke my site:

In Drupal 7 I used to be able to just goto the terminal and do a drush sqlc and manually update the modules table in the database to disable it. But in Drupal 8 there is no modules table for me to make edits.

How do I disable this new module I installed via the drush command line? (drush pm-uninstall doesn't work as it throws the same error in the shell)

Just remove the module folder and the site will work again. And do a clear cache. I'm not sure if it leaves any orphaned entries in the Database. If so, how would one delete them?


How to avoid Pathologic module to change a javascript src value? I need to insert a javascript code in a textarea field of a node. This one:

<script type="text/javascript" src="http://www.avaibook.com/js/avaibook.js"></script>

The problem is that this line becomes:

<script type="text/javascript" src="about:blank"></script>

The real source value: http://www.avaibook.com/js/avaibook.js is replaced by about:blank.

I already know that the pathologic module is the cause (if I disable it it works fine), but can't disable since I need it for other purposes.

Is there any way to avoid this?

You can try adding Javascript in your template files by using

<?php
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/mytheme.js');
?>

also this works in modules etc as explained here: http://drupal.org/node/304255

sometimes it is comfortable to add whole JavaScript inline:

drupal_add_js('jQuery(document).ready(function(){
   // Your stuff
   })
', 'inline');

Hope that helps avoid that module behaviour.


How critical is SA-CORE-2018-005? The Security advisories does not mention the usual classification for how critical this is (probably because it is about 3rd-party libraries). Can the whole site be compromised with this vulnerability or is it about accessing restricted content?

Ref.

https://www.drupal.org/SA-CORE-2018-005

https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers

The specific vulnerability seems to be the ability of a requester to send one request path to the webserver, but use an HTTP header to make Drupal see a different path.

The rewrite happens early, so the access layer in Drupal/Symfony runs as intended. But it bypasses path-based restrictions that happen earlier ("on higher level caches and web servers", according to the CVE at https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers).

For example, if you use .htaccess to restrict /admin/* from outside your IP range, that might be bypassed, but Drupal's own access system will still work as it should.


Warning: unlink() expects parameter 2 to be resource, string given in drupal_unlink() (line 2194 of /includes/file.inc) I'm using drupal_unlink() for deleting my files, but don't know why I'm keep on getting this error repetitively?

Warning: unlink() expects parameter 2 to be resource, string given in drupal_unlink() (line 2194 of /includes/file.inc).

<?php
$query = db_select('temp_container_mapping', 'c');
$query->innerJoin('temp_image_holder', 'i', 'i.nid = c.nid');
$query->fields('c', array('cid', 'nid', 'container', 'users_list', 'api_key', 'regions', 'abbreviative'));
$query->fields('i', array('id', 'nid', 'image_path', 'image_style', 'final_image_name_path'));
$query->condition('i.image_style', $param_image_style, '=');
$query->range(0, 10);
$entries = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

if (!empty($entries)) {
  foreach($entries as $value) {

    $container_id = $value['cid'];
    $nid = $value['nid'];
    $id = $value['id'];
    $image_path = $value['image_path'];
    $image_style = $value['image_style'];
    $final_image_name_path = $value['final_image_name_path'];
    $container = $value['container'];
    $users_list = $value['users_list'];
    $api_key = $value['api_key'];
    $regions = $value['regions'];
    $abbreviative = $value['abbreviative'];

    //Establish Connection with server
    $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array('username'=>$users_list, 'apiKey'=>$api_key));

    $service = $client->objectStoreService('cloudFiles', $abbreviative);
    $container = $service->getContainer($container);

    $temp_arr = explode("/", $final_image_name_path);
    $end_element = end($temp_arr);

    try {
      $file = $container->getObject($end_element);
      $fileExists = true;
    } catch (Exception $e) {
      $fileExists = false;
    }

    if ($image_style == "245") {
      $image_style_w = "168";
    } else {
      $image_style_w = $image_style;
    }

    $style = $image_style_w."w_".$image_style."h";
    $display_style[$image_style] = image_style_load($style);
    image_style_create_derivative($display_style[$image_style], $image_path, str_replace("rcf:///", "public:///rackspace/", $final_image_name_path));

    if ($fileExists) {
      //File is ther needs to overwrite
      $file->setContent(fopen('sites/default/files/rackspace/'.$end_element, 'r+'));
      $file->update();
      print 'existing overwrite
';
    } else {
      //New file just to upload
      $container->uploadObject($end_element, fopen('sites/default/files/rackspace/'.$end_element, 'r+'), array());
      print 'new one
';
    }

    drupal_unlink("public:///rackspace/", $final_image_name_path);
  }
}
?>

probably a typo ',' -> '.'
drupal_unlink("public:///rackspace/" . $final_image_name_path);


Is there a way to get field associated with content type? I have to do some functionality with fields associated with a content type, this i have to do before creating content for it.

In custom module tried using node_type_load('digital_iq_2012'), this function loads content type details alone and not the fields associated.

Do we have a way to get the fields as well?

Any help?

You can use field_info_instances('node', $content_type).

With field_info_instances('node', 'article'), I get the following.


Facebook Style 'Read More' instead of standard Pager in QuickTabs? I am using Quicktabs to display a few views (grid style). At the bottom I am using the standard Pager that comes with QuickTabs. Is it possible to replace that with a 'Show More' link (ajax style?) Example would be at the bottom of a Facebook Wall, or here- http://gdgt.com/answers/

Thanks for the help!

You can use Views Infinite Scroll.

  Views Infinite Scroll provides a pluggable pager that enables Views infinite scrolling by using jquery.autopager plugin. Using this module with Views page display will load another page whenever the user reaches the bottom of the page.


How to search in field collection item? I want the Drupal Default Search to look into Field Collection items.

I currently have a field_resources collection with a field_description and a field_file, and the search should be looking into both.

Is this possible? What simple alternative could I use instead? An external search module seems a bit overkill.

As say in Search interface the search system already indexes all visible output of a node; i.e., everything displayed normally by hook_view() and hook_node_view().

You can activate and configure in the display settings of your content type the custom display "Search index" than will be used for indexing.

If this doesn't works in you case, you can implement hook_node_update_index to add any information you want on the node before is indexed.


What query string is used to display products in commerce kickstart? I am creating a php script to display all the products from commerce kickstart database

But the image is in a table called file_managed and the products are in commerce_products and i cant seem to figure it out. what query is used to display the products in commerce kicker or how do i select all the product and images from the database using sql?

You can use the function commerce_product_load which is documented here. I am sorry if you are saying Drupal is not loaded and you have to use a straight php query.


Theme user pictures in comments in drupal 7 I'm trying to set a specific style for user pictures in comments in drupal 7, but can't find how to do it.
I know there is a module for this (http://drupal.org/project/imagecache_profiles) but it's really an overkill since I just want pictures to be themed in comments, according to a style I already created in Image_cache configuration.

In comment.tpl.php, there is a <?php print $picture; ?> , but it's directly the html for the image, so I can't apply the theme function of image cache, for instance theme('imagecache','size32x32', $data->users_picture);
The $author variable is also html.

Is there a way to get the theme function to work in this comment.tpl.php file ?
Is there another way to achieve this ? Thanks !

To help you understand the syntax, have a look at the comment.tpl.php documentation, here you will find the different variables and a link to template_preprocess_comment() where they are defined:

$variables['picture']   = theme_get_setting('toggle_comment_user_picture') ?
                          theme('user_picture', array('account' => $comment)) : '';

So there's a theme function to render this picture: theme_user_picture() which state you should have a look a the template file: user-picture.tpl.php which finally send you to template_preprocess_user_picture().

There you can override this function copying and pasting the original code and changing the bits and parts you want to suit your needs (put this code in your template.php file):

function YOURTHEME_preprocess_user_picture(&$variables) {
  //change only the relevant part and leave the rest of the code
  //For Drupal 7 imagecache is in core so I put the correct syntax
  $variables['user_picture'] = theme('image_style', array('style_name' => 'size32x32', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));

  //...
}

Have a look at the $variables to find a way to target comments or add a class there and use CSS as dkiscool mentionned.

NB: if you don't like browsing all the API documentation, there's a faster way, use theme developer (see this answer).


How to debug: How Can I see the form arrays with its components (fields) in a loaded page? I would like to changing a title of a button in a form, and I would like to have a tool for debug, like devel or another, so I can see in real time, after a page is loaded, what is the structure in forms, subcomponents, name of every field.

So I know how could add a line to the code in my custom module to change the title of a form button.

How would you do it? Steps, method, tools, please share.

Note: These are my first steps in programming modules, changing simple things for now.

Thanks for your suggestions!

Debugging in Drupal can be a bit frustrating when you first start out but you'll get the hang of it quickly :)

Debug is a really convenient Drupal function to output your form array (or any array/object) from any custom module/template.

In the case of your form, you can invoke hook_form_alter in you custom module to call the debug of your form. (You can find the form ID by looking at the page code and replacing the - with _. For example "user-login-form" would be "user_login_form" here)

 function YOUR_MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
   if($form_id == 'your_form_id') {
     debug($form,'form',TRUE);
   }
 }

Then (after clearing caches) once you visit the page with the form, Drupal will output the $form array as an entry in your watchdog log (admin/reports/dblog).


How to alter search query to include custom fields? How can I alter the query for user search (using normal Drupal search) so that instead of searching only email and username, it will also search custom user fields (from fields module)?

For the normal Drupal search you can do so by defining a custom search type in a module.

Use hook_search_info() to define your custom search type & hook_search_execute($keys = NULL, $conditions = NULL) to create or extend your search query.

More available hooks can be found at the Drupal's Search interface or by looking up the search contrib module under yourdrupal\modules\search\search.api.php


Hide publishing options in hook_form_alter without unpublishing node? I'm trying to create a very slimmed down node edit page for a content type. One of the things I'm doing is hiding the additional_settings section with #access = false.

This is what I'm using:

$form['additional_settings']['#access'] = FALSE;
$form['options']['status']['#default_value'] = TRUE;

With #access = false, when I save the node after editing, it set to unpublished.

I've tried using $form_state['values']['status'] = TRUE; in a form submission handler, but that doesn't help.

You could just convert the element to a value type, that way it will be hidden from the form display but will be passed through to the submit handler as normal:

$form['options']['status'] = array(
  '#type' => 'value',
  '#value' => 1
);

You can do the same thing for the rest of the elements in that fieldset, then set the fieldset itself to a container type and remove the title:

$form['options']['#type'] = 'container';
$form['options']['#title'] = '';


How to create a link that uses a route? I am trying to add a link to a taxonomy landing page, like this

$breadcrumbs->addLink(Link::createFromRoute($term_name,"/taxonomy/term/$tid"));

but I get the following error : Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/taxonomy/term/2041" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of C:\drupaldevsites\pup-dev\docroot\core\lib\Drupal\Core\Routing\RouteProvider.php).

The argument has to be a route name.

Try:

$breadcrumbs->addLink(Link::createFromRoute($term_name, "entity.taxonomy_term.canonical", ["taxonomy_term" => $tid]));

See the docs for this method.


Alternative ways to clear the Drupal cache We have a busy database server and when we try to clear the cache on Drupal, Drupal tries to TRUNCATE cache tables and that causes a backlog until the MySQL hits to maximum number of user connections (which is 800).  This is causing problems for us.

As far as we can tell, the problem is being caused by the locks during the table truncation.

Are there any alternative methods to clear cache that can help avoid this situation?

While your cache bins are in MySQL, truncating tables is by far and away the quickest method to clear the cache. It's not a particularly expensive operation, so if it's backing up your db connections I would get your sysadmin to investigate what config issues might be causing that (or whether it's simply a lack of sufficient resources).

As MPD notes in the comments above, your real problem might actually be the cache rebuild after the flush has happened, though. You should be able to confirm that after a bit of testing.

You can take the pressure off the database by using redis/memcache/etc as a cache backend instead of the database. Doing that will also make considerable speed improvements to your site in general.

Your mileage will vary, of course, but it's very likely that flushing cache from memory will be a quicker operation than flushing it from the disk. As Mołot notes below, writing the new cache items to memory rather than disk will also give you a performance boost (there will still be reads and writes to MySQL, but far fewer writes in theory).

As with anything, it needs testing on the bare metal to see how any of this would affect your specific configuration.


Initialize & override a Drupal7 jQuery module's (Superfish) provided .js, in code I'm migrating a Drupal6 site to Drupal7.

The v6 site was subthemed in Fusion, and used its bundled Superfish menu js.  The init I used that worked was:

$(document).ready(function(){
 $("ul.sf-menu").supersubs({
  minWidth:    12, // min sub-menu width, em
  maxWidth:    27, // max sub-menu width, em
  extraWidth:  1,
 }).superfish({
  hoverClass: 'sfHover',
  speed:       0,   // ms, cref jquery animate()
  delay:       0,   // mouseout delay, ms
  animation:   {opacity:'none',height:'none'},
  autoArrows:  true,
  dropShadows: false,
  disableHI:   true,
 }).supposition();
});

In moving to D7, Superfish has been UN-bundled from Fusion, in favor of using the Superfish module for system-wide support.

I'm using the module's js in some custom markup, and need to init the module & override the module's defaults.

I understand that in D7, we need to init jQuery a bit differently.  My 'best shot' so far (which, unfortunately, is NOT working) at reproducting what I had in D6 is:

( function ($) {
        Drupal.behaviors.mySuperFish = {
            attach: function(context, settings) {
                $('.sitemenu-inner .sf-menu ul', context).supersubs({
                    minWidth:    12, // min sub-menu width, em
                    maxWidth:    27, // max sub-menu width, em
                    extraWidth:  1,
                }).superfish({
                    hoverClass: 'sfHover',
                    speed:       0,   // ms, cref jquery animate()
                    delay:       0,   // mouseout delay, ms
                    animation:   {opacity:'none',height:'none'},
                    autoArrows:  true,
                    dropShadows: false,
                    disableHI:   true,
                    dropShadows: false, /* Needed for IE */
                }).supposition();
            }
        };
    })(jQuery);

noting that the targeted div/tag has changed.

With this code in place, Firebug is showing me no errors; then again, I'm seeing no sfHover autoclassing, or any of my Superfish submenu functionality.

What am I still doing wrong here?

The JavaScript that you have written for Drupal 6 and 7 does the same thing, only the targets has changed a bit ul.sf-menu vs .sitemenu-inner .sf-menu ul.

This gives a few options as to what could be wrong.

You have a different superfish version, that behaves a bit differently
Your markup has changed and doesn't work like it did for your Drupal 6 site.

It's hard to debug why you're not getting the desired result, you could try to test out superfish on a static page and see if you can get it working. That will reduce some of the complexity and reduce your problem to a JavaScript/jQuery problem.


drupal 7 get title token without anchor tag I am using a view with a "content:link" field to display a custom link for each content in my block.

I have job listing in block and want to add a link for each job "Apply". When users click on "Apply" it will redirect to a webform with title of the respective job.

So in my View under the REWRITE RESULTS setting I have selected Rewrite the output of this field and added my custom anchor tag like below:

 Apply Now

It works but it's putting title with anchor tag. So the output URL becomes

 <a href='20?id=Team leader'>Apply Now

Here I want the value of title token, without an anchor tag. Is it possible? Or any other way to do this job?

I solved this issue. As described below :

We can use fields as token only whose we selected a block field.

I have selected title as block field with link to content node. so it was taking title anchor as token. I have removed tick for  "Link to node" option from title field settings.

Now it's working fine.


Cron Cache not working I'm using the Cron Cache module to empty my cache tables especially the cache_form table who take 200Mo in 2 days ,but the probleme is that i notice that the module is not working anymore for few days ago .I'm thinking that it's the expire module maybe ??!!
Please any help ..
NB:
I launched the cron 2 times in 10 min (in 24 hours) and nothing happened on the database while i'm configurating my module to flash the cache tables every 24 hours

I Uninstalled the expire module and the Cron cache module returns to work as usual


How to treat users as Anonymous in Confidential Groups? Here is my problem.

Mark an Organic Group as Confidential Group while creating it.
Users will be asked with a question saying would you like to be Anonymous while joining Confidential Group.
If user opted for Anonymous then all the content and activity inside group will be shown as Anonymous user as Author in front end but who posted details will be tracked in back end with user details. So, Technically Content Author is author of the node, but Author field should be shown as anonymous in front end !

This will be useful in Sensitive Groups where user identity should be hidden.

Any hooks or out of the box modules or solutions for above three problems ?

I would add a "anonymous" field in the user account: admin/config/people/accounts/fields

then, in node pre-processing, do a check to see if the author of the node is anonymous and re-write the author field accordingly.


How to remove image script if it has no image? I created a block using views.
The fields has image, title and body.

While the article has no image, it still render out the image script and it make a space before the title.

How do it make the image script disappear if there is no article in its.

Go to Image field configuration:

Click on No results behavior section.

You will get the option to hide.


My 960 grid system has wider columns that standard. 55px instead 40px for 16 columns I was surprised to discover my website is wider than is supposed to be.

I am using Drupal + Omega Theme that uses 960 grid system.

The total width of the site is 1180 instead 960.

The columns are wider:

On 16 columns options: they are supposed to be and 40px they are 55px
On 12 columns options: they are supposed to be 60px and they are 80px.

The gutter is 20px and is ok.

What is the problem?

On wide screens, Omega (or in fact: its base theme 'Alpha') will switch to the wide lay-out. You will find the css for it in alpha/css/grid/alpha_default/wide/alpha-default-wide-16.css and alpha/css/grid/alpha_default/wide/alpha-default-wide-12.css.

This responsive behavior can be controlled from the Omega theme settings page.


How to configure the CORS module for multiple domains? I have JSON content I want to deliver to multiple domains. I have installed the CORS module. I have configured to deliver to one domain like this:

*|<mirror>,http://www.other-domain.com

This works. However, I want to configure for a list of domains and can't work out how to configure that. The following doesn't work:

*|<mirror>,http://www.other-domain.com,https://www.and-another.com

Nor does

*|<mirror>,http://www.other-domain.com
*|<mirror>,https://www.and-another.com

How do I configure this?

Upon further investigation, this seems to be an issue with the CORS module, and has been patched, so hopefully fixed in future versions.

https://www.drupal.org/node/2780297


Change Views BETWEEN min/max filter to a cleaner URL format? Is there an easy way to change the default exposed BETWEEN filter to work with:
price=1000-2000
Instead of:
price[min]=1000&price[max]=2000?
Would it be reasonable to create my own Numeric filter or am I looking at a lot of modification?

You can always create redirects with rewrite rules outside of Drupal, in your server configuration. You can add them in Drupal settings too.
There is a module that did this for Views in D7 but it needs more help with D8, help if you can:
Query Parameters To URL


Can visit the page but can't see the tab it should have Not sure how to word it and I am sure plenty of other people have run into this problem, so I apologize in advance.

I have the following code:

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

  $items['admin/config/content/authoring/messages'] = array(
    'title' => 'Messages',
    'description' => 'Configure what messages are displayed for the differing content types and who has permission to see them.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('content_type_message'),
    'access arguments' => array('administer content type messages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/content/authoring/messages/settings'] = array(
    'title' => 'Settings',
    'description' => 'Configure who has permission to see them.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('content_type_message_roles_form'),
    'access arguments' => array('administer content type messages'),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

The second page I can access when I go to 'admin/config/content/authoring/messages/settings' but I do not see a tab on the first page ('admin/config/content/authoring/messages') to go to this second page. Anyone know what I might be doing wrong?

Drupal doesn't show tabs when there is just a tab defined or visible for the currently logged-in user (which includes the case users don't have the permission to see other defined tabs).
If you look at what Drupal does, for each node there is node/%node/view and node/%node/edit; when users don't have the permission to edit a node, they don't see any tab, in the node page.

See the following screenshot, taken from drupal.org at https://www.drupal.org/node/5, using an account with the permission to edit the node.

You see the View, Edit, Outline, and Revisions tabs.

Compare it with the screenshot taken using an anonymous user account, for the same page.

You don't see any tab, but the screenshot is for the View tab.  In fact, if you try accessing https://www.drupal.org/node/5/view as anonymous user, you would see the same as in the last screenshot.


How can I get the group ID of a node? I have this node that belongs to a group, and I want to get the group ID of that node, to print it, something like $node->nid; but with the group id.

Is that possible?

The relationship between group content and a group is via a membership relation.  Since it is possible for group content to be a member of multiple groups then the following code will retrieve the list of groups:

$groups = og_get_entity_groups('node', $node);

This is a multidimensional array with the group entity_types as the key and memberships as the value. Each membership is an array with the membership id as they key and then group's entity id as the value.  So to go from a group content node, to all it's group parents you would use ...

foreach (og_get_entity_groups('node', $node) as $entity_type => $og_memberships) {
  foreach ($og_memberships as $membership_id => $entity_id) {
    if ($entity_type == 'node') {
      // Assuming we only want to deal with node groups, we can
      // access the group node with...
      $group_node = node_load($entity_id);
    }
  }
}


Create a new node when a field is added to a node How can a element (say an image) that is entered as a field (when creating a new node), also be created as a separate new node at the same time (either through copying the image or by referencing it)?

Option A

I myself wouldn't do that - I think that generally it's a practice that doesn't worth the time and risks (as would be explained in Option B) but anyway:

In drupal 7 this can be done with the Multi Node Add module. There isn't a version for Drupal 8 yet; If you don't have the knowledge to port it to Drupal 8 you might hire a PHP programmer to do that for you. An alternative would be to copy the desired fields from 1 node to another via this module. This module is going through a porting process at this era.

Guessing that both modules work only on 1 content type at a time, and can't recreate content in another Content type: You could handle that by cloning your nodes inside the same content type (X) with Node Clone or a similar module, and than convert all clones to their other, similar content type (Y) with Node Convert or a similar module.

Option B - Advice and workaround with Views.

As an SEOer, I would recommend on finding other way to enrich your sites' content; Cloned content is quite a good recipe for lowering both your PQS (Page quality scores) and in some cases - Your PageRanks as well... This becomes more serious with every passing year.

It could be better to create more sophisticated content pieces based on the first node content via the Views module (which is part of the Drupal 8 core); Here is an intro to Views 8. Many tutorials are available in Youtube for that module.


Views: how to enable Title Link per role? In Drupal 7 Views, there is an option to Link title field to the original piece of content. How can I enable the link per role? I only want to show the link for administrator and staff, so it will be much easier to modify.

Drupal 6 had a view node permission, but it was removed from Drupal 7 for some reason.
This module adds it to Drupal 7:
https://www.drupal.org/project/node_view_permissions

If only the administrator and staff have the view node permission, only they should see the link in your view.

This of course will also only allow administrators and staff to view the node page too.

You could also create a template for that view field.
In the view settings, under advanced, there should be a 'theme' link. Click it to see what your field theme file should be named.


How can I differentiate between third-party and custom modules in the list of modules? If I have administrative access to a Drupal site, I can see the list of the modules enabled for the site.

How can I differentiate between third-party and custom modules?

You can just do this by looking at sites/all/modules folder - if the sitebuilder was a good one you will see two folders "custom" and "contrib". In modules administration page there is no simple way to differentiate between them.


Select all team data from a drop down I have a drupal form  with a drop down list of teams like team A, team B, Team C and on submit it goes to page /team-page/[team-id] and displays the particular team details.So how do I do if I have to select all team data? because my page only accepts team ids and I want to use /team-page/all.

if your teams data are coming from the same table use drupal db select and table api to create a table where u can see all the data
try to ajust that to your system

  /**
 * Render a filtered list of entries in the database.
 *
 * DBTNG also helps processing queries that return several rows, providing the
 * found objects in the same query execution call.
 *
 * This function queries the database using a JOIN between users table and the
 * example entries, to provide the username that created the entry, and creates
 * a table with the results, processing each row.
 *
 * SELECT
 *  e.pid as pid, e.name as name, e.surname as surname, e.age as age
 *  u.name as username
 * FROM
 *  {dbtng_example} e
 * JOIN
 *  users u ON e.uid = u.uid
 * WHERE
 *  e.name = 'John' AND e.age > 18
 *
 * @see db_select()
 * @see http://drupal.org/node/310075
 */
function dbtng_example_advanced_list() {
  $output = '';

  $select = db_select('dbtng_example', 'e');
  // Join the users table, so we can get the entry creator's username.
  $select->join('users', 'u', 'e.uid = u.uid');
  // Select these specific fields for the output.
  $select->addField('e', 'pid');
  $select->addField('u', 'name', 'username');
  $select->addField('e', 'name');
  $select->addField('e', 'surname');
  $select->addField('e', 'age');
  // Filter only persons named "John".
  $select->condition('e.name', 'John');
  // Filter only persons older than 18 years.
  $select->condition('e.age', 18, '>');
  // Make sure we only get items 0-49, for scalability reasons.
  $select->range(0, 50);

  // Now, loop all these entries and show them in a table. Note that there is no
  // db_fetch_* object or array function being called here. Also note that the
  // following line could have been written as
  // $entries = $select->execute()->fetchAll() which would return each selected
  // record as an object instead of an array.
  $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);
  if (!empty($entries)) {
    $rows = array();
    foreach ($entries as $entry) {
      // Sanitize the data before handing it off to the theme layer.
      $rows[] = array_map('check_plain', $entry);
    }
    // Make a table for them.
    $header = array(t('Id'), t('Created by'), t('Name'), t('Surname'), t('Age'));
    $output .= theme('table', array('header' => $header, 'rows' => $rows));
  }
  else {
    drupal_set_message(t('No entries meet the filter criteria (Name = "John" and Age > 18).'));
  }
  return $output;
}


Use url alias for page parameters I'm new to Drupal and created a basic page in which the clean url is

/todo

If I want the todo's for a certain month I can do

/todo?month=januaray

However what I would like to do is provide a clean url which looks like

/todo/januaray

I tried modifying my .htaccess file like explained here

RewriteCond %{REQUEST_URI} ^/todo/(.*)$
RewriteRule ^.*$ /todo?month=%1 [L]

But that didn't seem to work. Is there any easy way to achieve this?

This will work:

RewriteRule ^todo/(.*)$ todo?month=$1 [L,QSA]

No need for the rewrite condition.

That will internally forward, e.g. http://example.com/todo/january to http://example.com/todo?month=january.

Make sure you add that code before Drupal's main index.php RewriteRule


Show tax from shipping? I'm building on Commerce Kickstart 2. The problem is that for shipping it displays only flat price, there is no tax amount calculated seperately.

Is it possible to shipping like:

Express shipping subtotal 10€
Shipping tax 23% 1,23€
Total: 11,23€

Or show shipping as line item so that shipping tax is calculated to product taxes amount?

You can do it by using Tax option under store-> configuration.

Just go and add a tax rate.

Now you can apply tax rate using rules easily on event something like "after saving new commerce order.

And then add action you want to perform.


How to deal with unverified users in Drupal? What do you do with unverified emails in Drupal? I see some have been unverified for several months.

Is it possible to resend the email or to auto delete them?

you should try the Logingtoboggon module. it has this feature

  Allow users to login using either their username OR their e-mail address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log
  in". The other brings the user to a separate page, but returns the
  user to their original page upon login.
  Customize the registration form with two e-mail fields to ensure accuracy.
  Optionally redirect the user to a specific page when using the 'immediate login' feature.
  Optionally redirect the user to a specific page upon validation of their e-mail address.
  Optionally display a user message indicating a successful login.
  Optionally combine both the login and registration form on one page.
  Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt
  for important information on configuring this feature!).
  Integrates with Rules module to do various tasks when a user validates via    email validation process (see
  http://drupal.org/node/880904 for an example)

I have put the feature you are looking for in bold.


Can you make a node title \ heading link to it's NID? I'm looking for a way to click a node's title to refresh it's very page. For example, if the current node is node/1 and I'll click it's title \ H1 the page will be refreshed...

Tried to go to > structure > Content types (desired content type) > edit > edit display, but I couldn't find an option to edit the Page-heading \ h1 there.

I must say I'm looking for a non-modular solution (preferably without customization also).

Thanks.

There are possibly few ways to do this.

Not sure if this actually works, but I think it does, you can install Display Suite and go to Manage Display tab and apply one of display suite's layouts to your "Full" view mode. After you do that, Display Suite will give you all the fields (including Title) on the Manage Display tab of that view mode. From there you just need to configure the fields and config the "title" field and check the option "Link title to node".

You could also do it from template files, I guess it qualifies as non-modular? For example in node.tpl.php or page.tpl.php (wherever the page_title is being printed) one can easily create a link to the current node if the $node object is available or if not the node ID's available from the URL always. From there it should be a pretty easy call to l():

<?php print l($page_title, 'node/'.$node->nid); ?>


Change language of a JS element when language has been changed from Drupal language switcher? First of all, sorry for the really confusing title, but I have no idea how to make it more reader friendly.
On my website, there are three languages: English, Finnish and Swedish. The user can change between these languages from the default Drupal language switcher.
Now the key part of the website comes from an API that I think is in JS. That JS element has its own language changing parameter.

  src="//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=sv&leaflet_gshim=1">

So in order to change the language of the JS element I would need to change that "lang=" part to what language I want.
I have that script with the address to the API in my page.html.twig file to make the API call to work all across the site.

Is there a way to change the lang=sv to lang=en and lang=fi when the user changes the language through Druapl language switcher?

From the companys API support they said:

  you have different pages for different languages:
  website.fi/drupal/ (englisch)
  website.fi/drupal/sv
  website.fi/drupal/fi
  This means that you should have a different script tag for each of these
  paths. I guess Drupal allows that with help of a language variable
  that is accessible in your page template. (But I really know little
  about Drupal, so that's just a guess)

I am sorry for a long and confusing post, but it is really crucial to get this to work and I am losing my mind.
PS! I am really new to Drupal.

Something like this is what you're looking for I think.

theme_js_alter($js) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  foreach ($js as $key => $value) {
    if (strpos($value['data'], 'www.websiteofapi.com/alpportal/oa_head.js') !== 0) {
      $value['data'] = "//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=$language&leaflet_gshim=1"
    }
  }
}

Also see Get current language in template


Create defaults for panels to be deployed on install only We have a mini panel that we use to create a footer area. This is deployed on install of a new multi-site through our custom installation profile. I would like to set default content items in the panel regions on install. If I were to do this in a feature, then any changes made by the site administrator would be reverted on a features-revert-all command. How do I go about creating this as part of an install file?

To start, I created my mini panel as I wanted it to be and did an export. I saved the export code to a file in a custom module I created. I used install file in the module and this hook_install function:

function custom_footer_install() {
  if (!ctools_export_crud_load('panels_mini', 'fat_footer')) {
    $filename = drupal_get_path('module', 'custom_footer') . '/panel_exports/profile.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $panel = ctools_export_crud_import('panels_mini', $contents);
    ctools_export_crud_save('panels_mini', $panel);
  }
}


Problem: users are logged out automatically without any reason, while navigating to the website Hi After some time Im having a very serius problem, while logged in users interact with the website they are logged out without any reason.

For example, I log in, then I interact some minutes with the website, then for example I try to access to create an article (or whatever) then I get an access denied because I was logged out automatically, I do not know why...

Any idea?

There are some settings regarding cookie session lifetime in the settings.php file. These settings might not be allowed for overwriting and your server might have its own rules.

 ini_set('session.cookie_lifetime', 2000000);
 ini_set('session.gc_maxlifetime', 200000);

Check admin/reports/status/php.


What is the reason of hidding comments and links in node.tpl.php? What is the reason of first hiding the comments and links and later showing theme in node.tpl.php?

even if I delete following three lines of this system it does not change anything,
hide($content['comments']);
hide($content['links']);
<?php print render($content['comments']); ?>

from node.tpl.php

    <div class="content clearfix"<?php print $content_attributes; ?>>
            <?php
              // We hide the comments and links now so that we can render them later.
              hide($content['comments']);
              hide($content['links']);
              print render($content);
            ?>

          <?php
            // Remove the "Add new comment" link on the teaser page or if the comment
            // form is being displayed on the same page.
            if ($teaser || !empty($content['comments']['comment_form'])) {
              unset($content['links']['comment']['#links']['comment-add']);
            }
            // Only display the wrapper div if there are links.
            $links = render($content['links']);
            if ($links):
          ?>

              <?php print $links; ?>

          <?php endif; ?>

          <?php print render($content['comments']); ?>

You don't need to remove them from your node.tpl.php -- but that is always an option.

I recommend a better solution, however.

First, you can check out this resource to read more about how to deal with fields when they are being displayed on a node.

A really good solution (and one I always recommend) is using modules like Display Suite to customize the fields on your content type. You can customize the create/edit form as well as you can control which fields you want to be visible when visitors are looking at nodes.


How do I create a menu item when a node is submitted? I have created a new content type and want to add a menu item every time a user creates a new node for this content type.  I can catch the submission using hook_node_submit, but I don't know how to add it to a menu from there.

Try using the menu_link_save function.

<?php
$item = array(
  'link_path' => 'node/' . $node->nid,
  'link_title' => $node->title,
);
menu_link_save($item);
?>


How to hide the View tab in user page? In the user page (www.example.com/user), there are [View | Edit] tabs. Is it possible to hide the View tab and leave Edit tab there?

You could also just use hook_menu_local_tasks_alter() in D7:

function MYMODULE_menu_local_tasks_alter(&$data){
foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "user/%/view"){
            unset($data['tabs'][0]['output'][$key]);
        }
    }
}

Documentation


Media Module Bulk File Upload Is there a way to bulk upload into the Media module? What I'm trying to do is get a huge batch of images into the media Library browser. It seems like you have to first establish the image as an entity in the D7, so most of these bulk methods using something like rsync of scp wont work.

The Plupload integration module allows you to upload multiple files at once.

I've used this module before and I think it works really well. It also allows you to drag and drop files onto the browser window to initiate the upload.


Allow view access to current user and admin I'm creating a view to list user sessions statistics. (Data selected from table myuserstat, there is UID field, myuserstat rows is not a Content Type, just table)

I want to make access url like /mystat/{user}, to list data of specified user.

How can I allow users to see their own stat, and admins see all users stat?
For now i only found how to limit to the current user:
contextual filter->UID->Provide default value->logged user id.
But in that case, how to allow admins to view all users?

Create another view or a page within same view with path /mystat or path can be different without using contextual filters. And in page seetting option in view choose access from none to role and select admin role.


Drupal integration for streaming video I am working with an STI product for wowza media server to allow streaming video on our website made in drupal 7. I am using panels for the profile pages which will have 8 guest camera docks which is simple enough. it will also have a text chat as well as a main video dock for the person who owns that profile. Anyone know how I might be able to set a flashvar to the userid of the profile by variable so i do not have to custom code each profile as people sign up? I want it so when a user signs up they have a profile with all the features and those features are specific to that user so that when one person goes to broadcast it doesnt broadcast to every profile.

Based on your comments and the fact you will be writing some custom code for the video player in your site. You can easily include the Drupal user id into flash variables.

In order to do this, you will load the Drupal user object of the currently logged in user. This is quite easy to do.

<?php

$global $user;
$drupaluserid = $user->uid

?>


How to associate the current Node ID when running from Block layout? I created a Drupal 8 View that creates a block of content associated with a content type.  The block has a context filter of "Content: Node ID". I can place the Node ID of different nodes in the Views Preview and receive different content for each Node ID.  The Views Block seems to be working well in Views Preview.

I would like to place this Views Block in a region of Block layout.  I need the block to obtain the Node ID of the current node so it will display unique content for each different node -- just like in Views Preview.  I have not been able to figure out how to associate the current Node ID when running from Block layout. Some blocks have this ability -- for example "Page title" and "Main page content" that ship with Drupal 8.  Is it possible to give me Views Block this ability?

I've thought of two alternatives to what I have written above:

write a module that creates the block I need -- obtain the current Node ID and display the Views Block.
integrate the Views Block into the twig file associated with the content type -- when the node is displayed, twig will call Views with the Node ID and return the needed content.

Any suggestions?

This feature is already present in form of the contextual filters in views (not limited to D8). To do this:

Add a contextual filter in your view block of "Content: nid"
In "when filter not present" select "provide default value".
Select "Content id from the URL".

And this block will automatically take in the nid from the URL.


Reload only the content area of a website while the sidebars remain static Is it possible to reload only the content area of my website while the rest of the sidebars remain static? I notice that twitter does this, i am wondering if it is achievable in drupal. Thanks

Yes, it's possible to update the content area without updating the sidebars using Ajax or Ahah. There are multiple modules for implementing ajax functionality in various parts of Drupal:

Views Load More
Ajax pages
Views
jQuery AJAX Load
etc.

It will depend on the specific requirements of your site and its content as to which method would make the most sense.

Besides Ajax modules, another more advanced option is an idea often referred to as "Headless Drupal" in which you use Drupal as a backend in conjunction with a dynamic front-end framework like Angular or Backbone.

If you're just getting started with Drupal though, I would encourage you to get a bit of experience building simple Drupal sites before getting too focused on Ajax functionality. If you're not already familiar with Javascript, you'll likely end up being somewhat limited in terms of what you can do with the out-of-the-box functionality available from community contributed modules.


What is the benefit of making sub theme in drupal? I have created a sub-theme of a theme in Drupal 7. I have done all changes to create this and it is working fine. But I am confused what actually it is for, what are the benefits of making this?
I know the differences between base theme and sub-theme but I need more information why we create sub-theme.

For instance. You override only files you need to and you have in your sub-theme directory only these files, not all. You can update parent-theme and not overriding your customizations.


Migrate users from one site to another At the moment I've got 2 drupal 7 site. Now I want to merge those two sites together. If I export the user table in the database from one site and import the data directly into another site, will that be working? Btw, The users don't have any related contents like nodes or comments in the site so I guess the only table I need to worry about the user table. The only concern is the password. I'm not sure if I import the data the user password will be the same.

You need to use Drupal-to-Drupal data migration module. Project page says

"With migrate_d2d 2.1, we are introducing a wizard-based UI for defining your Drupal-to-Drupal migrations. Enabling the migrate_d2d_ui module will add an "Import from Drupal" subtab to the Migrate dashboard - visit that tab, enter the credentials for your source Drupal database (versions 5, 6, or 7), and follow the steps to define how your legacy content maps to the destination Drupal 7 site."


Autoload Mapping for modules I'm trying to better understand how Drupal 8 autoloading for classes is automatically mapped to the src directory in modules.

Basically, I'd like to know how the system knows to look in the modules/module_name/srс directory when searching for classes.

I can't seem to find any details on how it's done through the composer.json files or the autoload_psr4.php files. Perhaps I'm looking in the wrong place?

Drupal 8 follows PSR 4 autoloading standard which is implemented by composer autoloader.

While some Drupal namespaces are registered statically in composer.json and core/composer.json other namespaces are processed dynamically (see DrupalKernel::classLoaderAddMultiplePsr4).

PSR-4 namespaces and autoloading in Drupal 8


db_select get value of the field I have order form with field reference number. when a new order is submitted i need to get the last reference number. I did something similar long time ago in Drupal 7 but now i need to do it in Drupal 8 and i don't know how. I noticed that fields in database are written as 'node__field_ref_number'

DRUPAL 7
$query = db_select('field_data_field_order_reference_number', 'f');
$query->condition('f.bundle', 'order', '=');
$query->fields('f', array('field_order_reference_number_value'));
$query->orderby('field_order_reference_number_value','DESC');
$query->range(0, 1);
$query->execute();
$result = $query->execute();
$record = $result->fetchAssoc();
//drupal_set_message('previous order №: ' .print_r($record['field_order_reference_number_value'], true));
$title =($record['field_order_reference_number_value']) + 1;
//drupal_set_message('order №: ' .print_r($title, true));
$form_state['node']->field_order_reference_number['und'][0]['value'] = $title;
$form_state['node']->title= 'reference number ' .$title;

So far i can get only nid of nods of that type (content_type_order)

DRUPAL 8
$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'content_type_order');
$results = $query->execute()->fetchAll();
drupal_set_message('value' .print_r($results, true));

If I understood correctly, this snippet would get you the number:

use Drupal\Core\Database\Database;

$query = \Drupal::database()->select('node__field_order_reference_number', 'f');
$query->fields('f', ['field_order_reference_number_value']);
$query->orderBy("revision_id", 'DESC');
$query->range(0, 1);
$last_order_reference_number = $query->execute()->fetchCol()[0];

If you need to further understand the database schema related to your field, you could try these commands:

mysql> show tables like '%order_reference_number%';

+----------------------------------------------+
| Tables_in_drupal8 (%order_reference_number%) |
+----------------------------------------------+
| node__field_order_reference_number           |
| node_revision__field_order_reference_number  |
+----------------------------------------------+
2 rows in set (0.00 sec)

mysql> describe node__field_order_reference_number;

+------------------------------------+------------------+------+-----+---------+-------+
| Field                              | Type             | Null | Key | Default | Extra |
+------------------------------------+------------------+------+-----+---------+-------+
| bundle                             | varchar(128)     | NO   | MUL |         |       |
| deleted                            | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                          | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                        | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                           | varchar(32)      | NO   | PRI |         |       |
| delta                              | int(10) unsigned | NO   | PRI | NULL    |       |
| field_order_reference_number_value | varchar(255)     | NO   |     | NULL    |       |
+------------------------------------+------------------+------+-----+---------+-------+
7 rows in set (0.23 sec)

mysql> select * from  node__field_order_reference_number;

+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | field_order_reference_number_value |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| page   |       0 |        17 |          28 | en       |     0 | 123                                |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
1 row in set (0.00 sec)


SA-CORE-2013-003 - Files directory Not fully protected I'm using Pressflow 6.38 and I'm trying to implement SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities | Drupal.org inside of /etc/httpd/conf.d/pressflow.conf configuration file, like following:

<DirectoryMatch "^/(tmp|var/www/html/current/files)">
    # Turn off all options we don't need.
    Options None
    Options +FollowSymLinks

    # Set the catch-all handler to prevent scripts from being executed.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files *>
        # Override the handler again if we're run later in the evaluation list.
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    # If we know how to do it safely, disable the PHP engine entirely.
    <IfModule mod_php5.c>
        php_flag engine off
    </IfModule>
</DirectoryMatch>

however still getting following message in Status Report page:

  Files directory   Not fully protected

See http://drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the files directory to help protect against arbitrary code execution.

My environment:

# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.8 (Santiago)
# rpm -q httpd php
httpd-2.2.15-55.el6_8.2.x86_64
php-5.3.3-48.el6_8.x86_64
#

quote from SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities | Drupal.org:

  Additionally, the .htaccess of the temporary files directory and
  private files directory (if used) should include this command:

  Deny from all

instead of using .htaccess inside of /tmp directory (which can be wiped), I placed following rule inside of my pressflow.conf:

<Directory "/tmp">
    Deny from all
</Directory>


Create node fields with values that change every week but old values are being stored My company has about 15 oil tanks. Every week a guy checks the remaining oil in every tank and writes down the numbers. I want to create a visual representation of the remaining oil in every tank. I have a drupal installation already setup in my server and I thought that I could incorporate a solution in the existing site. What I have done so far:

I have created a new content type called tanks.
Created the various fields (like tank_id, volume, status etc) that will hold information about the tank.
I also have a field that is called latest_amount where I want to store the most recent measurement of oil in the tank.
I have also written some basic php code that does a simple division (latest amount/volume), gets the percentage of the tank that is full and I'm thinking about drawing with html a basic shape that will be green if it's above 75%, yellow if it's 25%-75% and red if it's below 25% (maybe there is a module that can help me with this drawing).

My problem is that I want to keep past measurements so that I can create a graph with these percentages over the last 3 months. Is there any way for me to keep these stats along with the date that the specific field value has been added? Also, is there a way to restrict node editing to only adding a new value in the latest_amount field every week (i.e. not being able to alter any other information about the tank)?

Check the module field_collection

  Provides a field-collection field, to which any number of fields can
  be attached.

add field collection to your tanks content type
in collection add fields for stats like date, amount etc
after that you can store latest amount and display them in views, charts etc


How to count the number of values in a multi value field with the Paragraphs module? I’m currently using the Paragraphs module. I have pretty much set up a simple bundle with a title, image and text area. I went into the basic page content type and added the paragraph field reference which worked fine. This had a limit of up to 6 paragraphs per basic page. They can add less than 6, just not any more than 6.

My question is, how do I count how many paragraphs have been entered on that particular basic page. I’m trying to count the amount of paragraphs added so each time it’s added it can dynamically modify the class containing the paragraph.

For example, using Foundation 5 I want to count how many entries have been made and if there is 3 paragraphs then I want the name of the class to be foo for example.

If you're theming the paragraph field using a theme template or a preprocess function, an $id or $variables['id'] variable is available that has the count of the current paragraph item.


Set up Mailhandler with IMAP Gmail I can't figure out how to configure Mailhandler with an IMAP Gmail account locally with MAMP.

I've been following the recommendation at http://drupal.org/node/207366#gmail and it is never working fine. The test mbox that ships with the module works just fine.

My settings are:

Protocol: IMAP
Folder: INBOX
Domain: imap.gmail.com
Port: 993
Username: username@gmail.com
Password: mypassword
Extra commands: /ssl

I've tested different combinations like:

Switch imap.gmail.com to gmail-imap.l.google.com
Changed port to 995 or 587
Trimmed username to "username" only (w/o @gmail.com)
Switched /ssl by /ssl/novalidate-cert, /tls, /notls...

Most of these attempts were without any conviction and only because the default config wouldn't work and return the following error when saving:

Warning: imap_open() [function.imap-open]: Couldn't open stream {imap.gmail.com:993/ssl/novalidate-cert}INBOX in MailhandlerPhpImapRetrieve->open_mailbox() (line 118 of /docroot/sites/all/modules/mailhandler/modules/mailhandler_php_imap/plugins/mailhandler/retrieve/MailhandlerPhpImapRetrieve.class.php).

And this error when hitting "Test connection":

Mailhandler could not access the mailbox using these settings

Any idea what I'm missing to make this work ok?

P.S. : I can ping imap.gmail.com or telnet on port 993 just fine.

Unfortunately, MAMP (even the Pro version) basically provides no support for G-mail.  For evidence, look at the comments on the official guide on the MAMP blog.

Although I haven't tried it, one of the comments suggests this solution.

And here's another way to set up postfix on Lion without relying on MAMP.

I too use MAMP, and instead of working with mailhandler I use the SMTP module instead, which allows Drupal to send messages locally independent of the local mail configuration.


Modifying superfish menus to gives extra block of data I am using superfish menus and it works fine and i want to add extra column in superfish menu which will display some stand alone data. how do i alter superfish menu to do this. I have shown in image what i need to do.

I am not sure you can achieve this with Superfish without a major hack to the module. Try using OM Maximenu which can create menus with all other module blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.


How to customize the shopping cart? This is a real puzzle, if I disable the image field of the display mode of variations, it is still displayed in the shopping cart.

Can someone explain to me how to customize the shopping cart ?

I do not understand. The "Teaser" display mode does not exist and the other display modes are not listed in the view. Why ?

In the last screenshot it looks like you're using the teaser view mode in the cart view. However, in your first screenshot, it looks like you haven't enabled and configured the teaser view mode on the variations. Scroll down on that page, open the Custom display settings, select Teaser, and click Save.

Afterwards, hide the image from the teaser view mode by clicking on the Teaser link below the Manage Display tab.

Finally make sure to do this for all variation types you got, if you do it only on one bundle and add a product (variation) of another type to the cart, the change won't be reflected in the cart view.

It seems the above solution doesn't work as expected, although it used to work for me at some point.
Another solution you can try is removing the rendered order item completely from the view, then adding a new relationship from the order item to the product variation and eventually add only the specific fields of the product variation you want to display to the view's fields.


Use route annotation I'm trying to create my first module. I'd like to know if I can use annotation route like Symfony instead of separated files.

For example, can I use the second snippet instead of the first one?

hello_world_settings:
  path:  '/hello/world'
  defaults:
    _content:  '\Drupal\hello_world\Controller\HelloWorldController::myCallbackMethod'
  title: 'Hello World'
  requirements:
    _permission: 'access content'

/**
 * @Route("/hello/world",name="hello_world")
 * @Method({"GET"})
 */
 public function myCallbackMethod() {

AFAIK, Drupal doesn't support any of the Symfony route annotations.  The code is present in vendor/, but not used by core.

The closest thing is the concept of Entity links, which are part of the Doctrine annotations on the entity class.  These link names can be used in the ::toUrl() method to generate the canonical link for an entity, the edit link, etc.  However, the routes still need to be defined in the routing.yml file.


Images in content type: reusing and limit In a content type template, I allow images. The only widget that appears for that field, is a File Upload widget. What if I want to reuse the image that has already been uploaded?

Also, how do I raise the limit of uploaded images from 10 to more?

Thanks
Artur

Use the FileField Sources module to allow you to select new or existing files through additional means, including:

Re-use files by an auto-complete textfield
Attach server-side files uploaded via FTP
Transfer files from a remote server (cURL required)

4. Select existing files through the IMCE file browser

Also, to raise the limit of uploaded images from 10 to more, edit your image field settings and set the "Number of values" to "unlimited"


Display View in Simplenews Email I have a view block on my frontpage ('news-block') that displays 3 headings which are links to the 3 latest news articles in my website (content-type = 'news').

How do I display this view block in my Simplenews? Alternative suggestions are welcome. I assume this data will display whatever it is at the time of sending, which is fine.

Depending on what you want, you can either use a module like Insert View that allows to embed views as a token inside the newsletter body (dynamically, you can choose the view per newsletter issue) or you override the newsletter body template and embed the view there using views_embed_view() (hardcoded per newsletter category).


FACETS : Add "Apply" button that will apply all filters in one query Is it possible in D8 to add an "Apply" button that will apply all facet filters in one query and not having an ajax reload on each option changed ?

i find this for D7 :

https://www.drupal.org/project/ajax_facets/issues/2700063

i am not quite sure  what's been the issue of that issue.

i have created an issue on the facet module and the situation is :

Not soon in the drupal 8 version. This would be a big refactor of the way queries are built right now.

https://www.drupal.org/project/facets/issues/3013702


could i overwrite the array value by the preprocess function? a module that have an array,which value are $links[0]['text']="hello" and $links[2]['text']="world". could i overwrite them value by the mytheme_preprocess_node function in template.php. if can., how do i do?

You could only overwrite them if they are accessible within template_preprocess_node(). For example, if the module adds $links to the $vars (or $variables) array, or to the $node object, in its own implementation of preprocess_node(), you could simply do:
$vars['links'][0]['text'] = "i have changed this text";
If the module does not add $links to the $vars/$variables array or to the node object, you would not be able to change it from mytheme_preprocess_node().


$base_url set to an external domain causes problems when logging in I am developing a conference site with Drupal 7. The site is hosted at domain1.com. The conference is covered by another organization, and they require the conference page to be accessible from their own domain, something like organization.com/conference2014.
Fortunately, Drupal has the $base_url variable and the site is accessible from organization.com/conference2014.

My problem is when I want to access administration interface of Drupal from organization.com/conference2014?q=user/login. After I enter my credentials, Drupal redirects me to the organization.com site which is administrated by the organization administrator. When I access again organization.com/conference2014, it still asks me for the password.

What I need to achieve is, after entering the credentials, being redirected to organization.com/conference2014, and being to perform any administration task.

Do you have any idea on how to tackle this problem?

You can set action on after login user.

And that action could trigger through set a perticular trigger.

please use these url to solve this issue in your site.

www.example.com/admin/config/system/actions
www.example.com/admin/structure/trigger/user

Hope this works for you.

Thanks
Sanjay


Taxonomy term related content When click on any term, content related to that term should be displayed on the right hand side of a page. I have my taxonomy tree on left sidebar using Drupal API function.

What I had done is:

Created view with content type, containing all products related to
taxonomy terms.
Add a field in that content type with field type "term reference"
and widget type "simple hierarchical select" module.

Now what should I do in order to filter the term based content? Any Ideas?

If I understand your question correctly, sounds like you maybe want to use a contextual filter for the taxonomy term TID, and embed as a block in the sidebar for taxonomy pages.

This may help: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7

Steps to help:

create a relationship, Content: Taxonomy terms on node, choose taxonomy, check require this relationship
add contextual filter, Taxonomy Term: Term ID, select the relationship you just made, check "provide default value- Taxonomy term ID from URL, Load default filter from term page.

Just checked on a vanilla install, and that worked a charm for me...


turn off wysiwyg for full html filter format? How do i set it so that the wysiwyg doesn't turn on during full html mode.

I would prefer to hand edit the html during full html filter mode without the wysiwyg editor stripping my html.

I'm using CKEditor.

You can switch to HTML display in D8 by clicking on source tab. So that you can retain Full HTML processing and work without output.


How to create a union of two views? I'm trying to get a union of a user's nodes and comments sorted by "post date".
This post links to sandbox projects for D6 but there is nothing for 7.

This post has an example of using hook_views_pre_execute() and a SQL UNION in D6. This doesn't work for D7 with views 3.

I came across merlinofchaos' comment

  Because we're now using Drupal's new query generator, the query is a SelectQuery object which you will have to modify or replace. Look up Drupal 7's new database layer for more information.

Does anyone have an example of how to do this or any other solution to combine two views?

Here's a working and tested example:

/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(view &$view) {
  if ($view->name == 'my_view') {
    $query1 = &$view->build_info['query'];

    // Basic setup of the second query.
    $query2 = db_select('another_table', 'at')
      ->condition('some_field', 0, '>')
      ->condition('some_other_field', 12345);

    // The number of fields (and their aliases) must match query1.
    // Get the details with:
    // dpm($query1->getFields());
    $query2->addField('at', 'some_field', 'alias1');
    $query2->addField('at', 'some_other_field', 'alias2');
    $query2->addField('at', 'some_other_field2', 'alias3');
    $query2->addField('at', 'some_other_field3', 'alias4');

    // Verify that queries are very similar.
    // dpq($query1);
    // dpq($query2);

    // Matrimony.
    $query1 = $query2->union($query1, 'UNION ALL');

    // Manual test.
    // dpm($query1->execute()->fetchAll());

  }
}

This works for most views.  However some style plugins may do fancy stuff that won't work with this technique (Calendar module I'm looking at you).


Datatables Module not Sorting all Columns I am using the DataTables module (https://www.drupal.org/project/datatables). The sorting option does not work for all columns, and I am not sure why. I'd like the ability to have all columns sortable as this is just in the DOM, shouldn't that be a possibility?

For example:

Columns that do sort: Content Text, Terms, Dates...
Columns that do not sort: View Conditional (if this then that results)

Here is 2 of the table columns html output:

Title

There is a checkbox in the views datatable settings next the "TITLE" column above...

There is not checkbox enabling sorting on the column below (views conditional):

BLM

EDIT:
This might be due to the sType (https://datatables.net/development/sorting)

In the DataTables module, changing line 298 from FALSE to TRUE allows all sorting... I am sure there is a reason not to allow this, but not sure why. Investigating sType more to apply another elseif on string or whatever type is being produced by the views conditional...

Line 298:

if (empty($options['info'][$field]['sortable']) || !$fields[$field]->click_sortable()) {
        $column_options['bSortable'] = TRUE; //changed from FALSE
      }

Line 301:  //checks what sType the data is:

else {
        // Attempt to autodetect the type of field in order to handle sorting
        // correctly.
        if (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
          $column_options['sType'] = 'html';
        }
        elseif (is_numeric($fields[$field]->last_render)) {
          $column_options['sType'] = 'numeric';
        }
        elseif ($fields[$field] instanceof views_handler_field_date) {
          $column_options['sType'] = 'date';
        }
        $column_options['bSortable'] = TRUE;

STRING is not one of the options in here. Though the documentation says it could be: http://legacy.datatables.net/usage/columns#sType

I attempted to add it like so real quick with no results:

elseif (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
      $column_options['sType'] = 'string';
    }

I used a hook_views_data_alter() to add 'click sortable' to the field that didn't have that option.

/**
 * Implements hook_views_data_alter().
 */
function utagta_helper_views_data_alter(&$data) {
  // Allow the views fields to be sortable.
  $data['views']['view']['field']['click sortable'] = TRUE;
}


Reset Password in drupal 7 I want following functionality when user click on forgot password.

I want user will get an email to rest his password. when he click the link, A new password wil generated and send into his email

Any idea?

Thanks

By default Drupal has forget password functionality which will send the one time password link to the user. may be you can use this  https://www.drupal.org/project/simple_pass_reset module if it matches your requirement

https://stackoverflow.com/questions/24051390/change-admin-password-in-drupal-7


How to make a field required using JavaScript injector I have a field that is part of a content type that I need to make required by using a JavaScript injector.  The reason that I can't just make it required while setting the rules for that field is because I have to parse a string that will display on the same page whether or not I need to make it required.  Any thoughts?

Matt -

I would recommend looking into hook_node_validate(). This is a function hook provided by Drupal core that allows you to add custom validation into the form. While you cannot select "required" from the field UI, perhaps you can validate it here and then return an error if the form doesn't provide the correct information for that specific field.

Other things to investigate: hook_form_alter() and hook_validate - where you can add custom validation functions into the Drupal form array itself.

Helpful links:
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_validate/7

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


User ID problem when programmatically creating nodes I have written a migration script that migrates data from Drupal 4.7 to Drupal 6. It is highly customized for my purposes. I am able to create new nodes with no problem. However, after I save the nodes I am noticing that the user that created it is showing up as "Anonymous" and in the database it has a uid of 0. Yet, when I wrote my code I have set it to 1 when the migrated user id has not been found. I have even double-checked to make sure that it is setting the uid to 1.

Why would this be setting it to uid = 0 when I specifically set it to 1?

  $node = new stdClass();
  $node->type = 'opinion_article';
  $node->title = $blog->title;
  $node->body = $blog->body;
  $node->teaser = $blog->teaser;

  //We need to associate the content to the user that created it.
  $node->uid = 1;
  $node->name = $account->name;
  $node->status = $blog->status;
  $node->comment = $blog->comment;
  $node->promote = $blog->promote;

  //Set a default topic of Migration Data.
  $node->field_topics[] = array('nid' => 820); ###### Remember to update this node ID to reflect the topic nid on dev once created. It is nid 916 on the dev server.  ################

  //Set the parent group
  $node->og_parent = $parent_nid;

  //Create the node
  $node = node_submit($node);
  node_save($node);

The problem is that node_submit() contains the following code.

  if (user_access('administer nodes')) {
    // Populate the "authored by" field.
    if ($account = user_load(array('name' => $node->name))) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

When it's not able to load the user object having $node->name as username, it sets the user ID to zero.
As you have already set the values for the node object, it is useless to pass the node to node_submit(); it would be better to just pass it to node_save().


Is it a good practice to declare drush as a dependency of a contrib module? Is it a good practice to put "drush/drush": "^9 || ^10" in the required section of the composer.json of a contrib module if drush is actually its only interface?

I'm maintaining a contrib module, that can be operated only by using drush, but as far I saw in other similar modules (like: https://www.drupal.org/project/data_fixtures ) - drush doesn't appear in the composer's dependencies. Is there any reason for that other than maybe "crowd psychology"?

I'm just considering putting drush as explicit composer dependency of my contrib module.

If the module doesn't do anything when Drush isn't installed, for example because it's only implementing Drush commands, adding Drush as dependency in composer.json is perfectly fine.

I don't see any reason for not adding it in the composer.json dependencies. Probably, the users who don't add it as dependency for their modules think that most users download the module from the project page on drupal.org and the dependencies on composer.json wouldn't stop them from installing the module.

I would rather add the dependency from Drush in the composer.json file, in the same way I would add a dependency from a module the Standard profile installs, in the .info.yml file of a module I develop.
Eventually, I would add a hook_requirements() implementation that doesn't allow users to install the module when Drush isn't present, for the users who install the module from the user interface or using the project archive downloaded from drupal.org.


Alter values available in node reference field based on term reference I have a content type structure as mentioned below,

Content Type

Field Collection

Term Reference
Node Reference
Text Field

What I want to accomplish is, As I select the Term Reference value; the available values in node reference field with auto complete widget should only be of those nodes that have the term reference value assigned.

FYI The field collection will have multiple values.

It looks like I am late to answer your question :), but I hope this will help someone.

Using Dynamic dependent fields you can achive this, but it support Entity Referencefield not Node Reference
Documentation for Dynamic dependent fields


What's wrong with my custom node template? I'm attempting to make my first custom node template that is supposed to be used for a certain content type with the machine name of "content_block." I copied the "/modules/node/node.tpl.php" file to my theme's directory at "/sites/all/themes/mytheme." Then I renamed the file to "node--content_block.tpl.php."

Then I cleared the site's cache via "Administration » Configuration » Development » Performance."

It seems to only be partially working. Some of my content type's field variables render, but not with the values I expect. Others don't render anything but the word "Array".

My template code looks like this:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if ($field_headline == TRUE && $field_headline != " "): ?>
    <?php print render($title_prefix); ?>
    <?php print $field_headline_level; ?><?php print $title_attributes; ?>><?php print $field_headline; ?></<?php print $field_headline_level; ?>>
    <?php print render($title_suffix); ?>
  <?php endif; ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php print $field_content; ?>

One thing I definetly don't understand is when to use print render($variable) and when to use print $variable.

Use print render when the variable is a build array and use
Use print when the variable is a PHP string containing HTML.

For more details, render arrays on d.o. (render and build arrays are the same thing).


Set the template for the frontpage How do I change the Drupal 8 frontpage template, so it doesn't use the regular page.html.twig template?

Enable twig_debug and you will see HTML comments surrounding the output that tell you what template suggestions are available. In this case you will get output like:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.html.twig
   * page--node.html.twig
   x page.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/page.html.twig' -->

Naming your template page--front.html.twig will use that template for only the homepage.


How to fix 'Cannot access empty property' when visiting admin/reports/databasereport? Fatal error: Cannot access empty property in /home/public_html/sites/all/modules/dba/database/mysql.report.inc on
  line 44

I get the above fatal error on a WSD when clicking on /admin/reports/databasereport  (using Drupal version 7.22).

Any idea what it means and how to fix it?

I haven't used the Database Administration module before but when i looked on the line 44 of that module and I found that:

$value = new stdClass();
$query = db_query('SHOW GLOBAL STATUS');
foreach ($query as $row) {
  $column = $row->variable_name;
  $value->$column = $row->value;
}
return $value;

It means you can't fetch the data from 'SHOW GLOBAL STATUS' SQL statement. So i think maybe your current MYSQL account didn't have right to do that.


How can I prevent text areas from being resizable? Text areas in Drupal 7 are resizable by default.  I would like to turn this off, but when I checked a text area with Firebug, I couldn't find the CSS that was making it resizable.

How can I prevent text areas from being resized?

It's JS that makes the text areas resizable, not CSS. I think the simplest way to disable this behaviour for all textareas is to implement THEMENAME_textarea() in your theme and remove it there:

function THEMENAME_textarea($element) {
  $element['element']['#resizable'] = false ;
  return theme_textarea($element) ;
}


Where to change default translation language for drupal 7 while using entity translation module? I'm doing some translations, but I'm not sure how to change the "original content" to english. I can't seem to find a setting to change it to english. Anyone knows where to go for this?

You have to first delete your translations then you will be able the select another language under the dropdown box for the original content.


how to get form element value before submit in drupal i have form has first name and last name  field,and a custom login form,when user login it redirect to another page,and i want to get first name and last name fields in that page..,

this is the way i tried...,

function doner_user_login(&$edit, $account) {
  drupal_get_form('doner_step_3');
  $val=$form_state['values']['about_fname'];

  $edit['redirect'] = 'http://test.good.com/moll/ijs/d67/step31?fname='.$val.'';
}

Once an user has logged in, the GLOBALS $user with the information related to this user is ready to use. It isn't neccesary to add an argument to the URL in your redirection.

If it isn't loaded the information you want, you could store that variable in the $user object.

function doner_user_login(&$edit, $account) {
  drupal_get_form('doner_step_3');
  $GLOBALS['user']->doner_variables = $form_state['values']['about_fname'];
}


How to use hook_node_presave to change field's value Basically, I want to put first name & surname together into $node->field_par_contact_name

But it gives me warning. (See below)

function partnership_node_presave($node) {
  if($node->type == 'partnership') {
    $first_name = $node->field_par_contact_first_name['und'][0]['name'];
    $surname = $node->field_par_contact_surname['und'][0]['name'];

    // https://drupal.org/project/field_hidden
    // Hidden variable
    $node->field_par_contact_name['und'][0]['value'] = $first_name. ' '. $surname;

    // Warning after save: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of .../drupal-7.23/includes/entity.inc
  }
}

Updated, please see image:

For starters, you're probably using the wrong array key for the field value that you're saving; 'name' should be 'value' there.

$node->field_par_contact_name['und'][0]['value'];

Second, you're actually using Taxonomy Term Reference fields for your "first name" and "surname" fields. One important point about Reference fields is that you can't always assume that the referenced entities have been fully loaded and are available in your object. By default, when the node object is loaded, that field only looks like this:

$node->field_par_contact_first_name (Array)
  'und' (Array)
    0 (Array)
      'tid' => 284

Only the 'tid' key is definitely there. 'name' is a property of the referenced term, and isn't usually automatically available. (Subsequent code may actually load the referenced term and make it available within the $node object, but that's just happenstance if so.)

You would have a much easier time of it if your "First Name" and "Surname" fields were text fields instead of references. Then, those values would belong directly to the node itself, rather than to a separate taxonomy term being referenced.

If you're stuck using taxonomy term references, though, then you should make a point in your code to load the referenced term, then get the values you need from the $term->name property itself.


How to get fields from taxonomy terms? I am able to retrieve taxonomy terms programmatically, (as long as I only want to reference the default fields, 'tid' and 'name'). But how do I access custom taxonomy fields?

$vid = 'MACHINE_NAME';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
    $tid = $term->tid;
    $term_name = $term->name;

    // REFERENCE CUSTOM FIELD VALUES HERE...

}

I have tried all manor of ways I have seen, but can't get any of them working, eg:

$value = $term->FIELD_NAME->value;
$value = $term->get('FIELD_NAME')->getValue();

How do I reference custom taxonomy term fields by their machine name, from what is returned by getStorage('taxonomy_term')->loadTree($vid)?

The entities aren't loaded by default (for performance reasons), but TermStorage::loadTree takes a $load_entities parameter:

  If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

That will give you access to the fields. E.g.

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vid, 0, NULL, TRUE);


Load all field collections of a given type Currently I am using a query to load field collections of a specified type, but I wonder if there is a more drupaly way to do it?

$query = db_select('field_collection_item', 'fci')
  ->fields('fci', array('field_name', 'item_id'))
  ->condition('fci.field_name', $field_collection_name)
;

$result = $query->execute()->fetchAllAssoc('item_id');
$fcs = entity_load('field_collection_item', array_keys($result));

Lets say you have field collection with type 'field_my_dates'. So you can get field collection details using node and collection type as given below.

<?PHP
    $itemCollection = field_get_items('node', $node, 'field_my_dates');
    $wrapper = entity_metadata_wrapper('node', $node);
?>

Thanks


Cache is not cleared I have a weird problem that the cache won't be cleared. It all began since I added a template file "field--custom-field-name.tpl.php". The field is attached on user entity type.

I put var_dump(get_defined_vars()) to output the available variables that I could use. I modified the file to begin using some of the variables, and cleared the cache. I found that the page is still showing var_dump output.

I tried:

Clearing the cache under performance tab
Disabling/Enabling themes
Emptying the cache* tables in database
Renaming the field template file
Deleting the field template file

I don't have Drush, though.

The page just doesn't go back to normal; it just keeps showing the var_dump() output.

How can I fix this?

-Update-
admin/reports/dblog has nothing useful, clearing cache has no error output.
To me it's like it doesn't remove the var_dump call from cache when I remove/update that field template, and it sticks to somewhere permanently.

I've also checked every file in the same folder, not var_dump or output statements found.

Could it be a bug of drupal cache?

The conents of the template files are not cached. So your concern is misplaced.

I am assuming that it is views. Edit the view goto Advanced->Others->Theme Information you can find out which template file is being used. Goto to the file and make the necessary changes or else copy the default file from the views module to the location.

Even if the above is not solving your problem, the var_dump is coming from the database and not code.


Is the mail_logger module safe for production? I'm having intermittent problems with emails that are silently failing on a production environment. I'm troubleshooting with the mail_logger module, and it would be extremely helpful on production.

However, for some reason I feel that this is a 'development/debugging' module and not something recommended for production. Are my fears unfounded?

No, it doesn't enable any developer backdoor features (e.g. arbitrary PHP execution, code/stack dumps, etc.) if that's your concern.

For the most part, its code base is Views integration & an admin interface wrapped around its core function; intercepting outgoing mail through hook_mail_alter() and storing in the mail_logger table.

I'd say the only concern there is privacy for your users.


BaseFieldDefinition setDisplayOptions ... type = 'string_textfield' ... unable to set default placeholder or size? I'm unable to get a default placeholder and/or size to register against a BaseFieldDefinition. I'm trying something like:

$fields['company_name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Company Name'))
      ->setDescription(t('What\'s your company called?'))
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'settings' => [
          'display_label' => TRUE,
          'size' => 10,
          'placeholder' => '',
        ],
        'weight' => '9',
      ])
      ->setDisplayConfigurable('form', TRUE);

But when I enable my module, and check the 'Manage Form Display' tab for the relevant entity, it shows the defaults (size = 60, placeholder = {null}).

Does anyone know how to get these working..? Especially the placeholder one.

I think you need to be calling "setSettings" on the field, not passing the settings as a part of the display options.


How to eMail a periodic summary of flagged nodes to users of some role? I'd like to create a periodic summary email that gets sent to a specific role.

The summary email would include things such as:

flagged content / users
count new users
count new nodes
most viewed content
flagged content / users

Item #1 is really the main goal - instead of send an email each time a user flags a user or node, I'd like to send a daily summary of all of the flagged entities.

How would you approach this?

Assuming you think of creating a view for such flagged content / users for (say) "current day", there is a solution to do what you're asking about. This solution uses the Rules, Views and Views Rules module, as further detailed below.

1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

  ... provides two types of elements in Rules, configured with a "Rules" view display:

  Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

  Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

  Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'

After you enable the Views Rules module, use Views to create a view of your "* flagged content / users*" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a Rule Component using the view of display type 'Rules'

Create a Rules Component, using these guidelines:

Add whatever Rules Conditions you might want (if any).
Some Rules Actions you'll need to create (add) for sure:

Create a variable, with no initial value, say you name it "eMail Summary" (machine name email_summary), which will be used in subsequent Rules Actions.
Add a Views loop (by using the link that says Add view loop), and select the "Rules" display created in the previous step. Configure the parameters and variable names. And for each views result contained in your Views loop (about some "flagged content / user", as in your question), perform a Rules Action like Set a data value, for the email_summary variable from the previous Rules Action. The actual value to be assigned, is the previous value of email_summary, to which you append the desired data about the Views result being processed. For this you can use the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).
Add a Rules Action to Send an eMail to a selected role (as per your "periodic summary email that gets sent to a specific role"), whereas for the body of that eMail you simply use the value of the email_summary variable.

If you're not familiar enough with Rules to create and populate that email_summary variable, you may want to have a look at the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?", in which a similar variable is used.

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

4. Schedule the Rules Component for daily execution

Make sure you have the "Rules scheduler" enabled (a sub-module of Rules).

Improve your Rules Component from the previous step, by adding a Rules Action (as the last action to be performed) to Schedule a Rules Component, whereas the actual Rules Component to be scheduled is the Rules Component itself. You want it to be scheduled in "1 day from now" (to make it happen daily).

To execute this Rules Component the very first time, just execute your Rules Component "manually". To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

Assuming your QA-testing succeeded, and assuming your cron jobs are running also, the eMail should get created next time cron runs (after an amount of time, depending on the amount of time you configured in your Rules Component to get it rescheduled).

PS: The above addresses "Item #1" of your question, though it should be pretty forward to use a similar approach for the other items in your question.