How to add a user rank in their profile? I want to have rank for every user. A simple -> amin rank is 18 with 300 points.

Any suggestions?

Use a combination of the Rules, Userpoints and User badges module, as further detailed below ...

Add a new badge

Have a look at this Rules example (in Rules export format):

{ "rules_grant_a_new_badge" : {
    "LABEL" : "Grant a new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "user_badges", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "7" } },
            "DO" : [
              { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
            ]
          }
        ]
      }
    ]
  }
}

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 7, it will grant the user badge.

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?"). However, by using the Conditional Rules module, you can consolidate the logic for various user badges in a single rule, e.g bronze for 7 points, silver for 77 points, gold for 777 points.

The clue to make this rule work is the very first Rules Action "Load user points of a user". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

Remove a new badge

If you want "a user's old badge to be replaced by a new one", then you should also add a 2nd Rules Action to the rule shown above. The action to be used is remove_badge_by_name (instead of add_badge_by_name).

Only grant a new badge once

To avoid "displaying a message each time when user getting more than 7 user points" (as in your question), just add a Rules Condition like "NOT User has badge". This is one of the Rules Conditions provided by the User badges module.

Display the badge

To actually "display the badge with the username at the top", you could use what's written in the Community Documentation about User Badges, i.e:

  To display user badges in your theme use:

<?php
  if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
  }
?>

  Note: $uid means 'a user id' here, not the literal use of $uid. Most people will use the uid of the node ($node->uid) or comment ($comment->uid) author.

  In Drupal (and theming), $node is a PHP object that represents the node, and $comment represents the comment. They are not always both available in every template file, so check the comments at the top of the file to see what is available. You may have access to other uids (user ids), and in these cases you can replace $uid with that value.


Log in problem in maintenance mode I have a maintenance site problem. I can't go to the login page.

I tested in my localhost in maintenance and I could log in on /user.

I copied file system and database online but here I can't access the login page so I can not see the site to make changes and upload data.

This is the site:
redlily.it/

I have displayed the $content variable in a div.content with display:none style. But in '?q=user' and in '/user' i have no loggin form.

Why am I not seeing the log in form under '?q=user' and '/user'?

You can run below queries on database to get your site online:

UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';


Trying to configure parent link and child links in menu I'm trying to create a submenu in the same way shown in the screenshot
module.links.menu.yml:
custom_forms_entity_export_csv.export:
  title: 'Export'
  description: 'Export Menu'
  route_name: custom_forms_entity_export_csv.export
  parent: commerce.admin_commerce

custom_forms_entity_export_csv.export_sales_form:
  title: 'Export Sales'
  description: 'Export Sales to a CSV file.'
  route_name: custom_forms_entity_export_csv.export_sales_form
  parent: commerce.admin_commerce

custom_forms_entity_export_csv.export_menu_form:
  title: 'Export Menu'
  description: 'Export Menu to a CSV file.'
  route_name: custom_forms_entity_export_csv.export_menu_form
  parent: custom_forms_entity_export_csv.export

module.routing.yml
custom_forms_entity_export_csv.export:
  path: '/admin/commerce/export'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Commerce'
  requirements:
    _permission: 'access commerce administration pages'

custom_forms_entity_export_csv.export_sales_form:
  path: '/admin/commerce/export/sales'
  defaults:
    _title: 'Sales'
    _form: \Drupal\custom_forms_entity_export_csv\Form\SalesExportCsvForm
  requirements:
    _permission: 'use custom export csv'

custom_forms_entity_export_csv.export_menu_form:
  path: '/admin/commerce/export/menu'
  defaults:
    _title: 'Menu'
    _form: \Drupal\custom_forms_entity_export_csv\Form\MenuExportCsvForm
  requirements:
    _permission: 'use custom export csv'

module.links.task.yml
custom_forms_entity_export_csv.export_sales_form:
  title: 'Download Sales'
  base_route: custom_forms_entity_export_csv.export
  route_name: custom_forms_entity_export_csv.export_sales_form
  weight: 100

custom_forms_entity_export_csv.export_menu_form:
  title: 'Download Menu'
  base_route: custom_forms_entity_export_csv.export
  route_name: custom_forms_entity_export_csv.export_menu_form
  weight: 100

But all I end up with is all three links, Export, Export Sales, and Export Menu as children under the same Commerce menu, like shown here:

What I want is for Export to have an arrow on the right to expand a submenu containing Export Sales and Export Menu.

Your 2nd menu link needs the parent property referencing your first custom_forms_entity_export_csv.export route :
custom_forms_entity_export_csv.export_sales_form:
  title: 'Export Sales'
  description: 'Export Sales to a CSV file.'
  route_name: custom_forms_entity_export_csv.export_sales_form
  parent: custom_forms_entity_export_csv.export


DRUPAL_ROOT undefined on module installation I try to install the live_agent module. When I go to enable the module, I get the following errors:

  Notice: Use of undefined constant DRUPAL_ROOT - assumed 'DRUPAL_ROOT' in /sites/all/modules/live_agent/live_agent.module on line 319

  Warning: require_once(DRUPAL_ROOT/includes/errors.inc) [function.require-once]: failed to open stream: No such file or directory in /sites/all/modules/live_agent/live_agent.module on line 319

  Fatal error: require_once() [function.require]: Failed opening required 'DRUPAL_ROOT/includes/errors.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /sites/all/modules/live_agent/live_agent.module on line 319

The code causing the error is the following one.

 /* 318 */ function live_agent_buttons_form(&$form_state) {
 /* 319 */   global $base_url;
 /* 320 */
 /* 321 */   $settings = new liveagent_Settings();
 /* 322 */   $la_buttons_grid = $settings->getButtonsGridRecordset();
 /* 323 */   $recordset = $la_buttons_grid->toArray();
 /* 324 */
             // ...
 /* 373 */ }

Any help on debugging this would be greatly appreciated.

The error about the undefined constant DRUPAL_ROOT could be caused from the index.php file that is corrupted, or that is returned corrupted from APC, or similar extension. DRUPAL_ROOT is always defined when Drupal bootstraps.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

As for why the error message is reported for that module when a function that doesn't contain any reference to the constant is executed, I think that is caused from the autoload function Drupal registers, drupal_autoload_class(), which is trying to load the file containing the class.


How can I filter users within a user-configurable range in Views? For example, consider a dating website.  Each user has an Age stored in their profile.  They also have a Max age and Min age, which are the maximum and minimum ages of people they hope to receive interest from (in other words, users with ages outside the range Min age - Max age should not be allowed to contact that user).

How can I build a page in Views that filters the results for the current user to show other users that both meet the current user's age range and for which the current user meets their age ranges?

In other words, I need to somehow filter the results like this:

Only show users that have ages within the range of the current user's Max age and Min age (example: current user is 20 and wants to see users from 18-25; filter to show users from 18-25)
Only show users for which the current user has an age that falls within the range of their Max age and Min age (example: current user is 20 and wants to see users from 18-25; filter to show users who want to receive messages from someone age 20)

Is this something I can somehow do with contextual filters, or do I need to write my own custom filter?

Install sandbox project Views arguments in filters
Add four contextual filters to your user view:

User:Uid, hide view when filter not available, Exclude (you will send in the user's own uid and exclude him from the result as you do not want him to be matched against himself)

Global:Null, hide view when filter not available, and give it an administrative title of 'current age'. (You will send it the current user's age as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'min age'. (You will send it the current user's min age preference as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'max age'. (You will send it the current user's max age preference as a param).

Then add normal filters as follows:

That should take care of the view, and you now just have to construct a link to add the parameters manually, or override a view hook to do so. Possible candidate would be hook_views_pre_view where you have direct access to args param, but on other hooks it should be available on the $view object.
Something like this code will work, and you can just add your own defensive programming and substitute where appropriate.
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "compatible" &&  $display_id == "page" && user_is_logged_in() && count($args) != 4) {
    global $user;
    $account  = user_load($user->uid);
    $age = field_get_items("user", $account, "field_age");
    $min_age = field_get_items("user", $account, "field_min_age");
    $max_age = field_get_items("user", $account, "field_max_age");
    $args = array(
      $account->uid,
      $age[0]['value'],
      $min_age[0]['value'],
      $max_age[0]['value']
    );
  }
}


How to programmatically embed iframe in a page I am trying to render a page with iframe embedded in it. My code is as follow

public function giveHugs() {
  return [
    '#type' => 'inline_template',
    '#template' => '<iframe frameborder="0" style="border: none;" width="400" height="400" src="{{ url }}"></iframe>',
    '#context' => [
      'url' => 'yahoo.com'
    ]
  ];
}

Some how its not rendering the iframe , rather it is embedding the drupal site it self. How can i render iframe in a page?

Unless you provide an absolute URL, Drupal will treat it as relative. So yahoo.com becomes https://example.com/yahoo.com, which explains why you're seeing your own site embedded.

To solve, just use an absolute URL:

'#context' => [
  'url' => 'https://yahoo.com'
]


Accessing all taxonomy terms from one specific vocabulary through url I want do display all my terms from one vocabulary over drupals pathauto url scheme.
So f.e. I have example.com/taxonomy/term/314 or after pathauto: example.com/screwdriver/slot or example.com/screwdriver/torx. This works good.

But if I visit example.com/screwdriver, this page doesn't exist.

Actually I'm kind of puzzled, that this is not working out of the box. Do I really have to implement a custom module for this?

Is there a functionality made for that particular page? Is that a term namde, a node or a view? Any kind of entity? Because if it is not, nothing will show up, obviously. Create a view page showing all taxonomy terms within that vocabulary. Taxonomy pages are for taxonomy terms only, not for taxonomy vocabulary based on some url scheme.


Can I change the location of the cached Twig templates? By default, the Twig template cache appears to go into /files/php/twig.

I was wondering if it's possible to change this location? I use a shared file mount which is shared between multiple developers and my concern is that the Twig cache will be in competition with another developer.

Alternatively we can disable caching but this is not always appropriate.

Yes you can, put this in settings.php or any file loaded by it like settings.local.php:

  $settings['php_storage']['twig']['directory'] = '/path/to/tmp/folder';
  $settings['php_storage']['twig']['secret'] = $settings['hash_salt'];

Note that the directoy must exist already.


How do I preprocess_html() a panelized page? My intentions is to take a panelized page and use fields provided in that page to create class names on the body element.

When I preprocess the page, I don't get the original node information and can't pull the information I need.

My panelized page has 1 pane that has the node-> content pane in there.

If I could just get the NID of the current page, then it would be okay. But that doesn't even show up in the variables in the theme_preprocess_html() when a page has been panelized.

Solution was to use menu_get_object(). Here is a nice article outline usages of it as well.

$node = menu_get_object('node');

Thanks you David for the answer.


Using CCK or Taxonomy with Custom Fields in Drupal 7 I am building a site that will contain data about athletes. I'm trying to decided wether to represent the athletes as CCK or Taxonomy Terms with custom fields. Athletes will contain information such as name, DOB and image, each athlete will have a page.

News articles, sports, venues, events, and teams will be other content within the site, these could be tagged with the athlete terms if we use the taxonomy solution. The alternative would be to use node reference if athlete as a custom content type.

The Taxonomy route seems more flexible and seems like a good route to take according to this article http://www.juliakm.com/how-decide-between-using-taxonomy-terms-and-cck-field-classify-content-drupal-site I just wanted to check with people in the community if there are any drawbacks to this approach or advantages of using CCK instead?

In Drupal 7 CCK and Taxonomy Terms with Fields are in the core. The two seem incredibly similar, I was wondering what is the reasoning behind having both?

Thanks,
Pete

My idea: make CCK fields of all personal data you want to collect about the athletes. (length, weight, ...) These are different for every athlete.

When you have items that are similar, you should use taxonomy. (Type: Soccer player, Golfer, ...)

Using both taxonomy and CCK makes a complex but great system!

*An example:

I'm making a "travel" website about Spain. A website with many pages.

On my website about Spain I have a regio related page. This page shows content about cities, golf tracks, parks, ... It has an image on top (CCK field), a "tag" (taxonomy term to link pages - show list with simmilar content), a "regio tag" (also taxonomy list of all regio's) and two text fields: positive / negative (CCK fields to enter good and bad things about this city / track / park and so on.

The image and positive/negative fields are for all pages different. The "regio tag" can be the same for some pages (same with the tag).

This way you easily make a view with similar pages people can visit!*


Clickable image contents with checkbox I have created a site consisting of image galleries, gallery consists of image and a description for it. I want that the user should be able to select multiple image contents as checkbox so that he can add them to cart. After selecting the images I want to compare the details of the selected images.
How can I achieve this?

Try the  Commerce product comparison module

  This module allows you to compare products. This is a familiar feature on commerce website.

There is another module called Dynamic properties

  Provides a dynamic properties field that allows to store product properties or similarly structured information. A property consists of an attribute, the name of the property and a value. It belongs to a category.


Twig template for two different instances of the system branding block On the block layout page, I added the "Site Branding" block twice, once for normal use (all nodes except content type landing page) and once for landing page use (all nodes of content type landing page).

I themed the block using the twig template block--system-branding-block.html.twig, but this modifies both blocks.

Is there a way to get more specific and create a twig template for each block, or should I re-create the landing page block some other way so that I can use a different template?

EDIT: My goal is to actually change the HTML of the block, so I can't use a pure CSS approach.

There's a few things you can do. Here's three.

Consider using a pure CSS approach. If you look at the body element for your page there may well be different classes you can use to make different selectors for styling the block. Modern CSS, particularly with the availability of :before and :after pseudo selectors, is incredibly powerful and you very often don't need custom HTML to adjust styling for different cases.
You can also implement hook_theme_suggestions_alter in your theme (in the file mytheme.theme) to supply alternative template suggestions based on the current path, for example.

Following this example, your code might look like:

function THEME_NAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);
  $path_alias = str_replace('-', '_', $path_alias);
  $id = $variables['id'];

  $suggestions[] = 'block__path_alias__'.$path_alias;
  $suggestions[] = 'block__' . $id . '__path_alias__'.$path_alias;
}

Another option would be to create a second variant of the site branding block then use the option in Drupal's block system which lets you turn blocks on or off by content type.


Imagefield submit breaks when I move it in the DOM I've got a fairly straightforward "user profile" content type.  The design of the edit page for this content type has the Imagefield file uploader/thumbnail preview in the right sidebar rather than in the main content area.

I've tried several different methods to get this to work out, and none of them have yet worked.  The one I'd like to use is to grab the form-field wrapper with jQuery, and then append it to the right-sidebar region.  Like this -

$('#profile-pic-ahah-wrapper').appendTo('.region-sidebar-right .section');

For some reason, this renders the submit button on that form field totally unresponsive.  It's still there, it still shows up when I tinker with it in Firebug, but it doesn't respond to clicks or hovers at all.  I'm stumped for now, except that I guess this has something to do with it being AHAH?

Thanks in advance.

I think you need a clone() in there to move the event handlers along with it.  Check out http://api.jquery.com/clone/ and see if that helps.


Filter excludes date in end date field I have a view in Drupal 8 as below.
[The date column in below list, is not an event. its order item. so date showing is order complete date only]

When I filter with start and end date, the data shown excludes the end date. It just shows the in-between records, but it does not include the end date.
I am unable to figure it out from the code.

Any help?

Time also matters (date fields also has time, usually it's set to 0 am). Check in your database what time is associated with the date. If the time is i.e. 11 am or even 00:00:01 am (H.m.s), it will be excluded. It also can be changed the base date by your settings. (i.e. when you create a new date it can be created by default to 0 o'clock and to 12 o'clock too. Or even it can be the node creation time too.

Please note, when you compare date/time most probably the UNIX timestamp will be compared (in views at least)! Reason: drupal save UNIX timestamps into the database, when you create a view you will see the relation is in the query, so the inputed date will be converted to timestamp and a default time. And this default time can be mess up the things.


Check, anywhere during a session, if a logged in user has previously logged in There are a number of properties on the global $user object
https://api.drupal.org/api/drupal/developer%21globals.php/global/user/7

But I can't figure out how to see if a logged in user has ever previously logged in, or if this is his/her first session. When logged in, the $user->access, $user->login, $user->timestamp values all seem to point of the current session.

I can set a cookie and check for that cookie myself. But I suspect I'm just missing something Drupal already has ?

A cookie would work. Another way is to add a field to the user entity that you can check that field first to see if it's empty, and then modify it with a Rule, triggered by the log in action


Permissions not saving I'm working on a development site. Up until recently I haven't had any trouble with saving permissions, everything was working fine, until I added the different user roles for the site. After I added them all, I went back, and started to assign the correct permissions to the correct users types. I hit save, and... nothing.

No error message, no message at all. And the save didn't take effect. I'm starting my head over why it suddenly just isn't working when it was working before. Is there a limit the the amount of users types that Drupal allows?

This sounds a lot like a php runtime issue. PHP has a configuration called max_input_vars, which you can use to set a limit on the number of input vars php will accept. This will affect the number of $_POST and $_GET variables that can be fed into php. The default is 1000, and I suspect, if you have lots and lots of user type, you're hitting up against this ceiling.


How to load jQuery assets before blocks and regions I need a jQuery script to load immediately before a certain block shows on my Drupal 8 front page. I'm trying to use the following but I get 'TypeError $ is not a function' in code inspector. Here's my script:

$(document).ready(function() {
  $("#slideshow").zAccordion({
        ...code...
  });
});

The problem is the first line. In Drupal 8 what is the preferred way to write this script to accomplish what I want?

You have to wrap the javascript to avoid namespace conflicts.

(function ($) {
  $(document).ready(function() {
    $("#slideshow").zAccordion({
        ...code...
    });
  });
})(jQuery);


Rules Scheduler Component parameter is empty I created a rule for scheduling a action component after 48h. The rule gets triggered correctly and the task shows up at the "Workflow" tab in rules.

The problem is that the scheduled component gets an empty parameter and so can execute the actions. Drupal log shows an "The variable or parameter node is empty." warning.

Here is the rule:

{ "rules_set_submission_status_to_archived" : {
    "LABEL" : "SUBMISSION: Set submission status to archived",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "archived", "submission" ],
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--submission" : { "bundle" : "submission" } },
    "IF" : [ { "entity_is_of_type" : { "entity" : [ "node" ], "type" : "node" } } ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_times_up_for_submission",
          "date" : "+2 days",
          "identifier" : "Archive submission [node:nid] \u0022[node:title]\u0022 after 48h.",
          "param_node" : [ "node" ]
        }
      }
    ]
  }
}

Here is the scheduled component:

{ "rules_times_up_for_submission" : {
    "LABEL" : "Times up for submission, archive and pay back credits",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "archived", "submission" ],
    "REQUIRES" : [ "rules", "commerce_credits", "php" ],
    "USES VARIABLES" : { "node_to_archive" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-to-archive" ],
          "type" : { "value" : { "submission" : "submission" } }
        }
      },
      { "entity_has_field" : { "entity" : [ "node-to-archive" ], "field" : "field_status" } },
      { "data_is" : { "data" : [ "node-to-archive:field-status" ], "value" : "submitted" } },
      { "entity_has_field" : { "entity" : [ "node-to-archive" ], "field" : "field_use_free_credits" } },
      { "data_is" : { "data" : [ "node-to-archive:field-use-free-credits" ], "value" : "0" } }
    ],
    "DO" : [
      { "commerce_credits_add" : {
          "entity" : [ "node-to-archive:author" ],
          "credit_type" : "credit",
          "number" : [ "node-to-archive:field-submission-price" ]
        }
      },
      { "data_set" : { "data" : [ "node-to-archive:field-status" ], "value" : "archived" } },
      { "entity_save" : { "data" : [ "node-to-archive" ], "immediate" : "1" } },
      { "php_eval" : { "code" : "watchdog(\u0027schedule\u0027, $node_to_archive);" } }
    ]
  }
}

So basically, the node is not passed to the scheduler component. Is there something broken in my system or do I miss something?

Some tips to help you find out what's happening / going wrong (based on revision 2 of your question):

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).
It could be a permission issue, i.e. think about which "user" (authority) the scheduled component executes with.

Some more tips to help you find out what's happening / going wrong (based on revision 3 of your question), and your extra comment which includes "... shows this error: "Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2227 of database.inc)." The log has a "page not found" warning from /admin/config/workflow/rules/components/manage/autocomplete/node_to_archive/form-xxx.../ ...":

Try to temporary remove that very last rules action (to execute that PHP code), and see what happens.
If the error still doesn't go away, it seems the time is right to start Rules debugging, as explained in my answer to "Where is the Rules Evaluation Log?".

Last but not least ...

About this part of your question:

  The problem is that the scheduled component gets an empty parameter and so can execute the actions. Drupal log shows an "The variable or parameter node is empty." warning.

Please have a look at what's described in my answer to "Why can my view not access the data of a new node when using Rules event After saving new content?". It explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...). I wouldn't be surprised that this is also what explains your problem. Here is why I think so:

Your (main) rule uses the event "after saving something".
Assume that the rules action (to schedule your component) actually happens (also) "before saving something"; In that scenario the part of your message that says "The variable or parameter node is empty." makes sense ... (get it?).

So it would be interesting to see what would happen if (even only to test), you'd replace the (single) Rules Action (to schedule your Rules Component) by the execution of an additional Rules Component (let's call it "Test_tip_from_Pierre") which is scheduled to execute after X secs or mins, and with a single Rules Action (equal to your Rules Action you now have in your main rule). Using that approach, for sure the node will have been saved before you actually schedule your original Rules Component. And that is what might resolve (eliminate / prevent) your warning like "The variable or parameter node is empty."


Can administration menu be configured with a stripped down menu that only gives the user access to post content? How would I go about setting up stripped down administration menu so that non-privileged users can see a menu allowing them to post content that they have permissions for?  Right now the user sees no menus in their admin menu.

From the role permission settings you can do so allowing him for access administration menu and then checking required permission sets (e.g. access administration pages)


SQL + Drupal: how to filter correctly using SQL within a Drupal Database? I have been using Drupal for quite sometime, but now I have come to a crossroad: using MySQL to extract data from my site's database via phpMyAdmin.

Everything was going great with the basics (I was going through w3school's tutorials), I learned a lot about SELECT, operators, booleans, etc., but then I came to a stop while trying to filter my results concerning dates, with UNIX TIMESTAMP.

I need to be able to filter results between two dates and, no matter what I do or try, my results are wrong.

I have been trying to wrap my head around this concept (which I believe I already have) but I haven't been able to filter correctly using timestamps.

I went back to square 1 to review syntax, so I want to think that's not my problem, but I definitely need help.

Has anyone found something in the web that might cover this issue? Everytime I look for UNIX TIMESTAMP articles, they are quite superficial (I guess this is not a very hard issue after all).

Thanks in advance.

I'll make an attempt but I haven't quite identified the problem yet. Does your result set deviate from the expected? Is there an error? Answers to those could make it easier to assist.

A Unix timestamp is simply the number of seconds since Jan 1st, 1970.

The query

SELECT type FROM node
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

works for me; it returns all nodes of type 'page' created in month 7 of year 2011. These queries also work:

SELECT * FROM node -- all pages from July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') = '2011-07';

SELECT * FROM node -- all pages from May, June, July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') BETWEEN '2011-05' AND '2011-07';

SELECT * FROM node -- all pages from weeks 33, 34, 35, 36, starting on Mondays
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%u') BETWEEN 33 AND 36;

SELECT * FROM node -- all pages created between 8 morning and 4 afternoon
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%H') BETWEEN 8 AND 16;

However, you can also use PHP to generate a Unix timestamp from a date, then simply compare that with the stored values (following is untested):

$t1 = mktime(0, 0, 0, 5, 1, 2011);
$t2 = mktime(23, 59, 59, 7, 31, 2011);
//$t2 = mktime(0, 0, -1, 8, 1, 2011); // 1 second before midnight Jul 31/Aug 1st.
SELECT * FROM node -- all pages from May, June, and July
    WHERE TYPE = 'page'
    AND created BETWEEN $t1 AND $t2;

I would suggest you take an exact query you're trying to use and execute it directly against the database in order to determine if the problem is with the query or something else. If it is the query, play around in there until you get the desired result or ask for help.

NB: Drupal expects tables to be enclosed in braces, in case it needs to handle table prefixes. This means the first query (in Drupal) should look like this:

SELECT type FROM {node}
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

If you don't use table prefixes it's not necessary (that is, it should still work) but it's good practice to always include them regardless.


Drupal.settings.basePath is not giving the base_url in js When I alerted the Drupal.settings.basePath it's just giving me a /. I have a full $base_url in settings.php. which I'm expecting to see instead of /.

How can I get the correct value of the base URL in javascript?

You need to pass it manually like this.

global $base_url;
drupal_add_js(array('baseUrl' => $base_url), 'setting');

Then call like this Drupal.settings.baseUrl.

Drupal.settings.basePath value is coming from base_path() api. See this documentation about base_path.


Automatically choose specific option from select field attribute based on inbound link / previous page? I have three pages that each describe a product that we sell. Each of those pages has a button/link that says "buy now". Those links all take you to a single Ubercart product page with a select list attribute where they can select the name of any of the three products that I mentioned previously and add that product to their cart.

I'd like to have the name of the product from which they came automatically selected in that attribute field. Is there a way to do this via some kind of URL string, or another method?

Thanks!

Use hook_form_alter or hook_form_FORM_ID_alter, check your stuff (get parameter maybe), then apply the selected item though the form api


How to link to dblog filtered by type? In my custom D7 module, I'd like to link to admin/reports/dblog/, however, I'd like to have it filtered by a certain type so when you navigate to that link, the type is already filtered for you.

Is this possible?

It is possible, but the values used to filter that list are put in $_SESSION['dblog_overview_filter']. Linking to that page and making it shows the messages filtered by type is only possible if you set that session variable with the right value. Looking at the code of dblog_filters(), I get that the following line would cause that list to show the logs about cron tasks.

$_SESSION['dblog_overview_filter']['type'] = array('cron');

References

dblog_overview()
dblog_filter_form()
dblog_filters()


How to add domain access to custom entity? Trying to do this for a custom entity, but it seems like Domain Access doesn't have its own entity to reference, and I'm not quite sure what method to use.  I'm still looking into it, but since I couldn't find a question on it yet, I thought I'd post this ahead of time in case anyone else has done this.

You can override the access handler.

You have to add the handler path in the entity anotation and create an access class extending EntityAccessControlHandler. Inside you can manage the entity access using the rules that you want.

You can copy for learning the Node access Handler:
https://api.drupal.org/api/drupal/core%21modules%21node%21src%21NodeAccessControlHandler.php/class/NodeAccessControlHandler/8.2.x


Why doesn't $row->path output its value? I made a view with a relationship, showing:

Title of the node
Title of the referenced node
Path of the referenced node

These values display as expected, but if I create a PHP field with the following code in the output, it only displays titles.

echo 'Title: '. $row->title.'
';
echo 'Title 1: '. $row->title_1.'
';
echo 'Path: '. $row->path.'
';

Why?

It is a known issue with views_php.  You should be able to access the field information through the $data variable though. If you have Devel installed just run dpm($data) in place of your code above and see how to access the field information.

For what it is worth, it is generally considered bad practice to store php code in the database. I would suggest taking a look and seeing if there is any way you can accomplish what you are after with a template file override or some other means.  If the only thing you are trying to accomplish is concatenation of those 3 fields with labels, you can do that with a regular views 'custom text' field and the tokens views provides.


Need To Update One Entity Through Another I've been trying every angle I can, but I keep running into Revision ID errors when I try to update a referenced or related entity of another entity. I believe this might be on the right track? I'm not sure why these are occurring. I just need a simple field to be updated when the related entity is updated.

It also throws this error:
DatabaseTransactionNoActiveException

Is there any documentation on how to update one entity when another is updated? I just need to be pointed to the right track on this one.

Okay figured it out. I needed to patch the Redhen module I'm using which was causing a Revision ID error. Im using the Relation, Rules Redhen modules together (and of course the Entity API). Here is the export of the Rule that did it:

{ "rules_update_employment_status" : {
"LABEL" : "Update Employment Status",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "relation" ],
"ON" : [ "relation_update" ],
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "relation:endpoints:0" ], "type" : "redhen_contact" } },
  { "entity_has_field" : {
      "entity" : [ "relation:endpoints:0" ],
      "field" : "field_employment_status"
    }
  }
],
"DO" : [
  { "relation_rules_fetch_endpoint" : {
      "USING" : {
        "relation" : [ "relation" ],
        "entity_type" : "redhen_contact",
        "number" : "1"
      },
      "PROVIDE" : { "endpoint_fetched" : { "endpoint_fetched" : "Fetched Endpoint" } }
    }
  },
  { "data_set" : {
      "data" : [ "relation:endpoints:0:field-employment-status" ],
      "value" : "20"
    }
  },
  { "drupal_message" : { "message" : "[endpoint-fetched:full-name]\u0027s Employment Availability has been changed to [endpoint-fetched:field-employment-status]." } }
]
  }
}

This let me access whatever fields on the endpoint that I wanted then change them if I needed to.


How to change the theme programmatically? I've just applied a theme and got an error such that I cannot even change the theme back to a working one (like Bartik).

I've read other threads but I could use hook_custom theme but I don't know how to get it to work.

What I'm doing is to edit the system.api.php and change the original lines of hook_custom_theme to this:

function hook_custom_theme() {
  // Allow the user to request a particular theme via a query parameter.
  if (1)) {
    return 'bartik';
  }
}

I've tried several variations but I don't know what I'm missing. Can anyone help me with this please?

Edit: I've realised that I need to write my own module to run that line of code, is it true? Is there a simpler way to just change the default theme or the weight of the themes programmatically somewhere?

You can install drush on your system and then from drush command you can change the theme using

drush vset theme_default <theme_name>

You can do the changes from database also. Either on the commandline, or via an administration interface (eg PHPMyAdmin) enter the following query

UPDATE system SET status=1 WHERE name = '<theme_name>';

Then either:

UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';
TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

Source: https://drupal.org/node/200774


Drupal 6 Feeds Module User Import & Ubercart I've noticed that in Drupal 7 there is a way to map fields for importing users, but I don't see the same option for Drupal 6. Am I missing something? I'm trying to import users that include address fields from a CSV, but I can't see a way to map it all correctly.

I need to import addresses, phone numbers, zip codes, join dates, etc. and make sure they're mapped to the correct member/user fields in Drupal/Ubercart

After searching high and low I finally found a workable solution.

Using user_import module in conjunction with this little custom module here I was able to import all of customer information from the old site.

It was exactly what I was wanting to do. All I had to do was match up the fields to my CSV file and I was able to get it all added in ot the appropriate uc_addresses tables.


Displaying another entity's form on a node I am trying to embed the edit form for a flag on my node (the full page view mode).
After some struggle, I finally figured out how to get the flagging form.  But once I have the form, how do I actually get it to display on the page?
function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($node->getType() == 'MY_CONTENT_TYPE') {
    $flag = \Drupal::service('flag')->getFlagById('MY_FLAG_ID');
    $flagging_entity = \Drupal::service('flag')->getFlagging($flag, $node);
    $form = \Drupal::service('entity.manager')
      ->getFormObject('flagging', 'edit')
      ->setEntity($flagging_entity);
    $form_obtained = \Drupal::formBuilder()->getForm($form);
    // How do I actually show the form on the node?

I looked at this question on rendering forms (which says use the formBuilder service, which I am already using). I assume I need to put the form in a render array but the documentation is not clear about how to do that.

\Drupal::formBuilder()->getForm() already returns a render array, see the FormBuilder::getForm() documentation.
To render the form, you just need to pass the results of getForm() to your $build array, then render it in your template.
In hook_ENTITY_TYPE_view():
function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  // ...
  $build['my_flagging_form'] = $form_obtained;
}

Then in your twig template:
{{ content.my_flagging_form }}

Or, if you're already rendering content in its entirety, you may not need to update your twig template at all.
As @4k4 noted in the comments, you can also add the appropriate meta data in hook_entity_extra_field_info to make your flagging form addition configurable (reorderable, etc) on your node's Manage Display screen. See Creating pseudo-fields in Drupal 8 for an example.


Alter the comment form I have the following code to alter the way comment form is displayed. After the bellow code everything is displayed as i want to but it does not add the comments.

 global $user;
     if ($user->uid) {
       $form['author']['_author'] = array
     (
        '#tittle' => 'Name',
        '#attributes' => array('id'=>array('name')),
        '#prefix' =>'

Name'.$form['author']['_author']['#markup'],
        '#suffix' => '
'
     );
     }
     else {
     $form['author']['name'] = array
     (
        '#type' =>'textfield',
        '#attributes' => array('id'=>array('name')),
        '#prefix' =>'

Name',
        '#suffix' => '
'
     );
     }

     $form['author']['mail'] = array(
        '#type' =>'textfield',
        '#attributes' => array('id'=>array('email')),
        '#prefix' => '
Email (optional)',
        '#suffix' =>'
',
        '#required'=>TRUE,
        '#weight' => 2
     );

    $form['comment_body'] = array
     (
        '#type' => 'textarea',
        '#attributes' => array('id'=>array('comment')),
        '#prefix' => '
Comment',
        '#suffix' => '
',
        '#weight' => 4,
        '#resizable' => FALSE
     );

     $form['author']['homepage']['#access'] = FALSE;
     $form['subject']['#access'] = FALSE;

     $form['captcha']['#prefix'] = '

';
     $form['captcha']['#suffix'] = '
';
     $form['actions']['submit'] = array (
        '#prefix' => '<button type="submit">',
        '#suffix' => '</button>

',
        '#markup' => '' . t('Say your piece') . ''
     );

    $form['#action'] = $_SERVER['REQUEST_URI'];

To submit the form i have to press twice on the submit button ( how can i solve it ? ) and after i submit the form again i get the following errors and i cannot figure it out how to solve them:

Warning: array_values() [function.array-values]: The argument should be an array in _field_filter_items() (line 513 of /home/mcristi/public_html/jhub/modules/field/field.module).
Warning: Invalid argument supplied for foreach() in text_field_validate() (line 119 of /home/mcristi/public_html/jhub/modules/field/modules/text/text.module).
Notice: Undefined index: homepage in comment_form_validate() (line 2155 of /home/mcristi/public_html/jhub/modules/comment/comment.module).

This thing causes the problem that the form is not submitted/saved :

 $form['actions']['submit'] = array (
        '#prefix' => '<button type="submit">',
        '#suffix' => '</button>

',
        '#markup' => '' . t('Say your piece') . ''
     );

    $form['#action'] = $_SERVER['REQUEST_URI'];

Is there any possibility to save the comment on the node page ? ( to not be redirected to /comment/reply/$nid)

You're overwriting the form elements that are already there, some of which are fields and so need to have their array structured very specifically (Why is hook_form_alter so messy in d7? has some background for that).

You can alter existing elements in the form without overwriting the whole thing like so:

$form['comment_body']['#prefix'] = '
Comment';
$form['comment_body']['#suffix'] = '
',


how to create path node/{some id}/add/{node_type} which loads node/add/{node_type} page Create a path node/{some id}/add/{node_type}  which loads  node/add/{node_type} page form.

I want to get that  { some id } to assign it default value in a form field client needed that url pattern as node/{some id}/add/{node_type}.

We can achieve this by creating route as below.

cust_group.route_name:
  path: '/node/{group_id}/add/{node_type}'
  defaults:
    _controller: '\Drupal\cust_group\Controller\CustNodeController:add'
  requirements:
    _permission: 'access content'   ( change permission according to your requirement)

And create a CustNodeController controller with method.

/**
 * Returns responses for Node routes.
 */
class CustNodeController extends ControllerBase {

  /**
   * Provides the node submission form.
   *
   * @param \Drupal\node\NodeTypeInterface $node_type
   *   The node type entity for the node.
   *
   * @return array
   *   A node submission form.
   */
  public function add($group_id, NodeTypeInterface $node_type) {
    $group_id =

    $node = $this->entityManager()->getStorage('node')->create(array(
      'type' => $node_type->id(),
    ));

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

}

make sure that {some id} != {node}.


How to use Sort By desc by default with toggle link enabled? I am using better exposed filter and added toggle link sorting for a field. But the toggle link sort Asc order on first click. I want to make it Sort Desc on first click.

I tried to write :

MyField Desc|MyLabel
MyField Asc|MyLabel

But it doesn't work.

I didn't found any suitable way to do this. What I actually did, I changed the link using jQuery.


Exposing archive view I'm using an archive view which is in Views by default but just needs to be activated. It works great and is displaying the way I want it to, but I was wondering if there was an easy way for me to expose the view so I can allow users to filter content by month or within a month range (eg. from Janauary 2011 to May 2011)...?

You need a Date filter. If you have the Date module enabled, you can activate the Date Popup widget to allow users to easily select dates. (The popup may only work on the Page display, e.g. http://yoursite.com/archive)

Choose the 'Date: Date (node)' filter.  Set the Operator to 'Is Between' and set the value type to 'An offset from the current time'. Using your example, you can use '-4 months' for the Min value and 'now' for the Max value.

Finally, click 'Expose' to show the date filter to your users.


Displaying one node for each unique field reference in View (e.g. one videogame for each developer) I have an view that display my custom content type (e.g. covers of video game titles).

Lets assume that I have this structure for my content types:

developer
|--title
|--country
...

video game
|--title
|--body
|--developer_ref (term reference, as choice list)
...

It works ok except for one thing. I want to display only one video game per developer here (the newest one).

So for example, if we have 3 different developers I want to display 3 items and each of it its the latest node referenced to each developer.

I know how to display 3 latest nodes, but that way they can e.g. all come from one developer.

I have already tried with agreegation on video game.developer_ref field:

But I don't know why it doesn't change a thing (I still see multiple games for some developers).

UPDATE:

This unfortunately only works if your developers were users. After reading your question again, it appears you have created them as content, in which case my answer does not work.

Views has a built-in feature for this called 'Representative node'. This can be used to

  Obtains a single representative node for each user, according to a
  chosen sort criterion.

So how to use this:

Start off by creating a view that lists users and add the Representative node relationship (in the advanced section).
Configure the selection criteria; in your case this would be 'Content: Authored on'.

This adds a relationship to Views, allowing you to add fields to the view.
If you want to show the rendered node instead of individual fields, add the Rendered entity field instead:

No need for aggregation.

Do note that this will always fetch the last node the user has created of every content type. You should add additional filters to the view to limit this to game-nodes, etc.


Always expanded menu items not showing up expanded in custom menu I have a custom menu profile-menu and have configured a block to display that menu. It has four menu items with 'expanded' => TRUE. However, during test runs these expanded menu items do not show as expanded. I've dug through the Drupal menu code and it looks like Drupal won't handle 'expanded' unless the variable 'menu_expanded' includes the menu name, which is odd because I've never had this problem outside of the test environment. I tried adding variable_set('menu_expanded', array('profile-menu')) to hook_install but for whatever reason when I call variable_get('menu_expanded') inside the test case that variable is an empty array.

If during the test case I call menu_cache_clear_all(); variable_set('menu_expanded', array('profile-menu')), everything does work as expected. The code that seems to be gated by this variable is in menu_tree_page_data.

What's the right way to make sure certain menu items (which I have defined myself in hook_menu) are always expanded? Because setting expanded => TRUE in hook_menu apparently doesn't cut it during test cases. Also, why am I only seeing this issue when running test cases?

I have investigated this a bit more and made a bug report on Drupal.org. It turns out the 'menu_expanded' variable is basically a redundant layer of caching which must be set by _menu_set_expanded_menus whenever the cache is cleared. However, if Drupal tries to call that function more than once in a single request, it will be registered as a shutdown callback instead of called immediately. This would work fine most of the time in normal use, but during test cases the shutdown function won't get called until after the tests are over.

Knowing that most of the time this operation will handle itself correctly, and that even if it doesn't it's just a cache clear away from being fixed, I've decided it is acceptable to add a direct call to _menu_set_expanded_menus in the setUp function like so:

function setUp() {
  parent::setUp('custom');
  // Call this function now to set up expanded menu item processing. Normally
  // we could wait for it to be called in a shutdown function added during
  // the menu rebuild in parent::setUp() above, but in this case it must be
  // handled before the tests are run.
  _menu_set_expanded_menus();
}


Renaming the field label from "author" to "created by" How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"?

To rename the label of a field add the preprocess function template_preprocess_node to your template.php file:

function *YOUR THEME*_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'group'){
    //Supposing that your field name is "field_txt_group"
    $vars['content']['field_txt_author']['#title'] = 'created by';
  }
}


How to append a new form element to a form via AJAX not triggered inside the form? Suppose I have a form only with a submit button.
After an AJAX response (not an #ajax form callback) I need to insert/append a new form element into this form.(it's not declared in the form-building function)

How will I initialize this new form element in the PHP callback function, in order to populate it with the data i am getting through ajax?

I could have initialize the form with a dummy element and copy its array to a new one?How will I hide this dummy element in the initial state of the form (before ajax)?

In the "Add more" examples out there, the initial form carries the first of these elements from the beginning... what if there is not from the beginning in the form?

In other words how can I get anywhere in the code a fresh-empty form element ready to be rendered?

You can add some custom value to the form_state and use it to determine whether to build a new form element or not. Please try the following example:

/**
 * An example form.
 */
function example_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  // Use this value to determine whether to build a new form element or not.
  if (empty($form_state['add_new_item'])) {
    $form_state['add_new_item'] = FALSE;
  }

  $form['example_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Example form'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['example_fieldset']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => FALSE,
  );

  $form['actions'] = array(
    '#type' => 'actions'
  );

  // add field button.
  $form['actions']['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add new form item'),
    '#submit' => array('field_add_one'),
    '#ajax' => array(
      'callback' => 'example_form_callback',
      'wrapper' => 'example-fieldset-wrapper',
    ),
    // hide this form element
    '#attributes' => array(
      'class' => array('element-invisible')
    )
  );

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

  $form['#attached']['js'] = array(
    array(
      'type'  => 'file',
      'data' => drupal_get_path('module', 'YOUR_MODULE') . '/js/add_field.js',
    ),
  );

  // append a new form element (after ajax)
  if ($form_state['add_new_item'] == TRUE) {
    $form['example_fieldset']['new_item'] = array(
      '#type' => 'textfield',
      '#title' => 'My new item',
    );
  }

  return $form;
}

/**
 * Submit handler for the "add-field" button.
 *
 * - set the $form_state['add_new_item'] as TRUE.
 * - rebuild the form.
 */
function field_add_one($form, &$form_state) {
  $form_state['add_new_item'] = TRUE;
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback.
 *
 * Returns the fieldset with all values in it.
 */
function example_form_callback($form, &$form_state) {

  return $form['example_fieldset'];
}

/**
 * Final submit handler.
 *
 * Reports what values were finally set.
 */
function example_form_submit($form, &$form_state) {
  $output = $form_state['values']['example_fieldset'];
  drupal_set_message('
' . print_r($output, true) . '
');
}

add_field.js

(function($) {
  Drupal.behaviors.your_module_name = {
    attach:function() {

      var form = $('#example-form');

      // the 'add-field' form element
      // this form element is invisible. It will be triggered by the custom link (not form element).
      var addField = $('#edit-actions-add-field');

      // add an example link
      $('#my-custom-link').remove(); // prevent from adding the custom link more than once
      form.after("ADD FIELD"); // add custom link

      // Attach mousedown() to the custom link in order to activate ajax.
      // Notice: You can attach click() to a normal submit form element (without ajax)
      // but it has to be mousedown() if the form element has an ajax attribute.
      $('#my-custom-link').click(function() {
        addField.mousedown();
      });
    }
  };
}(jQuery));


How can I exclude links to untranslated pages from Google search results? I have a multilingual site (English and Japanese).  Japanese is the default language.  Some pages have been translated into English and some have not.

I am using the XML Sitemap and i18n Modules as well as Translation Redirect (one of the i18n submodules).

For pages that are not translated into English, both the "English" and Japanese versions are appearing in Google search results-- even though there is no English version!  (Both links appear like this:

www.mysite.com/en/node/29
www.mysite.com/ja/pathauto-url

I have two sitemaps (Japanese and English) made with the XML Sitemap module.  The pages that have not been translated into English are still listed in the English site map, so I assume this is how Google found the pages.

How can I deal with this?

Is it possible to remove untranslated pages from the sitemap of the relevant language?  Or is it possible to automatically redirect all untranslated pages to the default language?

When using i18n xml sitemap, and when you have a menu set to be included in a sitemap (using xmlsitemap menu), even if that menu is set to display only for one language (localized to Japanese or English in my case using i18n_menu), it will still get added to the sitemap for both languages.

So, in this case, one solution is to avoid using xmlsitemap_menu and instead use xmlsitemap_node and add the node links individually.

Painful but it works.


Drupal adding an include I am using the Zen theme, what I could like to do is effectly add a php include for a header area. This is common code so a block will not really do.

I have html.tpl.php which is added automatically to each page is there anyway to add custom chunks to every page for example myheader.tpl.php

You can try module_load_include

  Loads a module include file.

Parameters

$type: The include file's type (file extension).

$module: The module to which the include file belongs.

$name: (optional) The base file name (without the $type extension). If omitted, $module is used; i.e., resulting in "$module.$type" by default.

Examples:

  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');


Can I handle calculating/charging for shipping after order placed? I am trying to determine if Drupal Commerce is the right ecommerce method to use for my client's project.

The workflow my client is looking for is:

Customer place order, and pays nothing for shipping.
My client will process order and determine shipping costs.
My client will charge customer for shipping, using CC data stored when they placed order.

Is this something that Drupal commerce can handle?

Yes, because Drupal Commerce 2.x and most payment gateway modules tokenize credit card details by default for the sake of reusable "stored payment methods." From a customer experience standpoint, you might want to offer some sort of estimated shipping amount, but so long as you're communicating that shipping costs will be calculated and confirmed with the customer prior to charging, there's not technical reason you could not charge the full amount during the fulfillment process.


Views exposed filters without "Apply" button I have created a view with exposed filters of term select list. How can I make the select list to work directly on selecting an item, instead of clicking on the "Apply" button?

Under advanced portion of view choose following

**Exposed form**

 Exposed form style: Basic | Settings

Then Choose autosubmit in Settings as shown below

This will hide the Apply button and the select list to work directly on selecting an item, instead of clicking on the Apply button.


How to create a confirm popup when delete item with field collection? I have configured a field collection field (unlimited items) for a content type and I want create a confirm popup when user delete an item.
For this, i found that i can directly go and modify 2 functions in the field_collection.pages.inc file. They are:

1. field_collection_item_delete_confirm

2. field_collection_item_delete_confirm_submit

I'm a newbie in drupal so I don't know how to use these function from the field_collection.pages.inc file, I tried to hook these function in template.tpl file but it's didn't work. Can someone help me ? Sorry about my English.

Here is what i did, to handle the deletion of a field collection item for a node:

Created a hook of type hook_node_view() in my custom module and
overridden the delete link for the field collection items, so that
they point to a custom path, that is declared in my custom modules
hook_menu().
Now the custom path is mapped to a template file (passing the field
collection item id).
The logic inside the tpl file processes the deletion of field
collection item (passed by id) using entity_delete_multiple() and
sets a custom message to be displayed back to the node view page.

more details


Multiple axis voting system (star rating) I tried Multiple Axis Voting System using Drupal FiveStar and Computed Field, but I am not able to understand the below 2 points:

Add a node reference field to the voting node type, make the targeted node type selected.
Setup the voting(aka.review) node type, add all needed field and fivestar fields for multiple axis voting. Remember set the "target" option to #3 field.

May anyone help me understanding this?

The idea behind this technique, is to have a node that can be reviewed, and then create review nodes that contain the votes.

The first step you list, requires you to add a node reference field on the review node, where you can select nodes of the type that can be reviewed. That will enable uses to select what they are reviewing.

The second step is to setup fivestar for the review node. You need to add the axis that should be voted on, and which users will be able to set when creating the node.


How do I  keep the sum of related nodes' specific field values in a field? I have two different content types: "Parent" and "Child".

On Parent nodes, there is a multi-value reference field where I keep some Child nodes of this node. Every child node has a field "Integer" and I keep some integer values in it.

What I want is keeping the sum of those Integer values of all child nodes of a Parent inside a field "Sum".

So I will have:

Parent 1 (sum=11)

Child one (integer=3)
Child two (integer=6)
Child three (integer=2)

Is it possible?

I managed to do this with Rules module, to keep it short.

By default, gave 0 to the value of integer for Parent content type.
Added a rule to calculate the value of Parent's integer field by summing up the values of child nodes and setting it to Parent's integer value. Event is creating new content
Added a rule to recalculate the value of Parent's integer field when adding or updating a Child content. For this, I am calculating the difference of new and old integer values of Child node. Then, adding this value to Parent's integer value.

If anyone is interested, I can also give the details of the rules.

Below is an export of the second rule:

{ "rules___aa_test" : {
"LABEL" : "__aa_test",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_update" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_parent_story" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_time_left" } },
  { "entity_has_field" : { "entity" : [ "node:field-parent-story" ], "field" : "field_time_left" } }
],
"DO" : [
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-time-left" ],
        "op" : "-",
        "input_2" : [ "node-unchanged:field-time-left" ]
      },
      "PROVIDE" : { "result" : { "difference" : "Difference" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-parent-story:field-time-left" ],
        "op" : "+",
        "input_2" : [ "difference" ]
      },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parent-story:field-time-left" ],
      "value" : [ "result" ]
    }
  }
]

}
}


Unable to log in due to session cookies not being passed in I have an html5 app which logs the user into drupal via services 3.11 but I am unable to connect.

Using the Chrome Postman plugin I can connect as expected.
The difference between Postman and my code is that the cookie session is not being passed from my app.
From what I have read the withCredential: true is supposed to pass the session cookie but it's not working for me?

api/user/login.json - Logs the user in as expected
api/user/token.json - returns the token as expected
api/system/connect.json - Always returns the data for Anonymous user 0

The system/connect code sent after login and token is:

                jQuery.ajax({
                    type: "POST",
                    url: connectUrl,
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (result) {
                        dosomething();
                    },
                    error: function (result) {
                        dosomething();
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-CSRF-Token', Session.user_token);
                    },
                });

For anyone else who stumbles across this problem I did finally manage to solve it with the following which ensures the credentials are pass for each call consistently. I'm assuming where CORS adds in the additional OPTIONS request, the credentials we're going through.

jQuery.support.cors = true;
    jQuery.ajaxSetup({
        xhrFields: {
            withCredentials: true   // Pass session cookie with requests
        }
    });


Add / Remove column in admin/content/node How can I add / remove columns in admin/content/node ?

Of course you can modify this page by implementing hook_form_alter in your custom module.

But the best approach is using Views and VBO module create your own contant admin page with columns and filters that you need. Module Administration Views will help replace Drupal core admin page with your own.


What is Best Way to Retrieve Status Messages in Multiple Locations? We like to share the status messages in multiple location in single request, so we retrieve them:

function get_messages(){
    $status_messages = array();
    //loop through each message type
        foreach (drupal_get_messages(null, false) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
return $status_messages;
}

Here, since we are passing "FALSE" to the drupal_get_messages function the messages are not reset which is what we like because multiple locations gets to call this function, however. At some point, the messages need to be reset.

One option is to clear messages at the last point of the request.
Where and how to do that?
Another option, would implement a cache
and run drupal_get_messages() with "TRUE" to call once and reset at
the same time. I am not familiar with cache in Drupal or PHP. How to
do that?

In short, we like to access status messages in multiple locations and $variable['messages'] is not available to serve the purpose. How to do that? Thank You for help

The solution was using Drupal cache pattern by storing messages in static space as following:

function get_messages(){
    $status_messages = &drupal_static(__FUNCTION__);

    if(!isset($status_messages)){
        //loop through each message type
        foreach (drupal_get_messages(null, true) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
     }
     return $status_messages;
}

Here, we get the static reference first and then check if its already set. if not, we retrieve the messages and reset at the same time by calling Drupal API function drupal_get_messages with "true" parameter. As result, we reset the messages that solves our problem and, in addition, our performance is improved due to caching

I have also summarize it all at my blog post "Caching In Drupal"


How to avoid that Drupal encodes my url I use hook_url_outbound_alter to change my url to /q=anything, but the url in browser is shown as /q%3Danything. How can I avoid that Drupal encodes the url?

Other choice would be to send q=anything as query, but then hook_url_outbound_alter includes the "?" character, and I can't include it.

if (preg_match('|^search/node/(.*)|', $path, $matches)) {
  $path = 'q=' . $matches[1];
}

Any idea? Thanks in advance.

you shouldn't need to add the "q=" drupal will deal with that side of things, especially when you turn on clean urls.


Add basic page title and its teaser view in basic page I wanted to have one basic page, that allows me to add brief data about other basic pages like title and some data in teaser view. ie to create basic page, whose content is, some content of other basic pages.

I know that we can achieve this by using view. But I wanted to know if there is module available that allows me to do this, so that I can select the pages which are to be embed in the page I am creating.

You can try Node Embed module.

Node Embed provides an input filter for CKEditor & FCKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node.

Nice documentation for this module can be found here.


Create and pre-populate a mutiple value field in field collection on new node with ajax call This question is in the same area as a previous I asked (How to create (& pre-populate) multiple “field collection” fields on an ajax call), but with the extra level of complexity that I'm trying to alter a multiple value field inside the field collection.

The Problem

I want to add a number of field instances to a multiple value field, inside a field collection when creating a node using an ajax call.

In order to create and pre-populate a multiple value field collection, you need to change the following value in the AJAX callback and then rebuild the form.

$form_state['field']['--machine-name-of-field-collection--'][LANGUAGE_NONE]['items_count'] = x;

However inside a field collection in $form_state, there is no field information, only entity information. So while I can change item_count for the field collection I can't alter it for any of the fields inside it.

The entity also doesn't seem to be fully created because it's on a brand new node so I can't load it and edit it.

Has anyone encountered this before? How do you work with fields inside entities on forms?

Ok so I didn't manage to solve this directly, but I did accomplish my intent behind this quesion.

The intent behind this was to pre-populate a field collection from another node on a node create form with an ajax call.

I'm still not sure how you alter the fields in a field collection on a form and I'll leave this question open in case anyone knows, however if you're looking to pre-populate field collections onto a node, then this blog post has an answer:

http://drupal.cocomore.com/blog/field-collections-exposed

And I posted an example using ajax to do this in an answer to this question (where I think it's more relevant): How to create (& pre-populate) multiple “field collection” fields on an ajax call


Change text format used for text field when displayed in a view? I have a content type with a text field that may contain a token from the Media module (that WYSYWIG inserts). This token is typically transformed into HTML by enabling a specific filter for the text format used.

However, I want to create a view for nodes of this type that just strips out the media token entirely. This allows me to show the content w/o any images or captions.

Initially, I thought I could add my own field formatter using hook_field_formatter_info and hook_field_formatter_view, strip out the token right in the formatter, and then use that formatter when rendering the field in the view (views lets you select a formatter, like Default, Trimmed, etc).

The problem there is that by the time hook_field_formatter_view is called, the safe_value for the field is already computed and text has already been run through the input filter (so the token has been transformed).

I wonder if there's a way I can create a new text format that doesn't include the Media token filter and somehow tell views to render the field using that, but it doesn't appear like I can.

I found an issue concerning something similar to you question on Drupal.org

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

There is some module code provided which may be useful to you.

The module looks like it uses a field formatter.  Instead of taking out the media tags, it aims to strip out the resulting html tags.

$pattern = array('/
.+<\/div>/im', '/
<\/p>/im', '/
]+><\/p>/im');
  $item['safe_value'] = preg_replace($pattern, '', $item['safe_value']);


copying actual drupal content to a different drupal site I know that one can use the export link to copy a content type or a view to another drupal site. But if that content type has a lot of content, is there a way to also copy that over as well?

It may be too late for this, but I needed the same thing and came across this thread so thought others might also. There's a new module called Data Export Import which does exactly what you need:

  The purpose of this module is to be able to export nodes, taxonomy
  terms and users to data files and then be able to import these data
  files into Drupal sites. There may be many uses for this module but
  the main one would be that it can provide a way to export data from a
  live Drupal site and then to import that live data into an updated
  version of that site.


How can I route automated emails through an email function in my module? I was unable to get HTML mail to use a template properly, so I have a mymodule_mail function that sends emails when a response is required from the user

function billiondollar_mail($key, &$message, $params) {
global $base_url;

$message['headers'] = array(
    'MIME-Version' => '1.0',
    'Return-Path' => 'xx@xx.com',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'From' => 'XXXX <xx@xx.com>',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
);

I have a switch case on $key that loads in html header and footer plus the email body.

I'm wondering if there's some way I can make the system emails (some sent via trigger/actions and the registration confirmation ones) use that same system. Right now they are in plain text, which is incongruous with the rest of the system.

If I can get them using that hook function I will need to know what $key value it would have and how to insert the message content.. presumably one of the $params

I think this is what you're looking for:

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7

"hook_mail_alter() allows modification of email messages created and sent with drupal_mail()... All core modules use drupal_mail() for messaging, it is best practice but not mandatory in contributed modules."


Setting a Variable in PHP for use in rules I have a variable I've defined via rules using 'Add a variable' called 'minimum_reached'. This is available to me for use in custom PHP code.

if($total >= $minimum_fund){
   $minimum_reached = 'yes';
   dpm($minimum_reached, 'min reached');
}

Once this is set to 'yes', the next action fires which Sets a data value of the current node's 'minimum reached' field to yes (depending on that above outcome). The variable is being set as the dpm works, but it's not being carried across to the next action. How do you define this variable in PHP for use later on? Thanks.

The Rules module doesn't seem to provide this feature.

I also tried using a rule set with a variable, but the variable was reset between each action. I tried adding return $minimum_reached at the end of each rule executing PHP code, but it didn't help.

The only way seems to use drupal_static(), if you are using Drupal 7 (e.g. with drupal_static('mimimum_reached', 'default value used when the variable is not set')), or a global PHP variable, if you are using Drupal 6.


How do I remove the colon from a form element's title - D7? I've hunted high and low for what generates this colon. I've looked in thetheme_form_element_label function and at the #title_display attribute in the form api, but I cannot see how to override it. It must come from somewhere? Thanks.

Well easiest solution is to use this module . But I am not sure you would be interested to install a module for this small task.

If not you need to do the following steps:

You need to copy the field.tpl.php to your theme folder.
Now in the template file you can find the code that outputs the colon.
Please remember to clear the cache.


Admin theme creation in Drupal I am new to drupal and I have a task to create a custom admin theme. I read a lot of tutorial to how to create a theme in drupal and I am familiarize with that. But never see how to create a new admin theme. I also wanted to customize the default <input type ="text"....> fields with custom css.
Thank you in advance.. :)

For Admin Theme

Create a custom drupal theme (its already answered).
Bring it to your drupal site.
Go to Home » Administration » Appearance, Select your theme in Administration theme select box and save


Custom migration not appearing in the migration UI I wrote a custom migration module, and I have enabled it in the Drupal 7 administration pages. I have searched through the web, but nothing shed any light on my issue. I came across this post, but it was not helpful.

I have under sites/all/modules/my_module the following 4 files:

my_module.info (contains the necessary info and included .module and .inc files)
my_module.module (contains my_migration_migrate_api())
my_user_migration.inc (contains class MyMigration extends Migration)
my_module.install (empty file by looking at online examples - http://btmash.com/article/2011-02-25/migrating-content-using-migrate-module)

I apologize, but I really don't know how I could be more specific with my question. Does anyone know what could be wrong?

Is your module enabled? (Seriously, my Drush Make file forgot to enable the module, and I was clueless, yesterday.)

If you use drush migrate-status from the command line, is your Migration listed?


Using theme_username() with no link to user page? I use this theme function to show the username of user:

 theme('username', array('account' => user_load($record->uid)))),

It works fine but the username is also a link to the user page. I just need to the username with no link at all.

I read the doc at:

http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_username/7

and I see that there is the argument link_options to handle this, then I guessed it was a bolean value and tried with (but not working):

theme('username', array('account' => user_load($record->uid), 'link_options' => 0))),

theme_username() will only output the username as a link if the link_path variable has been set. This is done by default in template_preprocess_username(), and will happen as long as the user viewing the username has access to view the profile.

If you want to change that behaviour you just need to add your own preprocess function which removes the link_path variable:

function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path'])) {
    unset($vars['link_path']);
  }
}

Bear in mind that the above will remove the link system wide. If you want to remove just for this specific instance, I think the best way would be to pass a custom variable to the theme function and check for it in your preprocess function:

$vars = array('account' = user_load($record->uid), 'surpress_link' => TRUE);
$name = theme('username', $vars);

function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path']) && isset($vars['surpress_link']) && $vars['surpress_link']) {
    unset($vars['link_path']);
  }
}


How to create view with user's flagged content? I created a flag 'Add to favorites' with the Flag module and I'd now like to create a view for the user's profile that sums up all his/her favorite content. I tried to add the relationship Flags: add_to_favorites (by current user) to my view, but then the favorites of the logged in user appear on every profile page.

How can I solve this?

Have you tried adding contextual filters -> USER -> get uid from url


Form returning value issue I am trying to adapt a Drupal 5 form to a Drupal 7 form, but something is not working. The form is correctly displayed, but when "Submit" button is clicked the information in the form is not correctly send to $_GET. What am I missing??

<?php
 function my_menu($may_cache) {
  $items = array();
    $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details',
    'type' => MENU_CALLBACK,);

 return $items;
}

function say_report_details($values = array()) {
  $form = drupal_get_form("report_details_form");
  //$output = theme("report_page", $form, $output);
  return $form;
}

function report_details_form() {
 $form["search"] = array(
 '#type' => 'fieldset',
 '#title' => t('Search params'),
 '#collapsible' => FALSE,
 '#tree' => TRUE,
 );

 for ($i = 1; $i < 32; $i++) {
  $days_opt[$i] = $i;
 }
 for ($i = 1; $i < 13; $i++) {
  $month_opt[$i] = $i;
 }
 for ($i = 2008; $i < date("Y") + 3; $i++) {
  $year_opt[$i] = $i;
 }

 $form["search"]["from_day"] = array(
  '#type' => 'select',
  '#title' => 'Date from',
  '#options' => $days_opt,
  '#default_value' => (($_GET['from_day'] == "") ? date("d") : $_GET['from_day'])
 );
 $form["search"]["from_month"] = array(
  '#type' => 'select',
  '#title' => '&nbsp;',
  '#options' => $month_opt,
  '#default_value' => (($_GET['from_month'] == "") ? date("m") : $_GET['from_month'])
 );
 $form["search"]["from_year"] = array(
  '#type' => 'select',
  '#title' => '&nbsp;',
  '#options' => $year_opt,
  '#default_value' => (($_GET['from_year'] == "") ? date("Y") : $_GET['from_year'])
 );

 $form["search"]["to_day"] = array(
  '#type' => 'select',
  '#title' => 'Date to',
  '#options' => $days_opt,
  '#default_value' => (($_GET['to_day'] == "") ? date("d") : $_GET['to_day'])
 );
 $form["search"]["to_month"] = array(
  '#type' => 'select',
  '#title' => '&nbsp;',
  '#options' => $month_opt,
  '#default_value' => (($_GET['to_month'] == "") ? date("m") : $_GET['to_month'])
 );
 $form["search"]["to_year"] = array(
  '#type' => 'select',
  '#title' => '&nbsp;',
  '#options' => $year_opt,
  '#default_value' => (($_GET['to_year'] == "") ? date("Y") : $_GET['to_year'])
 );

 $result = db_query('SELECT something in the database');

 $strs = array("all" => "All");

 foreach ($result as $store) {
   $strs[$store->tid] = $store->name;
 }

 $form["search"]["store"] = array(
  '#type' => 'select',
  '#title' => 'Stores',
  '#options' => $strs,
  '#default_value' => $_GET['store']
 );

 $form["submit"] = array("#type" => "submit", "#value" => "Show report");

 return $form;
}

function report_details_form_submit($form_id, $form_values) {
  $query = "";
// This next line is the one I am having an issue with right now.$form_values is empty
  foreach ($form_values['search'] as $key => $value) {
     $query .= "&". $key ."=". $value;
  }

 return array('admin/reporting/report_details', $query);
}

The code throws an error at last "foreach" as $form_values is empty for some reason.Thank you!!

By default Drupal form sends values using post method. If you are looking to recieve values in $_GET you will have to define #method attribute of your form to get.

$form['#method'] = 'get';


webform "Load a pre-built option list" not shown I use the webform module to build a form. I'd like to fill a select with values coming from a database. I use the hook

Here is some sample code:

    /**
     * Implementation of hook_webform_select_options_info().
     * See webform/webform_hooks.php for further information on this hook in the Webform API.
     */
    function custom_webform_pre_build_list_webform_select_options_info() {
        $items = array();
        $items['user_roles'] = array(
            'title' => t('Roles'),
            'options callback' => 'custom_webform_pre_build_list_user_roles'
        );

       return $items;
    }

    /**
     * Build an options list to be used with webforms select list based in drupal roles
     */
    function custom_webform_pre_build_list_user_roles() {
        $roles = user_roles();

        $contentarray = array();

        $contentarray[0] = t("Select user role");

            #$new_taxonomies = array();
            foreach ($roles as $role) {
                $contentarray[$role] = t($role);
            }

        return $contentarray;
    }

I activated the module. Now my problem is to select this list of entries for my select. I cannot see the "Load a pre-built option list" when I click "Add" under "options" for the select box in the form builder.
What am I doing wrong?

I'm using version 3.x of webform and the "Options element" module.

Thx, Sven

I had the formbuilder module activated. There is no possibility to "Load a pre-built option list"! I deactivated it then it works. The problem is, there is not a nice builder ui anymore ;-(


overriding ubercart - add to cart button I try to override add to cart button with hook form alter in custom module with this function but I got an error Fatal error: fatal flex scanner internal error end of buffer missed in. What can be the problem?

function uc_button_form_alter($form_id, &$form_state, $node) {
  if ($form_id == 'edit-submit-' . $node->nid) {
    $form['submit']['#attributes']=  array(
      'class' => 'node-add-to-cart',
      'xxx' => 'xxx',
    );
  }
};

Thank you

In D7, below is my solution for different product classes.

/* Overrides the Add to Cart form text*/
if ( !empty($form['nid']) ) {
  $node = $form['nid']['#value'];
}
else {
  $node = 0;
}
if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='uc_recurring_subscription')){
   $form['actions']['submit']['#value'] = t('Subscribe');
}

if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='credit')){
   $form['actions']['submit']['#value'] = t('Buy');
}

For regular product or just one product class, this should work.

/* Overrides the Add to Cart form text*/
if ( !empty($form['nid']) ) {
  $node = $form['nid']['#value'];
}
else {
  $node = 0;
}
if (($form_id == 'uc_product_add_to_cart_form_'.$node){
   $form['actions']['submit']['#value'] = t('Buy now');
}


Adding a custom Sort field in Drupal In our business we assign tasks to users based on the last digit of a company ID. When I created the view for these users, it was simple to create a "Formula" field and use RIGHT(field name, 1) to get this value.

I'd like to make an exposed filter that will allow users to only see companies ending in, say, 5 (for example).

Question: Is using the "Sort" function the best way to do this, or is there another way to add filtering to a table created by a view? It would be wonderful to add text search filters to each column, but I'm not sure if this is possible.

Question: How do I create a new field and make it available in the "add field" interface?

Thanks! Rich (who isn't the normal drupal developer and was left to learn on his own)

Hi Rich who isn't the normal Drupal developer and was left to learn on his own. Welcome to Drupal.

I've encountered scenarios in which I had an exposed sort with a dropdown list and I needed to remove all the options that didn't fit my pattern. I used a hook_form_alter() that modified the '#options list for the element to unset() the items I didn't want to allow the user to select. However, this method doesn't prevent those items from showing when -All- is selected, so that may not work if that's an option for your users.

The way you'd add a new field is to create a custom field handler but it sounds like what you want might instead be a custom sort handler or a custom filter handler. The three are similar but not identical in their implementation.


Display entity reference field in a views block I have two content types, "Contributor" and "Story".

Contributor has the following fields
1. Default title/label
2. Job title
3. Email address

Story has many fields, but includes an Entity Reference field that accepts multiple Contributor nodes.

When viewing a Story node webpage, I would like to have the "contributors" entity reference field to be displayed within the right sidebar using a views block. It should output all contributors that have been related to this Story node.

I have attempted to create a views block of Contributor nodes using Contextual Filters, but have not been able to output the contributors related to that story node. Are contextual filters the right method or should I have Relationships configured as well? If I have not set any contextual filters, all of the Contributor nodes are listed, but I can't seem to figure out which contextual filter and settings to use.

Just coming from memory I would recommend something like this:

Create a view of what you want to show. (In your case, a view of content-type="contributors")
Create a relationship in that view to the content that contains the reference field. (Just click on add a relationship, and search for the name of your reference field)
Create a contextual filter to filter by ID. This filter will also be the reference field name. (choose "Provide default value" then "Content ID from URL") This contextual filter will use your relationship.
Restrict that Views block to only show on that content type (in block settings of course).

What you're doing is adding a relationship to that reference field. Then it is available as a contextual filter, where you can then provide a default value to filter by content ID.

Note: keep in mind if ever your reference field is not available as a relationship in your view, you may need to first add a content or node based relationship.


content type field not printing In drupal 7, I defined a field for a custom content type and am trying to display its value via page.tpl.php.  Nothing is appearing in the rendered page.

Here's the relevant piece of page.tpl.php.  The field is 'field_mast".  Note that I added print $title just so I could be sure that this template is being used.  It is.

Perinote&trade; <?php print $content['field_mast'] ?>

       <?php print $title ?>
Organize Your Way

My content type fields are:

Label  machine name field type            widget
Title  title        Node module element
mast   field_mast   Text                  Text field
Body   body         Long text and summary Text area with a summary

And for Manage Display, I have:

Field   Label        Format
Body    <Hidden>     Default
mast    Above        Default

Finally, for my actual content, I have:

Title: Notes contacts....
mast: User Guide
Body
This user guide...
Text format: Full HTML

Any ideas on what I need to do to get 'mast' to print?

try

Perinote&trade; <?php print render($content['field_mast']); ?>

or this one

Perinote&trade; <?php print render($content['field_mast']->value); ?>

I recommend you to download and install devel module and write

<?php kpr ($content);?>

to see what $content contains. you can also call this function in hook_preprocess_page as well.


Loading nodes from another Drupal database using Views I'm trying to use Views to load nodes from another Drupal database defined in settings.php with a key of 'cms'. Both sites are Drupal 7. The other database is a different Drupal install which is acting as a content repository or centralized CMS. My goal is to create a new view type/group on the destination site, so when creating a view the site build can choose "CMS Content" instead of "Content". I'm hoping a site builder would then be able to build a view normally based on content types and content from the centralized CMS site, even if I have to tell views about all the fields in each content type.

In my hook_views_data() implementation I've set the 'database' key, but can't figure out how to read from the node table without overriding $data['node'].

function cms_connector_views_data() {
  $data['cms_connector']['table']['group'] = t('CMS Content');
  $data['cms_connector']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('CMS Content'),
    'help' => t('Content from the centralized CMS.'),
    'database' => 'cms',
  );

  return $data;
}

Of course this doesn't look for a node table, it looks for a cms_connector table in my cms database, which doesn't exist.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms.cms_connector' doesn't exist

http://views-help.doc.logrus.com/help/views/api-tables says that the key within $data…

  should be the actual database name of the table (not including
  prefix), but it can be an alias as long as the join information
  (explained later) contains the real name of the table.

I don't actually want to do a join, I want to create a base table from the other database's node table. But I tried this anyway (even though it doesn't really make sense) after seeing http://drupal.org/node/1713010#comment-6310438:

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

I've searched around here, d.o, and Stack Overflow, but most of what I'm finding is Some-other-database-to-Drupal, not Drupal-to-Drupal.

I found the https://drupal.stackexchange.com/questions/12736/using-nodes-from-another-site-database question here, but it's about node references, and is unanswered.

I thought about using Services to read XML/JSON from the centralized site, but there are too many hurdles to that approach. I don't really want to synchronize nodes either.

Consider looking at the Forena module. It can be used to query (not update) the data in other databases. Various DBMS formats are supported, such as another Drupal database also.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


How to display upvoted posts by user in a view? I want to display nodes upvoted by user in userprofile page in a view. I have number up/down rate widget with nodes, and user can take back votes by clicking on vote arrows.

I tried this:

Relationship:

node:votes
node: vote results

Contexual Filters

votes:user = -node-votes(user)

Filter criteria

(Vote results) Vote results: Value (> 0)

Problem

first problem is, whenever a user take an upvote back, and upvote again on same node, it duplicates on view result.

second problem = absolute value of vote result in field criteria is greater than 0. and this also brings downvoted posts on this view.

Hi Please check the data filters and widget type, for more details read readme file of module, there is (Views integration section)

Its working great if you configure according to documentation.
Thanks!


Views Export button to block I have a view with Data Export, where it creates a button to download the view's content, depending on a filter supplied by URL query parameters. I'm able to edit the the button using THEME_views_data_export_feed_icon in my theme's template.php. That's all good and works as intended.

How can I create a Drupal 7 Block that behaves just as that export button? Is it best to manually create a php block picks up the page URL/query to set as the export block link, or is there an easier way?

If I am correct, you should have a path/url to your Data Export Views (second column, at the top, Data Export Settings > Path). So you just need to create a block with a link to this URL in its body and it will directly launch the export procedure (no filters considered though). You may add CSS/Bootstrap class to your link and here is your nice export button in a block, which you can add anywhere in your website.


Forums 'Add Container' function not doing anything I have enabled the Forum module and ran into some rather annoying errors:

No 'Forum' link comes up in admin, I have to go directly to admin/content/forum
I click on 'Add Container' or 'Add Forum' and nothing happens
When I click on 'Create Content' I cannot see type forum (only when I view content types)
When I direct to node/add/forum I cannot create as the Forum dropdown box is empty (as I can't create Containers

I have run cron and update to no prevail. I read something somewhere it helps to manually update the database by incrementing the container row count or something?

I flushed the cache and it worked.
I created a flush.php file and ran it.

<?php
  drupal_flush_all_caches();
  drupal_set_message('cache flushed.');
?>

More information is available here.