PHP evaluation for "Send HTML email body" I'm trying to compose the body of an email using PHP evaluation within a rule.  The rule is triggered when a new content is saved.  Part of the email body is composed using HEREDOC and that works fine.  This is the code I'm having trouble with:

//  Provide download link.
 if ($node->field_software_product_sku === "Some Product Name")
     echo "Trial Version Download Link
";

The above code comes directly after the ending of the HEREDOC, but, before the closing '?>'.  I anticipate that in the future, I will need to add more clauses to the 'if' statement, so, it's important that I get this to work.

I've tried several different incantations for coding the 'if'.  I've tried using the token name enclosed in single quotes.  And, I've tried using “==” instead of “===”.  The only thing that seems to work consistently is commenting out the 'if'.  Then, the “Trial Download Link” text does appear in the email.  Unfortunately, the rule is to be used for multiple “skus”, so, I need to use the 'if'.

I'm hoping I've made a subtle mistake, or, overlooked something.

Can someone point me in the right direction?

Is there a way to debug the code to see why the 'if' may be failing?

If field_software_product_sku is text field you should test on value of the field something like:

if ($node->field_software_product_sku[LANGUAGE_NONE][0]['value'] === "Some Product Name"){
    echo "Trial Version Download Link
";
  }

other ways if it doesn't work, i suggest you to use Devel Module and dump the $node->field_software_product_sku using dpm function to see the value of the field:
dpm($node->field_software_product_sku) and then check on the value of the field.


Field Max Size limited to 10 for Integer in Number Module I'm trying to add an Integer as a new field to Users. Have installed the Number module and added a field type 'Integer' with a maximum value of 999999999999999999. But when I edit a user the field has a max length of 10. Is there a way to edit this?

Maximum number that Number module can hold is 2 147 483 647 (231 - 1), because of the size of SQL INT datatype. For larger numbers you must use string field or Bigint module, that allows to storing numbers up to 9 223 372 036 854 775 807 (263 - 1).


translate(localize) specific title of web form use preprocess func I have specific webform call careers , i have use webform localization model but the model does not translate the node title , some one told me to use  preprocess node func. but i did not now how to create theme i try to write some thing like this

function [themeName]_preprocess_page(&$variables) {
  if($node['id'] == 6) {
  $node['title'] = t($node['title']);
    }

But it does not work

The code doesn't work because the function receives only a parameter, and that is not $node. The correct code should eventually be the following one.

function mymodule_preprocess_page(&$variables) {
  if(!empty($variables['node']) && $variables['node']->nid == 6) {
    $variables['title'] = t($variables['title']);
  }
}

I am assuming you want to change the title when the node ID is equal to 6.


SQL query to access a field collection's data? At them moment, I'm only getting field_collection_item returned In the below example, I am trying to return the value of a field from all the field collections in the database but only get field_collection_item. This example is just the most basic field collection sql possible.

SELECT field_collection_item.item_id AS item_id, 'field_collection_item' AS field_data_field_grade_decimal_field_collection_item_entity_
FROM
field_collection_item field_collection_item

What do I need to change in this example? My SQL is terrible unfortunately. I just can't return any values from field collections using sql. I need to be able to do this for Forena Reports.
I'm getting the above code from views which returns the field collection values.

You can use the field_collection_field_get_entity() function to obtain the desired result without writing SQL, like this:

$node = node_load(12);
$items = field_get_items('node', $node, 'field_fc_field');
foreach ($items as $item) {
$fc = field_collection_field_get_entity($item);
// Do something with $fc
dpm($fc);
}


Add description for Field Group I am using the Field Group module on my user registration form.

Is there any option to add a help text (description) to the whole group, which has 7 input fields?

I want the users to be able to see some description text below the FieldGroup heading.

Go to Content type > Manage fileds > Field Group.

In the filed group you can find settings icon beside.

Clicking on that will give you a field to add description to.


Does Aegir 3 allow multiple SSL sites on the same IP Address? On our server some sites use SSL, some don't, some are Drupal sites, some are not.
All the sites are served at the same IP address and the non-Drupal sites each use their own certificates (or none) per their Apache configuration.

With Aegir 2 it was only possible to have: one IP Address for non-SSL sites and one IP address per each SSL Drupal site which would exhaust our purchased IP addresses.

Does Aegir 3 allow multiple SSL sites / certificates on the same IP address?

Indeed it does. From the release notes:

  Aegir 3 now supports SNI for SSL.


Query condition on entity reference field count I need to query an article with more than 1 tag (a field entity reference) in drupal entity query.

I tried this :

$query = Drupal::entityQuery('node')
                ->condition('type', 'article')
                ->condition('field_tags', 1, '>');
dd($query->execute());

But I got more than expected the articles id's and I don't why.

What is the good query to do that ?

Try to use the delta. This is explained here: QueryInterface:

$query = Drupal::entityQuery('node')
            ->condition('type', 'article')
            ->condition('field_tags.%delta', 1, '>');
dd($query->execute());


Localization - Hello World Example I am extremely tired right now and don't have time to read through verbose drupal 7 documentation.  Can someone just show me a quick Hello World example that will do the following in drupal 7?

I have a template file /sites/all/themes/mytheme/page.tpl.php and in it I have

<?php echo "Hello World"; ?>

When a person comes to the page in English, it should show "Hello world".  When the person comes to the page in French, it should show "Bonjour tout le monde".  How do I augment the command echo "Hello World" to do such a thing?  If language files are needed, show me how to structure them.

Thanks

Instead of "Hello World", use t("Hello World").

Using the Localization client module, you can add the translation of that string in any language you want.

  This module helps you fix translations on your site as you see the issues. Just by navigating around your pages, you'll be able to fix translations and fill in missing ones using the on-page translation editor. At the same time, if configured properly, the module also submits your translations back to the community, to localize.drupal.org or any other localization server.


How to use field variables in un-formatted view template? If found this, but I can't manage to apply it to my case. Here goes. (I'm new to PHP coding and Drupal.)

I want to add a HTML link into each row of my unformatted views template. For each row I want the link for the relevant piece of content.

I used the devel dpm to reveal the variables in the unformatted.tpl.php. But I can't find a variable for the link field. (I've added the Content: Link field in views and it's hidden.)

My understanding at the moment is I'll need to set the variable in the relevant preprocess function, which might look like this:

 function mytheme_preprocess_views_view_unformatted(&$variables) {
    $link = Location of link field variable
}

And then use it in the views template:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
    <?php print $link; ?>

<?php endforeach; ?>

But I can't find the link information and I can't find similar examples so I've probably gone badly wrong. How would I do that and is my basic understanding ok?

Ok so I've managed to get it working with:

<?php print $view->style_plugin->row_tokens[$id]['[view_node]']; ?>

I tried to use:

<?php print $view->style_plugin->row_tokens[$rows['id']]['[view_node]']; ?>

But it kept throwing undefined index errors, even though it was valid path from DPM.

rows (array)
  id (value)

id (the variable I used in the top working solution) didn't show in my DPM. Is that because I was calling it for the views unformatted tpl and id is a global variable?


Give access to private files to certain role? I have a few image styles set up. But they are all stored as "private" files. I want to be able to give anonymous users public access to these files, or find some other way by which to generate access to this file. My goal is to provide access to private files for certain anonymous users depending on certain conditions.

I am hiding all images on the server to avoid anyone accidentally gaining access to them, but some "private" images should be viewable if a certain style is applied. For example, I am selling images on my site. The "waterproof" image style should allow any user (including anonymous) user to see the private file preview. But only logged in users should be able to view it with the "high_res" thumbnail.

This is how I generate the URL:

$imageURL = file_create_url($badge->field_badge_image_image->entity->getFileUri());

This url can only be accessed by logged in users. If I try this code, I still get access denied.

$imageURL = ImageStyle::load('farm_logos')->buildUrl(
    $badge->field_badge_image_image->entity->getFileUri()
);

Is there no way to generate a URL that is accessible via public?

I also tried the "hook_file_download":

function mymodule_file_download($uri) {
    return array(
        "Accept" => "Accept",
        'Content-Type' => "image/jpg"
    );
}

But I was hoping this would make all private files public, but unfortunately it did not.

I found the problem. As per this page:

Once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.
For example: you have created a new content type with a file field which stores files in your site's private file directory. Next you create a node from this new content type and attach two new files. When the node is published links to both attached files are visible and anyone who can view the node may download the files. Now, if you unpublish the node, all attached files become inaccessible for download even if you use the direct link to the files that worked when the node was published.
Re-publish the node, and disable the "display" checkbox for one of the files. Save the node. Now one file is accessible for public download and the other is not accessible--even if you have the direct URL for the file that is not listed you will not be able to download this file.

So the problem was that I was expecting you could access a file if you have the right URL, even if that file is used on an UNPUBLISHED node. So to solve my problem I:

Published all the nodes I needed to have access to the image
Used "Rabbit Hole" to hide the nodes from the public


How can I have the nodes grouped in descending order and the nodes in ascending order? I have a view listing articles grouped by year (on the post date) which returns me a HTML list like this.

2018

- Article Feb 01, 2018
- Article Jan 05, 2018

2017

- Article Dec 01, 2017
- Article Nov 05, 2017
- Article Oct 03, 2017
- Article Sep 05, 2017

The years are correctly sorted in descending order, but I would like to have the nodes of each year sorted in ascending order, as in the following list.

2018
- Article Jan 05, 2018
- Article Feb 01, 2018

2017
- Article Jan 10, 2017
- Article Oct 03, 2017
- Article Nov 05, 2017
- Article Dec 01, 2017

I have tried to apply an ascending sort on the content, but it also affects the years.

I have also checked Views: how to ASC sort the grouping field #1 and sort DESC its content?, but I don't want to add an extra field for the year.

I have also tried the solution posted on Views, Group By, can't specify order? but it didn't work for me.

How can I achieve it?

You can use hook_views_query_alter

function MODULENAME_views_query_alter(&$view, &$query) {
   //print_r($view->query->orderby);
  if ($view->name == 'VIEWNAME') {
  // check the position on the orderBy function in the query
  // For this you can check the values with print_r() function.
   $view->query->orderby[0]['direction'] = "ASC";
  }
}


Add author to a newly created node When users sign up, I create a new node and add that user into one of the entity reference fields through rules.
What I built so far is the following.

After saving a new user event
Create a new content item action (Parameters: type: advisor_student_matching_program, title: title comes here)
Set a data value (Parameters: data: node_created.field_university_student, value: @user.current_user_context:current_user)
Save entity (Parameters: entity: node_created, immediate: 1)

Everything works fine except for the third step.
uuid: 692696f4-4c6d-45cc-8a5b-3b69f1925bd0
langcode: en
status: true
dependencies: {  }
id: register_university_student
label: 'Register University Student'
events:
  -
    event_name: 'rules_entity_insert:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 6f4c1ccb-973c-48ec-aed1-637bdb50e301
  weight: 0
  conditions:
    id: rules_and
    uuid: 3f479a19-06b2-4e05-80c2-4cff28650409
    weight: 0
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: abbb62e5-a610-4ab7-8e3a-f96a4570f049
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 3bce44f5-accb-4239-9c1d-377f29debebf
        weight: 0
        context_values:
          type: advisor_student_matching_program
          title: 'title comes here'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: eba88823-1ab3-493a-9b62-e22e49a2db4a
        weight: 0
        context_values: {  }
        context_mapping:
          data: node_created.field_university_student
          value: '@user.current_user_context:current_user'
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 779eadc9-f208-4cfa-b37e-351126c56243
        weight: 0
        context_values:
          immediate: '1'
        context_mapping:
          entity: node_created
        context_processors:
          immediate:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_entity_save
      -
        id: rules_action
        uuid: 18d0c0d6-d9c6-4fc9-8127-4291fe80081c
        weight: 0
        context_values:
          url: /register-uni-basic-information
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect

Should have used user, instead of @user.current_user_context:current_user.


How to change string which comes from breadcrumbs? I have used custom breadcrumbs module.

Now one of my title of blog has single quote or double quotes, which is having problems.

So, in titles i have added

  [node:title]

so output of the title whose having quotes are like

Home > blog > Politics > No Democracy but many other &#039;o-cracies&#039;

and i have added hook which will show the output is like this..

function myowntheme_breadcrumb($variables) {
    $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > -1) {
    return implode($sep, $variables['breadcrumb']);
  }
  else {
    return t("Home");
  }
}

How to remove that hash tag values and show on simple version ?

Your nodes contain apostrophe in their title. Node titles will be passed through check_plain() function and it uses htmlspecialchars() function to convert the quotes to HTML entities.

You may try by decoding them back

function myowntheme_breadcrumb($variables) {
    $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > -1) {
    return htmlspecialchars_decode(implode($sep, $variables['breadcrumb']),ENT_QUOTES);
  }
  else {
    return t("Home");
  }
}


How to access the published field in my PHP code? I am defining a datatype called slider

$nodes = node_load_multiple(array(), array('type' => 'slider'));
foreach($nodes as $slider):

and trying to iterate through each of them. I want to access the field which says if the content is publised or not. I tried this -

$slider->$status == 1

But this is not working.
Does anyone have a solution this problem?

Thanks

It is

$slider->status == 1

instead of

$slider->$status == 1


Limit reference field to nodes with referenced user I have two content types, Restaurant and Lunch.

Restaurant content is created by content admins, and can be viewed by anyone.

Lunch has an entity reference field that references nodes of type Restaurant.

Logged in users need to be able to create their own Lunch content, but only see their own Restaurant in the referenced node select list.

Content admins can also create Lunch content, but they need to see all available Restaurants in the select list.

I'm thinking I need to put a user reference field to the Restaurant content type, and then I could filter a reference view by the referenced user? But here is where I get stuck, how then will content admins be able to see all Restaurants in the select list?

I found this solution that works:

  Permissions (for a given content-type)
  Administrator & Staff - Edit ANY content
  Normal Member - Edit OWN content

  Views Contextual Filter - Content: Author UID

  WHEN THE FILTER VALUE IS NOT AVAILABLE
  - Provide default value: Type - "User ID from Logged in User"

  WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
  - Specify validation criteria: Validator - "USER"
  - Type of user filter value to allow - "Only allow numeric UIDs"
  - Restrict user based on role: Restrict to the selected roles - SELECT the role who can only edit his own content
  - Action to take if filter value does not validate - "Display All Results for the specified data" [important]

  The last step (marked important), makes all the data (view results)
  available to other users, who have access to edit any content.

See https://www.drupal.org/node/2317525


How can I find what nodes are causing 404 errors? I'm watching entries in my Top 'page not found' report page steadily rise.

I am unable to fix the 404 errors because I have several hundreds of nodes, and there is no indication of which node is causing the problem.

Is there a way I can see which nodes are causing the 404 errors?

Try a the "Recent log messages" report and apply a filter to show you only the "page not found" logs. You will then see a list of pages not found and you can click on the message to find out more details about it.

If the problem is that a lot of pages change their path then you might want to use the "Path Redirect" module (http://drupal.org/project/path_redirect) if you are using Drupal 6 or the "Redirect" module (http://drupal.org/project/redirect) if you are using Drupal 7 to let search engines know about the new path of the content.

Note: if you have clean URL setup make sure it is working and you are not missing the .htaccess file. It happen to me once when I move a site from dev to production and I didn't copy the .htaccess file.


Search in comments of specific content type I'm looking for a module that provides the possibility to filter/search in comments.

When there is content of the content type = Proposal you can comment on it. There's a good change that there will be 50 comments or more. Now I would like to have a search box beneath my content, above my comments that filter the comments when you search for a string.

I would also need to filter the comments for ex. between dates, by username, by number of votes, ... .

I've searched the internet but couldn't find anything that provides this functionality.

Has anybody ever needed this and which module you used or how did you approach this?

It's something like this I need:

For this you need to enable vote up/down and voting api module enabled
Then enable voting for 'Proposal' content type mentioned in the image

Now import the below code mentioned in views.

$view = new view();
$view->name = 'proposal_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Proposal comments';
$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['title'] = 'test comments';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['link_display'] = 'custom_url';
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* 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'] = TRUE;
/* Relationship: Comment: Votes */
$handler->display->display_options['relationships']['votingapi_vote']['id'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_vote']['field'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
);
$handler->display->display_options['relationships']['votingapi_vote']['current_user'] = 0;
/* Relationship: Comment: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
  'function' => '',
);
/* 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']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
/* 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';
/* Filter criterion: Comment: Author */
$handler->display->display_options['filters']['name']['id'] = 'name';
$handler->display->display_options['filters']['name']['table'] = 'comment';
$handler->display->display_options['filters']['name']['field'] = 'name';
$handler->display->display_options['filters']['name']['exposed'] = TRUE;
$handler->display->display_options['filters']['name']['expose']['operator_id'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['label'] = 'Author';
$handler->display->display_options['filters']['name']['expose']['operator'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['identifier'] = 'name';
$handler->display->display_options['filters']['name']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Comment (comment_body) */
$handler->display->display_options['filters']['comment_body_value']['id'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['table'] = 'field_data_comment_body';
$handler->display->display_options['filters']['comment_body_value']['field'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['operator'] = 'contains';
$handler->display->display_options['filters']['comment_body_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['comment_body_value']['expose']['operator_id'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['label'] = 'Comment (comment_body)';
$handler->display->display_options['filters']['comment_body_value']['expose']['operator'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['identifier'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Post date */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'comment';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['exposed'] = TRUE;
$handler->display->display_options['filters']['created']['expose']['operator_id'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['label'] = 'Post date';
$handler->display->display_options['filters']['created']['expose']['operator'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['identifier'] = 'created';
$handler->display->display_options['filters']['created']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Votes: Value */
$handler->display->display_options['filters']['value']['id'] = 'value';
$handler->display->display_options['filters']['value']['table'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['field'] = 'value';
$handler->display->display_options['filters']['value']['relationship'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['exposed'] = TRUE;
$handler->display->display_options['filters']['value']['expose']['operator_id'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['label'] = 'Value';
$handler->display->display_options['filters']['value']['expose']['operator'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['identifier'] = 'vote';
$handler->display->display_options['filters']['value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-comments';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['link_url'] = 'demo';

It will create a block in the admin/structure/block mentioned
 in the below image. Assign it to 'Proposal' content type.

It will be displayed under proposal node view page this way

Hope it will help you.


/admin path display login box along with access denied message (drupal 7) In drupal 6 when visiting /admin, an access denied message was shown in the admin theme along with a login box. How can I do the same in drupal 7? Currently the regular theme is shown along with an access denied message.

You need to give anonymous users "View the administration theme" permission. Then to provide a login box along with the access denied message, use the Login Toboggan module.


Why did the Apache directive to handle a clean URL get changed? I noticed that the clean URLs implementation has gotten more complicated in Drupal 7. Rather than RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] used in Drupal 6, Drupal 7 .htaccess has simply RewriteRule ^ index.php [L], with a comment that says "Clean URLs are handled in drupal_environment_initialize()".

I read through drupal_environment_initialize() and understand that it's using REQUEST_URI to manually set $_GET['q'], but why the change? I see the comment:

// When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
// not possible to append the query string using mod_rewrite without the B
// flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
// path before passing it on to PHP. This is a problem when the path contains
// e.g. "&" or "%" that have special meanings in URLs and must be encoded.
$_GET['q'] = request_path();

I've got some idea what this is saying, but can anyone explain in fuller terms the reasons behind the change? If it wasn't done this way before, was something (minorly or seriously) broken in Drupal 6 and prior?

There was something seriously broken, but it only affected a handful of cases due to fringe nature of the issue. Essentially, what happens is roughly (%26 == &):

Request: /lost%26found
Rewrite: /index.php?q=lost&found

The issue here is obvious when you see it this way: you end up with two $_GET variables, q = 'lost' and found which isn't set properly. Since the q variable is truncated, you end up with the wrong page or a 404 error.

Drupal 7 fixes this by simply redirecting to index.php and then parsing the original query string manually itself, bypassing Apache and PHP's parsing of it entirely.


How to hide row cell when using table in forms? I have a field widget that has multiple values per field and some are values or other form types that do not render any visible data. I want to use the table element to encapsulate these fields into proper structure.

The issue I have is that for each field within the "field"(ie. table row) a table cell is created, even for values, which resutls in empty 	. Sure, I can use the colspan on headers but that also requires adding some css styling to hide those empty cells to avoid padding/margin offsets from those empty cells.

So I am wondering if it is possible to somehow tell the row which fields to put together into one cell or maybe render them outside of the table itself. I could use a custom template but I need to use the tabledrag so I don't want to reinvent the wheel.

I also don't want to alter the structure of those fields since it is very important the structure stays the same. although I could probably fiddle with array parents, I'd rather not.

So ss there a simple way I can get rid of those empty cells that hold values and hidden fields?

--
I have found an old Drupal issue when I was going through the Table code https://www.drupal.org/node/1248940

I've just implemented it using a theme preprocessor to alter the tag from <td> to <span> and I've added the hidden and aria-hidden attributes. Hidden by itself works but it isn't supported by < IE10.

So as to prevent the loops on every table I've added a class to the table as well so I'm checking for 'form-table' first.

/* Implements MODULE_preprocess_HOOK */
function mymodule_preprocess_table(&$variables) {
  if ( ! in_array('form-table', $variables['attributes']['class']) )
    return;

  // Iterate the variables looking for form elements that have the type hidden
  foreach ($variables['rows'] as $key => &$row ) {
    foreach ( $row['cells'] as &$cell ) {
      if ( $cell['content']['#type'] == 'hidden' ) {
        $cell['attributes']['hidden'] = TRUE;
        $cell['attributes']['aria-hidden'] = 'true';
        $cell['tag'] = 'span';
      }
    }
  }
}


Error using module_invoke_all('requirements', 'runtime') in my custom module Why do I get

Additional uncaught exception thrown while handling exception.
Original
Exception: theme() may not be called until all modules are loaded. in theme() (line 920 of C:\wamp\www\test\includes\theme.inc).
Additional
Exception: theme() may not be called until all modules are loaded. in theme() (line 920 of C:\wamp\www\test\includes\theme.inc).

when try to call
    module_invoke_all('requirements', 'runtime')

from my custom module?

My guess would be that you have that line of code outside a function in your module. That doesn't work.

I have no idea what you are trying to do but you should at least move it into a hook, like hook_init() so that it's only executed when Drupal is fully bootstrapped.


View for the user followed by the author of a node I have installed the Flag module, and I have a view that displays how many followers (flags) an author has. How do I reverse that query, and output how many users that author is following?

This is a little tricky, but it is very similar to the article posted at http://drupal.org/node/326580.

Create a view of users
Add the "Flags: User flag" relationship making sure that the flags are by any user.
Add the "Flags: User" relationship which will allow us to filter by the person who did the flagging.
Add a contextual filter (D7) / argument (D6) fir the "User: Uid" and make sure is uses the "Flag user" relationship.
In contextual filter / argument, select the "Provide default value" option and add the following code snippet to pass the node author as the value.

Code snippet:

if ($node = menu_get_object()) {
  return $node->uid;
}

In order to get the count it will depend on whether you are using Drupal 6 or Drupal 7, but using the Views Group By module for D6 or the internal Aggregation features of D7 should be able to get you the number of users.


Node blog dislpay all content type blog in theme I have content type page with node called blog(page blog) and I want to display all content type blog in it(content of page blog). how can i do this in theme without using block or views.I'm try to do it by using this code:

<?php
$build = array();
$query = db_select('node', 'n')->extend('PagerDefault');
$nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(3)
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes,'full');
    $build['pager'] = array(
        '#theme' => 'pager',
        '#weight' => 5,
    );
}
else {
    drupal_set_message(t('No blog entries have been created.'));
}

    print render($build);
  ?>

and set it in body field for page blog. And when display blog page it's content nothing (or empty page!). I'm test my code and execute it in php code it work and print all blog that I have.
Any way to do this in Drupal theme?

if I understand correctly you'll need this query:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'blog')
  ->propertyCondition('status', 1);

$result = $query->execute();

then do you foreach($result);


Edit admin email template for new user registrations How do I edit the default email that gets sent to admin upon new user registration? I presume this is being managed by LoginToboggan because its being referenced in the email body text:

  UserName has applied for an account.

  http://example.com/user/XX/edit

  The user has automatically received the permissions of the LoginToboggan
  validating role. To give the user full site permissions, click the link
  below:

  http://example.com/user/validate/XX/XXXXXXXXXXX/XXXXXXXXX_XXXXXXXXXXXXXXXX-XXXXXXXXXXXXX/admin

  Alternatively, you may visit their user account listed above and remove them
  from the validating role.

If you look into logintoboggan.module you would see that this message is hard-coded and appended using the hook_mail_alter function and that it's altering the  Welcome (awaiting approval) (user_register_pending_approval_admin) located in admin/config/people/accounts. So if you like to append the data in the middle, you can edit the said email body in the admin page but if you also like to alter the message by logintoboggan then you need to implement hook_mail_alter also.


Views Data Export print feed icon in template file I created a template for my view (views-view-fields-xxx.tpl.php).  On my view page I use the 'Views Data Export Module' to export filtered views in XLS format.

I cannot figure out how to display the button on the top of the page.  I tried printing it out in my template file using :

<?php print $view->feed_icon ?>

but then it prints out the button on every field view.  Is there a way to print this field only once? Or another way to move the "feed-icon" to the top of my page?

Solution from: https://www.drupal.org/node/2117433#comment-9422881

Copy the views-view.tpl.php file from views into your theme (or its
templates directory if it has one). Note that you can rename the
file in certain ways to make it specific to an individual view or
display. The "Theme: Information" section of the views UI will give
you more information. Also see the blog post for more information on
that.
Clear the cache so the site starts using your new template file
instead of the default views one. The "Theme: Information" part of
the views UI should now indicate that your file is being used.
In your theme's version of the template file move the feed icon
section wherever you want it. Potentially you would put it under the
exposed filters or something. Currently the the feed icon part of
the template looks like this (move this whole section):

    <?php if ($feed_icon): ?>
      <div class="feed-icon">
        <?php print $feed_icon; ?>
      </div>
    <?php endif; ?>


Print a field in a set display mode I can print a field in content type tpl file with this:

<?php echo render($content['field_name']); ?>

But how can I print the field as a different display mode?

EG I might always want to print the teaser version of an image field, regardless of what view mode is being used.

There might be a shortcut to this but I don't know it...

// Get the bundle settings.
$info = field_info_instance('node', 'field_name', 'content_type');

// Get the field render array
$build = field_view_field('node', $node, 'field_name', $info['display']['teaser']);

// And print it
print render($build);

Moving the display building logic to a preprocess function would probably be a good idea.


The vertical tabs don't show when is one vocabulary I am working in Drupal 6, and I am using the Hierarchical select. If my taxonomy consists in two or more vocabularies associated to a content type, the vocabulary shows into vertical tabs but if my taxonomy consists in one vocabulary associated to a content type, the vocabulary doesn't show into vertical tabs.

I thank to you for your help.

It's the setting for "Minimum number of tabified fieldsets to show vertical tabs:" found at: /admin/settings/vertical-tabs

It's defaulted to 3, which means you must have 3 vocabs on the node type for it to put them in a tab... you can change the minimum value.


Get $form_state values from individual entity form fields I have a weird use case. I created a custom form with some fields and I added some other fields from one entity form like this:

public function buildForm(array $form, FormStateInterface $form_state) {
    $entity_fields = array('entity_field_1', 'entity_field_2');
    // added other form fields here
    $entityForm = \Drupal::service('entity.form_builder')->getForm($entity, 'default');
    foreach( $entity_fields as $key ) {
        $form[$key] = $entityForm[$key];
    }
    // etc
    return $form;
}

I need to get the exact entity field widget because these fields can be updated from the interface and I can't have them hard-coded.

Now, If I submit the form, the form state values for 'entity_field_1', 'entity_field_2' are empty. $form_state->getValue('entity_field_1') is returning an empty array. Other fields defined manually are returning the correct value when saving.

How do I get those entity field values? In drupal 7 I used field_attach_submit() to attach the form values to an entity.

You could also try $form_state->getValues()['entity_field_1'] as getValues() will build an array of values with the field name as the key.


Theming with css classes First of all I apologize for my stupid question...I am a new user in drupal and I don't know very much about php and css...
My trouble is the following:I have many elements in my website with class "field set" , all I want to do is to have a background and a border style for some of such field set, but I want to set differents style for a specific "fieldset" element! I try with firebug to find the elements and I found this:

      <form action="/completa-proximity" method="get" id="views-exposed-form-home-lista-completa-con-openlayer-page" accept-charset="UTF-8">

                <input type="hidden" name="circle_op" value="&lt;" />

                <fieldset class="openlayers-proximity-filter-exposed form-wrapper" id="edit-circle">

                  È a meno di
                  <input type="text" id="edit-circle-value" name="circle[value]" value="" size="3" maxlength="128" class="form-text" />
                  Chilometri

                  da
                  <input type="text" id="edit-circle-location" name="circle[location]" value="" size="20" maxlength="128" class="form-text" />

            </fieldset>

I want to set a specific background for the element:
   < fieldset class="openlayers-proximity-filter-exposed form-wrapper" id="edit-circle">
but I cannot find how to tell in the css to apply new style to this one and only this !!
I tried to set attribute to the class:
.openlayers-proximity-filter-exposed .form-wrapper .fieldset but nothing happened ..
Can anybody help me, please?? just tell me how it works when you have to customize classes into div as per this example.
Thank you all!!!!!

If you want to add a style to a particular element in CSS, you should use the ID of the element rather than the class as IDs are unique.

e.g

#edit-circle {
}


How to generate a link as 'href="#"'? In my theme, I have to output a toggle link like this:

Show LessShow More

Its not a real field or anything like that. Is there a way I can use link or path functions to generate this output instead? I am guessing since the title has two spans in it that I cannot, but lets assume there were no spans, I'd like to know if this is possible.

I tried:

{{ link('Show More', 'internal:#') }}

and

{{ link('Show More', '#') }}

The first one creates an empty href, which does not work. The second throws a fatal error.

You could just type it into the template and dont have to do anything clever or twig based? e.g.

Show more

The core html.html.twig quite happily does this for the #main-content link:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x


How to define an entity type within entity_get_info() Is it possible to define your own entity type so that a call to entity_get_info() returns your new type?

I found it. You use the hook_entity_info() hook.

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


How to set the Organic Group while saving a node based on the node's current language We want to use a hook_node_presave to set the Organic Group (OG) field on the basic page content type based on the node's language. We have created several OGs using nodes and each one is assigned a language so there is a mapping between Language to OG based on the OG node.

So basically, when the basic pages' language is set to en, then the OG with a language of en, will be assigned to the basic page's OG field.

Current nodes:

OG1
--Title = test 1
--language = en

OG2
--Title = test 2
--language = en-gb

OG3
--Title = test 3
--language = fr

basic page1
--title = some title1
--language = en
--og_field = ??

basic page2
--title = some title2
--language = fr
--og_field = ??

Expected result when the hook_node_presave is done:

basic page1
--title = some title1
--language = en
--og_field = OG1

basic page2
--title = some title2
--language = fr
--og_field = OG3

here is what i have tried, but not sure why it is not working (assume organic_group is the content type machine name)

function mymodule_node_presave(&$node) {

    if($node->type == 'page') {
        //get the OG node that has the same language as the current node
        $result = db_select('node', 'n')
           ->fields('n', array('nid', 'language', 'og_field'))
           ->condition('n.type', 'organic_group')
           ->condition('n.language', $node->language)
           ->execute()
           ->fetchAll();

        //store OG node's nid into og_field
        $node->og_field = $result->nid;
    }
  }

Using Rules, you can add an event for when a new node is saved, add conditions for both content type and language and then use an action for assigning the OG's nid to the og_group_ref field.

Use set a data value if cardinality of the node is set to 1 or add to list for more than 1.

Without rules or code, I would have a new node link in each organic group and prepopulate the language and og_group_ref fields.


How can I PUT a new file to a node using services 3 without overwriting the existing file? Using Services 3 I have it working fine to add a file using

endpoint/file
{"uid":"1","filesize":"99999","filename":"whatever.bin","file":"BASE64_ENCODED_DATA"}

and also to add a node with that file using

endpoint/node
{"title":"testrest1","type":"dl","field_dl_file":{"und":[{"fid":582}]},"uid":"1","language":"und"}

But how can I add a new file to the node? When doing PUT

endpoint/node/999
{"field_dl_file":{"und":[{"fid":999}]},"uid":1,"language":"und"}

It just overwrites the existing file. Trying to POST gives a whole bunch of errors.

Background

Services uses drupal_execute() with the node form to save updates to nodes, which won't entirely merge updates in with existing data.

If the update doesn't set a field at all, then it won't overwrite what's there, so in a sense it does merge data in that case. For instance, in your example, you don't set "title" in your update, and therefore it won't overwrite that field.

However, if you set a field, it will overwrite whatever was there previously. So, in your example, since you are setting "field_dl_file", it will overwrite whatever was previously there with whatever you set now. As you saw, this causes any existing files to be overwritten.

Solution

Probably the best solution (and I assume the one intended by the Services team) is to load the previous value of the "field_dl_file" in your script (via a retrieve call to the REST interface), then call the update with both the new value as well as the old value. In other words, merge the old data in with the new data on the client side (inside the script that interacts with the REST interface).

Another possible solution is to manually merge your "field_dl_file" field with existing values inside node_resource.inc (line 365 or so). I assume the Services team never intended this, and it would require changing the module directly (since there aren't any hooks there), so I can't really recommend it. It would, however, ease the work needed in the client-side script, which could be a benefit depending on your implementation.

Note: I referenced Drupal 6 code, though I'm fairly sure it applies to Drupal 7 as well (that part of Services 3 didn't change as far as I know).


How to print custom text on search no result with search-results.tpl.php? I want to print custom text if there is no result on search.

I'm using custom search-result.tpl.php and search-results.tpl.php.

My search-results.tpl.php is that:

     <?php if ($search_results): ?>

<?php print t($search_totals);?>

        <table class="views-table cols-4 search-results <?php print $module; ?>-results table table-striped">
.../* my results style here */

            <?php print $search_results; ?>

      <?php print $pager; ?>

    <?php else : ?>

<?php print t('Your search yielded no results');?>

      <?php print search_help('search#noresults', drupal_help_arg()); ?>
    <?php endif; ?>

It works correctly if there are search results but if there is no result it doesn't print anything although there is the <?php else : ?> part.

How can I print custom text if there is no result?

The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are no search results.

If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.

Open that file up for editing and you'll see the following at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

This is what's displayed if search results are not found (thus the 'else')...  Modify the text to be anything you want here.  The second line, which calls the search_help() function is the one that displays the search suggestions.  Feel free to replace that too....

And as always, before you can see your changes, you'll probably need to clear cache!


Field group horizontal tabs are displayed as accordions in small screens On Drupal 8 site using the default Bartik theme, I have setup the article content type to be displayed in horizontal tabs based on the "field group" module.

On normal/large screens, the article display page is rendered in horizontal tabs style (Good!):

However, in small screens, the article display page is rendered in accordion style (Not good!):

I have found an answer here Horizontal Tabs rendered as rendering collapsible fields which is for Drupal 7 and I didn't know how to convert it to work for Drupal 8.

Does anyone have an ideas how to keep the article display rendered as horizontal tabs for whatever screen sizes?

Perhaps try out the patch to make this setting configurable as proposed for field_group module in this issue

Users have reported that it applies cleanly and allows for the setting to trigger based on a custom breakpoint.

Testing it out and reporting success/failure on that issue gives a better chance for this feature to be incrorporated into the module itself.

NOTE: the patch probably needs to be applied to the dev version of the field_group module


How to register multiple member in one civicrm membership sign up form? I have a special promotion price set for member: Register 1 new member is USD 500, register 2 new members in one-time is USD 800.

In my membership sign up form (created using contribution page), I would like the user to enter 2 member details during sign up.

I found this function in event page, where user can register multiple participants in one event, and make payment. But, the payment can't extend the membership period and can't create new membership.

I tried to adjust my price set setting by changing "used for" option, but it shows error of "If you plan on using this price set for membership signup and renewal, you can not also use it for Events or Contribution."

By selecting it using for membership, I can choose the price option to have different number of terms. But, this can't be used in event page which allow multiple registration of participant / member.

Is there any way I can register multiple member in one membership sign up form?

I don't think you can do this directly within CiviCRM via the user interface. I get around this problem by using the webform (https://www.drupal.org/project/webform) and webform_civicrm (https://www.drupal.org/project/webform_civicrm) modules. Using this you have a far more flexible approach, and can produce a sign-up form that can create memberships for multiple contacts.

I've never understood why CiviCRM, which has a membership management as a core function, does not provide this functionality itself.


Cannot find module folder I installed Simplenews 8.x-1.0-alpha2 using /admin/modules/install and then pasting the url to the tar file.
Now I want to uninstall/delete it, but I cannot find where the folder is.
I have checked in /modules and /core/modules
I even tried uploading the dev version to the /modules folder, but it does not ask me to overwrite.
This is so strange, where else could it be?
Update
I tried as suggested by sanzante using Devel and echo drupal_get_path('module', 'simplenews')
it says modules/simplenews

but when I try to go there with FileZilla, it does not let me. I also re-started FileZilla multiple times.

Turns out that his site was moved to another server.

The FTP that I was seeing was from the old server. When I installed the simplenews it got installed in the new server.


How do I show related nodes as attachment in the term view block? I have created a term view and content view for list the terms nodes.
How can I show related nodes as insert view in term view block in Drupal 7?

To insert one view into another (and pass arguments) as a field use Views Field View module.

You'll have to use Has Taxonomy term ID Contextual filter in your Content Study Views, as No Sssweat suggested in comments, but you only need to choose the option to load it from the term page (not node page). And you don't need the additional ID Contextual filter for any exclusion (because you're not displaying it on node pages).

Then include that Content View as a Field on your Term View, it will automatically filter out correct Studied on each Term row.


Could anyone suggest a Drupal database versionning tool? Possible Duplicate:
  How do I manage collaborative development on a Drupal site?

Is there any Drupal database version like GIT for versionning files ? with drush or any thing else ?

I've already used features module but it doesn't cover all needs in database versionning to get back to one saved version of the project.

The real point is to get drupal usable by many "site builders" and can manage conflict. on some features

Thanks. :)

I think the Backup and Migrate module will help you. Here is a quote about it (from the module's project page):

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


Gmap/location design question Which modules and function should I use to store address of house and also display Google Map of it? I also want to use postal code, province, city each in views etc independently.

I understand I should use GMAP + location.

But not sure if I need to use Location CCK or Node Locations.

What is the best way to accept address and also show Google map in the node?

I don't know the relative merits of Node locations vs Location CCK for this scenario, but the CCK option's worked for me. Edit: With GMap enabled, you can select a Google Map as the field's formatter by going to Content management -> Content types -> Edit [content type] -> Display fields. If GMap's enabled, you should see an option Map only. CCK will handle storing the data. See my comment on this Q for how to get the table details. Edit2: Actually, if memory serves, Location doesn't store the CCK data as you might first expect. location.module stores locations in its own table, and the CCK field just stores an ID into that table.


Migrate Quiz Results Data I need to "migrate" all quiz results from one website to a new one. The quiz ID is different between sites, and therefore, copying over the table from mysql won't work. However, I've made sure that user IDs are the same.

The new website isn't launched yet and there is a lot of flexibility for how I need to set things up in order to migrate in the most ideal way.

Edit: Alternatively, is there any reason I shouldn't just migrate the quizzes with the same node ID?

Edit2: I am using quiz version 7.x-5.1 on the new site but if they have to be the same, I'll have to rebuild the training feature with the version on the old site, which is 7.x-5.0-alpha4+77-dev. We have about 25 quizzes with 10-30 questions each.

This isn't the "Drupal way" to do this, but I accomplished a successful quiz results migration by making a few compromises and doing things in an unorthodox way. If anyone can build upon this and add a new answer with the correct way accomplish, I would be delighted!

The compromise I made was not allowing users to view their old results, just their score. I also decided not to use the certificate and created a view page instead for individual scores to make a certificate that way. (See this SE Post for my issues with Certificate.) This killed 2 birds with 1 stone.

Steps I followed for a successful migration trial on the test website:

Add quiz_node_results table to new database:

mysql> insert into drupal.quiz_node_results (result_id, nid, vid, uid, time_start, time_end, released, score, is_invalid, is_evaluated, time_left) select result_id, nid, vid, uid, time_start, time_end, released, score, is_invalid, is_evaluated, time_left from drupal_web.quiz_node_results;

Replaced NID of quiz results with new quiz nid, run once for each quiz (there were 18 quiz nodes):

mysql> update quiz_node_results set nid = replace (nid, [old quiz node ID], [new quiz ID]);

Removed "view quiz results" from Gradebook view (custom view I built for showing results).

Please comment with foreseeable issues with this method.


jcarousel not working on block? 1) Place this module directory in your modules folder (this will usually be
   "sites/all/modules/").

2) Enable the module within your Drupal site at Administer -> Site Building ->
   Modules (admin/build/modules).

I have installed jcarousel module as shown in the above steps.
After that I have create a new views (block) and then added format jcarousel
On the settings I have added auto scroll after 2 seconds
But it does not scroll at all
Also previous and next button when clicked does work

What am I missing?

Works by me but only with jQuery version 1.8 and lower.

The above comment worked like charm!!!
I had jquery 1.10 so i downgraded it to jquery 1.8


How to show data of user that flagged a content(2 flag types)? I have 2 flag types for a content type. both flags have flag field. consider the user flagged a content by both flags. I want to show user data. I have problems in this situation. I add flag A and flag B in relationship part of views, after that I add "username of user" and "flag field" in fields part. but unfortunately I should add 2 "username" field, one of them should relation to flag A and other should relation to flag B(relation part in field setting). this is problem. because I want one field of "username", not 2 "username" fields.
What should I do?

Add a filter for the whole view that checks username in both fields as not null,  and set the operator to 'And'.

In your view under 'Filter Criteria' do the following:

Add user name with the first relationship and set the operator to 'is not empty (NULL).
Do the same for the second username field.
Click the dropdown arrow next to add for 'Filter Criteria'. Select And/OR, Rearrange and add an 'AND' operator between the two filter.
Hide the second username from display.

That way you can filter for users with both flags.


Where is the node_type variable set? Looking at the documentation for the Drupal 8 html.html.twig template file, I notice node_type is listed between the available variables for that template file.
Contrary to the other variables available to that template file, thought, node_type is not set from template_preprocess_html() nor _template_preprocess_default_variables(), which are the functions I expect to set the documented variables for that template file.

What function or method initializes node_type to the bundle of the currently viewed node for html.html.twig?

node_type is set in node_preprocess_html() from the Node module.

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function node_preprocess_html(&$variables) {
  // If on an individual node page, add the node type to body classes.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
    $variables['node_type'] = $node->getType();
  }
}


Drupal theme layout - recommendation based on example needed I am going to create a website that will have a layout similar (almost identical) to this one:
http://www.statoilfuelretail.com
Meaning:

position of all the menus/elements
picture in the background two
columns in the middle

All the graphics will be made by graphic designer - all I need is the theme (template) with layout I could use. Would be great if it was a Drupal 7 theme.

My question is: Which themes can you recommend (free and paid) that could be easily configured to match the layout presented on the website above?

If it were me I'd start with Bartik and go from there.  It's very solid and flexible.  It has the main elements you'll need.

But that's just me.  Take a look at http://drupal.org/project/corporateclean

If you are looking for something extremely quick and easy, your best bet is just browsing the different template websites that offer Drupal designs.  These have some themes similar to what you're looking for:

http://www.templatemonster.com/drupal-themes.php
http://www.themeshark.com/
http://fusiondrupalthemes.com/
http://www.sooperthemes.com/drupal-themes


Custom Entity is only showing via admin theme I implemented a custom content entity with Drupal console. By default the routing is done in JobListingEntityHtmlRouteProvider.php file. I am getting a standard path such as /admin/structure/my_custom_entity/id.

I tried to use URL alias pattern to change it such as /my_custom_entity/id. That worked but still give me the admin theme upon viewing the entity. I did defined a themable custom twig template but it's not picking it up.

I also changed _admin_route to FALSE in JobListingEntityHtmlRouteProvider.php routing file. No go.

Any help appreciated.

As 4k4 said in the comments, the route is being generated using the link template in the entity annotations. Changing these link templates should be how you set the path to any custom entity page. For future content entities, drupal console will use the base path specified in this step:
Enter the base-path for the content entity routes [/admin/structure]


How to install Commerce 2 on Drupal VM? I have a virtual machine running with a standard install of Drupal 8 on windows. See Drupal VM

I want to install Drupal Commerce 2 on the VM.

Do i use composer like the Commerce instructions say (composer create-project drupalcommerce/project-base mystore --stability dev).

If so where? In de folder on windows that I installed the VM in, or in the part after i use vagrant ssh (vagrant@drupalvm:~$).

Or do i need to customize one of the .yml files and then do a vagrant provision?

Please help. (sorry if I am to noob)

Like the Commerce docs say, you need to install it like any other Drupal 8 site. So, it is easier to use the composer command.

composer create-project drupalcommerce/project-base MYNEWSITE --stability dev

Where MYNEWSITE is the new Drupal 8 w Commerce 2 directory. You can do this anywhere on the host machine (ex. I always have them in /Sites).

From here, you can add Drupal VM to the project and tailor the config.yml to your needs, then vagrant up - just like you did with the vanilla Drupal 8 site you already installed. You should see the Commerce install screen.

There is likely a way to automate this with DrupalVM, though I have not tried that approach.


How do I create an Excel file? I'm developing a module. I need to give to the users the option to download the coupons in XLS (Excel) format.
How I can do this?

I'm assuming you are using some content type for the content needed on your module.  If so, then you can use Views with a module like Views Data Export.


why some fields hidden from node? well I have a content type in which I needed about 6 taxonomy fields..

it was working at first but suddenly it stopped showing taxonomy fields in node display page.

I used Field Permissions and Field Group modules and I show the fields in content type's display management. but nothing changed!

although I can use views to get and show the data but it may be an error in my drupal core or something.

Update: I disabled field group and field permissions.. every thing works fine now! but cause I need these modules I should continue trying!

I it been a long time that you created that content type ?

It is on a production website already ?

Are you working on a fresh Drupal 7 installation ?

You could delete and recreate that content type if there is no serious impact on your site or your data.

If you do that, then your can check if the situation happens again. Sometimes there are particular manipulations while working that are responsible for those situations (and you can find out if you did something in a certain way the first time).

But remember : to me this operation depends on the 3 questions that I've asked on top of this text.

Does it help a bit ?


Entity reference Hierarchical Select between three content types? I have three content types:

Courses
Sections
Chapters

Sections content type have Entity reference of Courses.

Chapters content type have two entity reference fields as Courses and Sections.

If I select the courses corresponding section I have to list out Chapters content type. I need a hierarchical structure.

How can I do that?

You could try that module conditional_fields

That link also may help Update multiple fields with ajax callback in form


Problem with images not displaying because domain is incorrect I have recently installed a Drupal site on our web server and this is the default host (replaced an old website with static files). This server also hosts another virtual host for another domain name and that installation is WordPress.

On blog posts on the Drupal site (regular pages are fine), images will eventually show broken icons and when you check the URL of the image, it's replacing the domain name for the Drupal site with the domain name for the WordPress site.

Clearing the cache within Drupal immediately fixes everything, and the images reappear and with the correct URL.

An additional oddity is that the images are broken inside our network, but from the outside they will show up even though using the incorrect URL. On the inside, it resolves to the internal IP address and on the outside to the public.

I'm using Apache 2.2.22 with Drupal 7.28.

I realize it could be an Apache issue or DNS issue, but I'm checking all avenues... is there a configuration for the Drupal cache that I should be taking a look at that could be causing this problem?

The first thing you need to do is stare at your Apache access logs for a while and see if you have inbound requests to the wrong URL.  You may need to configure per virtual host logfiles to see which vhost is handling which.

You may also want to disable Drupal caching (both page and block) to see if the problem persists.

My guess is that everything with your Drupal configuration is correct, but that you have inbound requests that Drupal is handling because it is the default site, and these are getting cached.

If the Apache logs indicate that Drupal is getting the wrong URL, then I would do the following:

Configure both virtual hosts to respond to the canonical URL, and the redirections.  Something like

ServerName www.example.com
ServerAlias example.com *.example.com

This will make sure the proper vhost is responding to the proper domain (which is guess is the root cause of your problem, ie you need a ServerAlias).

Configure httpd.conf or .htaccess to set up canonical URL redirection for both the Wordpress and Drupal sites.  Something like

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]

These help ensure that Drupal and Wordpress only ever see requests for a single hostname.

These two things make good sense on most live sites, too.

If you still have the wrong URLs and you are 100% positive about the traffic, then my next guess would be that you have a misconfigured settings.php somewhere in your organization, and you have two sites / servers running out of the same database (eg, DEV and LIVE are actually using the same database).  To fix this, you would need to find the offending site.


Add user edit fields to pane I have a pane on a Dashboard page that's supposed to be an accordion.

It's supposed to update user information. I still haven't figured out how can I add user fields inside this pane, for example:

Update your information:

Name      _______

Password  _______

E-mail    _______

etc.

Is that possible? Do I have to use a preprocess function to add that?

Thanks in advance.

There is a module in drupal called Form Block . This module will allow you to present many forms through blocks . Advanced Form Block is another module with same goal .

if these modules couldn't help you can do it by yourself .
create a module , create your own form , your form callback can be User save , export your form as a block .


Can a taxonomy term be loaded into an EntityMetadataWrapper? I want to load term fields in my application. Can I use  entity metadata wrapper with reference to terms?

Yes. Like so:

$term_w = entity_metadata_wrapper('taxonomy_term', taxonomy_term_load(TERM_ID));

The first parameter is the entity type ID. If you visit MODULE_NAME_entity_info(), you can see the key of the definition will match the ID you need to load it.


How to expose age range in views? I'm trying to add an exposed filter for an age range with the Views module.

I made a select age field for age 18 to 80, but I can't find how to add a filter range in views.
For Example, I would add a filter saying "from age__ to age__".

From the filter criteria choose the age field tick the exposed filter.
Choose grouped filters from the filter type to expose.
Choose the widget type. Then add values after changing the operator to 'is between'


how to get radio value from radio button by form api drupal How to get radio value from radio button by using the following code

$form['pd']= array(
  '#type' => 'radio',
  '#title' => t('Programme Day'),
  '#options' => array(0 => 'One Day Programme', 1 => 'Two or More Day Programmes'),
  '#required'=>TRUE
);

$form['one_day'] = array(
  '#title' => t('Date'),
  '#type' => 'date',
  '#description' => t('Please select the date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => -15:+1',
  '#states' => array('visible' => array(':input[name="pd"]' => array('value' => 0)))
);

$form['from_day'] = array(
  '#title' => t('From Date'),
  '#type' => 'date',
  '#description' => t('Please select the from date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

$form['two_day'] = array(
  '#title' => t('To Date'),
  '#type' => 'date',
  '#description' => t('Please select the To date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

I tried the following code but the value shows as array not value.

$prog_day = $form_state['values']['pd'];

$one_date = $form_state['values']['one_day'];
$from_date = $form_state['values']['from_day'];
$two_date = $form_state['values']['two_day'];

if you are looking for the submitted values you need to look in the $form_state and not the $form array.

use $form_state['values']['your field name'],
depending on element type you might have ['und'][0] or just [0] on the end.


Custom submit handler on node form not picked up I am altering a node form with hook_form_alter and adding a couple of submit handlers. When the form gets submitted they get picked up using:

foreach (array_keys($form['actions']) as $action) {
  if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
    array_unshift($form['actions'][$action]['#submit'], 'submit_handler_a');
    $form['actions'][$action]['#submit'][] = 'submit_handler_b';
  }
}

Problem is, if the form contains a field that can store multiple values, as soon as I click on the 'Add more' button for that field and a new value for it, when submitting the form my handlers are not being picked up.

What am I doing wrong?

Have a look on those form elements in the form array. They might have their own ['#submit'] in the array and you might need to add your custom handler on those too


Solr search page and custom filters I want to change the default sorting order of a pre-populated Solr search page (the option "Show enabled facets' blocks in their configured regions and first page of all available results" under "Behavior on empty search" of the Advanced Search Options). I thought the solution would be setting a custom filter but I cannot find the right syntax: I tried everything from "solrsort=ds_created:desc" to "sort=created:desc" and all the variants between... but I failed... Anyone may help me please?

Just a regular space seems to be working for me.  Add the following to the end of your search URL: "&solrsort=ds_created desc".

Just to be sure though, you can always go to the following reports page, to make sure the ds_created field has been indexed.  You can see all the fields apachesolr has in its index there: /admin/reports/apachesolr

Let me know if that helps!

============== EDIT ===================

Another option I've used is to create a small module that modifies my solr query and/or solr results... I actually set my default sorting in that module.  Here's a snippet of my code:

function YOURMODULE_apachesolr_query_alter(&$query) {
  //Set the sort default options.  These are different options.  Just choose one!
  $query->setSolrsort('sort_label', 'asc');  // by title
  $query->setSolrsort('ds_created', 'desc');  // by created date
  $query->setSolrsort('score', 'desc');     // by best match
}

:-)  Hope that helps, since the above wasn't quite what you needed...


Creating a views reference list to be used in a node reference I am using a view to create a limited list of nodes of a certain node type in a node reference. E.g. A logged in user may only select nodes she has created.

I am using a contextual filter in a references view. The contextual filter is set to:
Provide default value = User ID from logged in user
and:
Exception value = 1

So while a user may see her nodes only, the super user may see everything.

I like to add a third condition so that any user with the role of editor can see everything as well. Can anybody tell me how or point me in the right direction on how to approach this? I am running out of ideas.

Update: The exception actually doesn't work either. So the questions is: How can I create a references list where:

the owner can see only her nodes
UID 1 can see all nodes
a user with role editor can see all nodes

You can use entity reference module  (https://drupal.org/project/entityreference). It provides the forward and backward reference of views.


How to get the File Description on a custom field formatter? Greetings to all of you.

This is my first question posted around here, so any suggestions are welcome on improving how to better formulate questions.

Into the matter.
I have the following code in a Drupal 8 site:

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\MyModuleFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;

/**
 * Plugin implementation of the 'mymodule' formatter.
 *
 * @FieldFormatter(
 *   id = "mymodule",
 *   label = @Translation("My Module"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */

class MyModuleFormatter extends MyModuleFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();
    $files = $this->getEntitiesToView($items, $langcode);

    /**
     * Early opt-out if the field is empty.
     */
    if (empty($files)) {
      return $elements;
    }

    foreach ($files as $delta => $file) {
      $file_uri = $file->getFileUri();

      $elements[$delta] = array(
        '#theme' => 'mymodule',
        '#files' => array(Url::fromUri(file_create_url($file_uri)));
      );
    }

    return $elements;
  }
}

So far so good. Everything is working.

Now, I would like to include in $elements the file description.
Something like:

foreach ($files as $delta => $file) {
  $file_uri = $file->getFileUri();
  $file_description = <someting> // That's what is needed...

  $elements[$delta] = array(
    '#theme' => 'mymodule',
    '#files' => array(Url::fromUri(file_create_url($file_uri)));
    '#descriptions' => array($file_description);  // ...so it can go here.
  );
}

As stated by Berdir, it looks that the description is stored on the file field, not on the file entity.
Yes, seems to be there, somewhere in $items.

How to get it?

Many thanks.

That's right, normally you find the values from the field in $items[$delta].

To make this easier for field formatters getEntitiesToView() puts the item in the returned array. You find the item in _referringItem:

$item = $file->_referringItem;
$description =  $item->description;


Updating module using _update_n not appearing on update.php or in /modules/update I had to change the schema of a module I created. I added a function like this:

function cloudinary_update_7200() {

  $spec = array(
    'keywords' => array('type' => 'longtext', 'not null' => FALSE),
    'primaryImage' => array('type' => 'tinyint', 'default' => 1, 'not null' => FALSE)
  );

  $cloudinary_field_table = 'field_data_field_cloudinary';
  $revision_table_name = 'field_revision_field_cloudinary';

  $keywords = 'field_cloudinary_keywords';
  db_add_field($cloudinary_field_table, $keywords, $spec);
  db_add_field($revision_table_name, $keywords, $spec);

  $primaryImage = 'field_cloudinary_primaryImage';
  db_add_field($cloudinary_field_table, $primaryImage, $spec);
  db_add_field($revision_table_name, $primaryImage, $spec);

  //UPDATE FIELDS
  $description_spec = array(
    'description' => array('type' => 'longtext', 'not null' => FALSE)
  );
  db_change_field($cloudinary_field_table, "field_cloudinary_alt", "field_cloudinary_description", $description_spec);

}

So how do I get it to run? I've gone to /update.php but nothing. I tried /admin/modules/update and the module is not listed.

Yes, I have cleared my cash many many times. And yes, I've cleared it again.

Rename cloudinary_update_7200 to cloudinary_update_7100 in case if you are using 7.1 version (refer to hook_update_N) and try once again.
If it doesn't work perform SQL query to figure out the number of the latest performed update  of the module:

SELECT schema_version FROM system WHERE type = 'module' AND name = 'cloudinary';

If it is 0 - 7100 should work, if it is for instance 7101 - try cloudinary_update_7102.


When programmatically adding file field, how to set allowed file extensions? I'm trying to add a custom node type in hook_install() for my custom module. I've been able to add the fields I want but can't seem to find a way to set the allowed file extensions for file fields. (it defaults to .txt)

The example below shows how I create my file field. I have tried setting both allowed_file_extensions and file_extensions in the settings array but that does not seem to work.

How would I set the allowed file extensions for a file field?

    field_create_field(array(
        'field_name' => 'xxx_video',
        'type' => 'file',
        'settings' => array('allowed_file_extensions' => array('mp4', 'avi', 'mov', 'wmv', '3gp', 'mpeg', 'mpeg2', 'mkv')),
        'entity_type' => array('node'),
    ));
    field_create_instance(array(
      'field_name' => 'xxx_video',
      'required' => true,
      'entity_type' => 'node',
      'bundle' => 'xxx',
      'label' => t('Video'),
      'description' => t('Video to play in smartbox.'),
    ));

The allowed file extension settings are added to the field instance settings, rather than the global field settings.

The variable is called 'file_extensions' and not 'allowed_file_extensions'

It is also a textfield string value, rather than an array.

You could try something like:

field_create_field(array(
    'field_name' => 'xxx_video',
    'type' => 'file',
    'entity_type' => array('node'),
));
field_create_instance(array(
  'field_name' => 'xxx_video',
  'required' => true,
  'entity_type' => 'node',
  'bundle' => 'xxx',
  'label' => t('Video'),
  'settings' => array('file_extensions' => 'mp4, avi'),
  'description' => t('Video to play in smartbox.'),
));


Incorrect File Permissions When Images Are Uploaded in the CKEditor WYSIWYG using ElFinder on Windows When I upload and image in the WYSIWYG, the image is added to the /sites/default/files/ folder, but cannot be seen on the web becasue IIS_IUSRS does not have the correct file permissions. Also, the permissions are only viewable by an administrator.

I tried the answer given on IMCE image upload and permissions issue, but both the temp and destination folders give IIS_IUSRS and IUSRS read/write/modify. I have even tried temporarily giveing 'Everyone' full control to get this working, but that does not help.

First, I have to click advanced to view the uploaded files permissions. I don't have to do that on the folders or other files in the folder.

Then I have to give Administrator permission. Again, this is not required on the folders or other files in the folder.

Then I can see the file permissions and IIS_IUSRS has List folder/read data, not modify. Also, this is inherited from 'Parent Object' not the parent folder.

If I click Disable inheritence and remove all permissions, then click enable inheritrance and apply, the correct permissions re inherited and the image can be seen on the web.

Has anyone else experienced this? Why doesn't the uploaded file inherit the folder permissiosn correctly in the first place? Why do I have to disable then enable inheritence to get it to work?

I need to fix this because the web editors will be adding a lot of images and it is not practical for me to manually change the permissiosn every time.

I don't know if this is an error with Windows Server 2012, IIS 8.5, CKEditor or ElFinder.

I am using ElFinder, but was only able to tag this with CKfinder. I am using Plupload as well, but can't remember if it integrates with ElFidner or not.

P.S. This site is stil in development. I will remove 'Everyone' before it goes live.

I was able to correct this by enabling inheritance on the c:\windows\temp folder, after verifying that the IIS_IUSRS (machinename) account has read & execute/list folder contents/read permissions.  I was prompted about a potential security risk, but ultimately this fixed it.


Taxonomy in multilingual site I have developed a multilingual blog (two languages). Some of my articles are both languages.

I'm trying to do the following:

As you can see, this article is tagged with the 'Drupal Gardens' tag: (This is not my site. It's a blog with the functionality I would like to implement)

http://reyero.net/es/drupal/construyendo_sitios_web_multilingues_con_drupal_gardens

When you click on the taxonomy link, the next page is showing the articles with the 'Drupal Gardens' tag, but only in spanish.
http://reyero.net/es/taxonomy/term/85

Then, if you change the language to english http://reyero.net/taxonomy/term/85 is showing the articles with the 'Drupal Gardens' tag, but only in english.

How can I implement this functionality in my blog. reyero.net is not my site. It's a blog with the functionality I am searching for.

You must activate the module Taxonomy translation (i18n_taxonomy) then go to admin/structure/taxonomy/YOUR_TAXONOMY_NAME/edit and select:

Translate. Different terms will be allowed for each language and they can be translated.

Add a term and select the language and click the button Save and translate in the next page click the link add translation and create the translation.

Then create a node with this term that you hace create and you will have this functionality in your site.


The way to join the entity to itself and use joined fields in UI I have a list of locations and want to make a view of routes between them.
In classical sql the query will be:

SELECT src.name, dst.name FROM locations src LEFT JOIN locations вые ON src.name!=dst.name

I made hook_views_pre_execute:

function bd_create_views_pre_execute(\Drupal\views\ViewExecutable $view) {
  if ($view->id() == 'ways' && $view->current_display == 'list') {
    $input = $view->exposed_raw_input;
    $query = $view->build_info['query'];
    $query->leftJoin('taxonomy_term_field_data', 'joj', 'taxonomy_term_field_data.tid != joj.tid');
    $query->addField('joj', 'name', 'label1');
    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
  }
}

What is the way to bring label1 to views admin interface?

Or is there another way to join using only admin interface?

You'll need to change your starting approach; hook_views_pre_execute() is for modifying a View prior to execution, not for providing new table data to integrate into Views. You won't be able to plugin into the UI from this hook.

If you're wanting to plugin into D8 Views system so that it can be seen by the Views admin UI, you'll need to implement various plugins that the D8 Views modules will use to look up your table data, fields (columns) & relationships (joins) that Views can use to build queries on your data table.

Start by following tutorial examples like Building Views Query Plugins for Drupal 8 or by looking at a well-known module with Views integration (e.g. node, user) to understand & implement the various plugins that provide Views integration.


Views with attachment - How do I exclude pagination offset on every page but the first? I have a view with an attached view to display the first row with different fields and markup. This works perfectly except for when you start using the pagination.

When I press another page (in the pagination) to load the next group of rows, I don't want either the attached view nor the pager offset.

I've seen some solutions which rely on showing rendered nodes with a different view mode for the first row. I would very much like to find a solution which is compatible with fields instead.

My main problem is that when you've started going through the pages, the first row is always skipped. Even though that is the expected behaviour, it's not how I want it to be.

Here's the pager settings for the default display and the attachment display.

Pager settings

Default display:

Attachment display:

The rendered view

Here's how the rows are rendered on the first and the second page.
The blue box represents all rows (in my case only 1) from the attachment display and the red boxes represents the rows from the default display. The number in the boxes is the row id.

Please note how row 9 is never shown.

First page:

Second page:

There is a workaround described here: https://drupal.org/comment/4109006#comment-4109006. It is for D6 but as far as I can tell it should work in D7 too. The approach seems a little odd and I didn't try it out on my own, but it might solve your problem.


Can I use a custom CCK Link field as URL for Ubercart Product Image I created a custom link field for my Product content type using Drupal 6 and Ubercart 2.
Now instead of linking the Product image in the Product site to itself or show it as a slideshow I would like to create a link to the URL of the given field.

I found the function that displays the product image, which is called 'theme_uc_product_image' and replaced

 $output .= 'field_direct_shop_link[0]['url'];
$output .= '<a href="'. $destination_url .'" title="'. $first['data']['title'] .'"';

but it didn't work out!

Any ideas on how to solve this?

Thanks a lot in advance.
Best,
Manuel

Digging into Ubercart, this is the theme function you are talking about:

/**
 * Formats a product's images.
 *
 * @ingroup themeable
 */
function theme_uc_product_image($images, $teaser = 0, $page = 0) {
  static $rel_count = 0;

  // Get the current product image widget.
  $image_widget = uc_product_get_image_widget();

  $first = array_shift($images);

  $output = '

';
  $output .= '';
  $output .= theme('imagecache', 'product', $first['filepath'], $first['data']['alt'], $first['data']['title']);
  $output .= '

';
  foreach ($images as $thumbnail) {
    // Node preview adds extra values to $images that aren't files.
    if (!is_array($thumbnail) || empty($thumbnail['filepath'])) {
      continue;
    }
    $output .= '';
    $output .= theme('imagecache', 'uc_thumbnail', $thumbnail['filepath'], $thumbnail['data']['alt'], $thumbnail['data']['title']);
    $output .= '';
  }
  $output .= '

';
  $rel_count++;

  return $output;
}

First off, I hope you didn't go in there and start hacking away, but rather copied the above to your theme's template.php file and renamed it YOURTHEME_uc_product_image() and made your modifications there :)  But, either way, from the declarations of this theme function, the only data you have to work are in the $images argument plus anything uberfunky returned by ub's image_widget.  You might want to throw in some debug code to see if anything in there is what you are looking for like this:

drupal_set_message('
' . print_r($images, TRUE) . '
');

at the start of your copied function.  Just remember to clear your caches/theme registry so drupal sees your function.


How do I get the taxonomy term name of the current taxonomy term page.tpl.php? Im on d7. Im trying to get the taxonomy term name of the the taxonomy page that I am on. Since Im not on a "node" page, I can't get it by the $node->tid. What should I do?
Thanks.

Try..

http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_term_load/7

$term = taxonomy_term_load(arg(2));
$title = $term->name;

arg(2) should return the tid of the taxonomy page (taxonomy/term/tid).


Omega 4 without Drush Hi [still new to Drupal]

Due to certain constraints I can't install drush. Am I able to work on Omega 4 without Drush? The organisation I work for has strict online security and firewall. I have a lot if issues installing drush. So I have decided not to install it and would like ti work on omega 4 without drush.

Does anyone have a good place to start, or can anyone point me in the right direction?

I'm look for tutorials, forums anything that can help. This has cost me time and now i need to hit the theme.

Please can you assist?

You can user Omega without Drush but I do recommend to try to install the Drush. Even if you do not want to use Omega you need to have Drush for serious Drupal projects. It makes your life easy.


How to map a taxonomy term into Feeds Importer? I have several Blank sources in a Feed and I'm mapping a value to these blank sources in my custom code.

I have a working example to set a value of a field of type 'TEXT FIELD':

function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['value'] = $mapping['profile'];
        }
    }
}

My question is, how to do the same if the field is a term reference?

Thanks!

It was simpler than what I thought.

The code is exactly the same, but instead of 'value', we have to use 'tid':

function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['tid'] = $mapping['profile'];
        }
    }
}


How to delete invalid token? After a recent migration from D6 to D7 some of the product descriptions made in the body of certain content types contains technical data like this:

[0...+70°C: ±0,2°C]

This is interpreted as tokens by the site and I get this message when I try to edit the content and then save the changes:

The Body is using the following invalid tokens: [0...+70°C: ±0,2°C]

How can I get around this, since it is not possible to save changes? I have tried to change the value directly in the database and then clear all cache, but the problem is still the same.

What to do?

Finally found out what the problem was. It was the Metatag module that copied the content in the body (using tokens) and used it as metatag description text. So by simply editing the metatag description field I got rid of the problem.


Allow node author to assign edit rights for other users Use case: user X creates a node and wants to give user Y the ability to edit the node as well. Think page administrators on Facebook. An Entity Reference field can be used to allow the node author to associate other users with the node, but how to provide edit rights for selected users?

A simple and common use case is a business directory website where Employee X creates a listing for Company Y and wants to allow Employee Z to edit the listing as well. There are several similar solutions out there but I've not been able to find a specific module or recipe for this common use case. Any ideas?

As is usually the case, "there's a "module for that": Node access user reference meets the requirements for this use case by allowing node authors to select other users from a user reference or entity reference field and assign view, update or delete rights to the referenced users. Hope this is useful for anyone else who runs into this issue.


Why isn't Drush recognized as command? I ran composer global require drush/drush:8.1.3 and added C:/Users/username/AppData/Roaming/Composer/vendor/drush/drush to the value of the PATH variable.

drush status returns the following output.

 PHP configuration      :  C:\xampp\php\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\Users\username\AppData\Roaming\Composer\vendor\dr
                           ush\drush\drush
 Drush version          :  8.1.3
 Drush temp directory   :  C:\Users\username\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :

When I change directory to the one containing the Drupal files, and I run drush status, I get this error.

  'C:\xampp\htdocs\drupal-project\drush' is not recognized as an internal or external command,operable program or batch file.

Why?

There are many things to comment here: Why are you installing Drush 8 and why the specific (outdated) version 8.1.3?

What happens is that your global Drush looks for a site local Drush, finds something ("C:\xampp\htdocs\drupal-project\drush") and tries to execute it.

The recommended approach - at least if you have a site local Drush, which you have if you installed Drupal using Composer and "drupal-composer/drupal-project" - is to use Drush Launcher (instead of a global Drush). NB! Read this issue so it works smoothly on Windows.

After you have fixed the path so Drush Launcher is used instead of the global Drush, try drush status again. I expect it to find the correct site local Drush. You migh also want to try drush --versionto verify which version of the launcher and Drush itself that is used.

You can test that the setup is correct by running Drush inside the directory containing Drupal:

1) If you have installed Drush Launcher correct, you should get the following output:

# drush --version
Drush Launcher Version: 0.6.0
Drush Commandline Tool 9.2.3

2) If you however have installed a global Drush 9 (using Compser) in stead of Drush Launcher, you get the following output:

# drush --version
'PATH_TO_DRUPAL_PROJECT/vendor/drush/drush/drush' is not recognized as an internal
or external command, operable program or batch file.


How to show custom error messages below text field? I want to display custom error messages below that text field in comments form. Currently it displays all error messages above the page which is not acceptable.

I'm using this theme for my blog. I also used this but it's not working. As I'm new in drupal I'm struggling with this, please suggest any solution.

You need go to your theme's template folder and edit page.tpl.php'

Look for <?php print $messages; ?> and move it below <?php print render($page['content']); ?>

Thanks for the note @Kevin. If you wish, you can add if statements around the <?php print $messages; ?> that check the page url and/or content type if you need to have them appear below only for certain pages.


Can't access default Drupal twig functions I am unable to get a result back from app.request.attributes.get('_route'). What could cause this. I have tried similar variable and still get no response.

Because of Drupal's granular caching, it is not possible to make the global request object available in templates (at least by default); if a template was used on multiple pages, it would be cached with the data from one page and have incorrect information on any others.

If you require the request information in a particular template, you will need to add a preprocess hook to add the additional variable, and ensure that you add the correct cache tags.

To see what variables are available within a particular template, use {{ dump() }}