Special Character Encoding Issues in Node Titles I work in an IT department at a museum whose website is built on Drupal. I have experience with other CMSs, but I've only worked with Drupal a little bit. So far, I've been able to help them fix quite a few bugs with their site, but I can't find any information on how to resolve this particular one.
On any content type, if the Title field has a special character it displays the character correctly on the site, but if it's linked to on Facebook and it pulls the title, it ends up showing the entity number instead.

An example:

Science Movie Night: The Shaman's Apprentice

becomes

Science Movie Night: The Shaman&#039;s Apprentice

I've searched around, but I haven't found anything talking about how to combat this.

I just checked with Drupal 7, and it will replace Unicode Character 'APOSTROPHE' with its NCR equivalent (&#39;) in headings.  This is not a bug, but a security measure.

Apperently, when FaceBook receives this, it changes it to &amp;#39, with the result you observe.  IMHO, this is a bug in how Facebook treats incoming NCRs, and has nothing to do with Drupal.  (It is not a good idea for Drupal to have plain apostrophes in headings.)  You may want to report this bug to Facebook, but it will probably not be their top priority.

You may also add a feature request to the authors of the module the sites uses to interact with FaceBook, asking it to rewrite NCR apostrophes into a single byte ASCII before sending to FaceBook.  They may be more symphatetic.

(Btw: This problem has already been mentioned on stackoverflow: https://stackoverflow.com/questions/11821400/apostrophes-turns-crazy-on-facebook-app - but I'm pretty sure the upvoted answer is hokum.)


What's a good way to split a 'item_list' into two columns? I'm working in a custom module that will output to my custom theme in D7. This theme & module will never be used apart.

Say I have a simple list in a block (six items), I want it split into two adjacent columns of three items...

Can this be done only with CSS? (just curious, not a constraint)
What seems easier; should I render two lists & just float the second right?

You can do this just using CSS by giving the list items a width and floating left:

.list-class li { width: 50%; float: left; }

You might need to adjust the width to a static number depending on the padding you have on the <li>s.


Why does my module only list 10 nodes? I've been creating my very first module and have got some help here earlier. Now the issue is this: my module only list a maximum of ten (10) nodes.

The module is like a taxonomy term list, which shows nodes with a certain term. Althoug I have hundreds of nodes, and they each have the correct term, no term page shows more then 10 nodes.

If one node is removed, another one gets listed, so the error is somewhere else - but where?

Shortned down code:

function my_module_cmp($a, $b) {
  $a = (array) $a;
  $b = (array) $b;

  return strcmp($a['name'], $b['name']);
}

$term = taxonomy_term_load($tid);
$name = taxonomy_term_title($term);

drupal_set_title($name);

$terms = taxonomy_get_tree(10,0,1);

usort($terms, "my_module_cmp");

$counter = 0;
$result = taxonomy_select_nodes($tid);

foreach($result as $nid) {
  $node = node_load($nid);
  $alias = drupal_get_path_alias("node/$nid");
  $form['company_wrapper'][$nid]['title'] = array (
    '#markup' => '
' . $node->title . '
',
  );

  $counter++;
}

The taxonomy_select_nodes() function has as default limit of unlimited, so if it's only returning 10 nodes, I would suspect that's all the nodes it was able to match against the provided taxonomy terms.

Note that this function will not return any unpublished nodes, nor return any nodes you do not have access to because of any node-access controlling modules.

Also note that taxonomy_select_nodes() only returns nodes that match $tid only - and not any of that term's children which might be what you are expecting.


Show only comments from users with the same role I am currently analyzing a project and am encountering the following situation, where I'd like to know your point of view.

For a specific content type we would like to allow users to place comments, but they should only see the comments made by users with the same role. Only administrators should be allowed to view them all.

Anyone encountered a similar situation?

Disclaimer: I have not had need for this myself, nor do I posses a database where I could perform suitable testing for this. Despite this, I feel confident I understand the problem enough to provide a useful solution.

While I've been writing this answer, I've been struck by the complexity of it.
I've tried to take a step back, and consider if there are other options, but none other come to mind. Perhaps someone else will be able to offer an easier suggestion.

The standard Drupal answer will be use a View, and that is most likely the way I would go about this myself. Even if you require more flexibility than that, the SQL generated by Views would serve as an excellent boilerplate for your own code. It's important to understand, that in my example below, you are required to be able to pass in a "role-id", into the View. This in turn likely requires you to understand and use Page manager + Panels. PM+P can be considered daunting at first, but is a great tool every Drupal site-builder should be familiar with. Tutorial here.

Basic steps to creating such a View:

Create a View. It's important to note the "Show" dropdown on the views/add page. It should be set to comments, not content, that is the default.
By default, Views should create a relationship between the comments, and the content they are posted on. If it's missing, add it. (Comment: content).
We also want information about the posting users group, we need to add a second relationship, (Comment: Author).
Last, we must create a "contextual filter", a filter that asks the currently viewing user "Which role do you have?". Add (User: roles), as a contextual filter. The default settings in on the contextual filter, will likely have the "Relationship" configured to use "Content" for getting the role, but that will give us wrong data, so this needs to be changed to "author" instead.

Done!
Test it out by giving the preview a rold-id as argument, and see what results you get back.

Query below, ready to be pasted into a db_query()-call. This query could also more readily be adapted to take a user-id and "WHERE IN()", the users roles, if necessary.

SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM {comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
LEFT JOIN {users} users_comment ON comment.uid = users_comment.uid
INNER JOIN {users_roles} users_comment__users_roles ON users_comment.uid = users_comment__users_roles.uid
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (users_comment__users_roles.rid = '1') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

Below follows a full export of my View:

$view = new view;
$view->name = 'rolebasedcomments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'tmp';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 1;
/* Relationship: Comment: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'comment';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 0;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['subject']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['subject']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['subject']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['subject']['alter']['trim'] = 0;
$handler->display->display_options['fields']['subject']['alter']['html'] = 0;
$handler->display->display_options['fields']['subject']['hide_empty'] = 0;
$handler->display->display_options['fields']['subject']['empty_zero'] = 0;
$handler->display->display_options['fields']['subject']['link_to_comment'] = 1;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Roles */
$handler->display->display_options['arguments']['rid']['id'] = 'rid';
$handler->display->display_options['arguments']['rid']['table'] = 'users_roles';
$handler->display->display_options['arguments']['rid']['field'] = 'rid';
$handler->display->display_options['arguments']['rid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['rid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['rid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['rid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['rid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['rid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['rid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['rid']['add_table'] = 0;
$handler->display->display_options['arguments']['rid']['require_value'] = 0;
$handler->display->display_options['arguments']['rid']['reduce_duplicates'] = 0;
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 0;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;


Redirect after user pass form submit I'm trying to do a redirect after hitting the submit button in a Drupal 8 reset password form.

I use the theme_form_alter hook and a function as a new submit actions. The problem is, that the redirect works but no email is send.
If I uncomment the line for the new submit hook the mail is send but of course there is no redirect.

function theme_form_alter(&$form, &$form_state, $form_id) {
  if($form['#form_id'] == 'user_pass') {
    $form['actions']['submit']['#submit'][] = 'user_pass_redirect';
  }
}

function user_pass_redirect(&$form, $form_state) {
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', [
    'node' => '87',
  ]);

 $form_state->setRedirectUrl($url);
}

I'm doing exactly the same thing for the contact_message_personal_form form and it works.

So, I have no idea why that happens for the contact_message_personal_form and the user_pass has isn't working.

Thanks for your help

I found a solution. I compared the output from a dump of user_pass $form and contact_message_personal_form $form variable.
My problem was, that my $form['actions']['submit']['#submit'] array was empty. So I added the missing '::submitForm' parameter
and everything works.

function module_form_alter(&$form, $form_state, $form_id) {
  if($form['#form_id'] == 'user_pass') {
    $form['actions']['submit']['#submit'][] = '::submitForm';
    $form['actions']['submit']['#submit'][] = 'user_pass_redirect';
  }
}

function user_pass_redirect(&$form, $form_state) {
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', [
    'node' => '87',
  ]);
  $form_state->setRedirectUrl($url);
}

I have no idea why my variable was empty but this works for me.


Where is the code of a new view i've created? i'm using drupal 7 with starter theme of zen. i've created a view on a block, now i need to customize some parts of html / css in order to add just media query (css part) and add a <a> tag with display:none for desktop version and display:block for mobile. SO i need to modify html AND css of this view. I'm searching for the php file of this view and i didn't find it.

Any help please ?

If you click on the Theming link in the Advanced tab, you will get a list of possible template files that you can use. See here:

Next, you can click on "Display Output" to get a copy of the PHP that is powering the view. See here:

Copy that PHP into a file and save it using the naming pattern of your choice from the list beside "Display Output".

Click on "Rescan template files" to make your theme aware of the new template.

Now, any changes you make to that template - add CSS classes, etc - will automatically be picked up.

If you wish to edit HTML for the style or row, just click on the relevant "Style Output" or "Row Style Output" link instead of "Display Output".

I hope this helps you.


How to migrate from MySQL to PostgreSQL I need to know how to migrate my Drupal 6 database from MySQL to PostgreSQL. I also like to hear first hand experience tales about actual migrations.

P.S. I found this drupal-mysql2pgsql.pl migration script which apparently does the job but I could not make use of it due to the fact that I dont' know how to make " passwordless account in both databases". There is also this guide (in Thai) which adds credentials to database connection lines in the script. But it did not help either, as I could not connect to Postgresql. I know very little about Postgresql and may have had some silly mistake. Any through explanation/tutorial on this would be much appreciated.


How to print author's email address in in node template I have a content of type summary only visible by the author and administrators. I need to print in my node--summary.tpl.php the author's email address that was set at the account creation.

Any idea how this can be achieved?

Use

<?php
  print $user->mail;
?>

If $user is not available use

<?php
  $user = user_load($node->uid);
  print $user->mail;
?>


Add users from SSO server database to Drupal I am trying to implement an SSO system for Drupal system. The detailed description of the scenario can be seen in "Understanding Drupal's session management and user authentication".

I did implement the authentication part, as per the using the suggestions provided (thanks to Pierre Buyle). Now, I have a requirement to add the users to Drupal database which are already present in SSO database.
The IT team of SSO will create a form which will post this values to a URL on the Drupal site.

This URL have to catch the request and create a user in Drupal. I'll be using the method user_save() to achieve this.

My questions are:

How do I create this URL in Drupal? (Thought of using hook_menu and use $items to create the URL, but I don't want it to be accessible to users except admin.
How could I read the data from that URL?

I'm not asking for the complete code. Just pointers to which hooks or methods should I use for the use cases would be enough.

IMHO, integration of different system through form POSting is at the hack level. To let external system inject data into Drupal, the Services module let you easily build HTTP REST API in Drupal. It comes out of the box with a user API that allow external system to easily create new Drupal users.

Off course, you can create your own page to receive POSTed data from a form build outside Drupal. You simply have to declare it through a hook_menu() implementation. For access control to the page, you can either use the 'access arguments' to restrict access with Drupal permission system. you can also use your own 'access callback' to implement your own access control logic (ie. for instance, using a secret token based access control).


How to implement a multi-node edit workflow? I'm not sure if this exists. I'm looking for a multi-node edit workflow. I want to select multiple nodes then for each node selected show an edit form. This would be something like showing the first node edit form, then on save, show the next edit form, etc.

I came across the Multi Node Edit module, but it looks to be dead.

There's also this answer but it's not exactly what I want. VBO seems to work only for multiple edits on the same field, not one after another node edit forms.

You can achieve something similar with a combination of editable fields and views.

Then by loading all the nodes in a view with a table format, you can use the editable field and edit it right on the spot with AJAX.
Updating multiple nodes in a view using editablefields

If you wanted to update multiple nodes at once (assuming fields are the same) you can use Views Bulk Operations

The exact functionality you are asking for is defiantly custom and will require your own module. Selecting the nodes you want then editing them one after another is highly inconvenient IMO. A report/table format is much better for working with data.


drush fails to install drupal properly I installed Debian 7 in a VM, there is nothing there except for web server apache2, mysql, webmin, phpmyadmin, and drush.
Drush fails to install Drupal, gives me admin and password but it fails to log me in.
Error: Not Found
The requested URL /phurst/node was not found on this server.
Apache/2.2.22 (Debian) Server at xx.xx.xx.xx Port 80
Weird thing is that it works flawlessly on my localhost, my computer is more advanced, I use Debian testing branch in it.
I cannot figure out what is causing this, I added my user to group www-data, chowned web root (/var/www) to myuser:www-data.
I noticed that perms were not set, that is weird because drush set perms correctly, I set all perms on the site to 775 recursively, but I am still locked out of the admin area.
Another weird thing: I can install Drupal manually, but I need to use drush to go fast.
Thanks in advance.

Here is the answer to the riddle.
My live VM is on an older version of Debian, different document root, different apache2.conf.
It is much easier to edit apache2.conf in the newer version, and that is why it was working:

    Options Indexes FollowSymLinks

AllowOverride None

AllowOverride All
Require all granted

In older version, I copied apache2.conf to something else and replaced Deny for Allow, like so:

    Order allow,deny
    Allow from all
    Satisfy all

.
Completely different, I am mulling to move server to testing version, in spite that everybody advices against it.


How to print "rendered node" version of Node Reference field in template? I have two content types: Type A and Type B. I have a Node Reference field on content Type A (using References module) that is set to be displayed using the "Rendered Node" version of that referenced node. It references nodes of content Type B. How can I print the content of that field as a rendered node in a custom template file for content Type A?

In your $node object, you will find the subordinate node object at $node->field_fieldname['und'][0]['node']. To render this in a page you have to turn it into a renderable array. You do this with node_view(),specifying the type of display mode. Try:

<?php
if(isset($node->field_fieldname['und'][0]['node'])) {
  $second_node = $node->field_fieldname['und'][0]['node'];
  $view_mode = 'teaser'; // or 'full' as the case may be
  $render_array = node_view( $second_node, $view_mode);
  print render($render_array);
}
?>

EDIT

MPD is correct. The above assumes that the field is a Node Reference field. If you are using an Entity Reference field, the code should be changed to:

 <?php
    if(isset($node->field_fieldname['und'][0]['entity'])) {
      $second_node = $node->field_fieldname['und'][0]['entity'];
      ...


Export Nodes to RSS or CSV I need to export blog entries from Drupal to a XML RSS feed or a CSV file. I have spent countless hours trying to export it, however, no results whatsoever. I have created a new view based on the defaults of the Blog node and have set the following parameters:

Style: RSS Feed
Row style: node
Items to display: 25
Path: latestblogs/feed
Attach to: Blog page

The feed page does work, however, none of the entries are appearing. What do you think is the issue?

If you want to export a View as XML or CSV, you will want Views Data Export.

Edit: now that I know this is for Drupal 6, you will have to dig to find the releases for 6.x on the project page. Here they are.


How to refresh a coded block when a flag is clicked in it? I have created a block in which I display a flag. All of it is done programatically. The content of the block changes depending on the flag status, but when a user clicks on the flag, it does not refresh the page or the block. The content is currently refreshed only when I reload the page.

I have gone as far as to create a callback from my block module to a jquery file, but I do not quite know where to go from here. I am not familiar enough with jquery to fully understand what to do, and how to use the callback function. Here is what I have thus far in my .module file:

/**
* Implements hook_init().
*/
function mymodule_init() {
drupal_add_library('system', 'drupal.ajax');
}
/**
* Implements hook_menu().
*/
function mymodule_menu() {
$items = array();

$items['block/reload'] = array(
  'title' => 'Refresh block',
  'page callback' => 'mymodule_refresh',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

return $items;
}

/**
* Menu callback.
*/
function mymodule_refresh($action, $type) {

}

In a .js file which I have put in a folder 'js' in my module's folder, I have created this:

(function($){

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {

}

});

})(jQuery);

The easiest way would be to use the module Block Refresh. With this module you can set up any block to be reloaded both manually and by an interval. For your use case you would chose the first option, here is an example form the block configuration page:

You will see now a refresh button on blocks title, which could be hidden by the following CSS:

.block-refresh-button {
    display:none;
}

and then triggered by clicking the flag:

$(".flag").click(function() {
    $(".block-refresh-button").each(function() {
        $(this).click();
    });
});

I did not test the code.


Comment form not showing I got a panel and added a comment form for this certain node type but the comment form does not show up.

I have enabled commenting for this content type and appropriate permissions (can post comment) for any authenticated user.
I tried disabling the panel for node templates.

In both case the comment form still does not show up.
What could be wrong?

If you have changed the content type to allow for commenting, it does not back-propagate to existing nodes. So, check to see the individual comment settings on each of nodes that it does not appear on to make sure they are indeed enabled.


Altering all urls to include extra information What hooks are available for altering the urls? For example, there are language modules that, when enabled, provide urls such as /en/node/1 rather than leaving it as /node/1.

I want to have something similar in the url, that I can have access to without having other functionality compromised.

How is this accomplished?

So you're looking for a way to modify a link URL as it is being written? I looked into this recently and was surprised at how much hunting was required.

I went with hook_url_outbound_alter( &$path, &$options, $original_path ), which allows you to alter link URLs that are being written by the Drupal URL system.

There's also hook_url_inbound_alter( &$path, $original_path, $path_language ), which might be better as it includes the path's specific langauge - it depends on where you want the alteration to take place. I personally find hook_url_outbound_alter() reliable and simple to work with - it changes all appropriate URLs as they are written, and using $options you can reliably add and edit query strings (...?query=string&foo=bar) and hash frangments (...#someId).

Modify $path and it'll update the actual path that gets written into the URL href. Of course, this runs on all links, so you'll want to start by checking that it's a link you want to modify.

It's executed before aliasing, so it'll be based on the Drupal defaults. To give two very simplistic examples, if you want to modify only taxonomy paths:

function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  if(strpos($original_path, 'taxonomy/term') === 0) {
    // do stuff
  }
}

And/or if you only want it to run on particular pages, e.g. node edit pages:

function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  $current_path = explode("/", current_path() );
  if (count($current_path) >= 3 && $current_path[0] == "node" && $current_path[2] == "edit") {
    // do stuff
  }
}


Strict warning: Only variables should be passed by reference I get the following error:

  Strict warning: Only variables should be passed by reference in include() (line 18 of /home/sites/dev/theparce/sites/all/themes/parce/block--block--3.tpl.php).

This is the block code which is causing that error.

if ($user_gallery) {
  print render(node_show($user_gallery));  // Line 18
  print drupal_render ($user_gallery_edit);

}
else {
  print drupal_render($user_gallery_new);
}

Why do I get that error, even if I get all printed as expected?

That error happens when a function is expecting a reference as parameter, but it is not getting a reference.

In your case, render() is defined as render(&$element), but node_show() is defined as node_show($node, $message = FALSE), not &node_show($node, $message = FALSE).
The same would be true for drupal_render(), since the function is defined as drupal_render(&$elements).

As explained on Passing by Reference, when a function requires a reference parameter, you can pass to the function:

Variables (for example, a temporary variable containing the result of a function which is not returning a reference)
References returned from functions

Using other expressions, the result is undefined, and it depends from the PHP version.

render(node_show()) produces a fatal error in PHP 5.0.5, a strict standards notice in PHP 5.1.1, and a notice in PHP 7.0.0
render(5) produces a fatal error
render(new DateTime()) produces a notice in PHP 7.0.7


Best practice to implement stores I want to allow my site users to create stores,, in which each store can contain content.
so the store is basically a page which contain specific content.

what's the best way to implement this in Drupal?

We used OG extensively in many sites with stores that are auto-created when a user registers.  You can check out one of them here - www.craftsaid.com - each "store" is an OG.  We also did the same thing on Bandromeda.com.

Install Organic Groups Module - http://drupal.org/project/og
Install Rules Module - http://drupal.org/project/rules

After you have created a content type for your Group type (this can be anything you want it to be - if you're not familiar with OG it is an incredibly powerful platform that allows users to create groups to which other members may subscribe - essentially you create one content type as the "group" type itself and then any other content type can be set as "group content" that may be added to a given group) go to /admin/workflow/rules and add a rule for Event = After saving a new user account with an Action = Create a new entity with parameters of Entity type: Node, Content type: Your Group Content Type, Title: [use tokens to create your title configuration]

This will auto-create a Group upon registration.  Otherwise you could simply create a link to node/add/store (or whatever your group content type is) from wherever makes the most sense in your site.

That is a very basic explanation - there are probably 50 ways you could implement this to accommodate your general description of your need.  Hope that helps!


Add js conditional in theme.info Add JS in themes.info

scripts[] = js/style.js

scripts[] = js/custom.js

scripts[] = js/common.js

But I Want to custom.js and common.js Add Conditionally

custom.js add only Front Page

And

custom.js add all page escape Front Page.

I want to add js only From themes.info File.

You can do it by using this

function yourtheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/your-front-script.js');
  }
}


How to get accurate information about available security updates after End-of-Life? For a Drupal 6 site that use the update module, the "Available updates" report no longer shows accurate information about available security updates.

Of course, this is because after Drupal 6's End-of-Life date, all Drupal 6 modules on Drupal.org were marked as unsupported.

Is there any other way to still get accurate info about available security updates for Drupal 6?

Have a look at the myDropWizard module, a recently released module for Drupal 6. Some more details about it (from its project page, which also includes a screenprint about it):

Reports accurate update status for Drupal 6 modules now that Drupal 6 is End-of-Lifed and most contrib modules are unsupported by the community.
It does four main things:

It still shows security updates if a module is unsupported, so you'll know about security updates you haven't applied, regardless, and
It uses an alternate data source that reports whether a module is supported by the Drupal 6 Long-Term Support (LTS) vendors, so you'll know if it'll be getting security updates going foward
It will let you know about additional security updates made by the D6 LTS vendors! The LTS vendors are required to post their patches publicly, but there won't be any Security Advisories going out to let people know, and it won't be in the normal Drupal.org update status data (we create special security releases for the patches released by the LTS vendors, which appear in our data)
It integrates with Drush 7 or later. See "Drush integration" section below for more information!

While it uses a different data source, it continues to report usage information back to Drupal.org, so the community won't lose that valuable resource. This will let us know how many people are still using Drupal 6 in the next months and years!

Refer to "Getting accurate 'Available updates' for Drupal 6" for a related article about it also.


Rebuild form in AJAX callback I've got a simple form which I've added a little AJAX to. The form simply let's people add users to a list. That is, I've got a textfield where people can enter an e-mail address, and that e-mail address gets added to the list.

Now, the "Add" button is AJAX enabled, meaning that the add request gets posted as an AJAX request. However, I would then like the AJAX callback function to render the form again so that the newly added user appears in the list. However, I can't really see how I should do this.

I've tried to build the form ("from scratch") using drupal_get_form() in the AJAX callback function and then return that form, but that does not work. It just gives me the error :

Notice: Undefined index: form_build_id in /home/playground/www/public_html/includes/ajax.inc on line 320

How should I go about when I would like to rebuild the form from the very scratch as a part of the AJAX request, and then return that form?

In your AJAX callback, use $form_state['rebuild'] = TRUE; (drupal_rebuild_form).

$form_state['rebuild'] is very useful in multistep forms, but it can also be handy in Ajax callbacks.

I recommend checking out the Examples project as well.  Both the Form examples and the AJAX examples.

If you will add the relevant snippets of your code I will try to add more details.


Creating new users with Commerce & Rules: ERROR Commerce has a problem with the Rule to create a new User account for an anonymous order:

ERROR: Missing configuration for parameter param_field_[fieldname]

According to a drupalcommerce.org comment this is because of fields being required:

  The rule “Create a new account for an anonymous order” will fail if any of the fields it attempts to create are required. That failure will generate the ERROR: Missing configuration for parameter param_field_.

Despite this insight, no answer is give for how to take care of the error. It is necessary to my site to require some fields upon user registration. How can I get rid of this error?

During anonymous checkout, an email address is collected from the 'Account information' pane to create a new user (or append the order to an existing user).

You should be able to hook into the form on the 'Account information' pane and add your required fields. You will probably have to modify the rule (Create a new account for an anonymous order) to send along the extra fields for creating a new user with the required fields - when marked required, custom fields added to the user are added to the Create Entity action for user as well.

You can populate these fields using existing variables, or fields added to the Commerce Order or Commerce Billing Profile, or create your own variables (eg via hook_token_info_alter() to make variables available through the commerce_order).


Exposed form don't have class attribute In a form_alter, I simply want to add a class to an exposed form (this code works for a custom form) :

$form['#attributes']['class'][] = 'my_class';

But neither my class nor the default class (views-exposed-form, I can see it in $form['#attributes']) is printed in front in the form tag.

Any idea?

I guess hook_form_alter is not the right place to set attributes. But I may be wrong. What surely works is to set attributes in a preprocess function.

The following snippet adds the form ID as CSS class to every form. You could easily wrap some if-request around this to only fire on certain forms checking for $variables['element']['#form_id'].

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_form(&$variables) {

  // Add form ID as class to form attributes.
  $variables['attributes']['class'][] = 'form';
  $variables['attributes']['class'][] = 'form-' . str_replace('_', '-', $variables['element']['#form_id']);
}


Insert query for PostgreSQL In Drupal 7 with a developed custom module that insert data into a postgreSQL db, I use the following query :

$query = Database::getConnection('default', 'move')
  ->query("INSERT INTO clients (client_ref,client_lastname,client_firstname) VALUES('E11366235','DUPOND') RETURNING client_id")
  ->execute();

But the returned client_id is always 1.

If I set INSERT INTO clients (client_ref,client_lastname,client_firstname) VALUES('E11366235','DUPOND') RETURNING client_id in pgAdmin 3, the returning id is correct.

In both case data are inserted into database but Drupal doesn't return the good id.

Any explanation ?

According to all messages there are two ways to solve the problem :

1) db_insert

Using db_insert() to insert data and create a specific query for postgreSQL database to get the last id after insert :

// Default insert
(...)->insert("...");

// Call this query to get last id only for pgSQL
(...)->query("SELECT currval('sequence')")->fetchAll();

You juste need to replace sequence by the key provided in your postgreSQL database.

You have to call currval right after insert to stay in the same context.

2) db_query

Rewriting the entire query with specific synthax for postgreSQL database to get the last id :

(...)->query("INSERT INTO {$table} ($fields) VALUES($value) RETURNING $id")->fetchField();

Conclusion

The first solution seems to be the best to avoid rewriting all db_insert() functions.


Tell taxonomy links to use route in custom module I have a module where I created a route /page/tag/{term} that uses a controller for modifications to how the term page is handled.

The problem is that when any page displays these term links, they don't use the custom route, but the default /taxonomy/term/{id}.

How can I tell the taxonomy term links to use my custom route?

Adding the path as the term alias skips over the custom route entirely.

OR, how would I get rid of the custom route and create a pathauto pattern using the same path, but tell those pages to use my custom controller?

I have tried both methods without success...

Here is what I've tried with modifying the existing route:

modulename.services.yml

services:
  modulename.route_subscriber:
    class: Drupal\modulename\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber, priority: 100 }

modulename/src/Routing/RouteSubscriber.php

namespace Drupal\modulename\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
    * {@inheritdoc}
    */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            // i've tried both of these
            $route->addDefaults(['_controller' => '\Drupal\modulename\Controller\ListController::list_by_tag' ']);
            $route->addDefaults(['_title' => 'test']);
        }
    }

}

Edit: after seeing this, I thought about keeping my custom route and using the alterRoutes to change the links...

$route->setPath('/page/tag');

That worked, but it adds on ?taxonomy_term=123

How can I get the term name into the url? /page/tag/term

Update:

Still can't figure out how to get the term name from the route (without loading the taxonomy entity - I'd imagine that is too much load)

Also, I will need to make sure I'm in a specific vocabulary before changing the route.

Any ideas?

In my case, I'm also using a RouteSubscriber to change the default controller responsible for handling taxonomy term entities. I also wanted to use a custom template only for a specific taxonomy (called my_taxonomy in the example below).
Here is the code for the RouteSubscriber:
<?php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            $route->setDefaults([
                '_controller' => '\Drupal\my_module\Controller\DefaultController::listAll',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
        return $events;
    }

}

And here is the code for the controller. Note that a custom render array can be returned only for terms of the specific taxonomy my_taxonomy. All other terms fall back to the default controller used by the views module in the original route:
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\Routing\ViewPageController;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends ControllerBase {

    public function listAll(Request $request) {
        $render = [];

        $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
        $term = Term::load($tid);
        $bundle = $term->bundle();
        if ($bundle == 'my_taxonomy') {
            // render array for your custom template
        } else {
            // falls back to the default ViewPageController to handle all other taxonomies
            $viewPageController = new ViewPageController();
            $render = $viewPageController->handle('taxonomy_term', 'page_1', \Drupal::routeMatch());
        }

        // Return render array
        return $render;
    }

}


Views page redirect to current page with parameter in drupal 7, I use drupal_goto function for the redirection. I'm trying a few methods in d8, but couldn't make it work.

If I visited a certain page for example /views-page-example, I would like to redirect users to the same page, but with parameters. Once visited, the users should be redirected to /views-page-example?name=value. I'm using template_preprocess_page to trigger the redirection.

This is the current code I have so far:-

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function THEME_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();

  if ($current_path == '/views-page-example') {
    $path = "/views-page-example?name=value";
    $route_name = url::fromRoute($path);
    $response = new RedirectResponse($route_name->toString());
    $response->send();
  }
}

Don't send a response in custom code. Use an event subscriber to set the response, so that it can be returned by Drupal:

mymodule.services.yml:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

src/EventSubscriber/MymoduleSubscriber.php:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkForRedirection'];
    return $events;
  }

}

Source: https://www.drupal.org/node/2013014

Example to check the current path and that the query parameter is not present yet:

public function checkForRedirection(GetResponseEvent $event) {
  $request = $event->getRequest();
  if ($request->getPathInfo() == '/example' && !$request->query->has('name')) {
    ...


A General Strategy for Images with Captions in Content This is a 'general direction' topic. I'm looking for some strategy and philosophical guidance, before marching over to the module development forum at Drupal.org.

I'm new to Drupal, and am very impressed by the architecture - the flexibility and power of the framework as a whole.

However, like many 'newcomers', I've quickly discovered that there's some planning and investment required in creating a new Drupal site (which is apparently the subject of many debates that are shaping the future of Drupal itself - http://www.lullabot.com/articles/understanding-8-where-drupal-and-where-...).

At the moment, for me at least, there's only one piece missing, and that's a non-Javascript method for allowing content creators (site owners) to insert one or more images with captions into the content of a node (like a news article, or blog post).

I also understand that in terms of semantic purity, it would be nice if the content of a node was clean and tidy, without a lot of additional markup - and so I'm looking for an eloquent way to solve the image/caption problem.

I poured over several other solutions - although as a new poster here I can only share two links in this post :(

and...

http://purewebmedia.biz/articles/2013-01-10/how-insert-and-float-inline-... - which is a great write-up describing the difference between using an Image field (with custom locations/folders for image stores), vs. Media Manager - although it doesn't address the caption problem.

I've also read a little about the new Entity model in DR7 - and I'm beginning to wonder of File Entities, with some kind of token replacement might be the right approach? (although I confess I don't entirely understand yet if a token can be placed into the free text/content field of a node - like the main text of an article or news story).

What I'm looking for is a method that will allow a user to insert one or more images into the content area of any content type (article, basic page, whatever - assuming the field/function has been defined for the content type), and that when they upload and insert that image, they are allowed to enter additional information like a title, copyright, caption, date etc.

They should be able to 'see' the image in their WYSIWYG editor (although maybe not the metadata), and then when the node is published, the required metadata is retrieved and inserted via a hook, pre-processor - for example, by surrounding the image in a div, and placing the required metadata above or below the image (perhaps in additional divs or elements) - requiring only CSS to style the title, caption, etc. as required.

I also really like Image Styles feature of Drupal and so I'm wondering how this could all be brought together.

To be clear, this is not a gallery module. The requirement here is to be able to insert one or more images with captions (and possibly other metadata fields) into a the content/body or a story, news article, blog post etc.; needing only CSS to style the result (format caption, float left or right etc.)

Thoughts?

Any pointers on how to start with this?

Your desire for a "non-Javascript" solution is in conflict with your desire to allow users to "see" the image in their WYSIWYG editor, as you need to run Javascript for those to work.  So, you'll have to either drop the "non-Javascript" requirement, or be satisfied with image fields that may appear above or below the main body.  [Note 1: Images "above" the node body can be set to float left or float right, and thereby appear to be inside the text.  Note 2: If by "non-Javascript" you mean non-JS at render time, then no problem.]

Whichever way you go -- be it images embedded in a WYSIWYG editor, or images as file fields, you'll probably want to use the media module, as it can support either method.

There is a lot of information available on the media module, which is becoming "the way" to do images in Drupal.  Many additional contrib modules are compatible with media. You'll want to take a look at the following two configuration guides:

Media 2.0 Quickstart

Configuring embedded images with media and wysiwyg modules

Here is the point where I remember to take a step back and point out that my experience is with media 2.0-unstable7.  Depending on how comfortable you are with making adjustments to php code, you might prefer to use the stable release, which is currently 7.x-1.2.  I didn't have too much trouble with 2.0-unstable7, except for the fact that it does not support editing of arbitrary image metadata on WYSIWYG images, so I am using only image file fields at the moment.  If the only metadata you wish to attach to your images is a caption, then I expect that 7.x-1.2 should work for you, although I have not tried it myself.

In any event, I would recommend using the provided "title" field, and render that as a caption. Doing that is as easy as visiting admin/structure/file-types and clicking on "manage display" for the image file type.  This page works just like the "manage display" page in cck; you can just drag the "title" field up so that it is under the "file" field, and use css to style it as a caption.  You'll probably also want to download and enable the entity_view_mode module, which will allow you to define additional view modes for your image files.

As I said, I'm not embedding images in WYSIWYG editors at the moment, but the article you quoted gives good advice on that.  If you're using the media module, you should still be able to format the title field as a caption regardless of whether you're using file fields or WYSIWYG.


How to eliminate direct access to files in private directory? I have set up my Drupal 7 site for private files in a directory above root (../private). I also set my filefield on my node type to upload the image files to that private directory.

I have two user roles: man and woman. Both user roles can create nodes of a certain type, containing that image file field. Men can never see another man's photo; same thing for women. Men can always see a woman's photo; same thing for women.

Here are my current results:

When a man visits a woman's node, he can view the photo within the node content: http://example.com/members/76/gallery/public/photo-123

When that man views the page source and copies the image URL, he can view that image directly in his browser: http://example.com/system/files/styles/apply_simplecrop/private/pictures/1/Public/filename.jpg?itok=ABC123&sc=abcdefghijklmnop

If that man shares that direct link with another man, that other man can view that picture as well. If he shares the direct link with a woman or a non-logged-in user they are served an Access Denied message and cannot view that picture.

If a man tries to access that image URL without the "itok=" text in the link, he receives an Access Denied message.

My desired result in all of those examples above is to display an Access Denied message.

The ../private directory has an htaccess file containing Deny from all.

Am I missing a step? What can I do to securely deny direct access to those files in the way that I described above?

Thanks!

The issue is that the other man that gets the link should get an Access denied right? (The rest seems to work.) This is not how if works unfortunately. Private files are only private if the user is explicitly denied access to them (as happens to women and anonymous users). Since any man is allowed access to that file (he can view it under certain circumstances), the system will serve him that file.

Files are served from this part of system_menu():

$items['system/files'] = array(
  'title' => 'File download',
  'page callback' => 'file_download',
  'page arguments' => array('private'),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

Then file_download():

function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

As you can see, Drupal serves an access denied in case there are no headers. So, you should make sure that file_download_headers() does not return any headers.

You can achieve this by implementing hook_file_download() in a custom module and have it return the value of -1 as described in it's documentation. This will however always deny the user access to the file. So within hook_file_download you will have to find some way to conditionally allow the user access to the file. It is entirely up to you how you want to implement this, but a suggestion is:

Lookup the file object, by loading it from the file_managed table by its path.
Lookup the node(s) that have this image attached.
Lookup if the current user visited the node within x minutes by querying the history table. If not, return -1.

This gives a general idea of how Drupal serves these files and what you can do to restrict access. If you run into any problems implementing this, feel free to open a new question and reference this one.

And on a sidenote, if you are trying to prevent user from leaking photo's. If I find a pretty girl, I can also save the image and email it to a friend. If you block that I send a screenshot. In these case he does not even need an account. People will always find a way to circumvent limitations. Is it worth the effort to block this?


Organic Groups: how to add an invite link? I'm using Organic Groups (og) and Organic Groups Invite (og_invite) on a D7 site, and see a way to invite a user to the group, but only through the admin panel - enabling the permission for a group member to invite others does not add a link to the group page to send an invite - what am I missing?

I have recently used Organic Groups Invite module to add this functionality to a site. It will give you a "OG Invite Button" block that you can place on the user view page.

Edit: Sorry the block wasnt included I had added it with a custom module here is the code:

/**
 * Implements hook_block_info().
 */
function og_invite_button_block_info() {
  $blocks['og_invite_button'] = array(
    // The name that will appear in the block list.
    'info' => t('OG Invite Button'),
    // Default setting.
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function og_invite_button_block_view($delta = '') {
  switch ($delta) {
    case 'og_invite_button':
      $block = array(
        'subject' => t('OG Connect Button'),
        'content' => og_invite_button_block_content()
      );
    return $block;
  }
}

function og_invite_button_block_content() {
  //Get user from profile page
  $user_viewed = arg(1);
  $user_viewed_fields = user_load($user_viewed);

  global $user;
  $output = '';

  $query = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition('type', 'group')
  ->condition('uid', $user->uid);

  $result = $query->execute();

  foreach ($result as $row) {

    // Check if the user is already an existing member.
    $exists = db_select('og_membership', 'ogm')
      ->fields('ogm', array('id'))
      ->condition('gid', $row->nid)
      ->condition('etid', $user_viewed)
      ->execute()
      ->fetchField();
    if (empty($exists)) {
      $name = $user_viewed_fields->field_name['und']['0']['value'];
      $output .=  'nid . '/admin/people/invite-users/' . $name . '/' . $user_viewed . '">Invite To Your Group';
    }
  }
  return $output;
}

Some improvements could definitely be made like theming the link.

You will also want to add the name of the group to the button if the logged in user is the owner of more than one group.


I need to update a longblob value in the variable table using variable_set This would be in an install file in a module.  The purpose is to create setting for a module that is already installed (the module is node_revision_delete).  I know how to use variable_set to change a value in the variable table but not when it is longblob. Do I just use the variables from the module?  Do you know of any examples I could look at?

With variable_set() you can set a persistent variable to any PHP value, including array. variable_set() will serialize the value passed as second argument, and variable_get() will unserialize that value. If you pass an array to variable_set() for a persistent variable, variable_get() will return an array for the same persistent variable (if another module doesn't change that persistent variable's value to an integer, for example).
Suppose that you want to change the value of node_revision_delete_minimum_age_to_delete_time, which is set from that module in its installation hook using the following code.
  $node_revision_delete_minimum_age_to_delete_time = array(
    'max_number' => 12,
    'time' => 'months',
  );
  variable_set('node_revision_delete_minimum_age_to_delete_time', $node_revision_delete_minimum_age_to_delete_time);

If you want to change max_number to 24, you would use code similar to the following one.
$node_revision_delete_minimum_age_to_delete_time = variable_get('node_revision_delete_minimum_age_to_delete_time', array());

if (is_array($node_revision_delete_minimum_age_to_delete_time)) {
  $node_revision_delete_minimum_age_to_delete_time['max_number'] = 24;
  variable_set('node_revision_delete_minimum_age_to_delete_time', $node_revision_delete_minimum_age_to_delete_time);
}


How to populate search form with search term in View / Panels / Page? I've using Views and Page Manager to create a custom search results page. You can see it here:

http://quotefail.com/search/node/world

The page is being generated by Page Manager. I've got a Search Form in the top panel, but it starts empty. I'd like it to be pre-filled with the search term that was used to generate this page.

How can I prepopulate the search form with that search term?

Here is my page config:

Here is my Search View in the center panel:

Looks like from that link that the search form is the search block form, so you can do this as a theme form alter (you could also make a custom module in a similar fashion with form alters but this should serve your needs).  This goes in your template.php for your theme:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'search_block_form':
      //checking if arg(2) exists so it doesn't try to do this if some visits the search page straight away
      if(arg(2)){
        $form['search_block_form']['#default_value'] = arg(2);
      }
      break;
  }
}


What is the difference between {{ |t}} and {% trans %}? I notice that Drupal 8 support {% trans %} which, according to the Symfony documentation (The i18n Extension), adds gettext support to Twig.

{{ |t }}, as far as I know, is the legacy way to add translatable strings into Drupal templates. According to the documentation, t() translates a string to the current language or a given language.

Both support multi-language website.

What are the differences between those extensions?
When should I use one over the other one?

Both the {{ |t }} filter and {% trans %} ... {% endtrans %} blocks, when used in the context of Twig template file in Drupal, are part of the Drupal localization system. And translation for strings processed with either one are handled in the same way, and via localize.drupal.org. For simple strings of text they can be used interchangeably, however the %trans block has some additional useful features for complex strings.

The difference is that the t filter only allows for simple strings, while using a %trans block allows the use of dynamic placeholders in the string. Much like using the php t() function.

Here's a few examples:

Simple string translation via t filter:

{{ 'Hello Stack Exchange!'|t }}

String translation with placeholder:

{% trans %}Hello {{ user.name }}, today's date is {{ date|placeholder }}.{% endtrans %}

Placeholders are escaped by default, but can also be left-unescaped {{ var|passthrough }} or formatted as a placeholder {{ var|placeholder }}. This is equivalent to using @string, !string, and %string in the t() function respectively.

You can also use %trans blocks in order to format plural strings.

{% trans %}
  There is 1 comment.
{% plural count %}
  There are {{ count }} comments.
{% endtrans %}

For simple strings there are really no rules about when you should use |t vs. %trans. So I would recommend using whatever is easiest to read in your template. In my experience using the |t filter works well for short strings, while the %trans block is easier for longer strings of text.

More information about usage can be found here: https://www.drupal.org/node/2357633 and here https://www.drupal.org/developing/api/8/localization


Create Custom Search and result page I am trying to create a custom search page with two input fields.

Company Name and Certification Code are two fields to be entered by user.

I have a content type called certification and the search will be performed based on this Content type.

A field collection is used to enter certifications details(Certificate Name     ,Certificate Number    ,Certificate ,Issuing Date: ,Date of Expiry).

The result page will separated one or under the same page of search form.

I tried many ways and i am not convinced with the results. I created a page node--certification.tpl to show the result

Here i want two things :

In the search page Two input fields to be entered  ,the combination of two items in content type(company name,Certificate number.) Here certificate number is a field collection value.I couldn't search from the field collection.I used custom search module.
Show the result in this page directly when we search from the search page instead of showing the intermediate result page.

Search Page

Search Result looks like

I hope someone will help me to get a perfect search page.

Installing module or modifying .tpl files are not required to get a simple search page.

Creating a view and using Exposed Filters setting will get the job done.

Providing you high level steps below, you may need to research a bit more to accomplish this task.

Steps

Create a View.
Choose "Table" in Format section.
Add "Certificate Name ,Certificate Number,Certificate,Issuing Date,Date of Expiry" in field section.
In filter criteria, select your content type.
Also add "Company name, Certificate number" in the Filter Criteria.
Click Advanced > Better Exposed Forms > Better Exposed Filters.

Expose the fields "Company name & Certification number" as text fields.
You can expose this fields as a Drupal Block and assign it anywhere in the page.


Is there a good way to set available countries in Drupal Commerce shipping and billing? On admin/commerce/customer-profiles/types/billing/fields/commerce_customer_address and
admin/commerce/customer-profiles/types/shipping/fields/commerce_customer_address one is supposed to select the available countries in a little box. This is not ideal. So I would like to do this programmatically (possibly with drush), is there already a quick solution for this or do I have to delve into this myself?

Depends what you mean by 'quick', really. Yes, you can do it programatically. With PHP:

$instance_config = field_info_instance('commerce_customer_profile', 'commerce_customer_address', 'shipping');

$instance_config['widget']['settings']['available_countries'] = array(
  'GB',
  'US',
  'FR',
  // etc...
);

field_update_instance($instance_config);

Or with JS (I'll let you work that one out, selecting a bunch of <option> tags based on a bunch of values is very easy).

IMO the time-consuming part is building up the array of default countries in the first place; no matter what automated method you use to put the values in, someone needs to spend the time choosing and preparing them. You can't get away from that.


Get list of node dependencies in Drupal 6, is there a way to list by programmation (function or SQL code) the dependancies of a node ?

For exemple, I have videos that are nodes. Thoses videos are refered in other nodes. Before deleting the video I need to update the nodes which refer it.
I have the module "Node Dependencies" that lists the dependencies of a node in the UI, but I need to get this list with code.

Is it possible ?

Thanks.

Drupal does not know "dependencies" on it's own, so I assume it's something provided by the module you named. Yes, it is possible. After all that module is doing exactly this. Just read it's code and see, PHP is an interpreted language after all. It seems there is no module with that exact name on Drupal.org, so I can't provide more detailed instruction now. To find it yourself, you need:

Find implementation of hook_menu() in this module
Locate entry for GUI page that shows what you want
Find implementation of a function that obtains data for that GUI page


Error on when to load node? I have problem when our taxonomy term is linked with node but when i am clicking on term they go front page of site instead of current page
our code given below:

$ch1 = db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $ch AND book.entity_id = $nid
 ")->FetchField();

$chap1=taxonomy_get_children($ch1);
foreach($chap1 as $ca1){
    $link = l($ca1->name, 'node/' . $ca1->nid)."<br>";
    print $link;
}

How to handle this problem?

"$ch1" contain tids.

The function "taxonomy_get_children($ch1);" retrieve all children term id and not related nid...

You can retrieve all nid linked with a term with this function taxonomy_select_nodes

I will suppose $ch1 contain your tids in an array

foreach($ch1 as $tid){
    $nids  = taxonomy_select_nodes($tid);
    $nodes = node_load_multiple($nids);
    foreach($nodes as $node){
        $link = l($node->title, 'node/' . $node->nid)."<br>";
        print $link;
    }
}

I can't test this code, if it's valid tell me and i will remove this line :)


Multiple path alias for a url I've installed the pathauto module. I have a content type article. When I'm trying to create an article, the path is created automatically in the form content/article-title, that is fine.

However, I want to pass some dummy values via url like content/article-title/value1, content/article-title/value2. So now I have multiple aliases for the url.  I will create some functionality using this dummy value.

If I try to access node/10/value1, I can access the page. But I want to access with path alias like content/article-title/value1.

How can I access a page using content/article-title/value1, content/article-title/value1 and content/article-title?

I don't need to create multiple path alias for url. But I need to access page using above urls.

Is it possible?

Answer:

Eventually, I got the solution for this. Please refer http://www.phponwebsites.com/2016/08/drupal-7-pathauto-multiple-url-alias.html

You need to set path at config >> URL aliases >> patterns under that article patter you need to set something like.

content/[node:title]/[node:field_machine_name]

You can access with pattern url otherwise you can access by default with "node/nid".


How to disable Rich Text Editor in image field caption ? I am using Image Field Caption module. It provide a image caption field but I don't want any rich text editor appearing for the caption field. How to disable that for any specific field?

You used to be able to configure CKEditor to appear on a per-textfield basis, but apparently that's no longer possible in the 7.x-1.x versions of the CKEditor module.

The following issue offers a JS workaround:

https://drupal.org/comment/5601364#comment-5601364


How can I output aliases in a print function, so I can render links using aliases instead of nid? I have a theme using a views tpl file that is making it impossible for a View to link to node content using the node’s aliases' that i’ve set up. For example it is linking to the default node/36 instead of projects/projectname.

the view contains a grid of ‘thumbnail like content’ wherein each image links to it’s corresponding node. the views template file is renderering links as shown below:

<a style=" background-image: url('<?php print $thumbnail;?>'); "
class="w-inline-block portfolio-photo portfolio-1"
href="<?php print drupal_get_path_alias('node/').$row->nid;?>">

It’s hardcoding /node/ as a directory and use the function $row->nid

Is there an alias equivalent to nid? Instead of node/36 it the url should be project/projectname

To rewrite the above code using pseudo code it would be…

<a style=" background-image: url('<?php print $thumbnail;?>');"
class="w-inline-block portfolio-photo portfolio-1"
href="<?php print drupal_get_path_alias(‘projects/‘).$row->alias;?>”>

You should use the l() function:

  Formats an internal or external URL link as an HTML anchor tag.

  This function correctly handles aliased paths and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.

So:

<?php print l('Link text',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')))); ?>

You have to supply classes and any other attributes to the l() function.

Note that the first l() parameter (the 'Link text') can be HTML. For this you have to pass in the options array an element HTML set to TRUE. The above example can be:

<?php print l('Some text',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')
                   )
                 'html' => TRUE,
                 )
             ); ?>

Also, as noted by the documentation fragmento above, the l() functions handles the aliases. This is because internally drupal_get_path_alias() function is used.


Access denied for anonymous users clicking on download link I have a content type with a file field that has been formatted by display suite. I set the display suite formatter to download link.

This works fine for users who are logged in, but anonymous users get the access denied page. Is there some permission settings or file folder permission settings I need to deal with?
Accessing the raw file URL is possible for anonymous users though.

The formatter makes the link become something like this: http://example.com/file/980/download?token=OBVqG5D1va06NDH2_BcgF0vqwVhhNHsnNYcHYHGQ5_g

This was a bug in the file entity module and the latest stable version has the patch for this issue committed to it. If you had encountered this issue in the past, update file entity to the latest version.


Use exposed filters to reorder nodes? Just wondering whether I can use exposed filters to re-order a list of nodes rather than eliminating ones that don't fit the desired criteria.

E.g. If I filter for 'Monday' and have a list of nodes [Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday, Monday], then I would like the list of nodes to return as Monday, Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday.

At the moment my result when I filter for the term 'Monday', is just 'Monday'.

Any thoughts?

Cheers!

Depending on your display requirements, you might be able to use a table format.  When using a table format, you have the option to set columns to "sortable".

Format section:

Sorting settings:


Why are store translation files stored in the database? I have set up a fresh minimal Drupal 7 site. When I add 2 more language files e.g. French and German the database increases up to 3MB.

Why does Drupal store translation files to the database? What about performance? Wouldn’t it be much faster to load language files from the file system?

It's not likely that loading the translation files from disk would result in a faster page load time than it does from the database -- in fact I would expect it to be much slower. This is essentially the job of a database: store and organize a large amount of data on disk and provide other programs the parts they need quickly. Drupal (and all similar CMS's) are built on the assumption that for processing the content you are better off pulling from the database, and translations are basically just content. Disk-based optimizations usually help when you are trying to deliver unprocessed data as quickly as possible i.e. it's often faster to have the web server pull an image file off a disk instead of loading a script that loads a binary field from a database, and then streams it down.

There are several reasons that the database is likely faster for most use cases:

To keep translations flexible and manageable there are actually many files that go into translating the back-end (each module can have its own PO file for each language). For a production site you'd then also be looking for a place to store all the translated content so we aren't looking at loading one file, but tens or hundreds of files to process.
Each file has to loaded, parsed into useful structures, and then matched to the default (English) text. Yes, the site could cache a unified file, but that file could become massive and cause trouble on its own for some OSes and file systems.
The site content is already stored in the database so overriding displayed text would have to come from two systems (either you'd have some in file and some in database, or you'd have all the default language in database and the translations in files), which adds complexity an likely processing time as Drupal determines where to pull the data from next.

Now think about what happens with the translations in the database:

Since nodes (and other fielded objects) store all the languages in the same tables, most of the time Drupal doesn't have to do anything extra. All the translations for a given field get loaded with the object and then Drupal picks which to display at render time. When Drupal does need to load a translation specifically, Drupal is able to re-write the queries used so it again has the data on hand at the same time it would have had the default language (that rewrite time should be trivial since it had a write a query in the first place). So almost nothing extra needs to be added to the load time to load the needed translated text.

Finally you have to keep in mind that good page load speed is mostly driven by caching, which Drupal does in the database by default, it does not load even the full node objects whenever it can avoid it.

Disclaimer: I don't know that anyone checked a file-based system when the translation system was initially written and I've never seen actual numbers run, so this is mostly speculation.


How to show a map of the User's Location in the User's profile with Address Field and Geofield So, the location + Gmap module showed a map of the User's address in the user's profile once it was geocoded. Is there an equivalent widget that will show a map of the user's address in the profile itself?

Use module getlocations.  It also supports paths like "/getlocations/user/xxx" and "/getlocations/users" for location-enabled users


How to reset UID number back to default order? I have a Drupal 7 website with only UID1 user which is root admin. I deleted previous users. Now if I create a new user, it gets UID of e.g. 74.

It should be UID 2 and so on.

Anyway, I had same problem with resetting nodes back to 1. And I did it by following this answer, but it worked only if you have no nodes. Now, I have at least one user and I don't know if that query would work for 'users'.

I've found the discussion thread about the issue about why users table is not auto-increment and creating a new sequences table for that purpose.

  This is NOT a full sequences API not at all but it's enough for some uses. actions_aid and simpletest_test_id , that's duplicate code not to mention it belongs to the DB layer. This patch solves that. Further work: we can reuse this for users.uid as that should not be serial because of the known problems. The postgresql folks can create a version which uses proper sequences. The mysql folks can support more than the single serial mysql allows -- like a timestamp and a serial. Sorry for the hasty writeup.

In your case, you just update the value in sequences table to 1.

AND

You need to run ALTER TABLE sequences AUTO_INCREMENT = 1 as well.


Need to override block.tpl.php in a module I need to define a block--custom.tpl.php file in a custom module and have that override the theme block.tpl.php.

Here is where I have ended up and it's not working.

Tell Drupal to look in my module:

function MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE');
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE') . '/theme';
}

In hook_preprocess_HOOK() suggest a new theme file:

function MODULE_preprocess_block(&$variables) {
  $block = $variables['block'];

  if ($block->CONDITION) {
    $variables['theme_hook_suggestions'][] = 'block__MODULE';
  }
}

Now, I've created the file in the module's theme/ folder and called it block--MODULE.tpl.php.

I've turned on theme debugging in the settings file by un-commenting out $conf['theme_debug'] = TRUE;

Caches have been cleared multiple times. When I load the page I see in the debug comments:

<!-- THEME DEBUG -->
<!-- CALL: theme('block') -->
<!-- FILE NAME SUGGESTIONS:
   * block--MODULE.tpl.php
   * block--block--6.tpl.php
   * block--block.tpl.php
   * block--content.tpl.php
   x block.tpl.php
-->
<!-- BEGIN OUTPUT from 'sites/all/themes/THEME/templates/block.tpl.php' -->

And as you can see from the debug it is using the theme template file.

How do I get Drupal to select the proper theme file?

The following worked for me:

/**
 * Implements hook_theme().
 */
function rals_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['block__custom'] = array(
    'render element' => 'content',
    'template' => 'block--custom',
    'path' => drupal_get_path('module', 'rals'),
   );
  return $theme;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function rals_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->bid == 3) {
    $variables['theme_hook_suggestions'][] = 'block__custom';
  }
}

and succesfully uses my module-folder-located template file for rendering the block with bid == 3.

Good luck in any case!


How do I handle smart quotes and curly apostrophes? I'm building a new Drupal site, and the content authors and editors ared dyed-in-the-wool Microsoft Word users.  I've got WYSIWYG set up to force all pasting to be treated as "Paste from Word", so much of Word's garbage seems to be handled well.  The one remaining problem is characters like smart quotes, curly apostrophes, em-dashes, and the like.  Although I'm shooting for end-to-end Unicode, and theoretically that should prevent those characters from showing up as weird garbage, I consider it safer to use HTML entities, in case at some future point someone else changes something that interferes with the end-to-end Unicode architecture.
Is there a way to convert non-ASCII characters into HTML entities, either when they are pasted or before they are displayed?
Converting to straight quotes (and using Typogrify to render them as smart quotes) would be fine too, if you can tell me how to convert to straight quotes.  Preferably, other characters should be as well handled.

Converting to straight quotes (and using Typogrify to render them as
smart quotes) would be fine too, if you can tell me how to convert to
straight quotes.

I had to do that for an online dictionary I built recently with Drupal 9.2. What I did is to create a drush command that updates all nodes (creating a new revision) converting all quote characters to straight quotes or ASCII quotes:
<?php

namespace Drupal\diccionari_custom\Commands;

use Drush\Commands\DrushCommands;

/**
 * A Drush commandfile.
 */
class DiccionariCustomCommands extends DrushCommands {

  /**
   * Standarize quotes.
   *
   * @usage diccionari_custom:standarizeQuotes
   *   Usage description
   *
   * @command diccionari_custom:standarizeQuotes
   */
  public function standarizeQuotes() {

    $query = \Drupal::entityQuery('node');
    $entity_ids = $query->execute();
    foreach ($entity_ids as $nid) {
      $node = \Drupal\node\Entity\Node::load($nid);

      $new_title = str_replace('‘', "'", $node->title->value);
      $new_title = str_replace('’', "'", $new_title);
      $new_title = str_replace('ʹ', "'", $new_title);
      $new_title = str_replace('ꞌ', "'", $new_title);
      $new_title = str_replace('“', '"', $new_title);
      $new_title = str_replace('”', '"', $new_title);
      $new_title = str_replace('&#x2018;', "'", $new_title);
      $new_title = str_replace('&#x2019;', "'", $new_title);
      $new_title = str_replace('&#x02B9;', "'", $new_title);
      $new_title = str_replace('&#xA78C;', "'", $new_title);
      $new_title = str_replace('&#x201C;', '"', $new_title);
      $new_title = str_replace('&#x201D;', '"', $new_title);
      $node->setTitle($new_title);

      $new_content = str_replace('‘', "'", $node->body->value);
      $new_content = str_replace('’', "'", $new_content);
      $new_content = str_replace('ʹ', "'", $new_content);
      $new_content = str_replace('ꞌ', "'", $new_content);
      $new_content = str_replace('“', '"', $new_content);
      $new_content = str_replace('”', '"', $new_content);
      $new_content = str_replace('&#x2018;', "'", $new_content);
      $new_content = str_replace('&#x2019;', "'", $new_content);
      $new_content = str_replace('&#x02B9;', "'", $new_content);
      $new_content = str_replace('&#xA78C;', "'", $new_content);
      $new_content = str_replace('&#x201C;', '"', $new_content);
      $new_content = str_replace('&#x201D;', '"', $new_content);
      $node->body->value  = $new_content;
      $node->body->format = 'basic_html';

      $node->setNewRevision(TRUE);
      $node->revision_log = 'Converting quotes to straight quotes';
      $node->setRevisionCreationTime(REQUEST_TIME);
      $node->setRevisionUserId(1);
      $node->save();

      $this->logger()->success(dt($nid . ':' . $node->title->value));
    }
  }
}

Now, when outputting the content, you can use a text format and Typogrify module to do the conversion to smart quotes.
And if you have to perform that conversion in the title too, see my last comment in this Drupal.org issue.

Preferably your solution will handle other characters as well.

Both the drush command example and Typogrify settings can easily be extended to handle other characters.


"Undefined index" error for field which is defined I'm getting a strange error on a Views page, even though the page works. I get ten instances of this error:

Notice: Undefined index: field_video in include() (line 28 of
/path/to/drupal/sites/all/themes/mytheme/templates/
views-view-fields--screenings--panel-pane.tpl.php).

Notice: Trying to get property of non-object in include() (line 28 of
/path/to/drupal/sites/all/themes/mytheme/templates/
views-view-fields--screenings--panel-pane.tpl.php).

Here's the content of line 28:

if (preg_match('/media/', $fields['field_video']->content)) {
    unset($fields['field_featured_image']);
}

The idea is that if a node of the relevant content type has both a Video and a Featured Image, the view will drop the image and replace it with the video.

What's crazy is that the page renders just fine; the image disappears when the node has content in both fields. What's even crazier is that the error appeared after a minor tweak to the above code, so I reverted my change and it still throws this error, no matter how many times I flush my caches.

What is happening here? This very same code worked fine for a long time, but now I can't seem to get rid of this error!

First thing to note is you're seeing notices, not errors. Notices are a less severe type of PHP error. It's an alert that notes script execution is continuing, but something is wrong that could be a bigger problem. In your case, the array element $fields['field_video'] doesn't exist,
thus trying reference a property $fields['field_video']->content on a non-existant object causes PHP to fire off notices.

As Geoff mentioned, this can occur if your view rows are loading nodes that don't produce this field and throwing an isset($fields['field_video']) && in your if statement should fix your template from making bad references.


My if statements are working everywhere except in my hook_block_view function I am trying to make a custom form block in drupal.  I want it to display my form, then after submitting, show the results.  I have an if statement in the hook_block_view function saying if my form has been filled out to set $block['content'] to "Form Submitted".  This doesn't work though, it just displays the form again.  I have the same if statement in my hook_form_submitted function to either set drupal_set_message to either 'Submitted' or to display what was put into the form.  After submitting, when the page reloads, The form still displays, $block['content'] does not get set, but drupal_set_message() does.  What am I doing wrong?

Just thought of something, my block_view() only passes ($delta = '') is it just that $form_state['values'] is not being passed through the function?

<?php

/**
 * @file
 *
 */

 /**
 * Implements hook_block_info().
 */

 function search_engine_block_info() {
     $blocks = array();
     $blocks['search_engine'] = array(
        'info' => t('Search Engine'),
        'cache'=> DRUPAL_CACHE_GLOBAL,
    );
    return $blocks;
 }

 /**
 * Implements hook_block_view().
 */

 function search_engine_block_view($delta = ''){
     $block = array();
     switch ($delta) {
     case 'search_engine':
         $block['subject'] = t('Search Engine');
         //Check to see if the form has been submitted.  If not, show form, or else show results.
         if(!isset($form_state['values']['searchInput'])){
            $block['content'] = drupal_get_form('search_engine_form');
         }else{
            $block['content'] = 'Form Submitted';
         }
     }
     return $block;
 }

 /**
 * Implements hook_form.
 */

 function search_engine_form ($form, &$form_state){
    $form['searchOptions'] = array(
        '#type'     => 'select',
        '#title'    => t('You can search by GWF Number, name, email address or phone number.'),
        '#options'  => array(
            'gwf'           => t('GWF Number'),
            'applicant_email'   => t('Email Address'),
            'name'          => t('Name'),
            'phone_number'      => t('Phone Number'),
            ),
        '#value'    => 'gwf',
    );
    $form['searchInput'] = array(
        '#type'     => 'textfield',
        '#title'    => t(''),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value'=> t('Submit'),
        );
    return $form;
 }

 /**
 * Implements hook_form_submit.
 */

 function search_engine_form_submit($form, &$form_state){
    if(isset($form_state['values']['submit'])){
        drupal_set_message('Sumbmitted!!');
    }else{
        drupal_set_message($form_state['values']['searchOptions']);
    }
 }

$form_state['values']['searchInput'] is undefined in that function so this will never work. You could remove the if in this function and let search_engine_form return HTML if it is submitted. You can add it inside the if you're using for the message display.

You maybe have to use the #rebuild option on that form, so it gets rebuild.


Newsletter and email limit of provider Possible Duplicate:
  How to add newsletter functionality in drupal 7 (just stable modules if possible)

I need to know a good email newsletter system for Drupal that can trigger email send in batch. I know in WP how to do that, but have to previous experience with Drupal. I Have about 1000 email, and the provider allow only 200 mail / hour, so i need and option to send let's say 150 mail / hours and let the system go under the radar. Please, don't tell me to use mail-chimp, i know and it's not in Drupal but outside. i like a solution build in !

thanks in advance

My advice is to use "MailQ" (For Drupal 7 you can use "Queue Mail" instead) and "Elysia Cron" modules together.

Configure MailQ module to send 50 mails per one batch.

Configure Elysia Cron module to run MailQ cron hook every 15 minutes.
(note you need configure you cron job to run every 5 minutes or even often, more details in Elysia Cron readme.txt)

In this case MailQ will send 50 emails each 15 minutes - and you will got no more than 200 emails per hour.


Firefox/IE not displaying CSS with Drupal website In Firefox and IE (and maybe others?) it seems that the blocks that are built by drupal aren't having CSS applied to them.

Any help at all would be wonderful, as the issue I'm having is not knowing where the issue lies. The site is http://confluencenter.arizona.edu/.

p.s.
I am very new to CSS and Drupal

It's more like a CSS issue. Your CSS has to be more organize and standard cross browsers. Try not to use "!important", because you don't want to over-use it as you will end up causing headaches down when maintaining the site.

Here are some example you can fix.
Under file "blocks.css" line 303.

.pane-block-4, .pane-block-5, .pane-upcoming-events, .pane-block-6 {
  width: 31.25% !important;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

Since there are 3 classes on each "div"(panel-pane pane-block pane-block-4), you should use something like this instead

#mini-panel-front_blocks .panel-pan {
  width: 31.25%;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

Hope this help


IMCE image upload and permissions issue I've implemented the IMCE module and added it to the CKEditor. When we upload files though, the resized images come out fine, but the uploaded file itself is saved in the same directory with incorrect file permissions, which causes the file to not be viewable in the browser.

Upon inspection, the uploaded file has no effective permissions for the IUSR account, but the resized images have the needed permissions for IUSR.

Does anyone know how I can resolve this issue?

We are running IIS7 with Drupal 6.

The real issue is file permissions. When PHP uploads a file, it saves it in the temp directory. When that file then gets moved it retains the file permissions from the temp directory and does not inherit the destination folder permissions.

So check folder permissions of both your temp folder and the destination folder.


How to Display Image after submitting webform in the confirmation message page I have added field as file in webform so that we can add image in this file field. Now i want to display next page after submitting image file by using following code

[submission:values:image_file]

but I cant able to display the image in the confirmation page. how to display the image in the next page

Instead of it you can directly try to add image in Confirmation message.
You can find that under form settings in webform.

like this : <img src="[submission:values:image_key]"/>


Any way to add CSS for a single page/node? I'm cleaning up my big crazy style sheets (possibly pertinent to a future question) and I'm wondering the best way to add custom CSS to a specific node or page.
In particular, my work site's home page is a Panel Page and it has a bunch of different styling. Right now the CSS is just included with the main theme style sheet.
Is there a way to say, "if this is node Foo, then add foo.css"? Is CSS Injector what I'm looking for?
I might be interested in generalizing this to other nodes/sections/etc, but at the moment I just want to handle this one item.

This is the sort of thing that I'd do by code, but that's because that's just the way I roll.

In the template.php you will want something like:

function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'foo') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

Replace foo with values related to your own code.


How can I make Rules react to `User has logged in` when user logs in through CAS? I want to execute some php code when users log in, so I'm experimenting with the Rules module. I have it configured to fire a function of mine when a user logs in and it works fine, but it only works if the user logs in through Drupal. I am using CAS to authenticate users (thanks to the CAS module) and if a user logs in with CAS, the function never gets called. Is there any way to solve this?

Here is the function which is successfully called when a user logs in through Drupal:

myModuleName.rules.inc

function myModuleName_rules_action_info () {
    return array(
        'hello_rules_world' => array(
            'label' => "Print Hello World to error.log"
        )
    );
}

function hello_rules_world () {
    error_log("Hello Rules World!");
}

And here is a screenshot of the configuration:

UPDATE: I ended up using hook_user_login, which detects all logins without problem:

myModuleName.module

function myModuleName_user_login (&$edit, $account) {
    my_user_login_function($account);
}


How should I structure a multiple-value Field Collection where each value is uniquely named? I have a content type for a collage of six photos. For each photo there is a caption, a link, some link text, and the photo itself. The photos are of different sizes and in different places, and there can be only one photo in each spot per collage.

If I just use Field Groups, I have to create a different CCK field per photo per field, for a total of 24 fields.

If I use a single level of Field Collections I can get that down to six separate Field Collections and four CCK fields, but if I need to make a change that applies to all six photos, I have to make the change six times.

I can use two levels of Field Collections, with a main Collection that contains the four fields, and six other Collections named "Top Left", "Top Right", etc., each of which contains only the main Collection. This is maximally abstracted and would probably do, but it makes the node editing interface look like this:

Those redundant fieldsets are bothersome and are a dead giveaway that the underlying data is architected badly.

Using a single Field Collection that allows multiple values seems the most correct. It gets me down to one Field Collection and four fields. But the repeated groups don't have any identifying information other than their deltas, and if the client ever needs to add one they won't be able to keep track of which line corresponds to which spot in the collage.

Is there a way for me to put identifying information on each of the repeated values of a field or Field collection? Otherwise, is there a better way for me to do this?

You could simply add an additional field called "Location or Type" to the field collection with the various options. Then you can use that field in a view block to filter by, or even more simply in your node.tpl.php file.


How to put view results in an entity reference field? So the scenario is like this:
I have to create a "node" which has an entity reference field which can hold multiple values. I am looking for a way to be able to select view results to be stored in the entity reference field and I do not know how to do that in Drupal 8.
For Drupal 7 there was this module which does what I need https://www.drupal.org/project/entityreference_view_widget
I have tried doing it the custom way by creating views and placing them on the same page as the node create and then getting the resulting values with ajax to store in the field but I do not believe that is the best way to go about it as it does not seem reliable.
Any advice is appreciated.

The closest match to the link you shared is the Entity Browser module.

Goal of this module is to provide a generic entity browser/picker/selector. It can be used in any context where one needs to select few entities and do something with them.

The module allows you to build your own widgets (similar to the Media Library) to use with entity reference fields or in WYSIWYGs, via integration with the Entity Embed module. You can create widgets with multiple options, an option to create new content (with the entity_form submodule), and select existing content via view displays.