URL Aliases not recognizing Node Reference Tokens? I'm having trouble getting my URL Aliases to cooperate with certain Tokens... specifically Tokens generated by the CCK Node Reference module. Here is the URL structure that I'm trying to establish:

/department/course/lecture

Each section refers to a referenced node... so a lecture refers to a course which refers to a department. Make sense? My URL Alias structure, with Tokens in place, looks like this:

[field_course_department-title-raw]/[field_course_number-raw]/[field_lecture_display_number-raw]

When the URL Alias gets generated, it becomes:

/%5Bfield_course_department-title-raw%5D/%5Bfield_course_number-raw%5D/lecture-2

So the only Token that is working is the lecture (the last one). The first two tokens aren't even recognized by Drupal and, as you can see, are encoding the brackets from the Tokens into HTML entity codes. Those two are also the CCK Node Reference fields. Worth mentioning, the two offending Tokens were present and available in the Replacement Patterns section on the URL Alias settings page... so it would seem that Drupal should be able to recognize them, right?

What's going on here?! Help! Any ideas or suggestions would be greatly appreciated! Thanks in advance.

The issue I_THINK is that tokens are only generated on content in the current node, eg, it has no inherent intelligence to walk up the hierarchy of node references to find all your other info stored in other nodes.

So, it would appear you have a node ref to the course already in your lecture, so just make sure you have the correct [TOKEN] there (TOKEN-title-raw instead of TOKEN-number-raw perhaps?) but to get up level to the department, you probably have to put a field in your lecture node and populate it behind the scenes with the department node reference (via hook_nodeapi() and $op presave by node_load()ing the nid of the course and getting it from there)


Where to store JS and CSS that is not associated with a module? I've been given a ZIP file with the JS, CSS, HTML, and assets for a stand-alone jQuery application.  We would like to host this application through our Drupal 7 site hosted on Acquia Cloud.  I am looking for best practices on where to store this application. I've included additional info below but can supplement if there's other relevant info.  Can anyone suggest where I should store these files?

Due to some business-related decisions, we will always receive updates to this application in a ZIP file.  It may or may not receive updates. If it does, we'd like our content admin team to be able to manage it through Drupal or FTP.  It has not yet been decided if the application will be embedded in a page or accessed on it's own.

In our current site, we are not able to upload an entire directory and keep it in the same structure.  Each file must be uploaded manually.  We are fairly new to Drupal so I don't know if there is a module that would get us around this issue.

I am not allowed to make changes to the code or alter the directory structure (as that would require changes to the file references).

If there are no best practices for this, we can store it somewhere else and link out to it.  I would prefer to avoid this but if that's the recommended best practice, we can do it.

My gut feeling would be to place it in a folder in the root of your website and access it through a subdomain. I'm not sure, without knowing more about the application, if there is an effective way to integrate it with Drupal. It seems like it should stand on its own, in it's own directory structure, as it is a separate entity. I stand to be corrected here, but i don't see a problem with hosting it concurrently with your Drupal installation. It won't be manageable through the CMS, but without building the functionality in Drupal itself, it wouldn't be anyway.


More options for managing node display I am trying to clean up the node pages and am finding very few options under the Manage Display tab. Do I have to dig in to the code and css to get some more control or is there a module that allows for greater customization in this area?

I am thinking about options similar to what Views allows.

Adding relationships to pull in related content. e.x. author name from profile instead of using username.
A specific example: One content type has a photo and alot of text, and I want the text to wrap around the photo.

In general, as Clive said it is difficult to give answer to a question that broad in scope. But in general there are two broad directions:

Use Modules like Panels and Display Suite - These allows customizations in node pages by allowing you to chnage layout, add different contents etc.
Follow custom theaming path. this involves writing modifying the preprocess function and modifying the node.tpl.php

Any more specific info will require you to give out more details in terms of what you want exact in terms of layout and "clean up"


CSS Mobile-compatible Theme for Drupal? Are there any CSS Mobile-compatible Theme for Drupal?

Example of a CSS mobile-compatible site: http://framelessgrid.com/

"Responsive", as mentioned in your comment, is indeed the buzzword. On a small scale, I have had success using Sky to create a mobile friendly site.


How can I print $submitted in a region template? I have a region--content.tpl.php and am trying to figure out how to print the $submitted variable (usually printed in node.tpl.php).

--- EDIT ---

Including here the final code I used.  This lets you print out the themed user link where as the original code only printed the name as plain text.

function theme_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $node = menu_get_object();
    $user = user_load($node->uid);

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = 'By ' . theme('username', array('account' => $user)) . ' | ' . format_date($node->created, 'short');
    }
  }
}

The region template has no concept of the page context, so it doesn't know about the node by default.

You can give it that context by implementing hook_preprocess_region() in your theme's template.php file (or a module file), and seeing if there's a node available there:

function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'region_name') {
    $node = menu_get_object();

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $node->name, '!datetime' => format_date($node->created)));
    }
  }
}

After you clear the caches, your region template on node pages should have the $submitted var available to it. Obviously that might need a bit of tweaking to suit your needs.


joining 2 form, but submit handler can not work I joined this 2 form and the current submit only works for the 2nd form... also it is showing an extra save button :( can anyone help me how to join the submit,preview and delete button?

here is my code :

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

switch ($form_id)  {
  case 'product_node_form':

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

    module_load_include('inc', 'profile2_page', 'profile2_page');
    $profile2 = profile2_by_uid_load($uid, 'main');
    $entity_form = entity_ui_get_form('profile2', $profile2, 'edit');

    $form[] = $entity_form;

    dsm($form);

    return $form;
  break;
}

}

I'd sugest to build your own form using FAPI and create the nodes programmatically in the submitthandler.

Looking at what you get in hook_form_alter has of course a good learning effect.


Rule works but produced "err_empty_response" error when I want to edit it So I have created a rule, that works, does what it should exactly do (so the syntax and configuration is okay), but after creating it and waiting a while, the rule becomes un-editable and the edit page gives just WSOP, while disable, export, delete etc still keeps working. I tried manually recreating the rule, it again works and is editable for a while, until it does the same thing.  There is also no error generated on apache when this happens. I also tried it on multiple computers and browsers. I have clean path URL enable though, could that be an issue?
Here is the exported rule code

{ "rules_odeslat_pp" : {
    "LABEL" : "odeslat PP",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "user_update" : [  ] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "account" ],
          "roles" : { "value" : { "4" : "4", "6" : "6", "3" : "3" } },
          "operation" : "OR"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "account:field-pp-odeslany" ] } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : [ "account:field-stav-uctu" ] },
          "PROVIDE" : { "variable_added" : { "pz" : "PZ" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "pz" ],
            "op" : "-",
            "input_2" : [ "account:field-pp-odeslany" ]
          },
          "PROVIDE" : { "result" : { "ns" : "novy stav" } }
        }
      },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "mimemail" : {
          "key" : "vyplata",
          "to" : [ "account:mail" ],
          "cc" : [ "" ],
          "subject" : "Informace o Vaší odměně",
          "body" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "plaintext" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "language" : [ "" ]
        }
      },
      { "data_set" : { "data" : [ "account:field-pp-odeslany" ] } }
    ]
  }
}

Have you tried this on multiple servers as well? It is likely something on the server, so other browsers and computer won't make the difference. You did not specify the Drupal version but I ran into a similar situation with Drupal 8 while editing Views.

For me the solution was to increase the PHP memory limit. The linked page shows several ways to do this, but I chose to do it in the php.ini file. I believe it is 256M now.


Output views_embed_view to Ajax content I have a View block. I can print the content with views_embed_view function, passing $display_id, contextual filter, etc.

Now I want the user to click on a point in an image, and with Javascript, show the block in a div. So when the user click on different coordinates of the image, I show different product details in that div.

This should be possible to accomplish using Ajax ( $(#div-id).html() or div_id.innerHTML ), but my limited experience with Ajax is to retrieve a JSON formated data, not a full HTML block of a View.

How could I get it working? Is it possible at all?

I have finally solved it, by using the following code which goes in a custom module.  The problem I had was that it was not rendering anything as there were nested divs. If you play with styles or add some HTML between divs, it will show the data.

The code is available at http://www.seanbuscay.com/ajax-reader-demo/


When creating content: Force the checkbox "Provide a menu link" to be checked by default When creating content, I would like to force the checkbox "Provide a menu link" to be checked by default.

What I'm really trying to do:

I created a new content type
I used node_add to get the form associated to my content type and render it into my template.
In my module I used the hook_form_alter to hide some fields of my form.

But when the user submit the form and the node is created, there is no menu link created by default.

I looked everywhere for this! The Menu Force module does this:

  This module enables you to make the Menu Settings required on specific content types.

After installing a "Make the Menu Settings mandatory for this content type" tick box becomes available on the settings for each content type.


How to apply pager in a table using theme function? I am rendering and displaying data using theme table. I'm using

   $form['pager'] = array('#theme' => 'pager');

for displaying pagination. Now my intention is to display pager in two areas of screen. One is above the theme table and another one is below. I placed this code two times but pager is coming only once.

Can anyone please help me?

Added  the below lines in above and below theme table script.

     $form['pagerTop'] = array('#theme' => 'pager'); and
     $form['pagerBottom'] = array('#theme' => 'pager');


View with terms and if the're flagged or not on userpage I want to make a subscription-page on the users-page. A user can flag terms. On the user-page there should

1) It's no problem to get a view with flagged content

relationship Flags [flag name]
contextual filter Flags: User uid

(see How to create view with user's flagged content?). The view shows only flagged terms.

2) It's no problem to get a view with flagged and not-flagged content

relationship Flags [flag name] with current user & include only flagged content NOT checked
path like /subscription

But as soon when i alter the path to user/%/subscribtion, every user can see other subscriptions by altering the path. When using this path with option 1), i see only flagged content (??). Removing the contextual filter, shows all content but accesible for everyone.

How can i restrict the access to the own subscriptions, showing flagged and unflagged terms?

Views only has 2 means to restrict access to Views: via a role or via a permission. Neither can help here so you'll have to use some other means to restrict the route path.

One way to go about this is to use the Views Access Callback module which was built for the purpose of dynamically checking access to a View. Once enabled, any module can implement hook_views_access_callbacks() to define a custom callback that can be used for permission checks.

It should be pretty easy to define a simple callback that inspects the current path to see if it belongs to the current user:

/**
 * Implementation of hook_views_access_callbacks().
 */
function MYMODULE_views_access_callbacks() {
  return array(
    'MYMODULE_access_account_subpages' => t('Access Account Subpages'),
  );
}

/**
 * Check that the user is the owner of the subpage.
 */
function MYMODULE_access_account_subpages($account = NULL) {
  global $user;
  return (arg(0) == 'user' && $user->uid == arg(1));
}


Get node url alias/path when loading the node using node_load() Does the node_load() does not return the node url alias in the node object or am I missing something.

I know one way of getting the url alias/path is using the drupal_get_path_alias("node/NODE_ID"), however I was hoping the object return by node_load should contain node url alias as well.

No, the URL alias is not a field nor entity property, and it doesn't get added to the node object when it's loaded.

It would be trivial to add that data though, using hook_node_load()

function MYMODULE_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->url_alias = url("node/$node->nid");
  }
}


How to Install multiple version of Drush? I have Drush 6 installed in my system.

I need to install Drush 5 too (hosting doesn't support Drush6), how do I install Drush5 without uninstalling Drush6 and use both of them simultaneously, Drush6 for local development and Drush5 for SFTP.

In your .bashrc:

alias drush5=/path/to/drush5/drush
alias drush6=/path/to/drush6/drush

With this, drush5 will give you Drush 5, drush6 will give you Drush 6, and drush will give you whichever of these appears first on your $PATH.

Rename your aliases to suit.


Match JSON POST data with custom node fields Is there a fool-proof method to generate a correctly formatted JSON data object to be received by a create node resource given by a REST server, defined with Services in Drupal 7?

I have setup a REST server accepting the application/json content type. I have also set up an anonymous endpoint with the create node resource enabled and I managed to create a new item with the Poster plugin for Firefox with Content Type set to application/json and the following data

{"title":"Review","type":"story"}

I can't seem to get any further though. I am following this guide and the node is created but my data for the rest of the fields is not added. I use this JSON editor to generate my code so it matches the structure shown by the dsm($_POST) call I placed in node.module's node_submit handler for testing.

The JSON data I am trying to post looks like this (I remove all whitespace before using Poster):

{
"title":"great success!",
"type":"story",
"field_review":[
    {"und":
        [{"0":
            [
                {"value":"Some text"}
            ]
        }]
    }
],
"field_rating":[
    {"und":
        [
            {"rating":"60"}
        ]
    }
],
"field_product_type":[
    {"und": "1"}
],
"field_barcode":[
    {"und":
        [
            {"value":"33333333333"}
        ]
    }
]
}

What am I missing?

The function json_encode(); from my understanding.


How to create a module Dependency Graph? I am running a D7 site with 164 enabled modules. I need to create a module dependency graph so that I can get a better understanding of the module dependencies and find out which modules are critical.

I have checked out https://drupal.org/project/drush_mm but the page says it is obsolete and not present for D7.

Any alternatives?

There is the sandbox drush module dependency_analysis

It provides a drush command that produces a dependency graph using graphviz.  For me, I found that it was a simple matter of installing graphviz using homebrew:

$ brew install graphviz

And then follow the project page description.


How to import url of the nodes via feeds When I use url field in feeds import the url does not get imported for some reason

IIRC because the link field is multiple fields (title, link, description, etc.) you need to map it to the correct one, from quick google searching it seems the Link module dev version has a migrate file in it for this.


Latest update to 8.7 with Commerce caused Edit buttons to appear in place of shipping/billing information After updating core to 8.7, the input fields for shipping and billing information are now hidden and Edit buttons are in their place.  This has allowed users to checkout without entering shipping and billing information.  How can I show the required fields by default and get rid of the Edit button?

It looks like you have Commerce AutoSKU installed. The authors of the module modify one of Drupal's validation constraints which checks if fields are empty or not. This causes the addressbook form element to break, which what you're seeing, on top of other problems.

The issue is reported here, https://www.drupal.org/project/commerce_autosku/issues/3086828

The solution is to either uninstall the commerce_autosku module or apply the patch in comment #3: https://www.drupal.org/files/issues/2019-10-18/3086828-3.patch


Setting the form value to an organic group gid from validation hook of custom field widget (Drupal 7) I have a custom widget which can be used for a group audience field.  Instead of being a dropdown like the OG_AUDIENCE_WIDGET it is made up of three multiple select list, and the group which is actually selected is the one which is picked in the third select list.  I have the actual widget working but I am stuck on validation.  I have been trying to set the gid in a couple of different ways which have failed in a couple different manors.  First:

function multiselect_validate($element, &$form_state)
{
  if($form_state['submitted'])
  {
    $index = array_shift(array_values($element['wrapper']['dropdown_assignment']['#value']));
    $assignment_name = $element['wrapper']['dropdown_assignment']['#options'][$index];
    $query = new EntityFieldQuery();
    $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'assignment_group')
    ->propertyCondition('title',$assignment_name)
    ->execute();
    $node  = reset($result['node']);
    $assignment_gid = og_get_group("node", $node->nid)->gid;
    $value = $value[LANGUAGE_NONE][0]['gid'] = $assignment_gid;
    form_set_value($element,array('gid'=>198), $form_state);
  }
}

This kind of validation returns an error:

[11-Dec-2012 11:23:07] PHP Fatal error:  Cannot unset string offsets in /Applications/MAMP/htdocs/arcade/modules/field/field.default.inc on line 41

I also tried something like this for the final form_set_value:

form_set_value($element,array('gid'=>$assignment_gid), $form_state);

But when I do this and then look at the result nothing actually gets set into the field.

What is the proper way to set the gid for the field?

I'm assuming the validate callback that you have mentioned in your question is the #element_validate callback for the field widget element.

In that case, form_set_value must be set to a list of items because a field is inherently multi-valued. Each item in this list must conform to the schema of the field.

So, in this case:

$items = array();
$delta = 0;
$gid = ...; // From somewhere
$items[$delta] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE, // optional
  'created' => REQUEST_TIME - 3600 // optional (yesterday)
);
form_set_value($element, $items, $form_state);

To illustrate this better, I have a sandbox project up on drupal.org. It declares a new widget with hierarchical dropdowns just like you have described. You can check the code directly from http://drupalcode.org/sandbox/amarnus/1868742.git/tree/refs/heads/master or clone the project from http://drupal.org/sandbox/amarnus/1868742. Hope this helps!


Steps required for transforming some table into a Pie Chart & Bar Chart and by only using core modules? What are the typical steps and/or components required for transforming some data in a tabular format into a Pie Chart and/or a Bar Chart?

And this by only using (a) core modules of Drupal 7, and (b) some charting library that is used as the renderer to actually generate the graph?

If you wanna build your own custom module you can grab code from any one of the following modules and use them in your custom module.
Charts

Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.

Other modules
Views Charts

Provides a "charts" style output for Views module so you can render result-set not just as text (list, tabular) but as pie-chart, bar-chart, scatter-plot etc.

Charts and Graphs

Charts and Graphs is an API for developers. It can easily be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it.


Avoid the user is asked to download the files I am very new to Drupal sorry if my question is very basic or common.
I am creating a web site using Drupal 7 and I am using Tack da files module to tack files which are available for download.

My problem is that I have many PDF files in my site available for download, and the sites shows a popup window to download some of those PDF files. I do not want that popup window, but the site showing the PDF.

Why does it offers the user to download the files, instead of showing them?

By listening to it , it sounds that your browser does not have PDF plugin installed , that is why it downloads file instead of opening.

The same thing can happen to lot of your user, solution to that is Mozilla Project pdf.js

Drupal also have a module for this PDF Module, check that out and see if that helps.


drupal 7.35 .htaccess: Invalid command 'Order', perhaps misspelled or defined by a module not included in the server configuration I'm trying to deploy an instance of drupal with cloudfoundry. Everything loads up and seems to start correctly, but when I try to hit the page I get the following error in the logs:
../.htaccess: Invalid command 'Order', perhaps misspelled or defined by a module not included in the server configuration

I'm using the following php-buildpack: https://github.com/cloudfoundry/php-buildpack

I was able to get the app to load the install page and run by commenting out this line in .htaccess:
Order allow,deny

However I feel like this may cause security issues, and I really want a better fix to this issue./

The current iteration of the PHP buildpack uses Apache HTTPD 2.4.  The message that you're seeing is caused because you're using configuration that is specific to HTTP 2.2.

There are two ways to correct this.

1.) Update your configuration to use HTTP 2.4.  Instructions for migrating can be found here.

2.) You can enable the mod_access_compat module for HTTP 2.4.  This will allow you to keep using the older configuration style.  To do this, you should copy this file from the build pack, place it in the root of your project directory under .bp-config/httpd/extra/httpd-modules.conf and uncomment line #27.  Then when you push, the build pack will detect all the enabled module, include mod_access_compat from the configuration file and enable them.

If you have any trouble modifying the build pack configuration, see here for more details.


Disable render cache for a node type Is there a way to disable the render cache, which caches all the nodes by default, for a particular content type X.

I know we can disable the render cache site wide by commenting out

$settings['cache']['bins']['render'] = ‘cache.backend.null’;

in settings.local.php. But this is not a ideal approach for me as I need to disable the render cache only for a particular node type.

Also, I need to disable the cache for both Authenticated and Anonymous users for the content type X.

Any pointers on the same would be very much appreciated.

Like you said disabling the render cache site wide is not a good idea. If you need this for one content type you can do this in a view alter hook.

If you want to disable caching for authenticated and anonymous users you have to set cache max-age = 0 and trigger the kill switch for the internal page cache:

function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($entity->bundle() == 'article') {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

The same can be implemented in a theme in a preprocess hook.


Variable in file-audio.html.twig I created the following preprocess function to add a value.

function mytheme_preprocess_node__audio(&$variables) {
  $node = $variables['node'];
  $media_field = $node->get('field_image')->entity->uri->value;
  $variables['poster'] = file_create_url($media_field);
}

I want to output the content of $variables['poster'] in the file-audio.html.twig template.

<audio {{ attributes }} poster="{{ poster }}">
  {% for file in files %}
    <source {{ file.source_attributes }} />
  {% endfor %}
</audio>

{{ poster }} outputs an empty string. I have tried multiple methods, with no success.

I can get the variable in the field template (field--field-audio.html.twig), but it is not available to the child file template I am using.

How do I get the value of $variables['poster'] in the template file I am using?

So I figured this out, it was not straightforward or obvious, and I could find no forum or post detailing this method, so hopefully it helps others.
The preprocess function changes to preprocess field as:

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

  switch ($element['#field_name']) {
    // Machine name of the field
    case 'field_audio':
      $node = \Drupal::request()->attributes->get('node');
      // separate field (machine name = field_image) that holds image for poster
      $media_field = $node->get('field_image')->entity->uri->value;
      $variables['poster'] = file_create_url($media_field);
      break;
  }
}

Then in the field twig file (field--field-audio.html.twig), replace the appropriate item.content section (or all of them as I did, just in case!)

      {% set attr = item.content['#attributes']|merge({'poster': poster}) %}
      {% set mycontent = item.content|merge({'#attributes': attr}) %}

      <div{{ attributes.addClass(classes, 'field--item') }}> {{ mycontent }} </div>

Finally in the file-audio.html.twig template you just need to add the poster="{{poster}}" like:

<audio {{ attributes }} style="background: transparent url({{ attributes.poster }});">

I've done the same for Video, i.e. using a separate field for the poster of the html5 video tag, using the same method EXCEPT in the field template #attributes is #player_attributes as you should be able to see in the file twig template, named video-player-formatter.html.twig in my case. Happy to post the code if anyone needs it.

Thanks to the drupal forums, twig documentation and of course stackexchange for the snippets I picked up along the way to figure this out.


How to hide a menu from  page? The main menu comes with 5 items.

How can I hide one items from the < front > page, i.e. 4 items are shown on front page, 5 items are shown on other pages?

The easiest way is through CSS.

body.front .your-menu .list-item-identifier {
  display: none;
}


When shouldn't you use t(), st(), etc. with readable string literals? Drupal coding standards dictate that nearly all string literals should be passed through t() or st() for translation;  however there are some exceptions, such as titles in hook_menu().  When isn't t() or st() necessary? I've posted a community wiki answer hoping people will edit it.

Descriptions and titles in hook_menu() *
Descriptions in hook_schema() **
watchdog() messages *
Field/instance definition labels and descriptions ***

* potx extracts the strings
** don't get translated
*** can be translated with contrib, eg. i18n_field


Output Custom Field in Drupal 8 How can I output a custom field in Drupal 8 (Bootstrap theme)? Editing the field.html.twig file, if I have a custom field named field_title I thought

{{content.field_title}}

Would display it, but it doesn't. I've also tried:

{{item.content['#field_title']}}

To no avail.

The only thing that's worked for me is:

{{items[0]}}

But that picks up the custom field by its index number, instead of its associative name in the array.

What am I doing wrong?

{{ content.field_title }}

This should work if you've got a field with that machine name.  If you're trying to print the title, the current syntax is:

{{ label }}

An easier way to figure out if the variables that you are trying to use is actually usable is to download the Devel module and enable Kint. Then in your .html.twig template file, you can enter:

{{ kint(content.field_myCustomfield) }}

and you would get an array with all the available variables.  If you don't want to install the devel module, you can just use:  I would recommend Devel/kint, it makes everything prettier and easier

{{ dump() }}

You're only going to need to dig into the array if you're trying to do something really custom. Eg: I used the following code in one of my projects to dig down into a link field so that i can output the exact url into an A tag inorder to wrap an entire region in a link.

<a href="{{ content.field_card_custom_link[0]['#plain_text'] }}">

You can read more about outputting Variables in twig templates here:
https://sqndr.github.io/d8-theming-guide/twig/twig-debug.html

and on drupal.org here: https://www.drupal.org/theme-guide/8


How to get the view count of taxonomy term pages in Drupal 8? I'm running Drupal 8.3. Statistics module can count views of a node. But is there a way to find out view count of taxonomy term pages?

I'm looking for how many times a taxonomy term page is viewed, but not the count of how many times a taxonomy term is used in nodes.

Edit:
In short, I'm looking for a similar module as below for Drupal 8.  https://www.drupal.org/project/taxonomy_term_statistics

I found a Drupal patch for Statistics module, which tracks view count for all content entities. It seems like this feature will be integrated into the core.

After applying the patch, I can track view counts for taxonomy term pages.

Link to the patch:
https://www.drupal.org/node/2532334


Replace the drop-down in Views with an image map I am looking for a way to replace one of the exposed filters used in the Views module with an Image Map (e.g. a map of the country).

Is there a way for doing this?

Strictly off the top of my head here...

You should be able to point the theming of an exposed filter to a custom theme function. Take a look at Better Exposed Filters for how to do so -- it's different between Views 2 and 3 and a little different between D6 and D7. The key will be to build the image map such that the URLs it redirects to are the same format that Views is expecting. Eg: test?field_animals_value[]=Dog

'Course you won't be able to use this solution with any filter on changing content without updating the image map....


Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment) I have been tasked with a major upgrade from D5 to D6.  The upgrade is now complete and fully themed on my development server.  The current production site is very busy, with dozens of nodes being added on a daily basis.  I need to somehow sync the content from the D5 site to the D6 site, and am wondering if there is any modules to assist or recommended way of doing this?  I just need to retrieve the content and Ubercart orders from the last month and port them to the D6 site.  Thanks for any help!!

I have not found a better alternative to migrate module till date and I have done lots of migration including ubercart order migration. It has served me well for:

ASP.Net (MSSQL server) -> Drupal migration
D6 -> D7 Migration
Rails (MySQL) -> Drupal Migration

There are tons of other modules like node_export, views bonus pack, uuid features, deploy that will let you export content out of drupal site but nothing scales better than migrate module. Having said that, its some effort as you need to write your migration classes, but it comes with excellent features like:

Incremental Migration ( you can test your migration class, with small subset of content)
Rollback ( In case you realize you missed something )
Solid drush interface.

Also, once you get a hang of it you keep appreciating the fact that it always work. It knows what has been imported, it reports on warnings during migration, gives you a status update on your migration. Can't recommend it enough!! and the best part is minimum downtime, you keep syncing content till the last moment.


Safely delete book and its child pages I have a site with two books, each having about 300-350 pages each. I want to delete one of the book and its child pages.
I was able to load the pages using some custom coding. I also came across, node_delete() function which has the following code snippet:

db_delete('node')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('node_revision')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('history')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('node_access')
  ->condition('nid', $nids, 'IN')
  ->execute();

So, it deletes data from four tables; but I suspect there are other tables, from which the data needs to be deleted as well (one of them being book table). Could you please point out which of the tables needs to be checked?

book_delete module will address your issue !

  Book Delete adds the ability to delete entire books to the book
  administration page (admin/content/book). It uses a batch operation to
  allow deletion of large books.

Take a backup of database before doing any delete actions :-)

It just worked as expected !! Follow below steps.

Install module
Clear Drupal Cache
Go to admin/content/book
Select the book you want to delete and click on delete book link next to it.
Confirm delete !

That's it :-)


Change Password/Confirm_Password Password Tips How does one go about changing the Password Tips for the password_confirm form element?

This one specifically:

Recommendations to make your password stronger:
•Make it at least 12 characters
•Add lowercase letters
•Add uppercase letters
•Add numbers
•Add punctuation

Into something like:

Password should have:
• Minimum of 12 characters
• At least one lowercase letter
• At least one uppercase letter
• At least one number
• At least one special character
• No three consecutive same characters

I'm tried using the hook_element_info_alter() hook that calls a method my_module_form_process_password_confirm() and followed this template(https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_form_process_password_confirm/8.5.x).

But it doesn't seem to be working.

/**
 * Implements hook_element_info_alter().
 */
function client_element_info_alter(array &$types) {
  if (isset($types['password_confirm'])) {
    $types['password_confirm']['#process'][] = 'client_form_process_password_confirm';
  }
}

function client_form_process_password_confirm($element){
  if (($key = array_search('user_form_process_password_confirm', $element['#process'])) !== false) {
    unset($element['#process'][$key]);
  }
  $element['#process'] = array_values($element['#process']);

  $password_settings = [
    'confirmTitle' => t('Passwords match DOES IT:'),
    'confirmSuccess' => t('yes'),
    'confirmFailure' => t('no'),
    'showStrengthIndicator' => FALSE,
  ];

  $password_settings['showStrengthIndicator'] = TRUE;
  $password_settings += [
    'strengthTitle' => t('Password strength:'),
    'hasWeaknesses' => t('Password should have:'),
    'tooShort' => t('Minimum of 12 characters'),
    'addLowerCase' => t('At least one lowercase letter'),
    'addUpperCase' => t('At least one uppercase letter'),
    'addNumbers' => t('At least one number'),
    'addPunctuation' => t('At least one special character'),
    'sameAsUsername' => t('Make it different from your username'),
    'weak' => t('Weak'),
    'fair' => t('Fair'),
    'good' => t('Good'),
    'strong' => t('Strong'),
    'username' => \Drupal::currentUser()->getUsername(),
  ];

  $element['#attached']['library'][] = 'user/drupal.user';
  $element['#attached']['drupalSettings']['password'] = $password_settings;

  return $element;
}

so I managed to tinker enough to get something to work and I'm sharing it in case other people need it or something. Of course, I dunno if this is optimal or follows standards or shouldn't even be done in the first place but please feel free to add your input. It's in the my_module.module file, by the by. Oh and don't mind the text, was just kinda testing this out and all that jazz.

Without further ado, here's the code:

/**
 * Implements hook_form_alter().
 */
function <my_module>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === <my_custom_form_id>) {
    // Note that this isn't actually a hook
    $form['#after_build'][] = '<my_module>_confirm_password_after_build';
  }
}

function client_confirm_password_after_build($element) {
  $drupal_settings = $element['pass']['#attached']['drupalSettings']['password'];

  $drupal_settings = [
    'confirmTitle'          => t('Do the passwords match?'),
    'confirmSuccess'        => t('Yeah'),
    'confirmFailure'        => t('Nope'),
    'showStrengthIndicator' => TRUE,
    'hasWeaknesses'         => t('Password Suggestions:'),
    'tooShort'              => t('Make it at least 50 characters'),
    'addLowerCase'          => t('Add 7 lowercase letters'),
    'addUpperCase'          => t('Add 8 uppercase letters'),
    'addNumbers'            => t('Add 8 numbers'),
    'addPunctuation'        => t('Add 10 punctuations'),
    'sameAsUsername'        => t(''),
    'weak' => t('Forgettable'),
    'fair' => t('Meh'),
    'good' => t('Almost'),
    'strong' => t('You got it'),
    'username' => '',
  ];

  $element['pass']['#attached']['drupalSettings']['password'] = $drupal_settings;
  return $element;
}


Allowing HTML in block title - where is $block->subject created? I want to get a
 tag into a block-title but by default the brackets are turned into html characters. My theme's block.tpl is

<h2<?php print $title_attributes; ?>><?php print $block->subject; ?>

so it looks like the rendering isn't happening there. I can't find where $block->subject is getting processed. It's not in my theme's template.php. So where in core is $block->subject assembled?

You may be interested in Block Class Styles, which has an additional feature:

  Allows the ability to set a global text format for custom block
  titles; this allows you to now have HTML in your custom block titles.
  Yes, you can now have block titles that contain HTML markup!


Form API Ajax - how to disable also form elements that will be changed, not only triggering element? So, element that triggered AJAX gets disabled. But how to make Drupal also disable everything inside ['#ajax']['wrapper']? After all, allowing user to edit something that will get replaced as soon as AJAX response is ready isn't the wisest idea, and I'd like to prevent that. And my AJAX created elements have their own AJAX too, race conditions are pretty bad already.

Is there any ready-made module for that? Or API way I'm missing? If no, where exactly should I put that code to minimize risk of incompatibilities?

Edit: I'm looking for a safe and stable way. It means no hard-coded identifiers in JavaScript files. Solution that breaks when someone edits form definition, or one that works for only one AJAX in form is not enough. After all, I need to avoid race conditions, and I already noted I have multiple AJAX actions, working on different sets of elements, on one page - so no marking elements for disabling at PHP level. I can eventually mark them with classes like disable-on-X and disable-on-Y, but I need to know if it's X or Y AJAX happening. And ideally I'd just disable everything inside ['#ajax']['wrapper'] without any additional marks, as they are not really needed - but again, I would need to know proper ['#ajax']['wrapper'] in javascript.

You can disable/enable some elements during ajax using this jQuery script:

// Disable filters on ajax call.
  $(document)
    .ajaxStart(function() {
      // Place here all elements that must be disabled during ajax.
      $("#path-to-the-element").attr("disabled", "disabled");
  })
    .ajaxComplete(function() {
      // Place here all elements that must be enablec after ajax.
      $("#path-to-the-element").removeAttr("disabled");
  });

Update. Some helper suggestions:

You can loop all inputs in wrapper element and disable each of them
using jQuery.each
You can see what is the class or id attribute of your generated
element html. Also you can add some special CSS class disable-on-ajax
to all your elements or wrappers that must be disabled on ajax. Then you will be able to handle them with one line of jQuery code.

Update 2

I can suggest one more solution.
E.g. you have added class for your target elements 'disable-on-ajax'.
Then you can write function that will be triggered on blur, select change, click etc.(You'll need to implements all target triggger checks).
In this function you'll check if element has class "disable-on-ajax". And add second class "ajax-disabled". Then on ajaxStart you'll handle only element with class "ajax-disabled"

You can populate form ajax-triggering elements, add property like ajax_wrapper="wrapper", ajax_event="event type" and then in behavior attach events


How to check term ID present in database table before updating I need to increment a counter on every taxonomy page load. I am adding the code in taxonomy-term.tpl.php file in my theme. I need to add a new entry if the term is not present and need to increment the 'totalview' if its already present. Here is my code, can any one help me to add the condition.

db_insert('custom_file_download_count')
->fields(array(
  'totalview' => 1,
  'tid' => arg(2),
  'timestamp' => REQUEST_TIME,
  'uid' => $GLOBALS['user']->uid,
))

db_update('custom_file_download_count')
->fields(array(
  'totalview' => 1,
  'tid' => arg(2),
  'timestamp' => REQUEST_TIME,
  'uid' => $GLOBALS['user']->uid,
))
->expression('totalview', 'totalview + 1')
->execute();

Your compound key you need to check for is for uid & tid. You can check for a row's existance (thus, need to insert) with a db_query function call & rowCount method call.

if(db_query('SELECT totalview FROM {custom_file_download_count} WHERE tid = :tid AND uid = :uid', array(':tid' => $tid, ':uid' => $GLOBALS['user']->uid))->rowCount() == 0) {
  db_insert('custom_file_download_count')
  ->fields(array(
    'totalview' => 0,
    'tid' => arg(2),
    'timestamp' => REQUEST_TIME,
    'uid' => $GLOBALS['user']->uid,
  ))->execute();
}
db_update('custom_file_download_count')
->fields(array(
  'totalview' => 1,
  'tid' => arg(2),
  'timestamp' => REQUEST_TIME,
  'uid' => $GLOBALS['user']->uid,
))
->expression('totalview', 'totalview + 1')
->execute();


Can I have Composer or something else download a Git repo as a dependency of my contrib module? I'm working on a module and there is a sub module for scanning barcodes that requires this, quagga.
Currently you have to manually download the library and put it into the libraries dir. If I add this as a dependency to the module you cannot install it without doing this first.

Can I have composer or something download a git repo to the libraries when installing the submodule?

Edit:
libraries.yml

form:
  version: VERSION
  css:
    layout:
      css/commerce_pos_barcode_scanning.css: {}
  js:
    js/commerce_pos_barcode_scanning.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - commerce_pos/quagga
quagga:
  remote: https://github.com/serratus/quaggaJS.git
  version: 1.0.0
  license:
    name: MIT
    url: https://github.com/serratus/quaggaJS/blob/master/LICENSE
    gpl-compatible: yes
  js:
    /libraries/webrtc/adapter-latest.js: {}
    /libraries/quagga/quagga.min.js: {}

install.yml

function commerce_pos_barcode_scanning_requirements($phase) {
  $requirements = [];
  if ($phase == 'install' || $phase == 'runtime') {
    $path = 'libraries/quagga/quagga.min.js';
    if (!file_exists($path)) {
      $requirements['commerce_pos_barcode_scanning'] = [
        'title' => t('POS Barcode Scanning'),
        'description' => t('To scan barcodes, you need to install the quagga JavaScript library. How To'),
        'severity' => REQUIREMENT_WARNING,
      ];
    }
    else {
      $requirements['commerce_pos_barcode_scanning'] = [
        'title' => t('POS Barcode Scanning'),
        'severity' => REQUIREMENT_OK,
        'value' => t('quagga JavaScript library has been configured.'),
      ];
    }
  }

  return $requirements;
}

You can edit file composer.js

find "web/libraries/{$name}": ["type:drupal-library"], change to

"web/libraries/{$name}": [
                "type:drupal-library",
                "type:bower-asset",
                "type:npm-asset",
                "vendor:npm-asset",
                "vendor:bower-asset",

            ],

add repositories

{
            "type": "package",
            "package": {
                "name": "serratus/quaggaJS",
                "version": "0.12.1",
                "type": "drupal-library",
                "source": {
                    "url": "https://github.com/serratus/quaggaJS.git",
                    "type": "git",
                    "reference": "master"
                },
                "dist": {
                    "url": "https://github.com/serratus/quaggaJS/zipball/master/serratus-quaggaJS-v0.12.1-14-g862df88.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "^1.0.20"
                }
            }
        }

and run composer require "serratus/quaggaJS"


CKEditor "Source" button does not brings back the full html I have written a full html code

&nbsp;

But when I edit the content and click on the "Source" button provided in the CKEditor toolbar. nothing is showing up

In Advanced content filter I have given in Extra allowed content

p(*)[*]{*};div(*)[*]{*};li(*)[*]{*};ul(*)[*]{*}

In Custom JavaScript configuration I have given

config.allowedContent = true;

I know D8's CKEditor doesn't allow you to use the style attribute to prevent click jacking attacks, example.

Can't remember if D7 CKeditor did or not, but either way, it's bad security practice to allow people to use style attribute.

The better approach is to use a class.

...something goes here...

Your Drupal theme's style.css

.bg-red {
  background-color:red;
}


Add tid or name as a class to each item of a taxonomy term I'd like to add the term ID or the name of the term as a class to each one of my taxonomy terms on a node page.

note that I'm not using views, so I wonder how can I achieve this via template.php or any customized tpl.php, I couldn't find any module as well to add class to each term separately.

thanks.

You can modify the output of any field with:

drupal standard field tlps

Possible override templates are:

field.tpl.php

field--content-type.tpl.php

field--field-name--content-type.tpl.php

field--field-type.tpl.php

field--field-name.tpl.php
So according to your specification in comment
"product_display"  and the reference term field is "field_product_specs"
your custom tpl file name should be field--field-product-specs--product-display.tpl.php

OR

Fences

Fences is a an easy-to-use tool to specify an HTML element for each
field. This element choice will propagate everywhere the field is
used, such as teasers, RSS feeds and Views. You don't have to keep
re-configuring the same HTML element over and over again every time
you display the field.


Title in page does not change with different page of the same View I have a View which displays a list of content. The content is paged, like this

http://www.exampple.com/en/products?product=all&brand=0&page=4

I keep the parameter page as exactly provided by default View pager. However, when clicking on different pages, the TITLE of the page does not change, it is "Products | WEBSITE_NAME" all the time. I would have expected the page number to be added automatically, as the site domain name is. For instance:

 "Products Page 1 of 3 | WEBSITE NAME"

Is there a module or a config to achieve this, or must I do it through a hook and drupal_set_title function in my custom module ?

The above different title for each page is necessary to avoid SEO penalization by Google and other seo bots.

If you are using AJAX in your view, the title won't change. Also, try adding !1 or %1 to your view title.


Taxonomy terms language depending - why all languages are visible? What I want to acheive:
I have multilingual site (i18n module).

I have vocabulary named "brands" - terms of vocabulary don't need to be translated because they are the same in all languages.

I've also nodes that I can assign to languages and "brands".

In taxonomy - in multilingual options - I set this vocabulary to: Localize. Terms are common for all languages, but their name and description may be localized.

Now - the problem is - that when I enter from menu to "brands" and e.g. "volvo" in any language - all nodes (all translations in different languages) are shown.

I'd like to see only the nodes in language that is set.

I have other vocabulary - where terms should be translated also. I have set it to Translate. Different terms will be allowed for each language and they can be translated. and there everything works fine - depending on language.

How to acheive that with my first vocabulary?

Thank you for any suggestions.

I have set the vocabulary to Translate. Different terms will be allowed for each language and they can be translated. and duplicated each brand for each language and then updated each node - with setting term for particular language.

In my opinion this is workaround, but I couldn't find other solution.


Custom contextual filter on views using Group module in Drupal I need to add a custom contextual filter in my view for the logged in user who is also a member of a Group specified in field_groups of my node. field_group is an entity reference field referencing group entity provided by the https://www.drupal.org/project/group module.

What is the simplest way of doing it? I am open to suggestions.

I did not found anything about view filters for the group module. You can only list group entities, not nodes from a group.

Looks like there some support for Panels but I don't know the module that much.

So I took the time to write some code, I just finished testing it.

Just change yourmodule and your_view_id with the correct data and your view should only display nodes attached to groups from the current user:

/**
 * Implements hook_views_query_alter().
 */
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_view_id') {
    global $user;

    // Get current user groups.
    $groups = group_membership_load_by_user($user->uid);
    $groups = array_keys($groups);

    // Add join to filter on group ID.
    $join = new views_join;
    $join->construct(
      'group_entity',
      'node',
      'nid',
      'entity_id',
      array(array(
        'table' => 'group_entity',
        'field' => 'gid',
        'value' => $groups,
      )),
      'inner'
    );

    $query->add_relationship('group_entity', $join, 'node');
  }
}


Migrate Organic Groups from a Drupal 6 database to Drupal 7 I'm using migrate_d2d to migrate my Drupal 6 site to Drupal 7. I've already created several working migration classes to migrate the content of the D6 site into the D7 site. Now I'm working on migrating the organic groups and the related user memberships. I've read that OG (i'm using 7.x-1.19) got a build in migrate routine. When I checked /admin/config/group/group-migrate, I hoped to see some settings where I could insert the data of my legacy database, my User Migration class, click a button and be done with it. :-D
Unfortunately, that's not the case.

I have a hard time to find any documentation of how to use the migration functionality which comes with OG. Could anyone please give me a hint how one is supposed to migrate OG groups/memberships from a D6 database to a D7 database?

Many thanks!

The migration classes that come with Organic Groups are for doing a full site upgrade only. In other words, if you were to drag Drupal 7 files over top of your Drupal 6 site and run an upgrade, the migrate classes that come with OG would be helpful.

However, in your case (and mine) you are doing a full migration from an old Drupal 6 site to a fresh, empty Drupal 7 site. The classes provided by OG will not be helpful here, nor even show in your migration list.

What I'm currently doing is working on a manual migration path for OG groups using migrate_d2d to pull all the group nodes over. Then I'll write another migration to add users to these groups by injecting them into the right database tables. THEN as each of my other node types are migrated over, they will add themselves to the OG tables that track which content are part of which group.


How do I know when another contributed module deletes a block? I have written a Drupal 7 module that adds about ten fields to the block administration configuration form and saves the values for those fields in its own database table. My module does not create blocks, but rather extends the functionality of any block, regardless of what module created it.

My module should delete the data in its own table when any module deletes a block from the block table. However, how would my module know when this happens? Is there a hook or other "universal" method available to know when a block has been deleted?

There isn't a hook_block_delete(), even though there are hook_node_delete() and hook_entity_delete().
I've looked at development guides about creating blocks for some clues, but none of the ones I've found give examples of how they should be deleted. I've also looked at the source code of modules that create/delete blocks, like the Views module, but I can't tell how, or if, they send a notice that they have deleted a block.

There is no hook fired in delete of block, as you can see in the list of block hooks here block.api.php.

There is a topic in Drupal forum here.

I think the best way to handle this is by hook_form_alter something like.

/**
 * Implements hook_form_alter().
 */
function YourModule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'block_custom_block_delete') {
    // You get all information here of the concerned block in $form.
  }
}


drupal gridview drop down menu - showing all menu and sub menus under one parent I would like to show drop down menus in gridview format. ideally it should show all sub menus and sub sub menues under one parrent. any module which can service this purpose?

Maybe you could use the Superfish module? Here is a quote about it (from the module's project page):

... integrates jQuery Superfish plugin with your Drupal menus:

Unobtrusive JavaScript.
Keyboard-accessible, screen reader friendly.
Multi-column sub-menus. (Megamenus)
Easing effects with the jQuery Easing plug-in.
Automatic width calculation (sfAutomaticWidth plugin) (Use the development release)
Automatic sub-menu width calculation (Supersubs plugin), automatic sub-menu placement (Supposition plugin; prevents sub-menus from appearing off-screen.)
Touch-screen compatible. (almost)
Small-screen compatible. ( and vertical accordions)
Window width (client-side) and UA string (client-side and server-side) detection for touch and small screen plugins (no CSS3 media-queries)
RTL (Right-to-left) language support.
Plenty of built-in options for designers.
And a whole lot more...


Unlimitted entries in Watchdog table I need to set watchdog log entries to unlimitted. Now it clears every time when cron is called.

admin/settings/logging/dblog

now maximum is 100000, is there any better way to do this.

Just change the setting to "ALL" that should work. Please see the screen below !

Cron will run only if minimum limit is set in the select box see the below code in dblog module.

function dblog_cron() {
  // Cleanup the watchdog table.
  $row_limit = variable_get('dblog_row_limit', 1000);

  // For row limit n, get the wid of the nth row in descending wid order.
  // Counting the most recent n rows avoids issues with wid number sequences,
  // e.g. auto_increment value > 1 or rows deleted directly from the table.
  if ($row_limit > 0) {
    $min_row = db_select('watchdog', 'w')
      ->fields('w', array('wid'))
      ->orderBy('wid', 'DESC')
      ->range($row_limit - 1, 1)
      ->execute()->fetchField();

    // Delete all table entries older than the nth row, if nth row was found.
    if ($min_row) {
      db_delete('watchdog')
        ->condition('wid', $min_row, '<')
        ->execute();
    }
  }
}

If we select value as "ALL" which is 0, Cron won't delete any entries !

For Drupal 6,

You can use Elysia Cron module, to turn off the dblog_cron feature.

Elysia Cron Module tells,

  Turn off (disable) a cron task/feature you don't need.


Why is Rules Action "Create Linked Drupal User Account" not working? I’m using Drupal 7.56 and CiviCRM 4.6.31.

I’ve been using Rules in Drupal to create a Drupal User Account linked to the CiviCRM contact created.
But it's failing. I'm getting the following error:

  Cannot create user, email: invalid!!

This is the export of the Rule:

{ "rules_create_a_drupaluser_for_an_civicrmcontact" :
    {
        "LABEL" : "Create a Drupal user for an CiviCRM contact",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "REQUIRES" : [ "civicrm" ],
        "ON" : { "civicrm_contact_create" : [] },
        "IF" : [
          { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm_contact" ] } }
        ],
        "DO" : [
          {
            "civicrm_entity_action_create_user" : {
              "USING" : {
                "civicrm_contact" : [ "civicrm_contact" ],
                "is_active" : "1",
                "notify" : "0",
                "signin" : "0",
                "username_format" : "email"
              },
              "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
            }
          }
        ]
    }
}

It was working some time ago.

The link where I downloaded the civicrm_entity (release 7.x-2.0) is:
https://www.drupal.org/project/civicrm_entity/releases

For your convenience I've added the source code for the Rules Action civicrm_entity_action_create_user:

function civicrm_entity_action_create_user ($contact, $is_active, $notify = FALSE, $signin = FALSE, $username_format = 'first last') {

  if (!is_array($contact)) {

    // Perhaps we should be accepting object rather than array here?
    $contact = (array) $contact;
  }

  // We'll use the civicrm sync mechanism to see if Civi can match the
  // contact to an existing user.

  // Don't think this is a great approach but will use for now - could
  // just create the user but no great support for that yet.

  if (empty($contact['display_name']) || empty($contact['email']) || empty($contact['first_name']) || empty($contact['last_name'])) {

    $contact = civicrm_api('contact', 'getsingle', array(
      'version' => 3,
      'id' => $contact['id'],
      'sequential' => 1,
      'return' => 'email,display_name,first_name,last_name',
    ));
  }

  if (!is_string($contact['email']) && isset($contact['email'][0]->email)) {

    $contact['email'] = $contact['email'][0]->email;
  }

  // @TODO What happens if they don't have an email at this point?

  // An email is a pre-requisite for a Drupal account, so the action
  // fails if they don't have an email.

  if (filter_var($contact['email'], FILTER_VALIDATE_EMAIL) === FALSE) {

    drupal_set_message(filter_xss("Cannot create user, email: " . $contact['email'] . " invalid!!") , 'error');

    watchdog('civicrm_entity', 'Cannot create user, email %mail invalid.', array('%mail' => $contact['email']), WATCHDOG_ERROR);
    return FALSE;
  }

And here is where the error raises.

These is the Rules evaluation log:

Reacting on event CiviCRM Contact has been created.

 Evaluating conditions of rule Create a Drupal user for an CiviCRM contact.

 The condition civicrm_entity_user_exists evaluated to FALSE

 AND evaluated to TRUE.

Rule Create a Drupal user for an CiviCRM contact fires.

   Rule Create a Drupal user for an CiviCRM contact fires.

   Evaluating the action civicrm_entity_action_create_user.

   Evaluating the action devel_debug.

   Rule Create a Drupal user for an CiviCRM contact has fired.

Finished reacting on event CiviCRM Contact has been created.

And the Log Message gets this Error:

MESSAGE "**Cannot create user, email invalid.**"

Does anyone have any clue about what might be happening?

The explanation for the issue you're facing is within the comment lines of the Rules Action you included iin your question, i.e.:

  // @TODO What happens if they don't have an email at this point?

  // An email is a pre-requisite for a Drupal account, so the action
  // fails if they don't have an email.

The eMail ID for the CiviCRM contact you're using appears to be missing. So try again with a similar testcase, but make sure that for the CiviCRM contact some eMail Id is entered.

This probably also explains the "It was working some time ago": chances are that it was working, since you were using a CiviCRM contact for which an eMail ID was available.


Is it a great idea to upload php instead of writing phps in drupal interface At each time I write PHP code in blocks and views, I always think about this question : "What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?".

Is it a great idea to make users able to send php files instead of writting it. It would be a first step to manage the code after with name conventions to find the code easily and to be also able to read easily the code?

Or it's just a stupid idea that will generate a security mess ??

I think the solution is to put PHP codes in hooks... And anyone could say that it's insane to create a module just for one or two lines of codes... But most of time, drupal users has to do somthing like this several times in drupal. So why not combine all these hooks in one module that we might call whatever we want. So then just well-comment the code for good reading.

The little snag is : is there hook for each actions where we can add php code ?


How can I create my desired template name suggestion? For example, Imagine that I designed two main-menu with different style and template one for the header region (top bar, primary menu section)
and another for the footer region as a "footer map" on my site as it's common in the most sites.

Since Drupal 8 it's not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed").

  In Drupal 7 it was possible to specify separate block templates per
  region, such as block--header.tpl.php and block--footer.php to output
  different HTML for blocks placed in the header and footer regions. It
  was also possible to adjust variables based on the region in
  hook_preprocess_block(). Both of these features have been removed.

I decide to use below code, by using the below code I can add block region and id to the block template name suggestion:

function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }

If I have considered tree or even more footer region in my theme then my theme users should have this freedom to change the order
of displaying this designed footer menu independent of which sub-footer region that's inserted in;
It is more useful if we design in LTR languages (Like English) and RTL languages(Like Persian)Simultaneously.
But what's that become outputted from above code is something like this:
block--footer-1--mainnavigation-2.html.twig

I think it's a good idea to design the different menu with different semantic name template separately.
It's quite obvious if I need multi instances of a block then Its must probably be in different region, therefore, this difference in positioning make a good and sufficient semantic name convention to assign name to templates and get rid of complication.

for this reason, I want to remove the numbers from the end of block identifier because I think this is very dedicated and I want to achieve something like this:

block--footer--mainnavigation.html.twig

Something else that I want to pay attention to it is if I choose another footer names for example:
footer_menue instead of footer_1 then this hasn't necessary dynamics in theme layer due to the above reasons.

Anyway, the name convention that I like and follow out is:
What's this?(Most common part) it's block or page or....
Where should be placed? header, footer....
What is his name or usage? main-menu, Search Block,...
Like:Block+Region Name without Number+ Block(id) name without number

If you want to have more meaningful template suggestions, why don't you use better region names and block ids?

Region names are up to your theme, so instead of footer_1, use footer_something, and block configuration names are also up to how you configure/name your blocks.

You could use PHP to filter those things out, that's nothing really drupal specific, but that's likely increasingly complicated as you will have blocks and regions without those number suffixes, so you need to be caruful in not cutting those off.

Also, you could use suggestions based on the block plugin ID, not configuration ID, then placing the same menu multiple times will give you the same template suggestion.

Edit: If you really want to get rid of those kind of suffixes, then you could for example use trim:

rtrim('footer_1', '123_');

You can put whatever characters in there that you want, and it will remove them all from the right side of the string (there is also ltrim for left and just trim for both sides). Note that this will also remove a _ at the end if you have that.


Sending a newsletter more than once? Is it possible to re-send a newsletter once it's been sent?

I am using a Simplenews module and the Subscriptions module).

go to phpmyadmin database ->

go to table -> ' simplenews_newsletter '

Sent newsletter will have status 2, pending will have 1 and not sent will be 0.

edit and change the status of that newsletter to 0

Hurrey!!!! send it again :)


How to remove "Main Menu" title from Stark Theme I want to have just the main menu list elements displayed through only the stark theme and I can't seem to figure out where I should go to delete the title "Main Menu" that is above the main menu elements.

Go to admin/structure/blocks, find out the Main menu, click configure, and set title to <none>. This should resolve it.


What versions from the Symfony components are used from core? Which Symfony version does Drupal use for the Symfony components? Is it a goal to support the latest versions of the components or is this simply not possible?

It is more accurate to say that Drupal 8 uses Symfony components, rather than all of Symfony.  If you look at 'core/composer.json' you will see all of the individual components that Drupal uses listed out.  The precise versions that get installed are listed in the 'composer.lock' file.

Drupal 8.2.x uses the 2.8 versions of these components.

For Drupal 8.3.x, there are issues open for updating to 3.1 and 3.2, but these are still works in progress. (I think there may be a 3.3 issue, but I can't find it).

The goal is to start tracking the 3.x versions, but the conversion has not been straightforward.


specify $form elements to be excluded from display? I want to hide certain elements in form using form_alter or a template file. I have read somewhere that in Drupal 7 , we can specify $form elements so it will not display in form, but I can't remember!
Not unset() but some other function!

Using unset() isn't a good solution for forms (as I think you know), as you never know what submit/validate handlers might be expecting the unset element to exist when they're processed. This can lead to unwanted errors.

There are three methods you can safely use to 'hide' a form element

Use '#type' => 'value' on the element, which will have the effect that the value for the element will still be passed through to the submit/validate functions with its #value as normal. This is my preferred method.
Use '#access' => FALSE on the element to denote it should not be outputted to the screen.
Use '#type' => 'hidden' as Bart has suggested (although use of this depends on your use case; I imagine if you're trying to hide the value of a form element you don't want to output it in the form as a hidden input).


Missing form state values after adding submit function I added a submit function in the form_alter hook when inserting a node:
$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['save_as_draft'],
  '#limit_validation_errors' => [],
];

In the save_as_draft() function, I want to get the address value from the form state, but there are no values (except for the additional submit button).
function save_as_draft(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  var_dump($form_state->getValue('field_address'));                      // outputs NULL
  var_dump($form_state->get('field_address'));                           // outputs NULL
  var_dump($form['field_address']['widget'][0]['value']['#value']);      // outputs 'Address value'
  var_dump(array_keys($form_state->getValues())); // outputs { [0]=>  "save_as_draft" [1]=> "op" }
}

How can I get the form_state values in this alternative submit function without validating the whole form?
Is there another way of retrieving the form values instead of digging through the widget arrays?

Entity forms usually run as first submit handler the entity builder functions. Then following submit handlers can get the processed field values directly from the form object entity:
$entity = $form_state->getFormObject()->getEntity();
$field_values = $entity->field_foo->getValue();


Separating user edit form into small descent form I am developing a Community website in Drupal 7,where users got profiles with many fields, but these fields are grouped for Example: Basic informations,Hobbies, Education,Experience and So on..
In normal drupal, when user wants to edit his profile, he/she will be present with a huge form with lots of fields.
What i need is to separate these categories in different small forms, if possible using a custom module so the forms can be called like
   drupal_get_form('basic_informations');
   drupal_get_form('Hobbies');
If This will be possible then i will be able to opens this small forms in modal dialogs(ctools).

Any suggestion will be Appreciated.

No need for custom forms!

Profile2 will do all of the items you require! Here is the handbook to get you started.

This will let you have different forms (tabs) on the /user page and you can also choose which of those "subforms" you want on the user registration.


How to alter image style based on product custom attribute? I'm building a webshop based on Ubercart, and products have a custom attribute "sold out". When this attribute is checked, all product images should be displayed with a semitransparent overlay textbox: SOLD OUT. Theoretically, I found a couple of promising options, but none of them seems to me satisfying:

Using node--product.tpl.php to insert a custom overlay div around the rendered image. This is a very fragile solution, because I cannot put the overlay div inside the main-product-image div. Therefore, it's hard to make it responsive, and on the other hand, cross-browser issues might raise because of the opacity...
Adding a new image style and overriding theme_uc_product_image function. Since style_name is hardcoded here as 'uc_product', it is obvious to override this. But no node array is available here to decide whether to override image_style or not. Maybe a custom sql query?
Manipulating the default uc_product image style from code with hook_image_styles_alter function. Same problem: no node array here.

Any idea?

You could use ImageCache Actions module
and write your PHP field condition right on the generation of the image.

Custom Actions effect is what you need.


What is the easiest way to update thousands of users' "created date"? I want to change all user created date. Is it possible use VBO for that? However, I don't see any option to change the user's created date there.

Originally the site is migrated from Joomla; I have thousands of users with a blank created date, and I want to set them to a week ago.
Can this be done with VBO?

This answer assumes that changing the created dates is a one-time action, and that other modules in your Drupal site do not need to react to the users being updated.

IMHO, if you're looking at modules to do this, you're making things way too complicated for yourself. A simple SQL query should to the job:

UPDATE users SET created = 1234567890 WHERE uid <> 0;

You can choose / calculate the timestamp yourself (where it says 1234567890 in my example). I'm excluding the record with user id 0 because this repesents the anonymous user who does not have a created date.

How to run this query:

From a MySQL admin tool, like phpMyAdmin or HeidiSQL, whatever you have to access your database;
From the command line using the mysql command (don't know if this works on Windows):

$ mysql -u user_name -p -e 'UPDATE users SET created = 1234567890 WHERE uid <> 0' database_name

From the command line using Drush:

$ drush sql-query "UPDATE users SET created = 1234567890 WHERE uid <> 0"


How can I work on which particular pages a CSS rule is used? I would like to see a list of pages where a particular style is used so I can either delete/modify it.

You can see a list of selectors not used on a page using external tools, there is no way for drupal itself to create the list for you however.

You can find some suggestions here: https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website
I personally use the chrome developer tools as described in the above link.


Display quiz results for users I am developing an e-learning portal for a client; the client wants to be able to create quizzes and view the results of individual students, and probably draw a graph to give an overview of student performance. I am using the Quiz module to create quizzes.

The "quiz score" is not available if you use node as the view base or quiz.

I am able to list username, level, and quiz.

You would need to add a relationship which would be the Quiz Result : User.

Then you would find the quiz result : score in the fields


How do I add attibution links to 'teaser thumbnails' in Drupal blog posts? I'm running a professional blog on, I believe, Drupal 6.17. It allows me to include a 'teaser thumbnail' of an image with each blog post. However, many times I want to use free stock photos from sites such as flickr and freedigitalphotos.net as that teaser. However, these sites require you to include a link back to the photographer's page along with an attritbution on the same page as the photo. I'm not sure how to do that with Drupal's 'teaser thumbnail' option.

For D6, use the ImageField Extended module. It provides a very simple admin interface to give you a way of adding textfields, textareas, WYSIWYG textareas and checkboxes.


Two-factor authentication with code sent to email I'd like to ask you if there are any possibilities of a two-factor authentication with authentication code sent to email. I've found TFA module  which can send an SMS, and according to their documentation, also email:

  The TFA code can be sent out over mobile phone SMS (recommended) or
  via email.

but I haven't found any settings for email, it seems they just provide "API to customize the communication chanel". I've also found Rules module, which could be maybe used combined with other module.

Are there any other possibilites how to do the two-factor authentication with email?

It looks like the recently posted OTP module supports emailing of its one-time passwords. It's still a sandbox project though and I haven't tried it myself.

It shouldn't be too difficult to add email support to the TFA module you mentioned. If you're interested in getting your feet wet with Drupal development, it might make a good starter project.

I suspect you would have to do some custom development to get Rules to handle generating of the codes. Either of the two options above would probably be quicker.

Maybe it's just an academic point, but keep in mind that by emailing the token, you're straying a bit from the idea of two-factor authentication, which entails "a knowledge factor ("something the user knows"), a possession factor ("something the user has")." The line gets a bit fuzzy already though, when you talk about logging in from your phone or forwarding text to a computer via services like Google Voice.


Put file download image I'm using Drupal 7 and i've got 3 file field in content. I don't want see generic file, url file etc... I want spesific bg image on all my file field. How can i do this?

You can modify your theme's CSS to give every File Field a specific background image.  You would add this to your theme's stylesheet, looking for a "style.css" file in your theme folder.  The generic code for the background image would be:

.node-your-node-type .field-type-file {
  background: url("/sites/all/themes/yourtheme/yourbackgroundimage.png") no-repeat scroll 0 0 transparent;
}


Adding local task tabs to node display for specific content type I'm creating a custom module (it's called cil_meet) which adds two content types (organisation and room).  On an organisation node I want a local task tab (next to 'view' and 'edit') of 'add room', for administrators.  On a room node I want two tabs 'publish' and 'info'.

After some research, I've figured out a way to achieve this, but I want to know if there is a better way of doing this?

cil_meet.routing.yml:

cil_meet.addroom:
  requirements:
    _role: 'administrator'
cil_meet.roompublish:
#  path: '/meet/{organisation}/{room}/publish'
  requirements:
    _role: 'authenticated'
cil_meet.roominfo:
#  path: '/meet/{organisation}/{room}/info'
  requirements:
    _role: 'authenticated'

I've commented out the path for publish & info for now - I'll set up controllers, etc later.

cil_meet.links.task.yml:

cil_meet.addroom:
  route_name: 'node.add'
  title: 'Add Room'
  weight: 100
  route_parameters:
    node_type: 'room'
  base_route: entity.node.canonical
cil_meet.roompublish:
  route_name: 'cil_meet.roompublish'
  title: 'Publish'
  weight: 100
  base_route: entity.node.canonical
cil_meet.roominfo:
  route_name: 'cil_meet.roominfo'
  title: 'Info'
  weight: 101
  base_route: entity.node.canonical

This adds the tabs to all nodes.  So to remove the tabs from anything other than organisation or room nodes, I've got to add some code to the module.

cil_meet.module:

<?php
/**
 * Implements hook_local_tasks_alter().
 */
function cil_meet_menu_local_tasks_alter(&$local_tasks, $route_name) {
    $route_match = \Drupal::routeMatch();

    if ($route_match->getRouteName() == 'entity.node.canonical') {
        $node = $route_match->getParameter('node');
        if($node->bundle()!='organisation') {
            unset($local_tasks['tabs'][0]['cil_meet.addroom']);
        }

        if($node->bundle()!='room') {
            unset($local_tasks['tabs'][0]['cil_meet.roompublish']);
            unset($local_tasks['tabs'][0]['cil_meet.roominfo']);
        }
    }
}

All works as expected, the above may help others needing a similar solution.  Is there a better way of doing this?

Solution from Matt B only hides the tab on the node view page, but not on the node edit etc. The direct url will also be accessible in that case.

A better solution is to write a custom access handler

See Custom validation of route parameters


Opening user session programmatically using headers information I'm developing a website with an external user authentication provider. The whole login process is external, that I don't need to worry about. Once a user is logged in, the external provider adds extra data in the request headers (i.e. customer id), that I can use to map an external customer id with a user from the Drupal users table.

Which hook suits the best to open a session and login the user programmatically on each page request? (hook_boot() ?)

As the hook_init() doesn't works for the cached pages so the alternate option that seems to me is the hook_boot() (This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request),

However the discussion here on using the session during hook_boot make me feel that hook_boot() is invoked too early to use the session, as Drupal has not yet initialised the session.

  There is a trick to avoid the page is cached: Call drupal_page_is_cacheable(FALSE) in hook_init().

Check more here: using drupal sessions during hook_boot


Views SQL-query slow with big dataset and exposed filters I have a problem with a Drupal 6 site working with many nodes.

This is the SQL given by Views:
https://gist.github.com/ranbogmord/79bfa50e40db1322c9e0

The query takes 5-10s to run through and the specific content-type has 30 fields bound to itself. 21 of those are exposed.

Imagine this as orders in a business system.

Thanks!

Try denormalising the database by storing the relevant node objects in a single caching table. You can model your database schema on that of the core caching tables. That should speed up the query by reducing the amount of joins. Also, put indexes on any columns used in where clauses. If you insert/update rows in your caching table on update/insert of nodes using hook_nodeapi, your caching table should remain fresh. You could then either replace the view with a db_query in a custom module, or you could expose your table to views.

I haven't tried it, but you may be able to achieve this using the D6 object cache module.


Best practice for caching CSS libraries? Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme it says:

  Some libraries you load may not be needed on all pages. For faster performance don't load libraries where they are not being used.

At the same time, if you have many different files to load for each page, this will slow down the speed for each page load.

How big should the library be before you should consider to load it in a separate library?

How does the database caching system work? Will each library be cached in a separate CSS file? If I have page X and Y where i only need some CSS library on page Y, will both of them share CSS file A and then the other also have CSS file B? Or will these pages have only 2 different CSS files?

At the same time if you have many different files to load for each page this will slow down the speed for each page load.

You don't need to worry about this in Drupal, as Drupal will aggregate the CSS files when you have CSS aggregation turned on, and you should always have this enabled on a production site.

As such, you should ensure that only the relevant CSS is attached to an element/page to which it belongs.

For example, I'm creating a site right now that has a booking page. This page has a chart-like schedule on it, showing what time slots are available. It's not unthinkable that this could be swapped out at some time in the future. So I have all the CSS for that chart in a single file, and the chart is attached to that element of the render array. Therefore if anyone ever removes that element, or sets the access on it to FALSE, the CSS will not load.

Drupal will handle the aggregation in the background and serve an aggregated file that contains my file when the user is served the schedule, and serve an aggregated file that does not contain my file, when the user is not served the schedule.

So to sum it up, don't worry about having too many CSS files in Drupal. On the contrary, it's better to have your CSS modular, so that each file contains CSS to a specific element/page, and attach that file to that element/page. Drupal will handle the rest.

  And how does the D8 caching system work; will each library be cached
  in a separate css file? If I have page X and Y where i only need some
  css library on page Y, will both of them share CSS file A and then the
  other also have CSS file B? Or will these pages have only 2 different
  CSS files?

Aggregates are created as needed. If a page needs file X, Y and Z, it will create an aggregate that contains those files. If another page only needs X and Y, it will create an aggregate with those files. If that same page is visited by a loggeed in user that needs file A, then an aggregate will be created with those files.


Changing configuration using form I have created a form using which I want to make changes in the configuration.Currently I am submitting form doing something like this:

 public function submitForm(array &$form, FormStateInterface $form_state) {
  \Drupal::service('config.factory')
    ->getEditable('module.settings')
    ->set('module_entities', $form_state->getValue('module_entities'))
    ->save();
 }

But the problem is when I have submitted the form changes in the configuration are not reflected.But when I clear the cache after submitting the form the changes are reflected.what changes should I make so that when user submits form the changes are reflected thereafter?

Update: I tried to find my mistake and found out that configuration is getting updated but somehow the changes getting lost and not being reflected in the block which I have created. In the block creation code I am creating blocks for different entities depending on the entities present in the configuration.But the configuration is not showing correct values so block for required entities is not being created.Surprisingly when I clear cache the code works(which means configuration becomes updated).Does this mean for block creation I need to clear cache?
I am currently using this code:

 `public function getDerivativeDefinitions($base_plugin_definition) {
   $this->derivatives[$entity_type] = $base_plugin_definition;
   $this->derivatives[$entity_type]['admin_label'] .= ' (' . $entity_definition->getLabel() .')';
   $this->derivatives[$entity_type]['cache'] = ?;

}`

What should I add over here to make block depend on configuration without clearing cache?
In the plugin I am returning:

public function build() {
return array(
  '#theme' => 'links__entity__module',
  '#links' => $this->linkBuilder->buildLinks($this->request->attributes->get($entity_type)),
      );
}

Blocks are cached by default.

You don't need to manually clear those caches when you change your configuration, but you need to flag/tag your blocks output to tell Drupal that your block output depends on your configuration.

Read the Cacheability documentation. What you need is something like this:

$output['#cache']['tags'] = $config->getCacheTags();


Does module_invoke() work for non core modules? I tried using module_invoke('casrel','nodeapi', $node, 'view'), but what I get for  casrel_nodeapi() is a truncated $node and "load" instead of "view".

Does anybody have an idea on what is happening?

You are probably looking for module_invoke_all. The module_invoke function only invokes a module in a specific module (casrel.module in your example).

By the way, you usually do not need to invoke hook_nodeapi yourself. The node module invokes hook_nodeapi when necessary, if you just use the api functions (like node_view) correctly. If you need to alter a node before it's viewed, you need to implement hook_nodeapi instead of invoking it.


What's the default workflow for layouts in Drupal Bootstrap theme? Panels/Page Manager and Display Suite are probably the two most popular approaches to layout of items in Drupal. Both, however, are officially not supported by the popular Bootstrap theme (as opposed to Zurb Foundation, which actively recommends both Panels and Display Suite).

I've been right through the Drupal Bootstrap documention, and beyond this "what not to do", I can't find anything on what to do. I know how to work with vanilla-Bootstrap's rows, columns etc using classes; I'm just struggling to find the standard, going-with-the-flow expected approach to doing this in the context of Drupal.

Is there any official guidance on best-practise layout in Drupal Bootstrap, or failing that, what's the expected approach to applying the row and column classes to elements?

I've seen Views Bootstrap, which is kinda-sorta supported. It's the next step up from that I'm not sure about, and I'm wary of just attempting something then finding I'm going against how the theme is designed and expected to work.

I see your concern with the "unsupported" classification, just because that's an immediate red flag when looking for a module to provide some sort of core-like functionality. Since Bootstrap is really a frontend tool, I'm less concerned, since I'm generally just using it for its responsive behavior. In the past, I've simply used templates and preprocess functions to wrap or 'bootstrap' my content. Also, I've always used Display Suite Bootstrap layouts, which has been helpful in previous projects that are handed off to clients. Since it's a theme of choice, I'm interested to hear other comments.

EDIT

Before anything, you'll need to reference the Bootstrap CDN in your header OR install a Bootstrap Starter theme. Then, you'll need to install Display Suite and the Bootstrap layouts (linked above). You can then manage the display of a content type and choose a Bootstrap grid layout to add responsive behavior to your content type. If you prefer to use a template file e.g., you can copy the page.tpl.php from the core systems folder to your theme's template folder and add Bootstrap classes and elements to the markup. For more specific elements, such as menus and images, use preprocess functions in your template.php file to alter the markup. See the example below:

Bootstrap a menu:

function THEMENAME_menu_tree__MENU_MACHINE_NAME($variables) {
    return '
' . $variables['tree'] . '
';
}

Bootstrap a block:

function THEMENAME_preprocess_block(&$variables) {
    $elements = $variables['elements'];
    $classes = &$variables['classes_array'];
    if ($elements['#block']->subject == 'BLOCKNAME') {
         $classes[] = 'col-sm-6' . ' ' . 'col-md-3';
    }
}

Hope that's helpful.


Show block on specific views search result My view exposed search results path looks like this:

www.xyz.com/?field_port_tid=5971&field_length_value=&field_length_value_1=&field_cabins_value=&field_cabins_value_1=&field_price_week_range_value=&field_price_week_range_to_value=

I would like a block to show only if the path has specific taxonomy term in it (in this case tid=5971).

If you have the PHP filter (not advised but still popular) module enabled you can use the Pages on which this PHP code returns TRUE (experts only) option for block visibility with the following code.

<?php return (isset($_GET['tid']) && $_GET['tid'] == 5971); ?>


Solutions for frontpage that consist of only blocks What methods are there to construct a frontpage that consist of only blocks. I know i can setup panels + pagemanager and add blocks in that manner, but it seems a bit overkill to install panels just for 1 page of the site. Another solution was to create an empty Views page, but that seems a bit hacky.

Having that the frontpage consist of only blocks, what other methods are there that doesnt seem hacky or bloated?

The pages are already built from blocks, where the 'main content' block is the page content. These blocks are positioned in regions defined in the template.

I guess you want to reorganize the blocks? Have maybe multiple columns and so? Then you can either use panels or alter the theme with the regions you want. (This basically is what panels does, but at the position of the 'main content block'. Leaving the other blocks intact.)


CSRF token time life I've get CSRF token from url /rest/session/token. After have CSRF token, I can send request (get, post) to API and working fine. But after time, when I send request. It's doesn't work. I'm getting error permission denies. I think maybe CSRF token expire time. So I want know time life of CSRF token. And how to change time life of CSRF token.

This is the same question I had asked myself and I wanted to increase the lifetime to something like 6 hours.

However, the point behind CSRF tokens is that they change frequently so that nobody can try to steal one of those tokens and then use it to make a forged request. Here's the workflow I ended up using in my application:

Request a CSRF token.
Use the token to make requests.
If the request fails because the token has expired, go to step 1.

Hope it helps. Happy coding.


Drupal schema API not supporting MySQL date data type? I am getting this error with my existing database:

  no Schema type for mysql type date.

I did some research and it seems like schema does not support date type in MySQL.  What would you guys suggest I replace it with?  I'm presenting income statements and balance sheets on my site and I need to have some sort of date reference of each row(otherwise I wouldn't be able to figure out 2009 earnings versus 1999).

What other options are available?

You could define it yourself, have a look at http://drupal.org/node/159605#comment-1674678.

You should however only do this if you are sure that you will only ever use/support MySQL.

Portability with date data types among different databases is almost impossible. Drupal 7 initially had date types defined but they were removed again because there is simply no way to make them work consistently across multiple database types.

You might want to look at http://drupal.org/project/date, I'm pretty sure that allows to use dates that can not be mapped to a UNIX timestamp.


How do I keep l() from escaping my link's text? I'm using Drupal 7's l() function in my template as follows:

<h3>
  <?php print l(
    $fields['title']->content,
    'node/'.$fields['nid']->content,
    array('attributes' => array())
  ); ?>
</h3>

The problem is, this is causing apostrophes in my titles to display at &#039 instead of an apostrophe. How can I use l() properly to keep this from happening?

@Kojo's answer is getting a bit crowded and confusing IMHO so let me post my recommended approach here.

'html' => true

The key to the problem is passing the html option to the l() function like this:

<h3>
  <?php print l(
    $fields['title']->content,
    'node/' . $fields['nid']->content,
    array('html' => TRUE)
  ); ?>
</h3>

This tells l() to bypass the check_plain() function which normally escapes the link text.

Security

Using 'html' => TRUE is a security risk if you are not sure if the author can be trusted (ie. it is user generated content).

Depending on where the variables in your template come from, $fields['title']->content may already have been sanitized. You can test this by setting the title to <script>alert('hi');</script>. Load the page. If you see a javascript popup, you have an XSS vulnerability to fix. Fortunately, Drupal has a couple of functions built in for that.

Solutions for an XSS vulnerability

Use filter_xss(). A filter that only allows a small selection of HTML tags, fixes invalid markup, and filters out XSS risks. Example:

l(filter_xss($unsafe_text), $path, array('html' => TRUE));

Use filter_xss_admin(). This is a very permissive option, like filter_xss(), but only recommended to filter content entered by trusted site admins. Example:

l(filter_xss_admin($unsafe_text), $path, array('html' => TRUE));

Use check_markup(). This is the most configurable option. It uses one of your configured text formats, such as "filtered html", to filter out all but the whitelisted html tags (it will call filter_xss() for you). It will also apply other filters enabled on the text format. Make sure you choose a text format which has the "HTML filter" enabled in its configuration. Example:

l(check_markup($unsafe_text), $path, array('html' => TRUE));