Any way to filter by week number? Drupal 7, Views 3

I've got several views configured which display data over many years. The data is filtered by Year using a date field as filter criteria. For each year I have attachment views that I need to filter further by week. Rather than determining the exact dates for the weeks of each year and inputting them manually as filter criteria, I'm wondering if there is any way to add a filter criterion to filter by week number, i.e. week 1 thru week 52. That way the only date that needs to be set is the year for each view, and the rest happens automatically according to week number.

I am aggregating a lot of data by year and week in a table view where each column is an additional view attachment and trying to avoid having to manually enter the filters for week dates per year.

Does anyone have any advice/hints for me on this? Thanks very much.

Here is the code I am currently playing with:

function x_week_start($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return date('Y-m-d', $start);
}

function x_week_end($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return date('Y-m-d', strtotime('next saturday', $start));
}

$date = '2013-01-14';
$start = x_week_start($date);
$end = x_week_end($date);
$inquiry_date = date('Y-m-d', $data->field_field_inquiry_date[0]['raw']['value']);

if ($inquiry_date <= $start) {return FALSE;}

I should add that the field_inquiry_date field is a unix timestamp.

Here's a trick: create a new date format by navigating to Admin > Configuration > Regional and Language > Date and Time and clicking on the Formats tab (admin/config/regional/date-time/formats).

Set it to W (that's uppercase W), and it will give you week number, which you can use with any date.

That way you can include the date field directly in views, set the W filter and use the aggregation, filter, etc without any additional coding.


Drush command to switch to a multi-site child directory? Is there a Drush command that would cd into the directory of a particular multi-site instance, I mean to go to a directory like this one:

/srv/www/drupal/sites/alpha

where the parent Drupal resides in:

/srv/www/drupal

Thanks.

drush status produces a Site Path in its output which is what you're looking for. With some additional shell commands, you can parse this out.

MYPATH=/srv/www/drupal
MYDOMAIN=example.com

SITE_PATH=$(drush status --root=$MYPATH --uri=$MYDOMAIN | grep 'Site path' | cut -d':' -f2 | xargs)
cd "$MYPATH/$SITE_PATH"


Customize the appearance of sharing articles to social media I am new to Drupal and I just added a few buttons for sharing articles to social media (Facebook, Twitter etc.)
I want to customize the appearance of sharing posts.
After a few "research" I found out that I need to install meta-tags module to customize it...

The problem is that I can t figure it out how to change image or description. I tried but it didn`t work.
This is how it looks like a shared article, banner image instead article image and description with irrelevant details.

Welcome to StackExchange!

Assuming you are using D8, here are some instructions (D7 would be similar but slightly different).

The metatag module has some submodules to help with various metatag usages.  You will want to also enable the metatag_open_graph module. This will let you set the og* metatags.

First step in this is to go to the Content Type definition (structure->content types) for the page type (article?) you want to have metatag info on.  You will need to select the Manage Fields option.  Here you need to add a new field.  Use the "Use an existing field" option and add the MetaTags field to the content type.

Repeat this for any other content types you want to have Metatag info added to.

Once you have done this, you can go into the configure / search and metadata / metatag screens and define the defaults you want either globally or for the specific content type.  You can use "tokens" to indicate items from the node values.  E.g. [current-page:title] or [node:field_featured_image] and the like.  There is a browse available tokens to give you some guidance here.

Additionally, now that you have the metatag field added to the content type.  You can also manually modify the metatags for any single node if you have the rights to modify the metatag info.

This can be done while editing the node and opening the MetaTag tab (generally at the bottom of the form).

To keep facebook and twitter happy I think you generally need the title metatag, og description field and the og image field set.

Good luck.


Search page is not shown properly with D7 custom theme I am currently building a D7 theme for a website. I experiment some problems with the search page. After entering a search term the page "domain.com/search/node/[searched term]" is opened. But it just show the base page with nothing in the main-content block.

With another theme it works : results are shown properly on the search page and I can see both node tab and user tab. I assume something is wrong in my theme. I try to override
"search-results.tpl.php" because I read that this template is used to build the search page, but in my case it seems that the template is not used because if I put this code on it :

<?php print "foo"; ?>

there is no changes on the search page.

Any ideas ?

I finally solve the problem. The problem was my implementation of the template page "page.tpl.php" because inside this I never call :

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

As a consequence the results of the search were never shown, so I can't saw changes made in "search-results.tpl.php" ...


How do I get the file URI from an EntityMetadataWrapper object? Getting hold of file objects related to nodes through a field is easy using an EntityMetadataWrapper:

$wrapper = entity_metadata_wrapper('node', $node);
$images = $wrapper->field_images;

So that's great. However, I want to use some of the properties of the standard file object, and they're not available. When I look at the properties available on $images[0]->file using the above code, I see these:

fid
name
mime
size
url
timestamp
owner

Most notably, uri is missing, and in its place there's a url property, which is the full external URL to the image file. I want to manipulate these images via their URI (create thumbs, etc), so I'm left doing this:

$fid = $images[0]->file->fid->value();
$uri = file_load($fid)->uri;

Which seems to negate the whole point of using an EntityMetadataWrapper in the first place.

What am I missing? Where is the URI on the wrapped file object? If it's not available, for the love of all things good and pure, why not?!

I'm aware I could deconstruct the URL back to a URI, but that also feels very unnecessary.

Big thanks to MPD for pointing me in the right direction. In short, without the File Entity module, files aren't entities, so they don't naturally have the 'properties' I was expecting.

The Entity module provides some on their behalf, but URI isn't one of them. Fortunately it's very simple to make it available using hook_entity_property_info_alter() and a custom property callback:

function MYMODULE_entity_property_info_alter(&$info) {
  $info['file']['properties']['uri'] = array(
    'label' => t("URI"),
    'description' => t("The URI of the file."),
    'getter callback' => 'MYMODULE_entity_get_file_properties',
    'schema field' => 'uri',
  );
}

function MYMODULE_entity_get_file_properties($file, array $options, $name) {
  switch ($name) {
    case 'uri':
      return $file->uri;
      break;
  }
}

After that, $images[0]->file->uri->value() is available as expected.


VIews Proximity Search Fields as Separate Block? Just a quick question, or if someone can point me in the right direction...

I have a website that needs to have a search field where customers can enter a service (e.g. photography) in one field, and a post code/zip code in the other so search for services near them.

To do this, I have  a content type for each service with addressfield, geofield and geocoder modules installed, and I have a view set up with an exposed filter criteria to filter the results.

This all works perfectly.

What I would like to do is have the filter criteria search in an external block at the top of every page (like the default drupal search block) that will show a list of results on a NEW page whenever a customer submits the form. Using my current method, I first have to direct customers to the page with the view on before they can search.

I experimented with the Search Configuration module (https://drupal.org/project/search_config) which lets you use the existing drupal search block, but can limit the results to only show one content type, which is perfect, but doesnt include the location post code field, and doesnt have the configuration of displayed results like views fields would do.

If anyone could offer up a bit of advice of where to go next I'd really appreciate the help.

If you are using drupal 7 You have an option to expose the filter as a block. and you can display the block in any region as you do all the other blocks. You would find this option under the advanced section in the views.

Please check the screenshot below


How to get my Back To Site button to point to the correct location? I recently logged out of my Drupal 8 site to see the pages not obscured by the admin menu.

I then logged back in (/user/login) and, to my surprise, it sent me to /user/1.

When I tried to click the "Go To Site" link - it sends me BACK to /user/1.

I did nothing out of the ordinary except log out.

How do I get my Back To Site button to point to the correct location (mydomain.com/) again?

You're just stating facts, that is how Drupal works. If you log in, you go to your profile site by default. That might not make sense for most sites, but that's what it does by default, there modules that allow you to change it.

And "Back to Site" takes you back you the last non-admin page you were on. If you are on the homepage, it will point you back to that. Again, that's a feature, not a bug


How to change default content type machine name in commerce kickstart? I am using Drupal commerce kickstart 7 . I have installed perfecly . I am using demo store also. It have content types like hats, storage devices , etc,... I am using hats content type. So products show url like that hats/lloyd-l40s-40-full-hd-smart-led-television. But i want to show like products/lloyd-l40s-40-full-hd-smart-led-television.How to rename???

Thanks in advance

You can only set the machine name when you create the content-type. After that, it is not editable anymore. That's why you have to think twice when you create a new content-type. Your only solution is to delete this content-type and recreate one with the right machine name.

If it is only the appearance of the URL that doesn't suit you, you can also use URL aliases modules like https://www.drupal.org/project/pathauto and replace the word 'hats' by the word 'products' for example (in the module configuration).


How to make booking calendar for accommodation facility I have web, let's call it AccomovationInSkyResort.com. It has 2 facilities with 3 entities which can be booked out (reserved):

Appartment house:

a) 1th floor (1)

b) 2nd floor (2)
Cottage (3)

How to make "booking (reservation) calendar" for accommodation facility?

By "booking calendar" I mean calendar showing available (not booked out) nights. I need 3 calendars at all.

I did some experiments with calendar module but it isn't so nice solution.

How did you solved this problem?

I think the module you mentioned is good for it. Each of the entity can have a boolean field "Booked". So it could have values 0 or 1. You can filter out nodes according this field value in you calendar view.

I suppose, " Apartment house 2nd floor" is just one entity, not a type of entity.


drupal 7 frontpage image scroller: getting image URL in overwritten view template? I am creating a frontpage image scroller. I have created a new content type with a title, blurb and image field, and created a view block and set it up on the frontpage. All good so far; this works.

I obviously want to use some javascript and custom HTML to create the image scroller so I have overwritten the views 'row style output' template (views-view-fields--content-type-for-scroller--block.tpl.php). This template is getting picked up correctly and I can customize my 3 fields.

The problem is that the output from the image field:

$fields['myimage_field']->content

includes markup for the image, similar to:

whereby I only want it to output the Image src so that I can use the image as a background to another element.

I'm not too familiar with Drupal 7 but I image somewhere 'further up' I need to overwrite what sort of output I want for that particular field using some preprocessor but I'm not sure how to do this? Or is there a better way in general to be doing this?

here two alternatives to get the image address:
(to both examples the machine name of the image field is *image_test_field*).

1) this example is using the $row offer by view template (in this case the name of the field was obtained using dsm($row) or print_r($row)):

  $uriImagefromView = $row->field_field_image_test_field[0]['rendered']['#item']['uri'];
  $urlImagefromView = file_create_url($uriImagefromView);
  // $urlImagefromView variable now has the path to the image

2) this example is loading the data from entity_load  (in this case the name of the field was obtained using dsm($entity) or print_r($entity)):

  $nid = $row->nid;
  $entity = entity_load('node', array($nid));
  $uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
  $urlImagefromNode = file_create_url($uriImagefromNode);
  // $urlImagefromNode variable now has the path to the image

I hope this information be useful.


How can I reference a field from a product display when calculating a price? I am creating a product where you can buy a shirt in custom quantities (3 smalls, 1 large, 4 mediums). The user types in the quantity, as well as select various product variations. Then by rules I calculate the price based on a fields I made called small_price, medium_price etc. So it would pull the users quantity input for each field and multiply accordingly e.g. small_price*small_quantity + medium_price*medium_quanitity. This is all working well, however it is currently implemented on the product level and not product display.

What I am trying to do is have the rule multiply a field from the product display by a field in the product variation. However the product display field is not available to me in rules. I have seen a couple of short hand answers on here about writing a custom rule but is there anyone who could explain it to me a little more in depth?

Thanks!

I generally recommend any information required for the pricing / fulfillment of a product to be stored on the product itself. I can see where you might need to do so based on information in the display, though (e.g. discounting products in a particular category).

In that case, you can't traverse from the line item / product to its display mode via the standard Rules data selector. Instead you need to use the appropriate action to load the node that references the product in question. Then you'll need to pass the line item and that node to a Rules component where you can use additional conditions to bring field data from the display node into scope (e.g. "Entity has field") and use the line item unit price manipulation actions on the line item to affect the pricing.


No images appearing? OK the site was fine until I updated the core of the website. Now the images do not show up. I have checked the paths and they are correct. I have checked the permissions and they are 777. I have an SSL on the site but as I say, it was all working well before! I've spent the last few hours trying to resolve this but to no avail. I've deleted and uploaded the core again - same. Any suggestions appreciated!

It can be something wrong with File system settings. You may check it here admin/config/media/file-system


Importing Webform Submission List (Text) with Feeds Tamper I am exporting Webform Submissions from one Drupal site and attempting to import them onto another site with Feeds.

Unfortunately, the "Select Options" Webform field (that allows for multiple options to be selected) looks like the following in the exported file.

I am attempting to import these results directly into Drupal with feeds. I wish for these to go into one List (Text) field called "Status Desired".

As you can see, these all have different headers and I want them all to go into the same field.

I tried to use the "Find replace" in Feeds Tamper to change the "X" to the correct value but I had no success.

For example, if the user selects all 4 of the options, only the last one is imported.

Is there any way for me to use Feeds Tamper to import this as is into Drupal?

Or will I have no choice but to modify the data in Excel?

I managed to find a solution on thejibe.

The Feeds Tamper setting I was looking for was "Rewrite".

In the last field, I added "Rewrite" and added tokens for each of the values separated by commas.

Following that, I added Explode.

I did a test import and had great success.

I hope this helps someone.


Problems with Search API and Entity Translation I'm building a two-language website (Ukrainian - main, English - second) with the new Entity Translation approach. This approach seems very promising however it does not support multilingual content indexing.

I planned to use Search API Database Search module for the website. I also installed Search API Entity Translation and Search API Entity Translation Database Search in order to make them play together.

However the behaviour I achieved is the following:

1. When searching the website from the Ukrainian version: when searching with Ukrainian keywords the search yields no results; when searching with English keywords the search shows results in Ukrainian (the Ukrainian versions of relevant content in English).

2. When searching the website from the English version: when searching with Ukrainian keywords the search yields no results; when searching with English keywords the search shows results in English (with highlighted relevant keywords).

As far as I understand there is a problem with Ukrainian content indexing. Is it somehow possible to fix it?

Make sure to enable the "title_field" field in the Fields tab of the index instead of "title", as well as any other translatable fields you want indexed.  Then, make sure to re-index everything.

By default, custom fields aren't enabled there, and neither is "title_field" which provides translations of titles via the Title module.


Drupal installation not working/ what is .htaccess I have a lamp server and using drupal. The is on Ubuntu server 14.04. My drupal version is drupal 8.0.0 alpha 15. I followed this guide to install both: http://youtube.com/watch?v=zsPc_Tb8bI8

The problem is that I am running it on a server version, so there is no ui. No browser access in Ubuntu server. I can access my webserver via my host machine of the VM, by typing: 192.168.1.5
This bring up the default apache page of Ubuntu. When I do 192.168.1.5/drupal, I gives me an error (404 error). I already tried to set the www-data:www-data permission via chown, but this didn't work. Also, while browsing for answers I came across .htaccess file. I remember copying it somewhere, shown in the video. Where should I have copied it and what does it do?

My final(real) question: how do I access the drupal installation from another computer(not localhost). Do I need to set somethi ng in the apche conf? Also, what is .htaccess

in response to your "real" question, a quick search can broadly answer that, but basically it is configuration file to control access of locations on an Apache Web Server.


Display 3 items by default in a multivalue field? I have a field collection which is a multivalue field with unlimited values.

when I opens the form, the field collection has a set of fields with "add another item" button. When I click the button, it adds one more set and so on.

Is it possible to have 3 sets by default and when the "add another item" button clicked, one more set is being added and so on?

You can do it by jQuery, when page loads simulate the click event on the add more button using onClick()


Way to prevent drush from eating custom profiles when updating core? I use drush make with a stub .make file to download a custom profile via git.

that profile has all of the modules I want all of my sites to start out with.

If I then go into that site, and run "drush up drupal", it will update core, and remove my custom profile.

This is not good, since all of the modules I downloaded with my install profile's make file get stuck into the profiles/myprofile/modules folder. This basically removes all of my installed contrib modules, and drush doesn't give me a way to put them any where else, so basically, I can't update core with drush.

Consider to use Aegir. It supports this usecase.


Display user's name instead of username For various compatibility reasons, I would like my usernames to be standard no-spaces combinations, so jbloggs / jdoe / etc. This becomes unsightly when displaying blogs ("jdoe's blog") or node authorship ("15/09/2016 jbloggs").

I've added first/last name fields to the account, but can't find a way to have them displayed by default instead of the username. I am on Drupal 8, so Profile2 isn't yet ready, which means this answer isn't an option. Likewise, this answer proposes using the "Real Name" module, which doesn't have a D8 version.

If it's any help, I would basically like the full name used in every display context, so if there's a blanket solution that would do that, rather than giving me control by node-type, that would be more than acceptable.

Lastly, if the above isn't possible without a module, can someone point me to some info on referencing account/profile fields in twig? That way I could at least override it in the most prominent places using templates.

I'd add a new field called Display Name (or similar), then then use hook__user_format_name_alter() to load in that field, and change the display name to use the field value instead of the user name.

Here's the change record for D7 -> D8, where it used to be hook_username_alter(): https://www.drupal.org/node/1408514


How to duplicate image file in the same folder i want to duplicate a image file in the same folder programmatically , so i'm used file_copy() function for this but the original file image replaced or renamed and in file_managed table on database no row created.

if ($form_state['values']['image'] != 0) {
            $fileo = file_load($form_state['values']['image']);
            $fileo -> status = FILE_STATUS_PERMANENT;
            $file = file_copy($fileo,'public://img_files/',FILE_EXISTS_RENAME );
            file_usage_add($file, 'image', 'file_img', 1);
        }

Thank you :).

To add entry for a file to a file_managed table, you could use code like:

global $user;
$file = new stdClass;
$file->uid = $user->uid;
$file->filename = 'image.png';
$file->uri = 'public://path/to/file/image.png';
$file->status = 1;
$file->filemime = 'image/png';
file_save($file);
file_usage_add($file, 'mymodule', 'mykindofusage', $node->nid);

Code shamelessly stolen from this answer by Clive.

Now, if you are using a file_copy function, it should work all right and create these entries for you. But you should always check what's in return value ($file in your case). If it's FALSE, you should not call file_usage_add, but output a message to check watchdog entries for failure reason.

If you will tell us what's in your watchdog, probably in another question, we'll be able to answer with more details about the reason of failuer.


How do I override an exposed filter input type? I'm writing a module to change input HTML attributes with the next code:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function custom_numeric_filter_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $field = 'yourfieldname';
  if ($form_id == 'views_exposed_form' && array_key_exists($field, $form)) {
    $form[$field]['#type'] = "range";
    $form[$field]['#step'] = 5;
    $form[$field]['#size'] = 5;
    $form[$field]['#min'] = 10;
    $form[$field]['#max'] = 60;
  }
}

The problem is that the type gets overwritten back to number by something else.
I have Better Exposed Filters installed, maybe it gets rewritten there but why? And how can I make sure my module code has priority? With the help from NoSssweat I made sure it was executed after BEF and it didn't help.

Try in this way:
function seven_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['node_page_form', 'node_page_edit_form'])) {
    $form['field_number']['widget'][0]['value']['#type'] = 'range';
  }
}

I think this post will help you, check once - https://www.drupal.org/project/drupal/issues/2958499#comment-12558959


My module adds a CCK field to an existing content type. How do I then modify an existing view to sort using the new field? I am building a new module ('best_answer') that builds on the functionality an existing module ('answers').

The new module adds a new CCK field ('best_answer_p') to a CCK content type ('answer') that was defined in the original module.

The original module also defined a view ('question_answers') which lists answer nodes, sorted by several factors. I'd like to modify this view so that it also sorts by the new field 'best_answer_p'.

I could do this by simply overriding the view, using the Views UI. However, what this means is that if any other module also wants to override the view in some way, my 'best_answer' sort will be lost.

So, I'd like to do this in a way that programmatically alters the existing view instead of overriding it. I am trying to do this using Hook_views_query_alter. But I run into an error.

Could anyone point me in the right direction?

Here is my code:

function best_answer_views_query_alter (&$view, &$query) {

  if ($view->name == 'question_answers') {

    // add the best answer field to the query
    $query->tables['node']['node_data_field_best_answer_p'] = array(
      'count' => 1,
      'alias' => 'node_data_field_best_answer_p',
    );

    // sort answers so that the best answer is displayed first
    $new_orderby[0] = 'node_data_field_best_answer_p_field_best_answer_p_value DESC';
    foreach ($query->orderby as $key => $value) {
      $new_orderby[$key+1] = $value;
    }
    $query->orderby = $new_orderby;

  }
}

Here is the error:

  user warning: Unknown column 'node_data_field_best_answer_p_field_best_answer_p_value' in 'order clause' query: SELECT node.nid AS nid, votingapi_cache_node_points_vote_sum.value AS votingapi_cache_node_points_vote_sum_value, node.created AS node_created FROM node node LEFT JOIN votingapi_cache votingapi_cache_node_points_vote_sum ON node.nid = votingapi_cache_node_points_vote_sum.content_id AND (votingapi_cache_node_points_vote_sum.content_type = 'node' AND votingapi_cache_node_points_vote_sum.value_type = 'points' AND votingapi_cache_node_points_vote_sum.tag = 'vote' AND votingapi_cache_node_points_vote_sum.function = 'sum') LEFT JOIN content_type_answer node_data_field_answer_question ON node.vid = node_data_field_answer_question.vid WHERE (node.status <> 0 OR (node.uid = 1 AND 1 <> 0) OR 1 = 1) AND (node.type in ('answer')) AND (node_data_field_answer_question.field_answer_question_nid = 2) ORDER BY node_data_field_best_answer_p_field_best_answer_p_value DESC, votingapi_cache_node_points_vote_sum_value DESC, node_created DESC LIMIT 0, 10 in D:\xampp\htdocs\drupal\sites\all\modules\views\includes\view.inc on line 771.

You should override the view and change the sort. I have never seen a module that attempted to alter a view defined by another module.


How to translate the Automated Logout module administration? How to translate language of the Automated Logout module administration?

I was searching for translation of polish language and tired other modules.

There IS a Polish translation of the autologout module available. Though it is currently only translated for 42%.

The way I understand (translate???) your question is something like so: How can I show the admin interface for the Automated Logout module in the Polish language?

To answer that question, just swich to the Polish version of your site, and then use the admin link. As an alternative, enable the "language switcher block" so that it is shown within the theme you're using for Administration. Then navigate to anywhere within admin (whatever language), and use the language switcher block to show the admin interface in Polish (for about 42%). If you also want the remaining 58% to be shown translated, then it's up to you to actually add your custom translations of the various missing translations.


Why is the View import option not shown in the views UI? I'm trying to export/import a view from a dev site to a qa site. Views UI is enabled. However, when I go to structure>views I don't see the "+ import view" option, only:

"+ Add new view" "+ Add new view from template"

Anybody any idea?

If the user you are logged in has the Administer Views
permission, if not then give this permission.
Also enable the 'PHP filter' core module.
Give the relevant user role the Use PHP for settings permission.
Paste the below url after your current url and you will see the
import views page.

admin/structure/views/import


How to assign a user a role during registration using Rules and Profile 2? I am using the Profile 2 module to select roles during the registration process. So a user selects a role (using a radio button) and then a rule fires to give the user the role that was selected.

Here is the rule I'm using:

    { "rules_give_user_a_role_after_registration" : {
    "LABEL" : "Give user a role after registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "account:profile-main:field-user-role" ],
          "value" : "Emporos"
        }
      }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } }
    ]
  }
}

The issue is that the role is not assigned to the user. Any idea why not?

If "...the role is not assigned to the user..." (as in your question), it must be that your Rules Action is not performed. And if that's the case, then that must be because your Rules Condition is not satisfied (true).

And the reason why your Rules Condition is not true, is pretty sure because you should add another Rules Condition Entity has field (related to your additional field in the Rules Condition you already have). And make sure to add that Entity has field condition BEFORE the Rules Condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Add multilingual support to Drupal 8 Hello World module Today we already can upgrade contrib projects to Drupal 8 (#D8CX) and there are more and more “Hello World” code examples for Drupal 8. Some of them:

Drupal 8: Writing a Hello World Module
Drupal 8: Hello OOP, Hello world!
Drupal 8: Hello, Configuration Management
Drupal 8 module development #3 - adding a settings page - revision
Drupal 8 isn't Scary, Pt. 1: Introduction & Creating a Hello World Module

Can we add multilingual support to such simple modules?

Drupal 8 has many improvements for interface, configuration and content translation. There are great series of articles from Gábor Hojtsy: Multilingual Drupal 8.

Let's make Hello World module settings from this article translatable.
Full module code is avalible here: https://github.com/kalabro/drupal-examples/tree/master/hello
This code was tested with core 8.x dev branch (ed8dfae 2014-05-19).

1. Preparing Drupal 8 installation

Enable “Language”, “Interface Translation” and “Configuration Translation” modules.
Configure multiple languages.
Place “Language switcher” block.
Check how “Configuration Translation” with Site information form.

2. “Hello World” module

Use Drupal 8: Hello, Configuration Management article as base for “Hello World” module.
This module provides static /hello page with hardcoded “'Hello, World!'” message in it. The message can be outputted in normal or upper case. There is a setting for message case:

Play with the code until it becomes yours.
hello.info.yml:

name: Hello
description: '"Hello World" module with config translation support.'
core: 8.x
type: module
configure: hello.settings_form

3. More complex settings

Let's make message on /hello page configurable (dynamic).
For this purpose we should update form and controller.

Add 'hello_message' textfield in 'buildForm' method:

$form['hello_message'] = array(
  '#type' => 'textfield',
  '#title' => t('Your "Hello World!" message'),
  '#default_value' => $config->get('hello_message'),
  '#required' => TRUE,
);

Update HelloController to take hello message from setting instead of hardcoding it:

$hello_message = $config->get('hello_message');

Check full code in repository: HelloConfigForm.php, HelloController.php and etc. Feel free to ask any questions.

4. Make settings translatable

Our setting 'Your "Hello World!" message' should be translatable.

First of all we have to add config schema. It is recommended to add schema for any modules with configuration.
hello.schema.yml:

hello.settings:
  type: mapping
  label: 'Hello World settings'
  mapping:
    case:
      type: integer
      label: 'Letter case of your "Hello World!" message'
      # translatable: true
    hello_message:
      type: text # translatable by default.
      label: 'Your "Hello World!" message'

Now Drupal knows what kind of data is stored in module config. Some of config data types are translatable by default (text, label, mail). You can also add translatable: true to settings manually (try to do it for “case” setting).

Add Configuration Translation support.
hello.config_translation.yml:

  hello:
    title: 'Hello World settings'
    base_route_name: hello.settings_form
    names:
      - 'hello.settings'

Just small YAML file and that's all.

To see “Translate settings” tab you need existing default local task (See hello.local_tasks.yml for an example. Note: because of a change in Drupal core, this file name is no longer correct. It should be hello.links.task.yml now.).

Only translatable settings are appeared.

P.S.: In Drupal 7 i18n_variable API is used for this task.


Activate bootstrap theme in BrowserTestBase phpunit test In a Drupal 8 testclass I am trying to install the bootstrap theme (v 8.x-3.1). It is saved in the /theme directory. No problem when using the UI. Unfortunately I get an error in the test when I try to install it with this code:

/*
 * Anytest
 * @group proreos
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 *
 */
class CalculatorControllerTest extends BrowserTestBase {

  public function setUp() {
    parent::setUp();
    \Drupal::service('theme_handler')->install(array('bootstrap'));
  }

The test exits with the following error:

PHPunit Test failed to complete; Error: PHPUnit 4.8.27 by Sebastian
Bergmann and contributors.
There was 1 error:

1)
Drupal\Tests\preosasde\Functional\CalculatorControllerTest::testCalculatorController
Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for
bootstrap.settings with the following errors: bootstrap.settings:schemas
missing schema

/var/www/vhosts/proreos/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php:93

Any advice on this? Anyone tried to install bootstrap in an PHPUnit test sucessfully?

Thanks!

Thanks to Berdir for the hint. The solution is to disable the schema validation here. It's done with this code in my testclass:

protected function getConfigSchemaExclusions() {
  return array_merge(parent::getConfigSchemaExclusions(), ['bootstrap.settings']);
}


show positive and negative votes i'm trying to make a 'top voted' view of nodes and I want it to appear like this:

title of node; 655 positive, 120 negative votes, total 775.

how do i do the '655 positive, 120 negative votes' part?

The Vote Up/Down module, while it supports Views 2 integration, only allows for a Voting Up/Down widget. With no support in the module for retrieving the vote count, you'll need to do one of the following:

Wait for the maintainer to add a views handler that supports up & down votes data.
Create your own patch that adds support for that data.

Given the current state of the project (seeking maintainer, 7.x version not released), you're probably going to have to go with #2.


Permission page broken All other pages are being loaded fine but when I go to permissions page it comes like this. What may be the reason for this ? Please help.

I had exactly the same problem few days ago.
Do you have the devel module install?

For me it was the problem, i can't explain why but when i desintalled it, all worked fine.

So maybe, try to desactivate and unistall it and maybe your page permission will work again.

PS: i just re-install the devel module to make a test and i have exatly the same permission page than you. For me it's the devel module the problem. (I'm new in Drupal so i had certainly make a mistake somewhere)


From where comes $scheme argument in image_style_deliver callback? In core image.module there is a menu item:

  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

As you can see, there is only one argument passed to it. But when we see "image_style_deliver" function, we see:

function image_style_deliver($style, $scheme) {

I don't know if I'm tired or what but... from where $scheme argument comes from? ;)

Drupal passes on extra portions of the URL as parameters by default. So for example, a URL might look like this:

http://example.com/sites/default/files/styles/style_name/public/foo/bar.jpg

Which resolves in image_style_deliver to

$style = 'style_name';
$schema = 'public';

The function then goes on to extract the rest of the unnamed arguments, and reconstitutes them to form the eventual path to the file.


In Drupal 7 how do I add an anchor tag to a path alias menu link I created a node in drupal 7 and given it a url path alias of 'testing'.   When I try to create a menu item that links to the path alias with an anchor, it throws an error

If I do node/1#this it works, but again not with a url path alias.

Is there a work around?

You can add the full url with the anchor tag. Not the best for deployment but a work around.


drupal_http_request() returns "Invalid JSON primitive" I am developing a module for Drupal 7 which calls a remote API. I am using drupal_http_build_query(), drupal_http_request(), and drupal_json_decode().
My code is as follows
$username = $form_state['input']['name'];
$password = $form_state['input']['pass'];

$authurl = variable_get('sgauth_base_url_authenticate', '');
$headers = array('Content-Type' => 'application/json');
$data = array('email' => $username, 'password' => $password);
$query = drupal_http_build_query($data);
$options = array('headers' => $headers, 'method' => 'POST', 'data' => $query);
$result = drupal_http_request($authurl, $options);

dpm($result);

$authurl is returning the correct url for the API.
When I look at the returned object I see the following
The request is (Note host, username and password have been hidden)
POST /SingPostApi/MobileAuthenticate HTTP/1.0
Content-Type: application/json
User-Agent: Drupal (+http://drupal.org/)
Host: xxxxxxxxxxxx.xxxxxxxxxx.com
Content-Length: 36

email=xxx%40xx.xxx&password=xxxxxxxx

Which seems OK
$result->code I see a 500 error
$result->data shows Invalid JSON primitive: email.
As far as I can tell my code is OK based on my reading of the Drupal API. I don't understand why I am getting the wrong data returned.
When I make he POST request from the Firefox HTTP Requester I get a 200 code and the data I expect to see returned
I would appreciate it if someone who can see where I am going wrong can point me in the right direction.

If your request URL accepts only JSON object data, then you need to pass the value as JSON object,
To convert the PHP array/object to JSON object use

drupal_json_encode($input);

If your request URL's output in the form of JSON object, you need to print the array/value after conveting into a JSON object and you need to add the header as 'application/json'

header('Content-Type: application/json');
echo drupal_json_decode($output);


Nesting views with a node reference field I am creating a Drupal site that is used as a task manager; each task node has the ability to reference another task node as a parent.
In the task list view, I would like to nest the same or similar view within each row, displaying that tasks children.

I've done something similar before by theming; however, I'm wondering if is there a standard, or emerging way of accomplishing this within the Views interface with a third-party module.

You can solve it with Viewfield.

  View arguments are supplied through tokens.

So, what you should do:

Add new type of your view (new Block, for example) and add contextual filter by node reference field.
You can modify display format etc.
Create for your tasks new field "View Reference" and set your new display type of view. Check «Always use default value».
Set [node:nid] in Arguments input.

Tested on D7.


How to store date_popup fileld in mysql For some reason I cannot save the value of my date_popup field (comment_date) to mysql database.
I need to use default value from existing field (field_due_date6) and store the new value to this field.
So I do the following:

function custom_form_alter(&$form, $form_state, $form_id) {
  $form['comment_date'] = array(
      '#date_format' => 'Y-m-d',
      '#date_year_range' => '0:+1',
      '#type' => 'date_popup',
      '#weight'=>1,
      '#datepicker_options' => array('minDate' => 0),
      '#default_value' => $form['#node']->field_due_date6['und'][0]['value']
    );
}

Then I'm trying to submit it to database:

function custom_support_comment_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $node_wrapper = entity_metadata_wrapper('node', $node);

  if($form_state['values']['comment_date']) {
    $node_wrapper->field_due_date6->set($form_state['values']['comment_date']);
  }
  $node_wrapper->save();
}

But when I click Submit button I got the error -

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. в функции EntityMetadataWrapper->set() (строка 122 в файле Z:\home\dd1\www\sites\all\modules\entity\includes\entity.wrapper.inc).

Could you please specify what I'm doing wrong?

Node Field must be expecting date field value in unixtimestamp format while the custom form will return the value in the format mention as '#date_format' => 'Y-m-d'. View of your form submit values will look like.

You should run the submit date value through strtotime() to get the unxtimestamp value for it before assigning it to node field.

$node_wrapper->field_due_date6->set(strtotime($form_state['values']['comment_date']));


Custom jQuery code loaded but not working I am trying to implement some custom jquery code for a 3D menu on my Drupal 7 site. I created two .js files one with the code and other one calling it on page. I have succesfully loaded both .js files throug my theme's .info file, however nothing happens, even tho i know the js code is 100% correct and working as it should. Im also using jQuery update module set to 1.8 so that shouldn't be a problem. As i am less than a begginer regarding jquery, i ask for your help. I can't understand why is code being loaded but not working. Thanks for reading and all the answers.

(function ($) {

   var Menu = (function() {

    var $container = $( '#rm-container' ),
        $cover = $container.find( 'div.rm-cover' ),
        $middle = $container.find( 'div.rm-middle' ),
        $right = $container.find( 'div.rm-right' ),
        $open = $cover.find('a.rm-button-open'),
        $close = $right.find('span.rm-close'),
        $details = $container.find( 'a.rm-viewdetails' ),

        init = function() {

            initEvents();

        },
        initEvents = function() {

            $open.on( 'click', function( event ) {

                openMenu();
                return false;

            } );

            $close.on( 'click', function( event ) {

                closeMenu();
                return false;

            } );

            $details.on( 'click', function( event ) {

                $container.removeClass( 'rm-in' ).children( 'div.rm-modal' ).remove();
                viewDetails( $( this ) );
                return false;

            } );

        },
        openMenu = function() {

            $container.addClass( 'rm-open' );

        },
        closeMenu = function() {

            $container.removeClass( 'rm-open rm-nodelay rm-in' );

        },
        viewDetails = function( recipe ) {

            var title = recipe.text(),
                img = recipe.data( 'thumb' ),
                description = recipe.parent().next().text(),
                url = recipe.attr( 'href' );

            var $modal = $( '

' + title + '

' + description + '
See the recipex
' );

            $modal.appendTo( $container );

            var h = $modal.outerHeight( true );
            $modal.css( 'margin-top', -h / 2 );

            setTimeout( function() {

                $container.addClass( 'rm-in rm-nodelay' );

                $modal.find( 'span.rm-close-modal' ).on( 'click', function() {

                    $container.removeClass( 'rm-in' );

                } );

            }, 0 );

        };

    return { init : init };

})();
 })(jQuery);

And here's the content of other JS file which is calling the function.

(function ($) {

$(function() {
Menu.init();
});
})(jQuery);

Managing javascript in drupal

As per the above link you should put your Javascript or Jquery inside the following :

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
   // add your code here
      });
    }
  };

})(jQuery);


Theme a subscriber field in Simplenews issues I need to address my subscribers in a more personal way. Thus I added fields for Mr./Mrs., firstname, lastname to the subscription block, and data gets collected nicely.
However, I can't see how to theme these fields in simplenews-newsletter-body.html.twig.
In the header of this template there's an example printing the subscriber's (built-in) mail.
 {{ simplenews_subscriber.getMail  }}

Trying the same as {{ simplenews_subscriber.field_lastname  }} doesn't do anything. I tried a lot of variations to this approach, but to no avail.
What's the secret of getting custom subscriber fields to print with Twig?

{{ simplenews_subscriber.field_lastname.value }}
In the header of this template:

Note that depending on the used caching strategy, the generated body
might be used for multiple subscribers. If you created personalized
newsletters and can't use tokens for that, make sure to disable
caching or write a custom caching strategy implemention.

To solve it I added in the sites/default/services.yml
services:
  simplenews.mail_cache: ~

  simplenews.mail_cache:
    class: Drupal\simplenews\Mail\MailCacheNone


Add a link into a drupal header and table I am currently in the process of creating a free sports betting site, and I would be able to manage the matches. For this, I create a table with the data from my table, but I would add a column to manage the matches, to remove them or modify them. Outside, I do not like to add a link in the header, for exemple:

 l(t('Modify'), 'link/modi');

Here is my actual code:

    function get_rencontre_all(){

    $header = array(
    array('data' => 'journee', 'field' => 'journee' ),
    array('data' => 'eq1', 'field' => 'eq1'),
    array('data' => 'eq2', 'field' => 'eq2'),
    array('data' => 'stade', 'field' => 'stade'),
    array('data' => 'date', 'field' => 'date'),
    array('data'=>'Opérations', 'colspan' => 1),
    );

    db_set_active('sport_db');
    $query = db_select('rencontre', 'r')->fields('r');

    $sorter = $query->extend('TableSort') //création de l'objet TableSort
    ->orderByHeader($header); //détermination du trier
    $result = $sorter->execute(); //exécution du TableSort
    db_set_active();
    return $result->fetchAll(PDO::FETCH_ASSOC); //revoie d'un tableau de lignes

}

function modulesport_page_rencontre_manage(){
    $rows = get_rencontre_all();
    //header qui définit les colonnes et les champs associés
    $header = array(
    array('data' => 'Journée', 'field' => 'journee' ),
    array('data' => 'Equipe domicile', 'field' => 'eq1'),
    array('data' => 'Equipe exterieur', 'field' => 'eq2'),
    array('data' => 'Stade', 'field' => 'stade'),
    array('data' => 'Date', 'field' => 'date'),
    array('data'=>'Opérations', 'colspan' => 1),

    );

    $page_array = array(
    'titre' => array(
    '#prefix' => '<h1>',
    '#suffix' => '</h1>',
    '#markup' => 'Liste des rencontres',
    ),
    'tableau' => array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows'=> $rows,
    ),
    );
    return $page_array;

}

Instead of returning returning $result->fetchAll(PDO::FETCH_ASSOC), You need to loop the result and add a link to the array like :

$rows = array();

foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
  $rows[] = $row + array('link' => l('MyLinkText', 'mylinkhere'));
}

return $rows;


Rules: Event user has logged in won't trigger rule I'm a newbie and using the Rules module, but Rules Event "user has logged in" won't trigger my rule.

I can set any event to trigger a rule (for example, user has logged out), but if I change it to "User has logged in", the rule is never triggered, even if conditions and actions remains the same.

This doesn't work:

Event: User has logged in
Conditions: None
Actions:

Set a data value
Parameter: Data: [account:field-point], Value: 1

But if event is: "user has logged out", there is no problem, the value changes to 1.

I had used "user has logged in" as an event in another site and it works, but in this particular case it won't.

Any idea why?

UPDATE:

I found the problem... maybe.

At a user's first log in I have a (first) rule to remove one role "new" and add a new one "active", I also set the date of first log in in a field and a second date that has a 1 year offset. The condition to this rule is if the user account has the role "new".

A user can also set some fields of his profile to be private or public by changing a field text list, I did this by setting a (second) rule that after updating a user account changes a set of cloned fields to blank when the value of a field is "private" and a (third) rule that copies the data from the original fields to the cloned ones when user selects "public". Both rules are triggered after updating a user account.

In this case, the first rule to change user roles never triggers; if I disable the third rule triggered after the user account is updated, then the first rule runs as expected.

So, it looks like I can't have two rules triggered by the same action, in this case, two rules triggered after the user account is updated.

The problem is solved by setting the third rule to trigger before saving a user account, but I still don't know what caused the problem.

Challenging Rules question ... also because there seem to be some things in it that don't match with Rules terminology or functionality. Read on for more details ...

Part 1: Refinements of your question

  Rules: Event user has logged in won't trigger rule

This is a pretty confusing title: Rules Event "User has logged in" should always be triggered ... when a user logged in. If that's not happening, then that seems ike a Rules-bug. Therefor I think a better title is "Why is my Rules Action not executed when using Rules Event 'User has logged in'?". If you agree, please edit your title like so.

  I can set any event to trigger a rule ... the rule is never triggered.

Rules Events are triggered by Rules, "you" cannot "set" them. Using custom code you may enhance Rules to trigger "custom" events to be triggered by Rules. Since this question is not about custom code, I assume you wanted to say "No matter which Rules Event I try to use ... the rule is never triggered".

  ... two rules triggered by the same action

Rules are NOT triggered by an action, they are trigger by a Rules Event.

Advice: Rules is all about Events, Conditions and Actions (ECA for short). You really need to think with those 3 crucial terms when using Rules ... And rephrase your question accordingly.

Part 2: Attempt to answer your question

What might explain what's happening

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Rules debugging

You clearly have a combination of rules that need some debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Obviously, if you have more then 1 rule (like 3?), you may want to  make it like Bingo1, Bingo2, Bingo3. Depending on the order they are shown, you also know the order of execution. Stupid, but simple and efficient (I think).

For more suggestions about Rules debugging, refer to  "How can I display the value of a variable inside a condition?"

Use Conditional Rules

In your case there are 2 rules involved that are triggered by the same Rules Event (= after user acount is updated). But how do you know in which "order" (which Rule gets executed first)? There might be some logic in rules somewhere to find the answer to that question.

But instead of searching for that answer (or hope the order matches with what you'd hope), I simply use the Conditional Rules module in such cases. Not only does it allow me to merge multiple rules together in a single rule (= much easier to maintain, etc), but "I" am in full control about the actual Rules Conditions (within a Rules Action!), and I can set the order of them in the way "I" want/expect them to be. You can use Conditional (if/else) logic within the Rules Action, or you can also use Switch logic.

For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework.


How to filter a view on a property of optional entityreference-related content (table join / views relationship)? Consider this example: we have three content types: Concept, Language, and Word.

The Word content type has two entityreference fields:

field_concept references concept nodes, and
field_language references a language node.

The view shoud list all existing concepts, with related words (referencing the concept via entityreference) in a second column. The words are optional; we always want to show all concept nodes. We can accomplish this by creating a non-required Views relationship based on the field_concept entityreference (Entity Reference: Referencing entity). (This results in a LEFT JOIN in SQL).

The problem is how to filter words on the field_language value, without filtering out any of the concepts. Consider the following data.

Concept | Word   | Language
---------------------------
CAT
DOG     | Hund   | German
DOG     | chien  | French
FIRE    | fuego  | Spanish
WATER   | Wasser | German

Say we want related words (if any) filtered on a particular language. The desired views result for German is this:

CAT
DOG     | Hund
FIRE
WATER   | Wasser

We cannot use regular (grouped) filters with a condition like field_language = German OR field_language = NULL: while this would show CAT, DOG and WATER, it would remove "FIRE" from the results, since there is a Spanish result for FIRE.

So it seems we need to have a condition on the JOIN itself, preventing any words other than German ones to be joined. This question somewhat addresses how this should work, but: how would I access the field_language values? This is the basic query created by Views to show the concept and word titles - I'm not seeing how I should modify this:

SELECT node.title AS node_title, node.nid AS nid, field_concept_node.title AS field_concept_node_title
FROM
{node} node
LEFT JOIN {field_data_field_concept} field_data_field_concept ON node.nid = field_data_field_concept.field_concept_target_id AND (field_data_field_concept.entity_type = 'node' AND field_data_field_concept.deleted = '0')
LEFT JOIN {node} field_concept_node ON field_data_field_concept.entity_id = field_concept_node.nid
WHERE (( (node.status = '1') AND (node.type IN  ('concept')) ))

It seems we cannot use the field_data_field_language.field_language_target_id value as a condition on the first LEFT JOIN without having another JOIN first, which would defeat the purpose - or am I missing something?

Can this be achieved with Views? Or are there alternative ways of doing this?

It seems we cannot use the
  field_data_field_language.field_language_target_id value as a
  condition on the first LEFT JOIN without having another JOIN first,
  which would defeat the purpose - or am I missing something?

Why would adding the column defeat the purpose? Add field_data_field_language.field_language_target_id from your Word and exclude it from the Views display.

Then in your view under Advanced Options add a tag to the query such as concept_word_lang_matrix_view

Then in a custom module implement hook_query_alter() to add your custom join (but not muck with the View fields or anything directly persay -- your Join is just refining results fetched by your View configured in the Views Admin UI)

A sample implementation of hook_query_TAG_alter looks like:

/**
 * Implements hook_query_TAG_alter for the Submission Is Open authentication
 * check of my business logic.
 */
function MYMODULE_query_SubmissionIsOpen_alter(QueryAlterableInterface $query) {
  #dpm(_MYMODULE_get_raw_sql_string($query));
  #dpq($query);
}

/**
 * This is a helper function to output the raw SQL from a db_select() type
 * query.
 *
 * Found via:
 * http://drupal.stackexchange.com/questions/51333/print-the-query-which-is-built-using-db-select
 */
function _MYMODULE_get_raw_sql_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }
    $string = strtr($string, $arguments);
  }
  return $string;
}

dpm() and dqp() are from the Devel module, they let you preview the SQL running from Views from within your module (where you're tweaking it).

Without having your server/DB I cannot just give you the SQL (nobody can do your homework for you). Writting the correct SQL is the hard part; altering the Views SQL is somewhat tricky but outlined here. goodluck.

EDIT
you may also find this documentation helpful:
https://drupal.org/node/1705998


Views - Rewrite Results doesn't work i have three field to show in views: title,body,desc.
in desc
I choose rewrite results and then put those
[title]
[body]
but nothing shows up. i used inspect element by chrome, desc is here but empty.

Add a field Global: Custom text at the end of your field list, add the replacement patterns in the `Text' box.

The is from the comment by Dom Day which worked for me.
Still wondering why the method in the question produced no output at all.


Table and Form in the same page I have a quick question. I work with a form that consists of the following:

$form['data_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Killer search engine!'),
    '#id'   => 'killer-search-engine',
    '#maxlength' => 1024,
    '#description' => t('Search by using tags and free text'),
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

    $form['table'] = array (
        '#title' => 'TABLE',
        '#type'   => 'table',
        '#value' => $table,
    );
}
return $form.

The form is appearing but the table element of it, even though it is filled with html code of an actual table(I checked through dpm($form)) does not appear.
Anyone with a quick fix?

Thanks beforehand

If you want to display the values in table format you can use Table theme
Example:-

$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
  );

$header and $rows  would be arrays.


Hook Menu and module prevalence I am implementing the following in a module:

function foo_module_menu() {

    $items['taxonomy/term/%'] = array(
    'page callback' => 'subproducts_populate_taxo',
   'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK);

    return $items;
};

This hook doesn't seem to work, i assumed it was because of the taxonomy module having prevalence on this menu item, so i gave my module a -1 weight.

Now strange thing, it work but only after clear cache once after applying the weight change. If i reflush cache the Taxonomy module take prevalence again even though i didn't rechange the weight..

Any ideas ?

Use hook_menu_alter() to override existing menu entries.


Site install fails with Aegir I've been using Aegir to install Atrium sites without a hitch. Users self register through Aegir to spawn their own open atrium sites. Today I noticed new atrium sites failed to install. A week ago this worked fine and as far as I know nothing has been changed with core content/modules. I did some comparisons in looking at the task log between the failed install and a successful install (from a week ago). The simplexml load and "Could not download project status information" is weird. Here's what I gathered so far. Task install log looks identical until near the end. The failed install shows the following after "downloading release history…":

Downloading release history from http://updates.drupal.org/release-history/drupal/6.x
simplexml_load_file(): 6.x:2: parser error : Specification mandate value for attribute http-e pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : attributes construct error pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : Couldn't find end of Start Tag meta line 2 pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:12: parser error : Opening and ending tag mismatch: p line 11 and body pm.drush.inc:2103

This goes on for several more lines - finally ending in the following error:

Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

This compares to This compares to the successful site task install log here:

Downloading project drupal to /tmp/drush_tmp_1368706259 ...
Downloading drupal-6.28.tar.gz was successful.
Md5 checksum of drupal-6.28.tar.gz verified.
Verifying signature for svn version control engine.
Verifying signature for bzr version control engine.
Project drupal (6.28) downloaded to /var/www/vhosts/site.com/platforms/atrium-1.0/drupal-6.28.
Project drupal contains: - 1 profile: default - 6 themes: pushbutton, min... (Expand)

The diff analysis looks similar again for many more lines, then shows the following error for the failed install log:

WD form: Illegal choice 5 in Roles allowed to use this profile element.
WD form: Illegal choice 6 in Roles allowed to use this profile element.

The rest of the task log for the failed install shows typical Aegir behavior of dropping the database and deleting directory.Searching through my general site logs, or when I run cron, I get

"Unable to fetch any information about available new releases and updates."
I also get that error when I try to manually run cron
Also a few other things like:

Warning: include() [function.include]: Unable to allocate memory for pool. in theme_render_template() (line 1079 of/var/www/vhosts/site.com/hostmaster-6.x-1.4/includes/theme.inc).

An illegal choice has been detected. Please contact the site administrator.

The "unable to fetch information about new releases..." error is weird and similar to the Aegir error on the failed install task log.
Unfortunately I don't know where to start. I'm wondering if this is a write permissions issue with drush, or php version issue. It;s starnge that it's happened suddenly, so maybe Aegir changed something on the fly. Don't know... Any thoughts? Thanks!

This line says it all:
    Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

Probably not a problem you or Aegir could do anything about. Just an Internet hickup.


trigger a form submission button using custom cron It's possible to create a cron that trigger the submission of a form ?
To be clearer, when my drupal cron is executed, this form will be submitted automaticlly ?
EDIT :
This is an explantion for what reson is the cron :
Im using apachesolr for indexing articles in my website,
some times it happen that some editors in the site delete articles, but the problem, these articles still exist in apachesolr... and when solr try to index again, the hole website crashes !!
so that's why I need to find out these deleted articles and delete them from solr indexing also...
this module do exactly what I need : apachesolr_integrity
this module add a new submission button in apachesolr configuration page : /admin/config/search/apachesolr to Delete orphaned nodes..
But I don't need every time the site crashes, I click on this form button, maybe the site administrator is not available that time, and the site still breaking :(
I thought about cron to do this this, and also if it can be made with rules, it will be a better solution because with rules I will tell system to directly delete Orphaned nodes when a content has been deleted, and with a cron, the site can still crashed until the next cron execution..
Anyway, the question is how can I add the code made by this module in either a cron or a rule.
Thanks in advance

This seems a little bit odd. Form submission are meant to be dealt with by humans in order to transfer information to a specific service.

So if you want to send any kind of request to a dedicated service, yes, that is possible using drupal_http_request.

  This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

If you want to submit a Drupal form on cron, then you can use drupal_form_submit.

  This function allows you to supply values for form elements and submit a form for processing. Compare to drupal_get_form(), which also builds and processes a form, but does not allow you to supply values.

If you want to execute any custom logic (which might also be the result of a form submission by humans) then this is also possible using custom code.

For all that, you will need to implement hook_cron() in a custom module.

If anything else, please elaborate on what it is that you want to achieve.


AJAX error when ctools_modal_command_dismiss() is called So I'm having a problem with dismissing a Ctools modal within a form submit's callback function. Once I have processed any submit data, I'd like to dismiss the modal without redirecting the page (easy enough), but each time I click the submit button with ctools_modal_command_dismiss() included in the callback function, I'm presented with an AJAX error such as below:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.

I'm stumped as to why this is happening. The modal works perfectly without the dismiss function.

function pay_rise_menu() {
  $items = array();
  $items['pay_rise/%ctools_js'] = array(
    'page callback' => 'pay_rise_modal_email_share',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );

  return $items;
}

function pay_rise_modal_email_share($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Share by email'),
    );

    $output = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('pay_rise_modal_email_share_form');
  }
}

function pay_rise_modal_email_share_form($form, &$form_state) {
  $form = array();

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#attributes' => array(
      'placeholder' => 'Recipient email...',
    ),
  );

  $form['body'] = array(
    '#type' => 'textfield',
    '#title' => t('Message'),
    '#attributes' => array(
      'placeholder' => 'Message...',
    ),
  );

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

  return $form;
}

function pay_rise_modal_email_share_form_callback($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
  $form_state['ajax_commands'] = ctools_modal_command_dismiss('Thanks. Your message has been sent.');
}

The above is invoked once the following link is clicked:

l('email', 'pay_rise/nojs', array('attributes' => array('class' => 'ctools-use-modal icon-mail')))

You are doing it wrong, ctools modal works a little bit different. Better do it like this:

remove #ajax property from form submit button, let it work as usual:

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

define submit callback as usual:

function pay_rise_modal_email_share_form_submit($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
}

build modal callback:

function myCallback($js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => t('My modal title'),
    'ajax' => TRUE,
    'build_info' => array(
      'args' => array(),
    ),
  );

  $commands = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

  if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();
}

ctools itself handles ajax submission.. That's it.


Drupal Commerce: Alter 'Checkout' link in user menu How do you hook into the 'checkout' link in the user menu?

If there is an item in the basket, want to be able to add a class to the 'checkout' link.

Ideally from the theme template and not hacking the core.

Use this function in your custom module to return a bool for determining if there items in the basket/cart.

function items_on_cart(){
global $user;
$cart = commerce_cart_order_load($user->uid);
$line_items = count($cart->commerce_line_items) ? true : false;
return $line_items;
}

Then in your theme template do the following...

function YOURTHEME_menu_link(array $variables) {

    $element = $variables['element'];
    $sub_menu = '';
    $name_id = strtolower(strip_tags($element['#title']));

    // add class to checkout link if basket active
    if ($name_id == 'checkout') {
        if (YOURMODULE_items_on_cart()) {
          $element['#localized_options']['attributes']['class'][] = 'active';
        }
    }


What are some alternatives to admin_menu module for Drupal 7? Is there an alternative to the admin_menu module for drupal 7? I like the fact that it contains all the site links in the dropdowns, but it seems to conflict with some of the modules I have installed and I have run into issues with this module. I'm not sure why its such a heavy module. I guess it has to transverse the entire admin link structure and rebuild it which causes issues.

What are some good admin_menu alternatives that provide very similar functionality?

you may use admin module in combination with coffee


Fatal error: Unsupported operand types in includes\common.inc on line 3022 I have upgraded Drupal 6 to latest version 6.36 and PHP to 5.6. I am getting Fatal error saying;

  Unsupported operand type while accessing admin/content/node.

Which is actually nothing but simple addition of an array to variable;

$elements += array('#title' => NULL, '#description' => NULL);

Any help?

From official system requirements:

  PHP 5.3.x and higher may produce errors or unexpected behavior

Thus, sadly, what you are seeing is pretty much "expected" unexpected behaviour. Drop back to PHP 5.2.x (x ≥ 5) or upgrade to Drupal 7 or 8 for a full fix.

If you want to only fix this one, consider what AyeshK wrote in comment:

  The $elements variable probably contains an array element that the key does not start with a hash sign and the value is scalar.

There is a lot of things about array operators. Comments under PHP documentation shows that many things are far from obvious. Also, it changed a bit from version to version. Have you tested if $elements is an array in the first place? "Simply" add tests to make sure if operand is still valid, and provide a fallback if it isn't (recreate original behaviour) and you will be good to go.


hierarchical select not working in multistep form I have created multistep form with help of

link
 and created hierarchial select in step 1.It is working for step 1
but when i click next button and goes to step2, and return step1 it is not working.

Please Help.

I'm hoping this will add more info to the above reporting, even though we have different websites, to hopefully enable a fix.
I have a 2 level hierarchical select taxonomy.  Refer to it in my people pages.  Created as Term Reference - Hierarchical Select. When registering a user go to select this term, which is supposed to save term lineage, forces user to select term from deepest level.

Selecting from pulldown menu and clicking add, it appears that the item is being selected correctly and shows up below the pulldown menu, with the option to remove the selection.  I then save, it says everything was saved correctly.  I scroll down to my selection, and it says nothing has been selected.

    If I go to a view based off of this information, it indeed finds no data.
    I do get data if I change the field from hierarchical select to List Select or check boxes and have the view be rendered taxonomy term.  If I have to use List Select I will have to change the terms to include the first level since it doesn't show or save this way. This list is going to expand as new courses get added.  We can't do check boxes perpetually.  It will get crazy long.

I did find this error message log, but I don't know after which change this appeared.
Notice: Undefined index: value in views_handler_filter_term_node_tid->value_validate() (line 219 of /var/www/vehicledev_ccom_nh/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).

Severity
notice


Links in map markers are for default language pages, not localized I am building a multilingual website where a page will display all locations on a map. Each marker on a map has a link to the location's page. However, only links to English pages are displayed in markers. I have tried both Geofield Map and Leaflet to no avail.

How can I make urls in map markers to be language specific?

Given the fact that I couldn't find an answer on the web, I might have missed something simple. I am new to drupal and any help is appreciated.

Here is how I solved it:

When creating View I added Language into Fields and Language into Filter Criteria.

That simple!


What is the difference between l() and url()? Why does Drupal provide l() and url(), which seems to have the same purpose?

l() creates a clickable link (an HTML anchor tag), while url() creates just a url. If you scroll down in the l() page you'll see the following source code:

  if ($use_theme) {
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  }
  // The result of url() is a plain-text URL. Because we are using it here
  // in an HTML argument context, we need to encode it properly.
  return '' . ($options['html'] ? $text : check_plain($text)) . '';

theme_link() has a similar construction. So l() is using url() to construct the anchor.

So summarizing, the one is for clickable links, the other for plain (unclickable) url's.


Using views with a custom table/schema I need to set up some views that will pull some data from a custom table I created.  Some views will need to pull content the regular way and from my custom table (where I may query for a particular nid, etc.).

How do I do this, or where is a good place to research?

Your module needs to implement hook_views_data().

The example given in the hook documentation is for a table defined from the following SQL.

CREATE TABLE example_table (
  nid INT(11) NOT NULL,
  plain_text_field VARCHAR(32,
  numeric_field INT(11),
  boolean_field INT(1),
  timestamp_field INT(8),
  PRIMARY KEY(nid)
);

function mymodule_views_data() {
  $data['example_table']['table']['group'] = t('Example table');

  $data['example_table']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('Example table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  $data['example_table']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  $data['example_table']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'base field' => 'nid', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['example_table']['plain_text_field'] = array(
    'title' => t('Plain text field'),
    'help' => t('Just a plain text field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['example_table']['numeric_field'] = array(
    'title' => t('Numeric field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['boolean_field'] = array(
    'title' => t('Boolean field'),
    'help' => t('Just an on/off field.'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      'label' => t('Published'),
      'type' => 'yes-no',
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['timestamp_field'] = array(
    'title' => t('Timestamp field'),
    'help' => t('Just a timestamp field.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

  return $data;
}


Creating a responsive long form submit I have a rather long procedure on form submit (need to send several email to different addresses); when the use submits the form, the application seems to hang while it is doing a lot of work. Is there a Drupal way to show a "operation in progress" (better showing an indicator) without using Ajax and/or Ahah?

This module looks like similar to your query Hide Submit


HTML / Mail System / SMTP Not sending approval in html I have a current Drupal site that sends out all emails using the HTML template. Users requests, reset password, webform but does not send out approvals in HTML. Anyone have this issue or know a solution?

I believe drupal will only send text emails by default. You will need a module to help you implement HTML emails. I have used Mime Mail in the past to do this.

https://www.drupal.org/project/mimemail

From drupal.org:

  This is a Mime Mail component module (for use by other modules).

  It permits users to receive HTML email and can be used by other
  modules. The mail functionality accepts an HTML message body,
  mime-endcodes it and sends it.
  If the HTML has embedded graphics,
  these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's
  stylesheet files in a themeable HTML message format
  If the
  recipient's preference is available and they prefer plaintext, the
  HTML will be converted to plain text and sent as-is. Otherwise, the
  email will be sent in themeable HTML with a plaintext alternative.
  Allows you to theme messages with a specific mailkey. Converts CSS
  styles into inline style attributes.
  Provides simple system actions
  and Rules actions to send HTML email with embedded images and
  attachments.


How do I override superfish styles? Do I copy the css files I want to override to a theme I am using?

This depends the implementation. If the super-fish functionality is already included in a theme (Example: Danland, Danblog), there is most probably already a .css section in the style sheet or a separate .css file related to superfish. If you modify these files, they might be overwritten if you make an update. Thus you optimally make the modification in a local file (local.css in our Example) by copying and modifying the css code.

If you install superfish separately you find all the instructions in the readme.txt of the module:

"How to style

If you know CSS, even basics of it, designing won't be a big challenge.

Here are some tips and tricks:

A) Always use a DOM inspector utility (such as Firebug).

B) Set the "Menu delay" option to a very high number such as 99999999. This will give you enough time to work with sub-menus.

C) If you are not using the built-in styles, set the "Style" option to "None".

D) Utilise the "Simple" style as reference; add the newly-created CSS file either to your theme CSS or as a new CSS file under the styles directory in the Superfish library (probably "sites/all/libraries/superfish/style"); putting it in the styles folder will automatically add it to the styles list in the block configuration."

More information can be found in the Superfish documentation at http://drupal.org/node/1125896"

i.p. 4. within the Installation section

"Upgrade users need to delete the module folder (sites/all/modules/superfish) before uploading the new one. Also, if having any modified CSS files, just move them from sites/all/modules/superfish/css/extra to sites/all/libraries/superfish/style"


Node hits getting cached for anonymous user We are using Drupal 8.8.5. For every page we are trying to provide a counter which increments whenever user hits that node. These are nodes are available to anonymous users. So whenever an anonymous user hits the node, the view counter on that node should be updated to show the no of total hits . So lets say Tom and Hary are anonymous users. Tom hits node1. On top of Node1 it says "View 1" times. Now when Hary hits Node1 it should sat "View 2" times. Again if Tom hits node1 it should day "View 3" times.
I checked How can I show node Hits (statistics)? and made the necessary code changes in basic.theme and node.html.twig. Still, it shows Viewed O times.
This is the code I have in the basic.theme file.
function basic_preprocess_node(&$variables) {
  $variables['node_view_count'] = 0;
  if (!empty($variables['node'])) {
    // Get the number of times the current node has been viewed.
    /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
    $statistics = \Drupal::service('statistics.storage.node')
      ->fetchView($variables['node']->id());
    if ($statistics instanceof StatisticsViewsResult) {
      $variables['node_view_count'] = $statistics->getTotalCount();
    }
  }
}

This is the code I added in the node.html.twig file.
Viewed {{ node_view_count }} times

I believe there might be a caching issue once it starts working. For each hit, the values should be updated.
On a side note, when I am using the Visitors module, the report is showing an updated page count even for anonymous users. I had to install the Advanced Page Expiration module, though.
How do I increment the node hit for anonymous user visits in each page and show it updated?

Ok i have resolved this using a database query and a custom block. Pre-req: Installing visitors module.
Then having this query in the custom clock
public function build() {
  $node = \Drupal::request()->attributes->get('node');
  $uidValue = $node->getOwnerId();
  $urlValue = $node->toUrl()->toString();
  $database = \Drupal::database();
  **$query = $database->query("SELECT COUNT(visitors_path) AS visitors_path FROM
(visitors) WHERE visitors_path='$urlValue' ");**
  $result = $query->fetchAll();
  $nodecounthit = $result{0}->visitors_path;
  echo "Viewed ".$nodecounthit." times";
//$nodeCount=MyBlock::test();
      }

this function ensured results were not cached.
 public function getCacheMaxAge()
  {
    return 0;
  }


Cannot see a Custom Block in Drupal 7 I'm trying to create some blocks with custom content in Drupal 7, but I cannot see them anywhere (Structure>Blocks)

I'm using Drupal 7
I have successfully activated the module
Cache is not activated

Here is the code:

bcndevcon.info

; $Id: bcndevcon.info,v 1.0.0.0 2011/02/09 10:11:15 BcnDevCon Exp $
name = "Custom BcnDevCon Modules"
description = "Custom BcnDevCon Modules In Code"
core = "7.x"
package = "Custom BcnDevCon Modules"

bcndevcon.module

<?php

function bcndevcon_blocks_info() {
    $blocks['my_custom_block'] = array(
        'info' => t('Custom Block Name'),
    );

    $blocks['my_custom_block2'] = array(
        'info' => t('Custom Block Name 2'),
    );

    return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function bcndevcon_blocks_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my_custom_block':
      $block['subject'] = t('Custom Block Name');
      $block['content'] = bcndevcon_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function bcndevcon_contents() {
  return '

      Hello World, this is a example custom Block

  ';
}

?>

Any suggestions?

Not sure if this is a typo just in the question... but you have your hooks defined as hook_blocks_* with an extra s at the end of the word block which shouldn't be there.


How can I remove the tab "Subusers" in the profile? I have installed the module subusers and appears a tab named "Subusers" in the profile.  How can I remove this tab?

I tested this code in template.tpl.php and I didn't work:

function mytheme_preprocess_page(&$vars) {

$unwanted_tabs = array('user/%/subuser');
  foreach ($variables['tabs'] as $group_key => $tab_group) {
    if (is_array($tab_group)) {
      foreach ($tab_group as $key => $tab) {
        if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $unwanted_tabs)){
          unset($variables['tabs'][$group_key][$key]);
        }
      }
    }
  }
}

I tried with this code:

function mymodule_menu_alter(&$items) {
    unset($items['user/%/subuser']);
}

Thanks.

The tabtamer module provides an easy way to remove tabs, both those generated by core as well as those generated by modules.


Better exposed filters override -any- only working on one filter at a time I have a view on a Drupal 7 site which brings in all content from 3 content types, which all have 3 different entity reference fields attached to them in order to relate them to specific areas of the site. On the view, I need to beable to filter by the 3 content types, which i have done by creating a filter on type with the 3 options. For the 3 enitity reference fields I also need to be able to filter on all the references but also have an "Any" option to enable it to show all. Due to the design of the website I need the "Any" option to have a friendly title rather than any, which I have implementing using Better Exposed Filters. For some reason the Override any feature of BEF will only override 1 field. And completely ignores the other 2.

It is working on the final filter. If i remove this filter it will work on another one, but never more than one at a time. Is there a setting I'm missing or is this a bug?

I tried this kind of configuration with more then one exposed filter, yes its only overriding label for last exposed filter. May be a bug, Why not simply modify -Any- option label with hook_form_BASE_FORM_ID_alter()

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'YOUR_VIEWS_MACHINE_NAME') {
    $form['FIRST_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    $form['SECOND_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    // and so on.
  }
}


Rules fatal error during update: Call to undefined method stdClass::events() What I have tried:

Clear Cache.
Disabled module and enabled it.
Try with registry_rebuild, module_missing_message_fixer, variablecheck modules.

Still getting the below error when I try to run update.php.

Notice: unserialize(): Error at offset 668 of 1298 bytes in \sites\all\modules\entity\includes\entity.controller.inc on line 261
Warning: Creating default object from empty value in \sites\all\modules\rules\includes\rules.core.inc on line 57
Fatal error: Call to undefined method stdClass::events() in \sites\all\modules\rules\includes\rules.plugins.inc on line 767

Debugging is the art of eliminating all possible causes for your problem. Below are some attempts to help you to find the real cause of your issue ...

1. Enable Rules debugging

Something that might help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules debugging, refer to the answer to "How can I display the value of a variable inside a condition?".

2. Disable all active rules and re-enable them one by one

Instead of "disable" of the Rules module (which will possible resolve your issue until you enable it again), try to leave it enabled. But start with a disable of all Active (enabled) rules.

If it is some custom rule that is causing your problem, if none of your rules are active, the problem should have disappeared also after you disabled all active rules. If that's the case, re-enable your rules again, one by one, do some test to ensure the rule you enabled did execute. Keep doing this until you hit the custom rule that makes the issue come back again. Then disable that rule again, and check if there are other remaining rules that also make the problem show up again. In the end, try to adapt the rule(s) that seem to cause the issue so that the problem no longer shows up. If you cannot solve it, do not re-enable that rule anymore and think of some alternative.

3. Special watchdog entries

Make sure to also check for any unexpected watchdog entries, it may help to get a clue about what is happening


Display different content on node pages depending on user role I have a list of items visible for all anonymous user and authenticated user. Then when the user click through, if the user is anonymous, I want to tell them, "sorry must be authenticated". But if they are already authenticated I want to show them the node.

I am using:

if($logged_in) {
   //display node
}

In my node--mycontenttype.tpl.php. How do I make this work?

Showing different content on the same page to user depending on role could be accomplished with the Panels module like so:

Install the Panels module and its dependencies.
Go to admin » structure » panels.
Enable and edit the page "node_view" template.
Click "add new variant".
Click "continue" on each screen until there is a button with "Add variant." Click "Add variant".
Under panel » content, click the gear in the upper left to add a panel of content for the logged in user to see. Save.
Click the gear in the upper right of the new content to get a menu. Select visibility rules » add new rule. Select role and set it how you want. Save.
If you want to show something different to anonymous users, repeat step 6 and 7 to add content and make it visible only to anonymous users.
Don't forget to save.


Put a wrapper div around every second row in drupal view Hi there I am trying to use a views template override to put a wrapper div around every group of two rows. If the last group only has 1 row ( say if there were 5 rows total ) I want to end the wrapper div.

I found some code for this but it's not working I am getting zero output from this I can see my comment tag but that it.

<?php
$group_nr = 1;                  // first group number
$last_row = count($rows) -1;    // last row
$wrapper  = 2;                  // put a wrapper around every 2 rows
?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id % $wrapper == 0) {print '
'; $i = 0; $group_nr++; } ?>
<?php print $row; ?>
<?php $i++; if ($i == $wrapper || $id == $last_row) print '
'; ?>
<?php endforeach; ?>

Any idea what I am doing wrong

My template is called views-view--homepage-awards--block-2.tpl.php

I want my output to look like this

row1

row2

row3

row4

row5

Any help would be greatly appreciated.

This should accomplish it:

<?php
  $last=count($rows) - 1;
?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!($id & 1)): // if this an even row id, open the <div> ?>
    <div class="row">
  <?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  <?php if ($id==$last || ($id & 1)): // if this the last or an odd row id, close the <div> ?>
    </div>
  <?php endif; ?>
<?php endforeach; ?>

It'll wrap each group of two rows with a div with a class of row and make sure if it's an odd number that the final div is closed.

Now, if you want to remove all the classes from those inner rows that Views inserts, then you just need to clean them up or out of that obvious if in the middle.

CAVEAT:  If you have done anything with Views pre_render()ing or other similar hooks that have deleted any of the rows out of the results and not reset the ids to be consecutive, this logic will most probably fail.