Can Drupal built-in search or Apache Solr find comments on the site made with Disqus? I'm evaluating comment systems and although I see disqus used in many cases I'm not sure if it is the best choice for me as I am uncertain that my site's own search system could show comments in search results.

Can Drupal built-in search or Apache Solr find comments on the site made with Disqus ?

Research I have shown so far is that Disqus has Search Engine Optimisation (SEO) -- for external search engines e.g. Google:-

http://wordpress.org/plugins/disqus-comment-system/
http://www.quora.com/Do-search-engines-index-Disqus-content

But what about your own search system on your site, or using Solr for example. I'd prefer not to use Custom Google Search to search my site as I want control over how my results are shown.

So I'm looking for 2 answers for searching Disqus comments: 1) for the basic built-in Drupal search and 2) for SOLR.

Thank you.

Looks like it may be possible on the server side via the Disqus API PHP wrapper - I widened my answer outside of Drupal to get more input: https://webmasters.stackexchange.com/a/52159/3738

Though I still have concerns about not fully controlling the comment data and if the API changes. I'd have to see real benefits for our situation for Disqus to be able to outweigh these potential issues. Another issue is that of usability (UX/User Experience): having already logged in to the Drupal site, the user has to log in yet again to use disqus, unless the well supported Facebook login to the Drupal site can be "carried" into the Disqus login automatically. Though some user testing has revealed some would prefer the Disqus approach to be simpler.


Enable CSS files in Omega 3 sub theme with Drush? Is it possible to enable CSS files in an Omega 3 sub theme with Drush?

Im working locally and regularly importing the latest database from live. I have a build script that I run to clear cache, enable modules im using etc. However im manually enabling the CSS files in my theme each time. Can this be added to the build script?

I'm only a bit familiar with Omega 4. In order for your css files to be "enabled" by default, you need to transfer the theme settings from the database into the theme's .info file and make sure this is enabled also in the live site. So if you have css/style.css and its declared in the .info file, Omega 4 will just follow the .info file.

Hope this helped. :)


How do I allow user to select table column they want in Drupal View? I am trying to create a Human Resources Portal for my organisation.
I have to create a table via View to show all the list of staff of the organisation which is about 500 employees.
My major problem is that not all the column is needed at every situation, sometimes they need to create a table with only few columns at a time, so I need to expose the users (HR Dept) the columns so they can decide which one they need at a time.
I have tried MediaTable module but that does not allow the user to hide columns themselves.
I need like a checkbox of columns to be selected.
Thank you

Give a look at Views Dynamic Fields module. I have used it in the past to create selectable table columns to display for views.

  The Views Dynamic Fields module provides a filter for use with Views
  module. This filter allows the user to pick and choose which fields to
  display for a rendered instance of a view for that user. This provides
  a customized view instance for each user.

  Features

  Users can dynamically choose the fields to view in their rendered view instance
  Default fields to show when no filtering is applied, can be configured
  Possible to always keep certain fields to display to the user
  An exclusion mode to allow reverse selection of fields when there are too many
  Great for creating and exporting reports from the view
  Works great with Fields Embed Views module


Image styles based on node type Let's say i have two node types:

Article - with 300x300 photo
News - with 100x100 photo

For now, i can define those two sizes in Image Styles menu and they'll be both created for both content types (so both Article and News will have two images generated - in size 300x300 and 100x100).

My question is - is there any way to set which content type shoud use which image style(s) ? Please note that i'm not interested in generating both of them and displaying just one. It would kill my server and my wallet (i'm using Amazon s3). Thanks in advance.

The setting on the content type's field display settings page allows you to choose image style to display. Drupal only generates styles when they're used somewhere.


How to retrieve data from set with drush_set_option() from within install profile I've been messing around with trying to pass varabiles to an install profile based on a signup form, as descripbed in this post. I'm able to get the data out of the form and into drush using hook_pre_provision_install(), but I'm not sure how to grab that data from within the install profile that was set with drush_set_option().

It appears the answer is simple: You can use drush_get_option().

  Get the value for an option.

  If the first argument is an array, then it checks whether one of the options exists and return the value of the first one found. Useful for allowing both -h, and --host-name.


What would the snippet(s) look like for multiple google analytics tracking IDs? I'd like to include 3 tracking IDs on all pages. I'm using the Google Analytics module and there are three fields in the custom javascript code under advanced settings.

Using Universal Google Analytics, in the Google Analytics Module 7.x-2.0 @ /admin/config/system/googleanalytics > ADVANCED SETTINGS > CUSTOM JAVASCRIPT CODE > Code snippet (after)

ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'foo'});
ga(function(foo) {
  foo.send('pageview');
});
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'bar'});
ga(function(bar) {
  bar.send('pageview');
});


How to Redirect search form to search api views I'm struggling to redirect the core search form /search/node/* to the search api views /s* .

I took a look at but nothing happens ...

http://api.drupal.org/api/drupal/modules%21search%21search.module/function/search_box_form_submit/7

also tried
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#action'] = 'search';
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
  else if ($form_id == 'search_box_form' || $form_id == 'search_theme_form') {
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
}

function MYMODULE_search_form_submit(&$form, &$form_state) {
  $default = search_get_default_module_info();
  $form_state['redirect'] = str_replace("$default[module]/", '', $form_state['redirect']);
}

Tried different modules ... but they don't pass the results..
Also tried to add the search form from views on the front page and managed to get it wrong .. all sorts of errors.

Cheers

try this function:

/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }
  else {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
  }
}


Rendering a region in region--footer.tpl.php I have my social media links in my sidebar_first region. And these social icons are included in my footer. So in region--footer.tpl.php, I have rendered sidebar_first region  but it is not displaying, I know this is a wrong way to render a side bar region in footer region, does anybody have idea how can I achieve this:

<?php if ($content): ?>
<footer id="footer" class="<?php print $classes; ?>">

    <?php $foter_menu = menu_navigation_links('menu-footer-menu');
      $variables['footer_menu'] = print theme('links__menu_footer_menu', array('links' =>      $foter_menu,'attributes'=>array(''),'heading'=>t('')));
      ?>

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

<?php endif; ?>

then in my page--front.tpl.php

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

as you wrote, you can override the region.tpl.php files, following the template name conventions - I would post a link, but drupal.org is down right now. A quick web search should get you to the right url and you can create a region specific tpl file.

you shouldn't try to render one region in another, but you can duplicate the code in both region files, or of course, you could also include the code in two blocks, one for each region


Allow users to edit their own content and admin-generated content On Drupal 6, how can I let registered users edit their own content and also allow them to edit an already existing admin content (just one content type) and then when saved, the user takes ownership of that node?

You can give the 'Authenticated user' role permission to 'Edit any <content type> content'. If you configure that content type to create a new revision by default, the user will be registered as the author of that revision (and if you don't give them the 'Administer nodes' permission, they can't uncheck the option to make a new revision). The original author of the node will however still be listed. I can't think of an easy way to change that automatically. But the users can already edit all nodes of that type anyway, so it would only be relevant if you use the node author for some listing or so - in that case, you can probably use Rules to do assign latest revision author as node author.

Edit: OK, so in that case this doesn't help. You can investigate if something along these lines works (I haven't done something like this so I'm not sure it's possible without coding):

Setup a condition for Rules with Context Rules, something like 'Node author is "admin"'.
Create a Rules action using Content Access to set 'Per node access control' if that Context condition is triggered.


Ordered list in Books navigation By default the navigation in books is an unordered list:

Vegetables

Carrots
Tomatoes

Fruits

Apples

Is there any way to make it an ordered list?

Vegetables

1.1. Carrots

1.2. Tomatoes
Fruits

2.1. Apples

It is possible manually.
Suppose you have a book entitled "Tutorial". inside it you have created 3 book pages entitled : "Installing", "Configuring", "Running".
When the book is dispalyed the 3 pages will be ordered starting with the most recent

To reorder the book, edit the book first and choose outline in the tabs

In that screen, click on the link "reorder an entire book". The result wil be the following:

Click on the link "edit order and titles" to access the interface where you can reorder the pages

Use the + icons on the left of pages to reorder thje book.
I hope this will help.


Programmatically Filter Node Access beyond permissions, views, etc Short Version:

What would you say is the best way to filter how nodes appear (in a binary sense: published vs. hidden) to users based off of a dynamic value?  This solution is beyond the scope of typical modules like Permissions, Views, or Content Access.

Long Version:

My application calls for having select nodes display to select users based off of values changed over time. For instance, lets say a user wants access a node but both the users and the nodes change their location (daily).  When a customer views the site (or any page) I want them to only be able to see nodes in their specified range.  Because of this the basic Permission and Views and other stock Drupal modules seem to be ineffective.  It seems like it would be a bad way to use the Permission system because their are so many variables in the user / node relationship.  I can't unpublish nodes because they need to remain active to other users, processes, etc.  Even a dynamic Views filter with custom php code for my distance measurement would be ineffective because then nodes would still be accessible by directly inputting the URL.

Thus far, I am planning on using hook_node_load() to perform my calculations - determining the user and node relationship - and then only return nodes that are applicable.  This should prevent direct URL access to unavailable nodes, keep active nodes that exist but don't match the criteria, and by default control

You say that you do not want users to be able to enter node URLs directly. To me this suggests you do need to use permissions, as it is the only way tou can guarantee your node won't be accessed.

The reason is that you never know which parts of Drupal might be displaying your node. For instance you could manually insert a drupal_goto in hook_boot to provide your own custom permission handling, testing the URL for the node id - however the node would still be accessible via Views. The great thing with Drupal is that all sorts of modules can use your data in all sorts of ways - however this means you have to present your data (in that case, your permissions) in a way other modules will understand.

You say that your permissions are distance-based. This means you cannot use Role-based permissions, since you would end up having one role per user. What you could use however is the ACL module - this provides an API allowing you to define per-user/node permissions.

You would then need to implement hook_node_update/hook_user_update to re-calculate the permissions and change the ACL for that node/user when the node/user is changed.


Sub-theme preprocess inheritance I am attempting to create a subtheme using showcase_lite as a base theme. For now there will be mostly just CSS alterations in the subtheme.

To start, I created just an .info.yml file to start with:

name: My Subtheme
type: theme
description: 'Subtheme for testing'
core: 8.x
base theme: showcase_lite

Most inheritance works fine (CSS / JS / Twig), but it seems that the preprocess functions in the base .theme file are not called anymore. I am talking about _preprocess_html() for example.

Is this expected behaviour? If so, how could I have these be called from my own theme, without copypasting them all?

Subtheme inheritance is a bit different in D8. I believe you are running into expected Drupal 8 Theming behaviour.

In D7, the parent theme's functions were called, followed by the subtheme's preprocess functions - I hope this is still the case, but it seems from your troubles that it might not be.

When in doubt, just duplicate the corresponding file in your subtheme.

Here's some more reading on the subject:

https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme
https://www.drupal.org/docs/8/theming/sub-theme-inheritance


I s there a way I can show node teasers but don't allow access to full content? I need anonymous users to to be able to se the node teaser but don't allow access to the full content is there a way to do this?

To prevent users from access the node you can disable the "View published Content" permission but that will disable it for all node types. If you like to disable it just for one node type you can checkout the content_access module.

You can use a view of content to display the teasers.

In the format section use the format "Unformatted list" and choose your content display Teaser.

If you use a page for the view, you should also check the page access in the page settings section of the view.

I'm not sure if you need the following (It depends on how you prevent the node access):

In the advanced section under query settings you can disable sql-rewriting. This allows you to disable the node_access check. But take attention to this:

"Disabling SQL rewriting will omit all query tags, i. e. disable node access checks as well as override hook_query_alter() implementations in other modules."


How to remove "leave blank for all" message from Views exposed filter After updating the Views module from 3.11 to 3.13, I get an annoying text that says:

  Leave blank for all. Otherwise, the first selected term will be the default instead of "Any".

Does anyone know how to remove it, besides using CSS?

This only happens in taxonomy term exposed filters.

Could it be a bug?

There is a problem with view 3.13. It happened due to this commit https://www.drupal.org/node/339384#comment-10548388.

Stated as:

  Issue #339384 by colan: Added help text to keep the exposed filter
  terms list unset to keep unfiltered "Any" option default.

Apply this patch or revert your view back to version 3.11.


is there supposed to be a default folder in sites/default? Just noticed I have a default folder in my sites/default folder so that I have sites/default/files and sites/default/default/files

Found out-
The node with audio file upload is HIDING the file as protection from third party download.That is why only occurring with that particular content type.

It depends what you mean by 'supposed to'.

Drupal core doesn't place that folder there, no. But that doesn't mean that someone/something else hasn't. You'd have to give us that information, we couldn't possibly know.

What I will say is that no module should be writing to that path unless you've explicitly told it to, and if you have your permissions set up correctly, then the web server won't have been responsible for creating the folder.

Again, though, impossible to say from here.


EntityQuery condition for multivalue fields I need to select some entities that have a certain field (user reference) empty or that field does not contain the current user as a reference.

I tried this, it works ok if the field is empty or if the field contains exactly one value. For multiple values it displays a wrong output:

$query = $this->entityTypeManager()->getStorage('my_entity_type')->getQuery();
$group = $query->orConditionGroup()->notExists("my_field")->condition("my_field", \Drupal::currentUser()->id(), "<>");
$query->condition($group);
$query->condition("type", "my_bundle_id");

$ids = $query->sort(...)->execute();

Any thoughts on how to make this work?

Try to use NOT IN instead of <>.

->condition("my_field", [\Drupal::currentUser()->id()], "NOT IN");

You can learn more here.


how to add .js programatically when in an entity list I'm in the hook_entity_load in my module and I want to dynamically add a .js library which I already have defined.
The thing is i need to get to  the block objec I'm on to add the library using $block['#attached']['library'][]

How do I get this block object?

The correct approach is doing it using a custom list builder, assuming you are using that and not a view.

class MyListBuilder extends EntityListBuilder {

  public function render() {
    $build = parent::render();
    $build['#attached']['library'][] = 'yourmodule/library';
  }
}

Then specify it in the annotation of your entity type.see Node/User or so on how to do that, most entity types specify either the default or a custom list builder.

If it's a view then you can implement one of the many views hooks, if it's not your own entity type then I'm not exactly sure why you need to add a JS there and you should explain in more detail what kind of list it is and what your JS does.


How can I setup a template for displaying all nodes of a given type? When I enabled the Blog module in D7 it allows a "/blogs/" page to show all blogs and then the standard blog view underneath that for single blog entries; how can I do this with my own content type?

I want to create a list of my image gallery content types that is tailored to my needs, and then have a view for individual galleries, while still keeping items in those galleries as separate nodes.

I've worked out what seems to be a decent way to reference everything, I just can't figure out how to setup a group view for the galleries. I could just make a custom article that uses PHP to query the nodes and do it all through custom articles, but I thought perhaps the Drupal themes setup allows something more eloquent.

You can create your content type and add fields to it to create sorting criteria.

Use taxonomy to define a vocabulary to plug into your content field.

Use pathauto to set up custom URL alias paths for your content.

Define a view to read your fields, filter all content to find what you want, sort and display it.  YOu can refine your searches using contextual filters, that will read the URL and extract information from it.

Sounds simple enough, but if you are unfamiliar with the modules it takes a bit of work to master them.


Enforce URL rules when posting content types so I created a content type "Regions" - This includes the 13 provinces in Canada listed as individual terms.

When creating a new post with the content type "Regions", you have to choose which term to post into. Let's say I would like to post a page "TEST POST ONTARIO", I post it in the term "Ontario"

I would like the URL from this post to be automatically changed to
www.website.com/region/on/testpost
by default, it posts to www.website.com/testpost

Is there a way to automate the url for when this content type is created? or would you have to manually change the url alias every post?

You want to use the PathAuto module.  This lets you create default patterns on a per content type basis that can use information from fields on the node to create a URL.


How to use conditions on a COUNT Expression? I am creating an appointment booking module for my drupal 8 site, which is 99% complete, but I am one or two lines of code away from completing my module. The problem is using a database condition on an Count Expression that has been produced after the database has executed.

This is the code I have so far:

public static function dateavailabilty() {
    $select = db_select('bookingdateandtime', 'e');
    $select->addField('e', 'datecode');
    $select->groupBy("e.datecode");
    $select->addExpression("COUNT(e.datecode)", 'count');
    $select->condition('count', 2, '>');

    $entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

return $entries;}

But the page returns "The website encountered an unexpected error. Please try again later."

The following error report is produce in the Drupal Admin Error Log Messages:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Champ 'count' inconnu dans where clause: SELECT e.datecode AS datecode, COUNT(e.datecode) AS count FROM {bookingdateandtime} e WHERE (count > :db_condition_placeholder_0) GROUP BY e.datecode; Array ( [:db_condition_placeholder_0] => 2 ) in Drupal\booking\bookingDTdatabase::dateavail() (line 51 of C:\wamp\www\modules\booking\src\bookingDTdatabase.php).

I need to use a condition to only produce results that has a count of more than 2. Obviously, if I cancel out this line "$select->condition('count', 2, '>');", drupal returns everything perfectly. So, using the condition doesn't work on data that has been added after execution.

How do I go about using the correct condition to apply to the Expression?

Many Thanks for reading and helping.

Conditions on aggregates are addressed with HAVING in MySQL, so something similar to:

$select->having('count > :cnt', [':cnt' => 2]);


Updating Drush when installed using pear When I run drush self-update, I get the following message:

  A newer version of drush, 7.x-5.8, is available.  You are currently running drush version 6.0-dev. The update process depends on how you installed drush. Some common update commands are: pear upgrade drush/drush,  git pull, drush dl drush --destination=[/path/to/drush].

When I execute pear upgrade drush/drush, I get the following message:

  Nothing to upgrade

When I execute sudo drush dl drush --destination=/usr/local/bin/pear/bin (/usr/local/bin/pear/bin is the directory where Drush is found from which), I get the following messages:

Unable to create /usr/local/bin/pear/bin/drush.                                             [error]
Project drush (7.x-5.8) could not be downloaded to /usr/local/bin/pear/bin/drush.

How should I update Drush when installed with pear?

Although there is a pear package for Drush-8.x-6.x, if you are going to run this version of Drush I would recommend cloning it from git, and updating it with git pull.  You can also check for newer code with git status instead of drush self-update.

Discussions on the deficiencies of drush self-update should probably happen in the Drush issue queue. Briefly, it no longer handles the update operation itself, and while it works well enough when using stable versions of Drush, it is easily confused in other circumstances (e.g. when Drush-7.x-5.8 is newer by date than the 8.x-6.x-dev that you are running, even though 7.x-5.8 is built exclusively from features backported from 8.x-6.x-dev.)


Adding additional fields to panels I'm working with Page Manager and Panels. I'm adding content (panels) to each custom page layout, and every panel has a title by default. Is there any way to add additional information, common to every panel, like a subtitle?

In other words, is there a way to add fields to the Panel entity?

Thanks!

Yes. You can do that with Fieldable Panels Panes (FPP). Here is a quote about it (from the module's project page):

... creates an entity that may be used in panel panes to create fieldable entity panes. These panes can be created either directly in the Panels UI or in a separate administrative UI and later added.
Once added, they can appear in the "Add content" dialog to be easily reused. Since they are fieldable entities, they can contain any kind of data that field API can provide.
Each entity supports revisions, and any revision can be made current without having to make a new revision.
Access control is provided by the CTools access method, for both view and edit access.
Bundles are supported and can be added via the UI or hook_entity_info_alter().
A Trello board is being used to help coordinate development.


How to create a new parent section on the Configuration page? When one navigates to Manage » Configuration, the page is divided into sections which (in the "Seven" theme at least) shows up in individual boxes. These sections have headings like "People", "Content authoring", "Development", etc.
I am able to create a settings form and place this inside any of the existing sections on the configuration page by associating it with the parent key in hello_world.links.menu.yml.
Example:
hello_world.greeting_form:
  title: 'Salutation settings'
  description: 'Configure the salutation message.'
  route_name: hello_world.greeting_form
  parent: system.admin_config_development

This places a link to the settings form for the "Hello World" module in the "Development" section. This is not where I want to place it.
Instead, I want to create a new section named "Examples", place this new section along with the others on the "Configuration" page, and make this new section the parent of my link to the settings form.
Below is an image of what I want it to look like. There should be a new section, named "Examples" as the section heading, and in that section, there should be a link to the settings form with the text "Salutation settings":

Here is a way to do it.
#example_codes.links.menu.yml
example_codes.base:
  title: 'Example Codes Module'
  parent: system.admin
  description: 'A Module with various Examples.'
  route_name: example_codes.base
  weight: 0

You need to define system.admin as parent.
And in your routing.yml should contain this base route.
#example_codes.routing.yml
example_codes.base:
  path: '/admin/examples-codes'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Example Codes Module'
  requirements:
    _permission: 'administer example codes configurations'


Who is online in domain access I am developing a website with Domain Access. Each domain has the same structure but different content. I would like to show online users. When I activate who's online block from block list in admin, it will display all online users. But, I want to display the 'online user' for a particular domain.

I use Domain Strict module so users login only their assigned domain.

How can I show 'online user' of a particular domain using Who's online block.

Domain Strict - Forces users to be members of domains in order to view content.

So they are still logged in to the whole system, that's what other modules can see.

The best you can do is to create your own module, or use PHP module to create a block with PHP filter. Use code similar to the one from this Drupal.org post:

// Count users with activity in the past defined period.
$interval = time() - 900;

// Perform database queries to gather online user lists.  We use s.timestamp
// rather than u.access because it is much faster is much faster..
$anonymous_count = sess_count($interval);
$authenticated_users = db_query('SELECT u.uid, u.name FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
$authenticated_count = db_num_rows($authenticated_users);

// Format the output with proper grammar.
if ($anonymous_count == 1 && $authenticated_count == 1) {
  $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}
else {
  $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}

echo $output;

Now you have 2 modifications to make:

Get rid of the whole "anonymous" part, as you don't need it.
Modify the $authenticated_users = db_query part to JOIN the table Domain Strict module uses, and only count users that have access to the current domain.


How to alter variable for ECK entity? We are using the ECK module where we have created component eck_highlight (machine name). How would we be able to modify the variable array using a preprocess hook?

Eck_highlight component has this field:

Field Reference to content types: basic, article, and event

Goal:

Call the preprocess to store 'info' array to vars (i.e. vars['info']). The info variable will be passed into the Twig template so we can use to output information.

mymodule_preprocess_eck_highlight(&$vars) {
    $vars['info'] += [
       'id' => 'some-id',
       'height' => 'some-height',
       'width' => 'some-width',
       'src' => 'src1'
    ];
}

We have tried to do the following but cannot alter the variables.

mymodule_preprocess_eck_highlight(&$vars)
mytheme_preprocess_eck_highlight(&$vars)

I am adding an answer so anyone who comes across this that i was able to resolve the issue. I had to use mymodule_preprocess_eck_entity(&$vars).

When i tried to use the machine name in place of eck_entity, it did not work.


Is it okay to store a $node object as a $_SESSION variable My contrib module currently stores a $node object temporarily in the variable table, and stores the nid for that $node in the $_SESSION variable so that the $node can be retrieved from the variable table at a later point.

Would it be okay to store the $node directly in the $_SESSION variable? Or would there perhaps be a performance of security impact?

If it is okay to store a $node object in the $_SESSION variable, do I need to serialize it first?

I think you want the ctools object cache API here, this is what views uses to store edits to a view until they are saved and is what Drupal 8 uses for node preview. In D8 it's called user temp store.


How to add JavaScript code to a webform? I want to add JavaScript code to a webform. For example, to add things like onclick, onchange, mouseover function to webform's textbox, textarea, select, email, etc.

How do I do so?

The recommended way to add a JS to any form in Drupal is using #attached to the $form element.

In order to add the JS to a webform, you would have to implement hook_form_alter or hook_form_FORM_ID_alter, and add the #attached

function MODULE_form_webform_client_form_3_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MODULE') . '/MODULE.js',
  );
}

Then create the MODULE.js file inside the module directory, and write your JS there.

Refer to The Drupal JavaScript API, to see how to work with JS in Drupal way.


Rebuilding or regenerating the teaser after changing the trim length in Drupal 7? I changed the teaser length from 600 characters to 300 characters for the Story and Book Page content types. How do I rebuild the teasers so that all teasers are updated to the new value?

Any help would be appreciated.

If you are using the Views module to display your teasers, and you are using fields in the View, then you need to set the trim length for each field in the View itself.
Are you using custom formatters? These might be buggy and/org disregard the trim length.
When you edit the node(s), check that the summary field is blank. (I quote from the node edit page: "Leave blank to use trimmed value of full text as the summary.")
For further troubleshooting, create a new node with a lot of dummy text. Does it get trimmed to 300 or 600 characters?

If the new node gets trimmed to the new value, but old nodes get trimmed to the old value, then there is a problem with your cache or with the old nodes.
If the new node also gets trimmed to the old value, then there is a problem with your fields or views.


How do I use Gitlab server as a central staging server? I just installed a Gitlab instance on my LAN.

I want to use it as the central repository for a Drupal dev->test->prod staging setup.

So, 1st step, I want to push my local "dev" workspace to the Gitlab repo.

Following instructions at Gitlab docs, I try

cd ./drupal8
git remote add origin https://gitlab.example.com/user1/drupal8-test.git

But that fails and returns

fatal: remote origin already exists.

Checking in the drupal dir

cd ./drupal8
git remote -v
    composer        https://github.com/drupal-composer/drupal-project.git (fetch)
    composer        https://github.com/drupal-composer/drupal-project.git (push)
    origin  https://github.com/drupal-composer/drupal-project.git (fetch)
    origin  git@github.com:drupal-composer/drupal-project.git (push)

I want to be able to push to the Gitlab repo, but I still obviously want composer etc to work in my dev env.

What's the right setup & workflow for using Drupal with a central Gitlab repo, making sure that I keep the ability to manage my site in 'dev' with composer?

Usually, people set up a remote named "upstream" for the source, in this case it would be https://github.com/drupal-composer/drupal-project.git. Remote "origin" should be the git URL of your Gitlab repo. So for you, here is a sample workflow:

The setup:

git remote rm origin
git remote rm composer
git remote add composer https://github.com/drupal-composer/drupal-project.git
git remote add origin https://gitlab.example.com/user1/drupal8-test.git

The result:

$ git remote -v
composer    https://github.com/drupal-composer/drupal-project.git (fetch)
composer    https://github.com/drupal-composer/drupal-project.git (push)
origin  https://gitlab.example.com/user1/drupal8-test.git (fetch)
origin  https://gitlab.example.com/user1/drupal8-test.git (push)

Get upstream files:

git fetch composer
git merge composer/8.x

Adding your own files:

touch myfile.txt
echo "hello world" > myfile.txt
git add foo.txt
git commit -m "Added my file."
git push origin master


Loading current revision node How do I construct an entity condition so that it loads current revision of all nodes? This is my attempt.

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'xxxxx')
->fieldCondition('xxx_module','tid', $tid,'=')
->age(FIELD_LOAD_CURRENT)
->execute();

Instead of loading the current revision, it loads the published revision.

By default, EntityFieldQuery checks the currently logged-in user has the permission to access the queried entities. This is could be undesired, especially when the queried entity is not shown to the users, for example when a module just needs to get a list of entities to delete them.

To avoid EntityFieldQuery checks the currently logged-in user has the permission to access the entity, you need to use the following method:

addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') for Drupal 7.15 or higher version
addMetaData('account', user_load(1)) for previous versions

Assuming you are using any version higher than 7.15, you code should be the following one.

query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'xxxxx')
  ->fieldCondition('xxx_module','tid', $tid,'=')
  ->age(FIELD_LOAD_CURRENT)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
->execute();

There could be a module that alter the query done from EntityFieldQuery and doesn't respect that tag; in that case, the query could still not return an entity revision that is not published.


How to setup a Multilingual site using A LOT of taxonomy terms and CCK content taxonomy? I am going through the process now of translating my site into multiple languages. I have A LOT of vocabulary terms and I use them with Content Taxonomy CCK fields on my nodes. I don't believe I can have separate vocabularies as the content taxonomy CCK field on the node can only use ONE vocabulary to save to.

So what are my options? What is best practice? I have wanted to offer my site in multiple languages for a long time but just a bit confused.

Also regarding menu items, should I create a separate menu for each language or use the Translate interface and search for each menu text string and add translations. There seem to be multiple ways to do everything and I think this is adding to the level of confusion. Anyone that has done this before it would be a great help!

My site is a online directory of listings, so LOTS of content and a rather complicated interface, so I want to make sure I start this off right, rather than just going into it by guessing. Thanks!

Thanks for the link! But I think you misread the question. I am not referring to menus.

I'm having trouble using localize terms method on vocabularies with the Content Taxonomy field on my node. It's showing both the vocabulary dropdown list of the terms as well as the content taxonomy dropdown list of the terms. They are translating just fine and showing properly, but it shouldn't be displaying double the dropdowns. Content taxonomy should be hiding the Vocabulary dropdown. I am trying to figure out why it's not. any ideas?

Check this for taxonomy translation:
http://drupal.org/node/335205

The approach for menu translation depends on your menu and site structure. It is a bit painful but I would recommend using the menu translation interface. Managing multiple menus may work fine if you are planning 2-3 languages max but as you add more languages it will get out of control.


Node access control based on users at the node edit page I want to ask is it possible to assign customized roles to particular users at the node edit page? For example, the node author/admin can assign "editor" role to user A & user B and assign "admin" role to user C at the node edit page. The node access control is different among different nodes and different users.

I found some related modules such as Permissions by Term and Permission by field but none of these can perfectly fulfill my requirements. I am using Drupal 8 so some modules may not suitable for me.

Is there any solution for that?

You could use the Group module for this. This module allows any node to be "assigned" to some group. And then it depends how you configure the group roles (which are NOT the standard Drupal roles) about who has what kind of permissions.

For your case, create a group type named something like "Node Authors", and then create a "Group" for each user (using something containing the user's name as its label). And tune the permissions which come with the Group module (which are different from standard Drupal permissions!) to fit your needs.

After you enable gnode, a submodule of the Group module, you can assign any node to a group. In D7, you could simply do so at the node edit page: there is an extra form field on the node edit form which can be used to select the group that you want the node to be assigned to. However, in D8 this is no longer possible, for reasons explained in this comment, and which states:

  ... all content-to-group relationships are now fieldable and we therefore need to ensure the user is presented with the fields that were configured on said relationship. A simple auto-complete to select a group would therefore not work.

Therefor, in D8, this is what you have to do instead, as described also in the feature request "UI: more easily select group for a node":

Open the Groups list and click through it.
Select the appropriate Group.
Go to Group content.
Select "add group content".
Select which group content.

More info:

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.


Creating a new variable by combining 2 field values In my theme’s preprocess node function i’m trying to create a new variable by combining 2 existing fields, both of which are text strings.
pseudo code is this:

$teachers_name = $firstname + $lastname;

When looking at a print out of the Teacher object using Devel, i see the field first name is an array, structured like this…

field_first_name
    und
        0
            safe_value ‘Lisa’

but so far it’s not working at all. i’m not accessing the variables correctly.

function myTheme_preprocess_node(&$variables){
    if($variables['type']=='teacher') {
        $variables['teachers_name'] = $variables['field_first_name’][‘und’][0]    [‘safe_value’];
    }

how can i access the text string of field 'first name'? thanks!

You should use entity module and entity_metadata_wrapper . I already answered a similar question in here.


Drupal 8 Jquery/Ajax Views Arguments Setup: I have two contextual filters, service area and ID.
In my view if I send {service_area}/{id} i get back the OR query, which is what I want. My question is, when I try to use Jquery to return this query, I do not get back the expected result, which is the OR of these two arguments.
Here is my code:
(function($) {
  Drupal.behaviors.searchresults = {
    attach: function (context, settings) {
      $('.currentFilters', context).once('search').click(function () {

        //hard set variable for this example.
        let args = [];
        args[0] = 'antelope valley';
        args[1] = '221';

        $.ajax({
          url: '/views/ajax',
          type: 'post',
          data: {
            view_name: 'webform_submissions',
            view_display_id: 'page_1',

            //This is where it may be causing an issue. I pass an array with the arguments, but no avail
            view_args: args,
          },
          ...
        });
      });
    },
  }
})(jQuery);

In my view I am able to see this OR if I preview with contextual filters as as seen in the image below:

If I just send service_area by itself as the argument, it will work. So my question is, what is the correct way of sending multiple arguments in ajax, any references/blogs to help me would be appreciated. Thank you!

I figured it out. I needed to pass a string not an object, the lack of documentation confused me.
    let args = 'antelope valley';
    args = args + '/207'

    $.ajax({
      url: '/views/ajax',
      type: 'post',
      data: {
        view_args: args,
 ...


Determine which region a menu block is rendered in I need to re-use the same menu in two different regions, with slightly different markup. My thought was to simply check which region the block was being rendered in, and use if statements to modify the classes/structure as needed.

I've hit a roadblock; I was able to find a way to get what region a block is in, but I can't figure out how to pass that data to the menu. Here's my current code:

// Add a region variable to a block.
function theme_preprocess_block(&$variables, $hook) {
    $block_id = $variables["elements"]["#id"];
    $block = \Drupal\block\Entity\Block::load($block_id);
    $variables["region"] = $block->getRegion();
}

I can output the region variable just fine in block--system-menu-block.html.twig, but trying the variable doesn't get passed to menu.html.twig, which is where I need it.

I feel like I'm a stones through form an answer for this, if someone could point me in the right direction I'd be greatly appreciative.

Quick side note: I'm very new to Drupal, coming from WordPress development. So far it's been a difficult transition, so please assume I know nothing about themeing :)

Figured this out with the help of an article!

http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion

// Add a region variable to a block.
// http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion
function THEMENAME_preprocess_block(&$variables) {
    if (isset($variables["elements"]["#id"])) {
        $block_id = $variables["elements"]["#id"];
        $block = \Drupal\block\Entity\Block::load($block_id);

        if ($block) {
            $variables["content"]["#attributes"]["region"] = $block->getRegion();
        }
    }
}

// add a template suggestion based on region name
// http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion
function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
    if (isset($variables["attributes"]["region"])) {
        $suggestions[] = $variables["theme_hook_original"] . "__" . $variables["attributes"]["region"];
    }
}

That doesn't do exactly what I was trying for, but it does let me use different templates based on which region a block is being rendered in. Close enough for me :)


Can i create custom content type without define .yml file in module? Sorry for my bad english grammar.
I write a module, allows the user to upload a file that contain list of content types infomation. Then my module will auto create content type for user.
But i don't know how to create content type without hard define many .yml file.

If your content type is fairly straight forward (i.e. using only Drupal's fields), you can create the content type within the http://localhost/admin/structure/types/add link and once you have it built the way you want it you can export it via: http://localhost/admin/config/development/configuration/single/export.

It will even give you the name of yaml file to boot!

If that avenue is not sufficient then you can follow: This tutorial about building custom drupal content entities; it is lengthy in nature, which is why I will elide the details.

And if you're going to use that tutorial, then I would suggest using drupal console to generate the boilerplate code for you.  It makes things quite simple.  Drupal Console, among other things, manages the generation of content entity boilerplate code.  It is quite helpful.


Limit currency for one product in Drupal Commerce I have enabled two currencies for price in Drupal commerce but I want to enable only one of them for one of products. At this moment I can see both of them in product creation time. Where or how can I set this?

I'm afraid there's no custom module for this, you'll need to alter the product form add/create to adapt to your settings/conditions (simplified logic below):

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_commerce_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  // Calculate the currency for a given product.
  $currency_code = 'USD';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#type'] = 'value';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#default_value'] = $currency_code;
  $form['commerce_price'][LANGUAGE_NONE][0]['amount']['#field_suffix'] = $currency_code;
}

A more complex and customizable option would be to use hook_field_widget_info_alter and modify the settings form to add whatever conditions you want for selecting a currency on a product form.


Export/Import Content Types/Contents to another Drupal site (version 6) I'm looking for something to help me to export my content types / contents i have locally in a drupal project. i need to use it in another Drupal project.

I just stumbled upon the Bundle copy module but it is only available for Drupal 7 and my project is version 6.26 - I can't update my core unfortunately for various reasons.

is there something similar working for version 6 please?
Thanks in advance

For content types, views and much more you can use features, while for the nodes, node_export will do the job.


How can I get exposed filter for content type from the view programmatically? I want to customize an exposed filter for content types, how can I get the exposed filter for a view in the code? And to know exactly which content types need to be dispalyed?

$route = explode('.', \Drupal::routeMatch()->getRouteName());
if (!empty($route) && $route[0] == 'view') {

  if ($view = Views::getView($route[1])) {
       $filters = $view->getHandlers('filter');

  }
}

It might be easier to get the display settings from the View storage (the configuration of the view):

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_1');
$display['display_options']['filters']['nid']['value']['value'] = 123;
$storage->save();

Here you should be able to find all options configured in the Views UI.


View modes are stuck on default view I had my site for quite some time and just started to use the display suite view modes feature for changing the displays per node. I made new view modes and tried to change them for my nodes, but it seems that its just stuck on "default" view mode which is the full content view. I currently on display suite 7.1.x and updated to the latest as of Jan-2015 and it still does the same thing. Any hints would be great.

This seems to be an ongoing issue as there are reports of other modules conflicting with the display suite view modes feature. For some it had to do with Panels as seen here:

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

  Posted by drupalstrap on February 17, 2013 at 5:57am Greetings,

  The only view mode i am able to use is the default view mode. As long
  as I am using the default view mode, I can switch layouts without any
  problem. If I try to switch to another view mode, it still uses the
  settings of the default view mode. I have tried every way of
  troubleshooting that I can think of including changing themes,
  altering CSS files and tpl.php files etc in order to try to isolate
  the problem. Furthermore, i am not able to apply wrapper or class
  styles via the UI settings. They don't appear in the source code.

  Anyway, I have been battling this for two days now and figured I would
  see if anybody out there has any suggestions. On the server side, I am
  using php 5.3 with apc. I have tried clearing cache hundreds of times
  as well as restarting the server to see if there was something in
  memory that was stuck. I have also tried other browsers so it is
  something related to my development environment I guess. LAMP???
  Please help. Thanks.

  Upload new files Comments  billsdesk’s picture Comment #1billsdesk
  commented 2 years ago I am having the same problem. I created a view
  mode and set it as the view mode to use when I edited the page. Yet,
  the Full Content mode is always used, and not the specified view mode.
  The Manage Display tab always opens the correct view mode. I turned on
  the view mode switcher, and it correctly identifies that the page
  opened in the full content mode. However, it does allow switching to
  the correct mode. I checked the permissions, and all is good. No error
  messages. I am using Drupal 7.22, and Display Suite 7-2.3. report spam
  on user billsdesk  alunyov’s picture Comment #2alunyov commented about
  a year ago Hello, I had same problem. In my case switching off panel
  for node view helped to solve the issue. I think it is something
  related with page manager. If you check settings page:
  admin/structure/ds/list/extras -> Other -> "View mode per node"
  option, in description you will find "Change view modes for individual
  nodes. A new tab 'Display settings' will appear on the content create
  form. You can also pass the name of a view mode through the URL, eg
  node/x?v=full. If you install the Page manager module and override the
  node view, Page manager will win."

  Added: check _ds_extras_menu_alter() in ds_extras.registry.inc. it
  explains a lot report spam on user alunyov  aspilicious’s picture
  Comment #3aspilicious commented about a year ago Status:  Active  »
  Closed (works as designed) Closing this works as designed. If you
  still have this issue and you DON'T have page manager enabled please
  reopen this one. report spam on user aspilicious  Geijutsuka’s picture
  Comment #4Geijutsuka commented about a year ago I'm having this
  problem on a new site I've been developing... The strange thing is
  that it's only happened within the last couple weeks. Something
  triggered this behavior, but I'm not sure what yet (trying to figure
  out STR).

  I set up a brand-new sandbox site with everything up-to-date and it
  seems to work as designed... flawless. I also don't have Page Manager
  or Panels installed, and I definitely don't want to have to resort to
  changing the view mode for every single piece of content. I'm going to
  update the problematic site (ds is up to date, but there are a lot of
  other updates) and see if that fixes it... if not, I'll be back.

In my case it wasn't panels that was causing the issue but it was due to the "revisioning" module that cause the view mode to get stuck on default. There has also been reports here:

https://www.drupal.org/node/2304917#comment-9550067

I updated to the latest revisioning v7.1.9 and it still causes issues with the view mode. The only option is to turn this off if revisioning is really not necessary.


How do I remove the inserted a span tag in an href parameter when using Full Calendar and Devel Themer When devel_themer is active inside of a Fullcalendar formated View, links contain the span tag. See below in the href parameter. This however does go away when I disable devel_themer and clear cache.

11:15

You can see in the status (bottom left) that the span tag (with devel_themer generated classes) is in the link.

This is what the Views Format Settings look like

And the general Views Admin

How might I fix this?

There are a lot of little bugs with devel themer. I would just throw a little jquery in one of the js files in the devel_themer module directory to hide any spans in that  tag

    $(document).ready(function() {
$('#divnamecontainer a span').remove();
});


Use Views or Write Raw Query? I've run across an interesting topic through my work during the past few months. I use the views module heavily in Drupal projects, but I find Views to be painfully annoying in terms of its speed and how it generates all this extra markup (even using style_plugin->rendered_fields).

I decided one day to ditch Views for a project and write a raw query using Drupal's PDO layer instead. I feel using the PDO layer (despite the fact that it might not be perfect) gave me the ability to grab only the data that I needed in an efficient query.

I brought up to a coworker, "Why don't we just write raw queries...? Views is obviously not integrated into core yet for a reason..." Their response was that Views are easier for beginners and are generally easier to use and to understand. I agree that's a fair point, but what about the performance differences? Don't the performance differences (if there are even any, I might just be configuring things incorrectly) outweigh the usability of the package?

My question is, is there really a big performance hit with Views? Does it make efficient queries, or does it run node_load for each row? I'd also like to know if there's a reason that Views hasn't been included in core yet.

Is Views better than writing queries using the PDO layer, or is it just a matter of personal preference? What about when working with teams?

Here is my take on it

Views

First and most basic advantage is it has a UI which makes it easier for beginners and people with not much knowledge php of to fetch data and display it just with a few clicks.
You can apply filters and relationships to make any kind of joins and filtration of data just with a few clicks.
It provides easy access to exposed filters which allows you do do sorting of data.
It has ajax support.
It has a built in cache mechanism to cache data.
You can AND or OR your data just by drag and drop.
It has support to display the data in various formats like grid, table etc which are available just at a click.

These are just a few points. Now if you try and compare these points to writing a PDO query then yes PDO is definitely fast but you forget after getting the data you also have to do the processing to display the data. Now if you try and do the above mentioned points in a custom module I am pretty sure you will run over a 500 lines of code to implement most of the features.Also don't forget the custom code which needs to be maintained.

If you want to compare views to a PDO check the views query time and the PDO query time it will not be a major difference. Views takes time to do all the rest of the fancy stuff you need to process sanitize your data and display your data in the format of your choice which takes time.

If you are comfortable with PDO I would definitely recommend you to go ahead and use it. The adv are you are using a core feature, 1 less module to me loaded so less http request to load the js and css files.

UPDATE: 10/03/2012
Also came across this node on drupal.org: http://drupal.org/node/242311


Edit Unit Price line item After Adding product to the cart I am working with Drupal Commerce.

How I could edit the Unit Price of all Commerce Line Items to $200 when "Add a Product to Cart" Event is fired. !

this rule update unit price Unit Price of all Commerce Line Items to $200 when "Add a Product to Cart" Event is fired.

{ "rules_set_unit_price" : {
"LABEL" : "Set Unit Price",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
  { "data_set" : {
      "data" : [ "commerce-line-item:commerce-unit-price" ],
      "value" : { "value" : { "amount" : 20000, "currency_code" : "USD" } }
    }
   }
  ]
 }
}


Get all Taxonomy Terms I have added a vocabulary as Sites with machine name as sites. I have added two custom fields in this vocabulary as :

1) URL
2) Status 0 or 1

I need to make a dropdown of all terms with status 1 something like.

  get term.name from term join vocabulary on vid where vocabulary.machine_name = sites and term.status = 1

$v =  taxonomy_vocabulary_machine_name_load('sites');

$t = taxonomy_get_tree($v->vid);

How do I get an array of enabled terms in the 'sites' vocabulary?

Yes, entity_load can be used, but you have to retrieve entity ids yourself:

$terms = array();

$v = taxonomy_vocabulary_machine_name_load('sites');
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $v->vid)
  ->fieldCondition('field_status', 'value', 1) // If your field name is 'field_status'
  ->execute();

if (!empty($result['taxonomy_term'])) {
  $terms = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
}

// dpm($terms);


How to force absolute links on a menu tree in Drupal 7 What I have

I currently have a menu with subitems printed out in my page.tpl like this:

in template.php

   function THEMENAME_preprocess_page(&$vars, $hook) {

       $sitemap_tree = menu_tree_all_data('menu-sitemap');
       $vars['sitemap_expanded'] = menu_tree_output(i18n_menu_localize_tree($sitemap_tree));

}

then in page.tpl.php I have

     print render($sitemap_expanded);

What I want

While this prints out the entire menu tree perfectly I need the links to be absolute in stead of relative (what they are now).
Any way of doing this in a Drupal fashion without too much extra lines ?

Thanx all.

What you probably want to do is theme the menu links differently for this menu.  In D7, you would  be overriding this function:

/**
 * Returns HTML for a menu link and submenu.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: Structured array data for a menu link.
 *
 * @ingroup themeable
 */
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

In menu_tree_output(), it also sets up per menu theme overrides, so, in your template.php file, you could create your own YOURTHEME_menu_link__MENU_NAME() function.  On first flush, it could look something like this:

function YOURTHEME_menu_link__menu_sitemap(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], array_merge($element['#localized_options'], array('absolute' => TRUE)));
  return '
' . $output . $sub_menu . "
\n";
}

but this is an intellectual exercise for me, not a real world one, since I don't have a D7 sandbox to test it out in but it looks pretty accurate, or at least a starting point.


How can i display view specific content type based on dynamic term name in node page? Hi i have a content type called "Resource" with 2 term reference fields, branches (A,B,C,D) other one is  resource category (rec cat 1,rec cat 2) ,and i have created view called branches list displayed all branches like below in one node page.

A
B
C
D

and i have created another view called resources list it contains info based on resource category term reference it's ok but i need to display this view items based dynamic branch term name in my node page like when i click A need to display related branch info in my node page.

Please Advice.

The resource list view should accept the branch as contextual filter. Have a look here: Views contextual filters taxonomy name

Maybe also consider using quicktabs for showing these views.


How to let users change their own profiles? I have a site running Drupal 7.9 and users can register for their own account. Some of the fields they have to input can change over time (email adress and phone number(s)). Is there any way for me to make it so the user can change his/her own email address and phone numbers?

The only thing I could find in the documentation (and controlpanel) was how to enable users to change their own username, which gets me sort-of there but not quite.

Also, I tried googling this for the longest time but I couldn't find anything. Maybe my search terms were wrong?

Any help would be greatly appreciated!

By default, users can change their own profile information, including their email address, and excluding the username. To change the username, the user must have special permissions. To change the profile informations, go to example.com/user in your website, then click the "Edit" button.


Delete all users and there content apart from user 1 I have been asked to help look after a Drupal site that was created by a third party. This site has lots of users (~13,000) and for each user lots of items of content was created.

I want to clean the database from users and content to improve performance. When a user try to log into the site via an ID a user account is created, a web service is called and the correct content is recreated. My next job is to create some cron tasks to keep the data controllable going forward.

I want a way to delete all the users apart from user id 1. I looked at VBO but every now and again it will stop running and I have to start again (it has never completed).

I have created a drush command which calls the following:

function delete_users_batch_delete() {
  drush_print('Deleting Users');
  $uids = delete_users_get_uids();
  $count = count($uids);

  $temp = 0;
  foreach ($uids as $uid) {
    $temp++;
    user_delete($uid);
    if ($temp % 25 == 0) {
      drush_print('deleted ' . $temp . ' from ' . $count);
    }
  }
  drush_print('All users deleted');
}

function delete_users_get_uids() {
  $result = db_query('SELECT u.uid FROM {users} u WHERE u.uid > 1');
  $uids = $result->fetchCol();
  return $uids;
}

However this is running very slow on my local machine. What would be the best way to delete everything quickly.

If I had started the project myself I would just run my install script which would set up a new instance of the site with it configured correctly. Sadly I don't have this and just one big database dump.

You can use Views Bulk Operations (VBO) module...

Above module allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.

There is a setting in the View's VBO options to enable a select all button that select all items across all users and unselect admin.


Flag module: Do not allow users to flag own content I am using Flag 7.x-3.0 to enable users to flag file entities. I only want users to be able to flag files that other users have uploaded. However, I am missing the checkbox option "allow users to flag own content" that I remember having been a part of earlier versions of Flag module.

Has this feature been removed?

This is a specific use-case so it may be better to approach this using the Flag API. Specifically, try hook_flag_access and add this to your custom module (or create one). This function takes the following parameters:

hook_flag_access($flag, $entity_id, $action, $account)

and what you are specifically interested in is the following:

$entity_id: The id of the entity in question.

$account: The user on whose behalf to test the flagging action.

The $entity_id will allow you to determine what user id created the entity and the account object will already contain the account of the current user so this function will block flag display if they are the same:

function YOUR_MODULE_flag_access($flag, $entity_id, $action, $account) {

  //load data for the entity
  $entity = entity_load($entity_type, array($entity_id));

  // if the account that created the entity is the same as the user attempting to flag it then block access
  if ($entity[$entity_id]->uid == $account->uid) {
    return false;
  }

}


Login box on one site to log you into another site too My client has a drupal 6 site. This is used with there clients to project manage projects. We are building a new main website for our client using drupal (6/7 yet to be decided). They wish to have a login box on the home page of there new website that will log you into the project manage site. So something like:

Go to main website
Enter user name and password for project site
Website changes to project site with user logged in.

Would this be possible? The user would not have a login on the main site.

Both sites would be running on the same machine. Part of me is thinking that maybe multi-site could be my answer.

Sure it's possible. There are many ways to do this.

A simple solution, if both sites are running the same drupal version, would be to make a custom form, and connect to the other sites database, and get the login form. You would need to make sure that the submit path would go to the project manage site.

When the form is submitted, they would automatically go the that site, and if user/pass is correct, they would also be logged in.

Disclaimer: I haven't actually tried this before, but it should work just fine. Drupal wont know where the form was submitted, so should be the same as being on their project site and using the login form.


Use a class on a DIV on specific content with Omega I'm using Drupal 7 and my theme is Omega. I have got a class "mask" and its CSS code is like so:

.mask {
    background:url("../img/header_mask.png") repeat-x scroll 0 0 transparent;
    height:200px;
    position:absolute;
    top:0;
    width:100%!important;
    z-index:101
}

I'm creating a class on Omega theme options to show content top, but my div shows on every page. So, I want show this class only on node pages.

This is my node.tpl.php:
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $user_picture; ?>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>

      <?php print $submitted; ?>

  <?php endif; ?>

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

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

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

Where should I add my "mask" class in this code?

You don't mention if it's a particular node TYPE that you're after.  If it is, then please clarify that.  You also don't say what the .mask div actually contains, so I'm going to assume it contains nothing and the content is the background image.  If this is the case then you can just put

 anywhere.  The position: absolute should mean that it won't dislodge any other content anyway.

I'm also not sure why you need !important after width.  If this class is something you're declaring then it shouldn't get overriden unless YOU want it to.  If you're worried about it then I'd namespace the class instead (ie .mytheme-mask).

EDIT

Put it anywhere, but write it like this:

<?php if (!drupal_is_front_page() && !$teaser) { ?>

<?php };?>

This means that if the page is a content page (not the front page) and not a teaser then place your div in the node.


radios options separated into different wrappers I'm trying to customize a radios field to wrap some of the options into a div.

What the best way to do it?

I had a look to theme_radio but no success on it :(
example:

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

    <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
    MY LABEL

ANSWER:

See Djouuuuh answers +

$output .= drupal_render($element['element'][$i]);

if you do this one below it won't work with ajax...

$output .= theme('radio', $element['element'][$i]);

In my opinion you can achieve that with a theme function, specified like this:

$element['example'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Example checkboxes'),
  '#options' => $options,
  '#theme' => array('custom_options'),
);

And then, you can write down the output just as you want here:

function theme_custom_options($element) {
  $output = '
';
  $output .= $element['#options'][0];
  $output .= $element['#options'][1];
  $output .= '

';
  $output .= $element['#options'][2];
  $output .= $element['#options'][3];
  $output .= '
';
  // ETC...
  return $output;
}

Does it seem correct?


Customizing the way the form is displayed to admin user I am developing a module which requires an administrator form.The admin will enter some settings data which will be saved in database.Then i will use these settings to display information to the website users depending on the settings chosen by admin.

So for administrator screen i need the form to be displayed like this

HEADING_ONE    HEADING_TWO     HEADING_THREE     HEADING_FOUR
TEXTFIELD_ONE  TEXTFIELD_TWO   TEXTFIELD_THREE     TEXTFIELD_FOUR

I need to have a table like structure. How can this be done?

You can make use of system_settings_form to make admin form and theme_table to make a table output.


Rendering Content Multiple Times in a Node I'm starting to dig deeper into themeing and I'm thinking maybe I'm misunderstanding something.

Basically I want to break apart the way the content is laid out in my node--example.tlp.php file.

I've started doing that with some simple render statements like  print render($content['group_factory_images']);

I started running into trouble when I wanted to pull the label off of the normally rendered flow and place them somewhere else with something like print render($content['group_factory_images']['label');

This wasn't working so I started to try and pull other items in, to see if it was a syntax issue or something else.

I came away with 2 questions: What is the right syntax to get labels rendered in a node?

And then; Can you only render a piece on content once? For example could I do something like rendering the body twice in the same node? (not that I would want to, but it illustrates the point I think:

print render($content['body']);

// other items rendered

print render($content['body']);

The display of a label is handled by the Field and not the template. The HTML for the field is passed to the template layer from the field API and the label HTML is lumped in with the field information itself. So basically you cannot alter or move the printing of the label in the template layer of theming. Consider the field data and the field label as one item in templating (i.e. $content['field_name'] contains the field data and label as one. Altering the label display (display label or not, inline, etc.) is done in the field display settings for the content type. The only way to alter the label is to do so at the field display level and again it is passed to the template with the field data as a final product.

Rendering content more than once, yes it can be done.


Working with operators when manually specifying options for a custom views exposed filter I am trying to build a custom exposed filter for a field using the Countries module.

Instead of listing all 200+ countries in the world, I want to list only three options Japan, Not Japan, and All (the site obviously has a Japan focus).

The sample code in this question is:

class views_handler_filter_MYMODULE_country extends views_handler_filter_in_operator {

  /**
  * Get value options for the select list.
  */
  function get_value_options() {
    // Replace $this->value_options with an appropriately filtered list.
    $this->value_options = function_to_build_filtered_list();
  }

}

The countries module stores countries as two-character ISO codes.  Japan is JP.  So I tried doing this:

    // Replace $this->value_options with an appropriately filtered list.

    $options = array();

    $options = array('jp' => t('Japan'));
    $options = array('us' => t('USA'));

    $this->value_options = $options;
  }

However, this code results in an error.  Additionally, I don't know how to specify the operator, and when I think about it, I'm not sure how to handle the operator conceptually, either.

The logic should be this: either JP or NOT-JP.  However, as I understand it, Views does not provide per-item operators; the operator is applied to the whole handler.  "Is one of..."  "Is not one of..." etc.

So, to do Japan or Not Japan, should I list JP for Japan and then all other possible values for all other countries for Not Japan?  (That wouldn't take too long, I'm just scared of missing one.)  Or is there some better way?

I'd appreciate any insight into how Views operators work and what approach I should take to building such a list.

This doesn't answer your question exactly but gives an alternative.

Views exposed filters have a grouping functionality that can be used to create predefined value/operator pairs, so you can configure it to give options like Japan & not Japan without actually giving the user the ability to select the operator.

Much nicer for the user.

See the attached screenshot as an example of a possible solution to your problem that requires no custom code (note I am guessing that JP is the correct value in this case).

There are a couple of things to be aware of:

There is a bug where if you use is empty or is not empty you still have to enter a value, even though it is never used. See https://drupal.org/node/1818176
You might get undesirable results if not all your content has country data. The reason is that if a field doesn't have data it is NULL and in views/sql you need 2 separate operators to match not a string vs not null. The grouping in views doesnt' let you select multiple operators so you cant have both "is not Japan" OR "is null". If your country data is a required field you have no problem here. - It's possible in this case you could alter the views query if "Not Japan" is selected and add in the "OR country IS NULL". You should be able to do that in hook_views_query_alter() and it still should be simpler than your current approach.

Note: I opened an issue for Add new filter operator "Is not equal to OR is empty"


Enable / Disable comment form in a module? I would like to set a given node's comment flag to 1 or 2 (to either show or hide the comment form) via my custom module, depending on certain conditions.

I have tried using hook_node_view, but this approach seems not to have worked:

function custom_node_view($node, $view_mode, $langcode) {
  $node->comment = 1;
}

Even if I explicitly set the comment flag to 1, it will remain 2 for a given node. If I dpm($node); just after setting the flag, the correct value will show in the devel information, but the comment form will still show...

According to comment.module, the values are such:

/**
 * Comments for this node are closed.
 */
define('COMMENT_NODE_CLOSED', 1);

/**
 * Comments for this node are open.
 */
define('COMMENT_NODE_OPEN', 2);

Is there a different hook I should be using to show/hide the comment form programmatically?

It looks like I can set the comment display correctly within hook_node_load(). I guess that runs a bit earlier in the process, and tells comment.module to not display the form for a given node.

Here's an example of what I ended up implementing:

<?php
/**
 * Implements hook_node_load().
 */
function custom_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->comment = COMMENT_NODE_CLOSED; // to close comments
  }
}
?>


Use Case : Registration of a Team for some event Here is my use case:

  The users can register for the website and then form TEAMS. One of the
  users would be the TEAM LEADER. The team leader can register for
  various events for his/her team(s). When the team leader registers
  his/her team, all the TEAM MEMBERS automatically get registered.

Now, how to implement the above functionality? That is:

How do I implement the formation of teams?
How do I implement the registration of the whole team entity for some event?

How is event registration handled?

For events, I have a content-type event. The registration for event can be done using two approaches. Either using flag module, or making a registration content type and using references (and nodereference-url) module. I haven't finalized on the approach yet.

Furthermore, I'm thinking of using OG module for team formation, but I'd like to avoid that as it'd be an overkill.

Kindly suggest approaches for my use case.

Thank you in advance.

What you just described can indeed be implemented in various ways but it really depends on how you have architectured your website. Here is how to do it using relation angway:
Use relation module
After installing relation, Create a relation type and name it something like is member of and it's reverse has member. The relation will be from user2user and with arity of 2.
I wouldn't suggest using any other configuration, such as using a single relation from leader to all members. Later it will cause you more pain.

The Membership
I don't know. How does your website work? how does one request to be member of a group? many of these concerns are addressed by OG already.

The registration workflow
Create another relationship registered at relation, from user to the entity type representing the event (the node if it is a node). Use the module rules_link or rules_pane. Create a rules component: register at event that takes two arguments: event node and registering user.
In this component you have to add:

Action: Create a list of any entity type.

name it rel_list.

Action: Add an item to list.

list:rel_list
item:node_event from component arg.

Action: Add an item to list

list:rel_list
item:registering_user from component arg.

Action: Create an entity

of_type:relation
of_bundle:registered_at

From your rules_link or rules_pane call this component and feed it current user and the corresponding node. The created relation entity is an indicator of membership, for leader only!

Add another component: Fetch team members, it's arg: leader user, it will provide: list of users->members. write a custom rule fetch team members and query all members using EntityFieldQuery or use the module efq_rules to fetch team members. for each queried user, use the above component to create the relation.

you definitely want to have rules_conditional installed.
Central Place for storing memberships.
Instead of a direct relationship from leader to team members you might want to have a node representing the team and create relations from this node to users. this way if you needed to change the leader it can be easily done with removing the is leader of relation and creating a new one to the new leader. But then, having this central entity, why not make it an organic group?
I usually choose relation when I need a fine grained control over memberships.


Why is form api ignoring the weight that i'm giving to the action buttons? (node edit page) So, I've implemented hook_form_alter in a custom module. I have added a button to the node edit form of a specific content type.

However, I can't for the life of me get the new button to display with the standard buttons ie save & preview. It just appears at the top of the page, regardless of the figure that i put in as the weight (I tried 100000000000000)...  Fingers crossed that this is just a 'newbie' oversight :)

Here is the code that I'm using:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'CONTENTTYPE_node_form') {
    // Add validation for a file
        $form['field_CUSTOMFILE'][0]['#upload_validators']['custom_file_validation'] = array();

    // Add update site button to CONTENTYPE node add/edit form
         $form['actions']['update_site'] = array(
            '#type' => 'submit',
            '#value' => 'Update site',
            '#name' => 'op',
            '#submit' => array('MYMODULE_form_submit'), /* NEED this */
            '#weight' => 99,
            );
         $form['actions']['submit']['#weight'] = 101;
         $form['actions']['preview']['#weight'] = 100;

        return $form;

  }

}

These lines from above were only added today but made no difference...

$form['actions']['submit']['#weight'] = 101;
$form['actions']['preview']['#weight'] = 100;

As always, anyway pointers would be very much appreciated :)

Edit:

This question was not answered in the indicated "This question has already a answer" link above... That link explains Drupal 7 specific code, although the post isn't tagged as such... This post was specific to Drupal 6 as tagged... In fact the code in this post didn't work for me because it was using Drupal 7 code :)

I added a cancel button to some Drupal 6 node forms in this fashion:

  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#weight' => 7,
    '#submit' => array('MYMODULE_node_form_cancel_submit'),
  );

so I'd suggest changing 'actions' to 'buttons' and see if it works equally well for you.


Magazine auto-publish by date & month I am developing a complex website which will serve as an online magazine.

I am currently experimenting with the Book module and organizing my content in months but I am not sure it is a long term solution.

I am trying to achieve a setup which at midnight of February 28th will automatically publish all content associated will the new month of March and un-publish content for the previous month.

I would greatly appreciate any suggestions to achieve this.

You can use cron to achieve this,

Use hook cron in your custom module and write the codes to publish and unpublish based on your conditions
You can use Elysia Cron to schedule this cron job to run in every month or every first day of a month. Or you can configure cron in your server to set exact timings.


Overriding Panels' default category structure The development house I work at uses Panels for stuff a lot, and they're a central design tool for our clients. While we're able to group our own Panels content types and View Panes by specifying a category name, it isn't so easy for everything else: there's the useless content types in the "Activity" category, the confusing content types in "Entity", the overwhelming and mostly-useless content types in "Node (Tokens)", the really useless content types in "Page elements" (Why would I need to repeat design elements already in place on the page?)... I could go on.

Plus random blocks are always dropped in the "Miscellaneous" category -- seemingly the last place I always look for content types I cannot find.

What I really need is the ability to organize Panels content types, and hide categories that aren't needed.

To that end I've started work on a module that lets the use build and organize Panels content types into custom categories. However, the first major roadblock I've run into is convincing Panels to use my layout instead of the one it generates from the plugin info hooks.

In panels/includes/add-content.inc is template_preprocess_panels_add_content_modal(), which is where Panels seems to set up its category tree (Via the function's $vars argument).

Is there any way of inserting a hook into the function chain that
discards the $var variable that Panels is passing to
template_preprocess_panels_add_content_modal() and instead
delivers my own?
If not, is there a way to override template_preprocess_panels_add_content_modal() with my own
version?
Or, best yet, is there a module somewhere that already does what I'm trying to do?

Many thanks!

"Whaddayamean you can override functions starting with 'template' like you can functions starting with 'hook'?" I ask...

I've finished my organizer and will post it as a sandbox module if my boss lets me. I ultimately just copied the source of template_preprocess_panels_add_content_modal() from panels/includes/add-content.inc and changed what was passed on -- $vars['categories'], $vars['categories_array'] and $vars['root_content'] were particularly important.

Surprised nobody answered this -- would've been an easy 10 points to just say "Yeah, template_preprocess functions work a bit like hooks in that you can insert your own version higher up the chain just by naming it a certain way..."


Add pagination to the results in custom module after split the row to many sub rows I try to build new module (Drupal 7), in some page I show the results to the user as a table like the following:

<?php
    $header = 'bla bla bla'; //header come here
    $query = db_select('myTable', 't')
        ->fields('t', array('field_1', 'start_date', 'end_date', 'due_date'))
        ->extend('TableSort')
        ->extend('PagerDefault');

    $result = $query
        ->limit(10)
        ->orderBy('t.startdate')
        ->execute();

    foreach ($result as $row) {
        $rows[] = array('data' => (array) $row);
    }

    $form['tablesort_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('Sorry, there is no results to show'),
    );
?>

and this of course works perfectly (each page has 10 rows), but for some reasons I have to split each row to multi sub row according to the start date and end date like the followin

foreach ($result as $row) {
    $timeInLoop = $row->start_date;
    while($timeInLoop < $row->end_date){
        //split the row to multi row (one week for each row)
        $timeInLoop = strtotime(date("Y-m-d", $timeInLoop) . " +1 week");
        $row->due_date = date("Y-m-d", $timeInLoop);
        $rows[] = array('data' => (array) $row);
    }
}

and here is my problem:
if some row has 10 weeks and other row has 2 weeks the total rows in the page will be more than 10 rows
how can I make them 10 rows in each page ???
thank you for your help

I find the solution here

$limit = 10;
$rows = pager_array_splice($rows, $limit);
$form['tablesort_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Sorry, there is no results to show'),
);

function pager_array_splice($data, $limit = 10, $element = 0) {
    global $pager_page_array, $pager_total, $pager_total_items;
    $page = isset($_GET['page']) ? $_GET['page'] : '';
    // Convert comma-separated $page to an array, used by other functions.
    $pager_page_array = explode(',', $page);
    // We calculate the total of pages as ceil(items / limit).
    $pager_total_items[$element] = count($data);
    $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
    $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
    return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}


Theme and Override Privatemsg messages/view/%thread I've managed to embed all the other pages within Panels as per the D7 Panels/Privatemsg patch, and the only remaining page is the /messages/view/%thread pages. After scouring the Privatemsg API documentation and the internet, I still cannot figure out how to manually present this view or how to embed it in another location either with the API or with regular Drupal theme .tpl.php overrides.

I need to get a sidebar on the /messages/view/* pages, preferably using panels.

  Is there a function call to produce or print the entire thread list/reply form?
  Do I have to break the reply form apart from the thread list?
  After obtaining the thread list using `privatemsg_thread_load()`, is it possible to pass the data back into the overridden privatemsg-view.tpl.php file?

Any and all thoughts or hints are welcome... thanks guys.

Take a look at privatemsg-view.tpl.php.

There is a preprocess hook where you may add theming variables to the privatemsg-view.tpl.php and execute any PHP code there. In my case it was:

<?
function MYTHEME_preprocess_privatemsg_view(&$vars) {
  $vars['author_uid'] = $vars['message']->author->uid;
  $vars['realname']= MYMODULE_get_realname($vars['message']->author);
}
?>

So here are some alternatives to populate the sidebar:

Use this PHP code to trigger a drupal context which will show a block on the sidebar
Programtically create other vars like the ones above. Those vars may contain sidebar data  you can use when theming the TPL file which contains the sidebar.

Also, here is a full privatemsg theming guide.


Why is my rule that reacts on event "After updating an existing user account" firing twice? I have a rule that e-mails me if a user updates a value of a field on their profile (this value is the name that is displayed for that user on the site; I e-mail changes to the names to make sure no one changes their name to something insulting, etc.)

However, the rule fires twice for a reason I don't understand.

The rule has a condition compare data value in which it checks to see if the account-unchanged and account variables have different values for the same field.  When I look at the rules debug log, I see that during Reacting on event 'After updating an existing user account', there is a second Reacting on event 'After updating an existing user account' within the first, and so the rule gets triggered twice.  How can I prevent this from happening?

If it helps, here is the rule:

{ "rules_notify_if_user_changes_name" : {
    "LABEL" : "Notify if user changes name",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-acc-displayname" ],
          "value" : [ "account:field-acc-displayname" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "myemail@myemail.com",
          "subject" : "[account-unchanged:field-acc-displayname] changed name to [account:field-acc-displayname] (UID: [account:uid])",
          "message" : "[account-unchanged:field-acc-displayname] changed name to [account:field-acc-displayname] (UID: [account:uid])",
          "language" : [ "" ]
        }
      }
    ]
  }
}

It sounds like some other module code is calling a user_save on hook_user_update triggering the rules event a second time.


Redirect comment permalink to their corresponding node paths Is there any way in drupal to  redirect comment permalink to their corresponding node paths or url alias?

I want to redirect all comment/x paths to their corresponding node-path. And it should handle pagers as well. If your comment is in the second page (when you have set a comments-per-page value in node type settings), it should be like

http://example.com/comment/111 to http://example.com/node/123?page=1#comment-111

http://example.com/comment/111 to http://example.com/node/123#comment-111
http://example.com/comment/112 to http://example.com/node/123#comment-112

Thanks in Advance!

I managed to acheive it through hook_menu_alter. It just works great for me

<?php
/**
* Implements hook_menu_alter.
* @author Md Eqbal Ahmad <*****@******.com>
*/
function MODULE_menu_alter(&$items) {
  $items['comment/%']['page callback'] = 'MODULE_commentpermalink';
}

/**
 * Redirect comment permalink to their corresponding node paths
 * @author Md Eqbal Ahmad <*****@*****.com>
*/
function MODULE_commentpermalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
    if ($page > 0) {
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
    }
    else{
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
    }
  }
  drupal_not_found();
}

?>


How do I translate to English? I have a Drupal 8 multilingual site (Spanish [default], English, Italian and Ukranian).

On admin/config/regional/translate I can translate to Spanish, Italian and Ukranian but not to English.

How can I translate strings to English with this UI?

By default, if you have English configured, it is not available as a translation target. However, you are only one checkbox away from enabling that feature:

Go edit English and make it available for translation. This will make English behave as any other language and from then on, you can "translate" to English as well:

All strings will still fall back on the built-in English text (eg. if you also have Hungarian on the site, untranslated strings in Hungarian will fall back on Drupal built-in English text). However when English is used for display, all your overrides will be effective. (Cross-language fallbacks can be implemented in contributed modules now with Drupal 8's service architecture for string lookups).

Source: http://hojtsy.hu/blog/2013-aug-20/drupal-8-multilingual-tidbits-12-english-can-now-be-translated

Result:


How to validate numbers in a webform custom composite element I have a Webform with a custom composite, and there I have a element which type is Number and i want to validate this element.

If I check required when the field is empty it show a message that the field is required, but if I put letters in the field show the same message when it should be that the field is not valid because it has letters.

I know how to do this with a textfield element but this element is not inside the custom composite with a regular expression . And even if i change the custom composite element from Number to Textfield I can not do it this, can not be validated individually.

Instead of putting validations just create a number type field. And inside the number field of the custom composite element, you can not enter the letters, only numbers can be entered so no concept/need for validating against letters.