Add markup inside a link (in the renderable array) in preprocess field My question is for D8...

I have a field which is rendered as a link. Let say for simplicity that it will be rendered like this: My Title

I would like to add a bootstrap icon inside the link to get a result like this: My Title

I know that I can take the url and the title from within the preprocess function to reconstruct a new link (#markup)... But is it possible to simply add the icon code somewhere in the array to get the same result?

I am adding some more information to clarify:

1-The field which is rendered as a link is a term reference field rendered as a linked label

2-Here is my try in the preprocess_field function to achieve this

function mymodule_preprocess_field(&$vars) {
  $fn = $vars['element']['#field_name'];
  switch ($fn) {
    case 'my_field':
      foreach ($vars['items'] as $key => $item) {
        $icon = '';
        $vars['items'][0]['content']['#title']=$icon.$item['content']['#title'];
      }
      break;
  }
}

Use the FormattableMarkup class for this:

$markup = new FormattableMarkup('', [
          '@url' => $url->toString(), // If $url is an Drupal\Core\Url object.
        ]);

$renderArray['your_element'] = $markup;

After edit:

Use the Markup class for this since your seem to be in control over your markup. If not use FormattableMarkup with placeholders for safety:

  function mymodule_preprocess_field(&$vars) {
    $fn = $vars['element']['#field_name'];
    switch ($fn) {
      case 'my_field':
        foreach ($vars['items'] as $key => $item) {
          $icon = '';
          $uri = $item['content']['#title'];

          $formattedIcon = \Drupal\Core\Render\Markup::create($icon . $uri);

          $vars['items'][0]['content']['#title'] = $formattedIcon;
        }
        break;
    }
  }

From the FormattableMarkup docs:

  When cast to a string, this object replaces variable placeholders in
  the string with the arguments passed in during construction and
  escapes the values so they can be safely displayed as HTML. See the
  documentation of
  \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
  details on the supported placeholders and how to use them securely.
  Incorrect use of this class can result in security vulnerabilities.


View grid mode won't work Background:

Drupal 7.41 site, all is up2date, minimalistic in modules, no customizations.

The problem:

I've created a view of fields and filtered it via content-type. The content itself is being taken from the node fine, but it won't appeared grid. So, basically My question is constructed of two simpler questions:

What causes can avoid the grid display of working?
Can I implement grid display just to certain fields and not to all of them?...

Some images of my View settings:

Your theme could be breaking the grid. Grid's are usually tables, so they generally work regardless of the theme - but if your theme is making any modifications to it the grid may break. I would suggest examining the HTML code that is being generated for the grid (in Chrome: right click the grid and select Inspect Element). Make sure that it's a table... and also examine the styles applied to it to see if any of them are breaking the normal grid display.
No - you can't tell Views to put certain fields in the grid and certain fields outside of it. I can't really imagine how that would work, or what you mean by that exactly, so it's hard to suggest an alternative. Perhaps two separate Views?


Changing the number of search results per page with the core search module What is the best way to change the number of search results per page when using the core search module?

I have both Drupal 6 and 7 sites that I would like to do this with.

In Drupal 6, the value 10 is hardcoded in  do_search().

In Drupal 7, the value 10 is hardcoded in the hooks, eg node_search_execute(), and there isn't a tag added that can uniquely identify the query for altering.  The idea has been floated in the issue queue, but as of 2013-01-30, nothing has been committed yet.

In the past I have hacked core and handled upgrades with patch management using the normal methods.

Overriding the hook implemented from the Node module is not possible because hook_search_execute() is invoked by search_data() using the following code.

  if (module_hook($module, 'search_execute')) {
    $results = module_invoke($module, 'search_execute', $keys, $conditions);
    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
    else {
      return array(
        '#theme' => 'search_results',
        '#results' => $results,
        '#module' => $module,
      );
    }
  }

$module is the parameter passed to search_data(). hook_search_execute() is similarly to hook_form() which is invoked for the module implementing the content type, not for every module.

I was looking for a way to alter the query executed to search nodes, and the only way I found is to alter the page callback for search/node. That is the way that requires less code.  Otherwise, the only alternative I can think of is implementing a search module to replace the search tab implemented for the Node module.

Since Drupal uses hook_search_info(), but doesn't uses hook_search_info_alter(), and hook_search_info() doesn't return much useful data (at least to help overriding the search query), I think there aren't other alternatives.


How to let CAS handle session I am using the phpCAS  library and would like sessions to be handled by that library.

I am instantiating the client this way:

function my_module_init(){
    ...
    phpCAS::client(CAS_VERSION_2_0,'casdomain' , 8443, '/cas',true);
    ...
}

I have it in hook_init() since I want to check for user authentication on each page load.

But I am getting this error.

  phpCAS error: phpCAS::client(): Another session was started before
  phpcas. Either disable the session handling for phpcas in the client()
  call or modify your application to leave session handling to phpcas

How can I get rid of this error and have phpCAS handle the session?

Thanks.

Any reason why you are not using the module cas? It seems like a fairly stable module with over 5000 people using it. I would give that a shot before attempting any custom code in hook_init().


Can't install experimental modules I installed Drupal 8.1.2, but I can't install modules of the category "core (experimental)". No problem with other modules or themes for example. I get no logs and no error message. Hitting the install button just redirects me to the extend page.

I have been able to install Migrate by installing Migrate Plus, which requires Migrate, but this does not solve the issue, in particular not for the other modules in "core (experimental)". Is there anything I have to do to be able to install experimental modules?

There's a core issue for failure to install experimental modules (or, more precisely, modules with parentheses in the group name with Suhosin): https://www.drupal.org/node/2665152


Contact form email template Currently, the whole email generated by the Contact module is without a single line break. They look very ugly. Is there a way to edit the email template for specific contact forms?

If you check core.services.yml you can see the service which sends mail (plugin.manager.mail).  It looks for  overrides for default mail plugin starting from message_id to module name. You can create simple new mail plugin which sends HTML mail and set this in configuration "system.mail".

 drush cset system.mail interface.contact your_mail_plugin  // this will change mail plugin for contact module

Creating a mail plugin is easy and you can find example here Drupal\Core\Mail\Plugin\Mail

MailSystem  module does this and it supports advanced options https://www.drupal.org/project/mailsystem


How do I redirect users visiting a path matching a regular expression? My question is the same asked in How do I redirect from /index.php/event/* to /event? but for Drupal 8.

Since the module suggested in the accepted answer for that question doesn't have a version for Drupal 8, how can I achieve the same with Drupal 8?

In Drupal 8 you use an event subscriber for this. You subscribe to a REQUEST kernel event, get the original url from the request, apply a regular expression and if this finds a replacement set the new url as a 301 redirect response.

mymodule/src/EventSubscriber/RedirectSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirectIndexPHP(GetResponseEvent $event) {
    $old_url = $event->getRequest()->getUri();
    $new_url = preg_replace('|/index.php|', '', $old_url, 1, $count);
    if ($count > 0) {
      $response = new TrustedRedirectResponse($new_url, 301);
      $event->setResponse($response);
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('redirectIndexPHP', 39);
    return $events;
  }

}

mymodule/mymodule.services.yml

services:
  mymodule.redirect:
    class: Drupal\mymodule\EventSubscriber\RedirectSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }


How to programmatically create Fields? How can I approach implementing the following in Drupal 7?

What I need to do is create a module which defines a new fieldable entity, called 'Company'. I have a list of, let's say, 20 fields that need to be filled out by each Company instance. These questions are predefined and some may contain custom validation.

At the moment, I'm at the point when I can add new fields to the Company entity. This works fine at the moment. My issue is that I need all these fields to be there as soon the module is installed, so adding them via the interface isn't an option.

I was wondering how can I approach this? I'd assume it comes down being able to do what can be done using the 'Manage Fields' UI programmatically.

Use field_create_field() to create the field itself and field_create_instance() to have an instance for the given entity bundle.

When creating fields as part of a custom module, you may or may not want to delete the field when the module is uninstalled.  To do so, you can use field_delete_field() if you want to delete the field and all field instance, or if you want to delete specific instances you can use field_delete_instance().


Display only the first n field items Goal: For a multiple-value field, display only the first n (e.g. the first 3) field items.

E.g. only the first 3 of 10 images in an image field.

I realize this is possibly by writing a custom field formatter. But I wonder if there is an existing solution available. Also to mix this up with existing formatters.

Hint: I use Display Suite, so solutions which involve that are welcome.

There is a setting how many items to display in Display Suite. The setting is demoed in this screencast: http://youtu.be/fa56OZcJq-4?t=1m20s


Migrate date time field using migrate source csv I am trying to migrate a datetime field from csv file but only few are being migrating and other are being failed.I am using migrate
I have created two datetime fields called as Activation Date and Expiry Date in article content type. Attached field type images for reference.
I am writing a custom migration yml file to migrate data from csv file. But only the date values from id 6-10 are being imported but not the date values from 1-5 .
While import I am getting error stating article_csv_import Migration - 5 failed.
I have included sample data and yml file for reference.
Can anyone please let me know what causing the first 5 dates import failing ? Any pointers for a way to debug migration process is greatly appreciated.
migration_examples/migrations/article_csv_import.yml
id: article_csv_import
label: Import Articles
migration_group: default
migration_tags:
  - Article CSV Migration

source:
  plugin: 'csv'
  # Full path to the file.
  path: public://subscription-list-small-copy.csv
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  enclosure: '"'
  header_offset: 0
  ids:
    - id
  fields:
    0:
      name: id
      label: 'Id'
    1:
      name: title
      label: 'Title'
    2:
      name: body
      label: 'Post body'
    3:
      name: field_activation_date
      label: 'Activation Date'
    4:
      name: field_expiry_date
      label: 'Expiry Date'
process:
  title: title
  body: body
  #activation date of the account.
  field_activation_date:
    -
      plugin: format_date
      from_format: Y-m-d H:i:s
      to_format: 'Y-m-d\TH:i:s'
      from_timezone: 'America/Managua'
      to_timezone: 'UTC'
      source: field_activation_date
  # expiry date of the account.
  field_expiry_date:
    -
      plugin: format_date
      from_format: Y-m-d H:i:s
      to_format: 'Y-m-d\TH:i:s'
      from_timezone: 'America/Managua'
      to_timezone: 'UTC'
      source: field_expiry_date
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

Sample CSV Data : subscription-list-small-copy.csv
id,title,body,field_activation_date,field_expiry_date
1,Title 1,Body 1,2012-12-22 2:36:03,2013-01-03 0:00:00
2,Title 2,Body 2,2013-08-16 0:00:00,2013-09-15 0:00:00
3,Title 3,Body 3,2013-09-14 0:00:00,2013-10-14 0:00:00
4,Title 4,Body 4,2014-04-08 0:00:00,2014-04-07 23:59:59
5,Title 5,Body 5,2014-09-30 0:00:00,2015-03-29 11:00:00
6,Title 6,Body 6,2014-12-09 12:29:00,2015-01-09 12:29:00
7,Title 7,Body 7,2014-12-31 11:08:00,2015-06-26 23:59:59
8,Title 8,Body 8,2015-02-25 19:12:00,2015-08-10 23:59:59
9,Title 9,Body 9,2015-03-01 11:19:00,2015-02-28 23:59:59
10,Title 10,Body 10,2015-03-02 18:01:00,2015-08-20 23:59:59

image-1 image-2

from_format: Y-m-d H:i:s means hours with leading zeroes, but there are no leading zeroes in your source. Use from_format: Y-m-d G:i:s (capital G)  for 24-hour-format without leading zeroes
see https://www.php.net/manual/function.date.php


Taxonomy view representative node contextual filter leads to incorrect results I have a view that is outputting incorrectly, perhaps not according to the code, but according to what I need it to do. So, a challenge?

The view lists colors (taxonomy terms from vocabulary 'Color') which have content assigned to them.

View type:      Taxonomy
Format:         Unformatted list
Show:           Fields
Fields:         Taxonomy term: Name
Relationships:  Taxonomy term: Representative node (required)
Filters:        Taxonomy term: Vocabulary (= Color)

The site must display different content depending on which area the user lives in. There is an 'Area' vocabulary, currently with two terms: East (tid = 1) and West (tid = 2).

Because of this, all relevant content types have an "Area" term reference field which can either be set to "East" or "West".

To get this to work, I added a contextual filter for the view.

Type: (Representative node) Content: Has taxonomy term ID.

A fixed value comes from this PHP:

$url = explode('/', $_SERVER['REQUEST_URI']);
$tid = 0;

if($url[1] == 'east') {
  $tid = 1;
} elseif($url[1] == 'west') {
  $tid = 2;
}

return $tid;

Values that don't validate cause the view to be hidden.

The problem: Taxonomy terms with content assigned to 'East' are being hidden from the list. I know that there is content using these 'Color' terms, but they are being excluded.

Here is what I think is happening:

View is executed for path 'domain/east'.
Representative nodes for each 'Color' taxonomy term are selected.
Contextual filter is applied to the representative node for each term - if the single representative node does NOT have the correct value for the URL (eg. 1, 'East' in this case) it is excluded.
Views output displays trimmed results, which are not representative of the actual data.

Does anyone know how I could get it to work properly? I'm hoping to avoid creating views for each area, as later, adding 'North', 'North West', 'South', 'South South East', etc, would get very frustrating. Ideally I'd be able to use a hook.

For example, would I be able to alter the representative node query, to get the contextual filter and change the SQL based on that?

Thanks for reading. :-)

First off do NOT put PHP code in the fixed value. This gets stored in the db which is a bad idea. Instead use taxonomy term ID from URL for the default value.

If that does not work as is use a hook. I would probably use hook_views_pre_view in this case. You can use the same code you have in your example to change your $args or $view->args can't remember which off the top of my head.


Can I give a role permission to configure one (and only one) block? Right now, I see that the administrator role has a premission called administer block. I would like to offer that permission to another role, but only for a specific block, not all of them. Is this at all possible?

try the content access Module for drupal 7.x might be exactly what you need


How to theme a quiz in D7? I´m trying to theme my quizzes, but even when I did manage to theme the quiz nodetype (node--quiz.tpl), that template is gone after the "take the quiz" button is clicked.

I´ve tried theming the multichoice-answering-form.tpl (as my questions are all of the multichoice type), but nothing happens.

I´ve checked the quiz module and haven´t found a default template according to this need. Or maybe I´m missing something?

I´ve tried creating the template quiz-single-question-node.tpl, it seems that even when it is "taken" the content isn´t correct, because I get an  undefined variable error.

This is what I´ve try into that template, and didn´t worked out:

print drupal_render($form);
print render($form);
print render($content);

Whith any of the three options I get the same undefined variable error.

Any help will be very much appreciated. Thanks!!

There are different templates that you could use to theme the quiz.

1) page--node--take.tpl.php this would take care of the basic page level template for all the nodes with the url of the form node/nid/take

2) node--quiz.tpl.php this would be used for the quiz page.

3) quiz-single-question-node.tpl as you guessed this is the one for the single page quiz node. there is one variable in that $question_node

<?php print drupal_render($question_node->content['body']);?>

that would render the quiz form on each of the quiz node. so this could be used to add additional things to the quiz node like a footer with instruction or things like that.

4) theme_quiz_question_navigation_form function is the place were the navigation buttons are rendered so you could either over ride it in your theme or create a template file. the variable would be $form.

5) multichoice-answering-form.tpl.php this tpl contains the part of the form other than the buttons in the multichoice question type. this has got a variable called $form. you can make the required changes and then render the same in the tpl with something like print drupal_render($form);

Or the above can also be done using the form_alter function with in a module or theme. the form ID to use would be quiz_question_answering_form

There are many other template and theme functions with in the quiz module to change the look and feel of quiz for example to change the design of the result page you have quiz-report-form.tpl.php

If you go through the files and functions of the quiz module you would see many other templates and theme functions.


Can't reorder items in Text formats On Drupal 7.15, I cannot save reordered draggable items at /admin/config/content/formats.
That is the dialog with all text formats and their options, and dragging them in order force their order of appearace.

I am able to drag items and reorder them, but after saving, items returns in previous order, in spite Drupal says "The text format ordering has been saved."

I do not have clue yet how to troubleshoot this issue, as there is no error anywhere.

This was very strange issue, now solved, but can't texactly the point that solved it, as i ran extensive code/config sweep both on code / server side. (Including Apache restarts, MySQL restarts, module maintance (many unused gone with the wind), APC configs, and running registry rebuids.


Separate templates for separate roles We have themed the user registration page by hook_theme() as follows

function ourmodule_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  $hooks['user_register_form'] = array(
       'render element' => 'form',
       'template' => 'user-register-form',
 );
 return $hooks;
}

This is getting reflected in the user creation page when we log in as admin as well. We want to use the custom template only for anonymous users.
How can we do this?
We prefer to do it via module itself.

You can use the role based theme switcher module. It allows you to switch the whole theme. If you only want to change one template you can use this thread.


facets not showing all the options drupal commerce Go to this page if you take a look to the facets at the sidebar you will notice that they are not displaying all the available options.

When I search 1 word at the search bar for example "tract" then the facets work as expected, but when I use 1 or more words the facets does not display all the options... Does any body have had this issue before with Facets of Drupal commerce?

Any suggestions?

you should probably set the filter in the view like this


Is there a database lock mechanism? I have a parent child entity relationship which is driven by a REST API. The payload contains data for both the parent and the child. The parent can have many children.
When the (child) payload is posted the API first checks if the parent exists (based solely on an ID value in the payload). If it does exist, that parent entity is assigned to an entityref field when the child entity is created. If the parent doesn't exist; it is created and the newly created parent is assigned to the child.
This works great.. until. It seems now that the API user is publishing multiple children with the same parent at the same time (I assume some sort of multi-threaded process). So the breakdown occurs when the first 2 children are created (at the "same time") and they both determine there is no existing parent; and then create duplicate parents.
Is there some Drupal db method that allows me to lock creation of a certain entity type; triggered by the first spot in the API code where the parent is to be created? I assume they are not exactly the same time; but they are within 1 second of each other and more precisely they are within the time it takes to create the first parent. Perhaps even a REST function to handle threaded calls?

Does not sound like a multi-threading issue to me?
If you have two childs having the the same new parent in the entity reference field (BTW, what approach do use for creation, this is rather tricky ..), it will be probably created "twice", but with different ids - no?
Why don't you create the parent entity first and assign it afterwards to the entity-reference field target_id or entity property (if you are controlling it yourself)?


render field collection with already defined custom formatter I defined a formatter for a field with hook_field_formatter_info()/view().  This field is a field collection and renders fine when I choose my custom formatter through the ui.

I can get my (already defined) field collection with:

$field_collection = entity_load('field_collection_item', array($field_nid))[$field_nid];

This returns a FieldCollectionItemEntity. (info) But how can I render this field colleciton programatically.

render($field_collection);

Does not seem to work and I don't see any methods to render this field collection through code even though the ui config has no problem rendering it as I've defined it.

Thanks!

So it turns out that the field collection 'field' will be treated like a normal field and rendered properly.  You don't need to load the field with entity_load. (We don't need any of the fields in the collection, we just want the entire collection).  And using field_view_field you can choose your custom formatter:

  //get the nid of the node that contains the field collection from any number of methods
  $node = node_load($nid);
  // the custom formatter was already defined using hook_field_formatter_info() and
  // hook_field_formater_view() (see drupal docs)
  $display = array('type' => 'custom_formatter_name');
  //print or 'return' depending if this is a module or a template file
  print drupal_render(field_view_field('node', $node, 'field_name', $display));

The two hurdles for me were (1) finding out that you can add the custom formatter to field_view_field() and (2) that I needed to print out this info (not return) as I was in a template file, not a function of a module (doh!).


Nested OR clause with EntityFieldQuery I have a table products structure like this

product_id   product_name   product_created_date   product_expiry_date  availability
----------   ------------   -------------------    -------------------  ------------
    1           x             12-NOV-13                14-JUN-14               No
    2           y             13-DEC-13                   null                Yes
    3           z             14-DEC-14                14-DEC-15              Yes
    1           p             12-NOV-13                14-JUN-14              Yes
    ----        --             -----                     ----               ----

I need a query like :

select product_id from products where (product_expiry_date>='12-DEC-14' or product_expiry_date is null) and availability='Yes'

how to do this using EntityFieldQuery?

I had to do a query like that once, here is how I achieve this with EFQ:

$matches = array();
yourmodule_mini_query('12-DEC-14', $matches);
yourmodule_mini_query('null', $matches);

function yourmodule_mini_query($value, &$matches) {
  $entityQuery = new EntityFieldQuery();
  $query = $entityQuery->entityCondition('entity_type', 'product');
  $query->fieldCondition('product_expiry_date', 'value', $value, '=');
  $query->fieldCondition('availability', 'value', 'Yes', '=');
  $results = $query->execute();

  if(count($results)) {
    foreach ($results['product'] as $p) {
      // By using product_id as array key, you deal with the duplicates
      $matches[$p->product_id] = $p->product_id;
    }
  }
}

Where $matches contains an array of product_id's that are available and for which product_expiry_date is null OR 12-DEC-14.

Hope it helped.

EDIT: As said in the comments below, the evaluation of the NULL value may require a second distinct query instead of calling twice the same function.


How to create entity within blockForm? I would like for users to be able to create new paragraph entities within the form of a custom block instead of going into the linked content type and adding the content.

In the past, I've always used the elements from this list but unfortunately it doesn't seem like there is an option for that.

Has anyone ever built anything similar to what I'm describing?

Thanks.

The easiest idea I could come up with would be to define the paragraph type through the UI. Then you'd have 2 options:

whether make a custom form with similar fields and create a new paragraph entity on form submission.
define a content type which has reference field to the paragraph type. Then you could simply render the node form which would handle all the logic of displaying the fields and saving of the paragraph it self.

I would prefer option number 2 since paragraphs are not meant to be stand-alone entities. They are meant to be parts of content. IMHO I don't think one paragraphs entity should be reused on multiple nodes.


Is there a built-in way to get a language+country locale pair? global $language only holds the language code. I wonder if there's any possibility to get a country code as well, at least of that country I set as default country at /admin/config/regional/settings.

Some external services need that locale (en_US, cs_CZ, de_AT) to be loaded in a matching language. Especially in multisites a language+country locale pair would be very handy for loading such services from within one module.

Possible workaround would be to set a new global variable holding a proper locale right?

you can get default country value using

<?php
print variable_get('site_default_country', '');
?>


How to make the search engine use search api db? I have installed search_api, with search_api_db, create 2 indexes, one for node, one for users.
The conf:

server: search_db server,
2 indexes: default_node_index and user_index
service class: database service

The one for users has parameters:

field: email (fulltext)
filter:role (limit to one only).

The index seems working good, it indexes the right number of users, I checked the uids in the db and it is corresponding to the good users.
But still when I use the search (search/user/something), the search is on the names instead of emails, and the role filter is not applied. So in short, it is not using the search_api_db. It looks like the whole system is overriden by some other fulltext on everything search. I'm stuck here

So ok I found out what is my problem.
I miss the other entity necessary to build to use the search api db: the search page using the search page module or views, instead of the system search page.

There is a tutorial here to have a more accurate and complete picture of the process: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages


How to create an extra field in the profile module to only accept the numeric values? I am creating extra fields in the user registration form. for this I am using the profile module.

In this module there is no option form creating a text field which should only accept the numeric values just like in drupal 7.

So how will I create such field in the user registration form?

Any idea?

Install CCK module. Enable the number module that comes with CCK module. Once you enable the module you can able to add integer field to the Profile Content type if you are using content_profile module to add fields to registration.

See the screenshow below that i just got to do it using CCK, Number, Content Profile module in Drupal 6.


How can I give permission to authenticated users to edit the content type 'ABC'? we have view and edit tab for any content

How can I have such a view and edit tab for authenticated user ?
I have given the following permissions to content of type 'ABC'
- Create own content
- Create new content
- Edit own content
- Edit any content
- Delete own content
- Delete any content
- View published content
But still the authenticated user cannot edit the content of type 'ABC'?
How can I achieve it?

When I try to access node/205/edit page as an authenticated user

I get the access denied message

DNA image

Use Devel module, especially it's Node Acces tool:

Devel Node Access (DNA)
View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

It will tell you exactly what permission is missing.
To debug for particular existing user, consider adding Masquerade to the mix:

The masquerade module is designed as a tool for site designers and site administrators. It allows a user with the right permissions to switch users.

That way you will be able to see DNA report just as the exact user who encountered problem.
What you should see is 2 lists:

If these look about right
Go to Home ⏩ Administration ⏩ Configuration ⏩ Content authoring and make sure your user has the proper text format permissions:


Captcha does not save form_id I added the CAPTCHA module to my drupal 6 website using this procedure and I'm trying to add the captcha to my user registration page.

However when I go to /admin/user/captcha the list with the default forms is empty. I expected the default list.

I entered user_register as the form_id, selected the standard captcha from the dropdown and pressed save. However it does not add the new form to the list. It's still empty. I also tried to save other values without success.

UPDATE:
I also tried reinstalling the captcha module and flushing cache without success. It's weird because I never had this problem on an other site with the same module/version

Installed version of the module: 6.x-2.4

UPDATE 2:
I enabled both the Captcha module and the Captcha compatibility module in the modules list.

The problem was the site didn't have writing permissions to the database. This meant that on installation of the module the necessary tables where not created and thus the above problem occurred.


appling different styles based on taxonomy I have a site with 120 categories of content. I've used taxonomy to make these categories. now I need to have some different styles base on the taxonomy which is used in nodes. OK? how can I do it.

I need something like page--article.tpl.php which you use to have different styles for different content types. but here I want to separate styles based on taxonomy

as my website is very big and heavy and has 700k visitors daily, I avoid using modules like panels or context! this modules will kill my site's performance and speed! so I need simple approach without using modules.

You can have specific template files by using theme hook suggestions. To change the node template, use the following:

function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Perform this only on certain content types.
  if ($node->type == 'YOUR_CONTENT_TYPE') {

    // get the taxonomy term (node category)
    $tid  = $node->field_YOURTERM[LANGUAGE_NONE][0]['tid'];
    $term = taxonomy_term_load($tid);
    $term_name = drupal_html_class($term->name);

    // add a css class with the category's name
    $vars['classes_array'][] = 'node-category-' . $term_name;

    // make drupal search for category-specific node templates
    // template files need to be named node--nodetype--termname.tpl.php
    $vars['theme_hook_suggestions'][] = 'node__' . $node->type.'__' . $term_name;
  }
}

Say your categories are like "Drink Wine", the $term_name would be "drink-wine". Lowercarse, no spaces. You can remove __$node->type if you want.

To change the page template, use the following:

function THEME_preprocess_page(&$vars) {
  $node = (isset($vars['node']) ? $vars['node'] : null);

  // Perform this only on certain content types.
  if ($node && $node->type == 'YOUR_CONTENT_TYPE') {

    // get the taxonomy term (node category)
    $tid  = $node->field_YOURTERM[LANGUAGE_NONE][0]['tid'];
    $term = taxonomy_term_load($tid);
    $term_name = drupal_html_class($term->name);

    // add a css class with the category's name
    $vars['classes_array'][] = 'page-node-category-' . $term_name;

    // make drupal search for category-specific page templates
    // template files need to be named page--nodetype--termname.tpl.php
    $vars['theme_hook_suggestions'][] = 'page__' . $node->type.'__' . $term_name;
  }
}


Remove addresses with only a country For a site I am working on I am using the address field. Each node can have multiple addresses and at least one is required. All the addresses are in the US so I set the default to the US.

When the user enters and address a new field shows up with the default country address. Whenever the go to edit the page a new one with just the country is also their. They save and soon there is a bunch of addresses with only a country. This causes other parts of the site to break.

I need a way to either make the default in the form none or to delete addresses that have only a country when the node is saved/updated.

I didn't have luck with either but admitably I am new to using hooks. Below is my most recent attempt by using the node presave hook.

function postal_default_node_presave($node) {
  if ($node->type == 'micro_property') {
    foreach($node->field_micro_address[LANGUAGE_NONE] as $address){
        dpm($address);
        unset($address['country']);
        unset($address['element_key']);
        $found = false;
        // Cycles all submitted address field components for the country to see if any have been filled
        foreach ($address as $value) {
            if (!empty($value) > 0) { $found = true; }
        }
        // Empty the address and location arrays if the fields were blank
        if (!$found) {
            dpm('not found reseting');
            $node->field_address = array();
            $node->field_location = array();
        }
    }
    return $node;
  }
}

The dpm messages are posting what I would expect but the node being saved is not.

I was on the right track and made a really stupid mistake and don't know why I didn't notice it. I was deleting the correct way but I was deleting the wrong thing. I was in a loop since there are multiple addresses.

// Empty the address and location arrays if the fields were blank
if (!$found) {
    unset($node->field_micro_address[LANGUAGE_NONE][$k]);
}


Interview available slot I'm currently doing recruitment system by using drupal 7..

In my system have 3 role..
1) applicant
2) hr admin
3) interviewer

Applicant can apply the job and HR admin will shortlisted the applicant. The interviewer can evaluate the shortlisted candidate during the interview session..

My question is there any module that can show the availability of the interview session..the idea is same like confrence session where we can register for the confrence and we can set the limit of audience.. Because i want the candidate can choose the interview session..

I've tried the signup module but i seem not working for drupal 7.

Thank you very much.

If a simple sign up you are looking for, have you tried Entity Registration? https://www.drupal.org/project/registration. Works similar to Signup module


Add roles to user during create and save account I want to add a custom role to a user during hook_user_create() and hook_user_update(). All goes well during user create, as long as I do $user->save() in the end. The site crashes during hook_user_update() if I do $user->save(). No role is added if I simply add the role with $user->addRole('role_name'), but don't save it.

This is for Drupal 8.

What am I doing wrong?

Found the answer: hook_user_presave() will do the trick.

I.e you add what you want to the user object (and don't save). Drupal will do the rest.


Zen sub-themes, sass vs inheritance I may be running into two conflicting methodologies here.

Basic Drupal theme philosophy is to sub-theme and only change what is different from the sub-theme.

I am using taxonomy hierarchy and theming their views slightly different.

Taxonomy       Theme
--------       -----
Zone           MyBaseTheme
-Arts          ArtsTheme (change the header image)
--Dance        ArtsTheme (change the header image)
---Company1    Comp1Theme (change the header image and menu items)
---Comapny2    Comp2Theme
--Theater      ArtsThee
---Thespians1  Thesp1Theme
---Thespians2  Thesp2Theme
-Sports        SportsTheme
--Boys         SportsTheme
---Football    FootballTheme
---Baseball    BaseballTheme
--Girls        etc
---Field Hockey etc

This would seem to mean the I could subtheme off of zen then only make some minor changes for each.  Common stuff such as font size and spacing would be done in MyBaseTheme.  Zen seems to use a large font for instance so I want to make it smaller.

I could change the banner images in each sub-theme off of MyBase.

So far so good except...

Zen seem to want to use the SASS methodology for CSS coding.

Copying Starter Kit stuff is getting me whole copies of every CSS attribute for every sub-theme.  I don't want copies, I want inheritance.

Anyone ever run into this problem?  Thoughts?

see this issue queue How to Approach Sub-Sub themes with Zen?

You dont copy zen starter kit for every sub-theme. You basically copy the .info file and template.php and create your theme folder. If you copy zen starter kit for every theme you'll run into the problem your seeing you end up "spamming" css files everywhere.

Sub-themes are best built smallest to biggest. By which I mean start off with the smallest number of .info file attributes and build up to the subtheme you want.

With so many subthemes you should be able to come up with 1 generic "base sub-theme" you then base all your subthemes off of in code.

Every sub-theme needs 1 uniquely named CSS file to properly fire off inheritance.


Deleted the Content Type now cannot delete or edit node of that type, but it is visible on site I have a node that I can see on my site, but when I try to edit it I get the error:

Notice: Undefined index: my_node_name_node_form in drupal_retrieve_form() (line 763 of /home/sites/my-site-url/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'my_node_name_node_form' not found or invalid function name in drupal_retrieve_form() (line 798 of /home/sites/my-site-url/includes/form.inc).

I cannot see the node by going to 'content'.

I believe that what has happened is:
I deleted a Content Type that was redundant on my site without realizing that there was a node of that type on the site. I guess that now the node doesn't its content type this is stopping it from being deleted.

I would like to know how to delete this node, or failing that unpublish it.

I know the NID of the node to be deleted.

I guess that one way of doing this would be manually using phpmyadmin. For this approach I would need some guidance on how to go about this as I am not very familiar with either how nodes are spread across the tables in the database or working in phpmyadmin.

Ideally you should re-enable module which supports that custom node type, so the node can be properly removed.

Otherwise, you can load, edit or delete the node grammatically.

For example, to load the node using drush command-line, you can run:

drush ev "var_dump(node_load(1234));"

To delete it, try:

drush ev "node_delete(1234);"

Alternatively, you can delete these nodes from the node table.

To find all other references, check your database, e.g.

drush sql-dump --ordered-dump | grep my_node_name


Add and edit nodes using the main theme In Drupal 7, I could use hook_admin_paths to decide if a page used the main or admin theme. This has changed in Drupal 8. This option is now set in a route definition. Existing routes, like node.add, can be altered. However, looking in node.routing.yml, under node.add, I do not see _admin_route: TRUE, which I intended to alter to FALSE.

What do I need to alter, and how, so that adding and editing nodes is done using the main theme?

You can configure this in UI, see the checkbox at the end of the theme list in /admin/appearance:

  [x] Use the administration theme when editing or creating content

This config option is then used to alter the route in the following code example, which would also answer how to alter the route in a route subscriber:

NodeAdminRouteSubscriber::alterRoutes()

  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

More info https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


print full url template I'm building a multi language site but I'm facing a problem with an url.
In my template i have the following print rule for an url <?php print $base_url.'/#project';?>
The base url only prints http://www.codedesign.be/#project withouth the language selector. url is normal url/nl/#project or www.codedesign.be/fr/#project

You should use the url() function to create URLs.

  Generates an internal or external URL.

This functions handles all complexity of creating an URL, including language prefix. url() handles exernal URLs too.

You can also use the l() function to create anchor tags:

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

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

In your case you can use:

<?php print url('<front>', array('absolute' => TRUE, 'fragment' => 'project'));?>


How to use $config->get for #default_value when multidimensional I am creating a form and I want to store the form values every time the form is saved, so I am using:

'#default_value' => $config->get('field_name')

However what would I do if my form item rather than being

$form['field_name'] = [
  '#type' => 'datetime',
  '#default_value' => $config->get('field_name'),
  '#date_date_element' => 'none',
  '#date_time_element' => 'time',
  '#date_time_format' => 'H:i',
];

was this

$form['section']['field_name'] = [
  '#type' => 'datetime',
  '#default_value' => $config->get('field_name'),
  '#date_date_element' => 'none',
  '#date_time_element' => 'time',
  '#date_time_format' => 'H:i',
];

I have tried unsuccessfully

'#default_value' => $config->get('section.field_name')

I have tried unsuccessfully

'#default_value' => $config->get('section.field_name')

Probably because you didn't set it first with section.field_name otherwise you can't retrieve it if you have not set it with that name.

Field names are supposed to be unique, so nothing different.

It really depends on what you do in set, you could give it whatever name you like

$config->set('lalalala', $form_state->getValue('field_name'));

and then retrive it with $config->get('lalalala'),

but convention is to give it the field name:

$config->set('field_name', $form_state->getValue('field_name'));


How to set 'INSERT IGNORE' in db_insert without db_merge Is anyone know how to set 'INSERT IGNORE' in db_insert?

I cannot use db_merge because I'm going to insert many rows.

$query = db_insert('table')->fields(array('foo', 'bar'));
foreach ($rows as $row) {
  $query->values(array(
    'foo' => $row->foo,
    'bar' => $row->bar,
  ));
}
$query->execute();

You've got two options:

Subclass InsertQuery and add that functionality in yourself (it's currently not implemented)
Use db_query() to run a raw SQL string instead.

The only mention of INSERT IGNORE in the Drupal 7 codebase is in DatabaseConnection_mysql:nextId; it's not actually used, but in its place is a raw query string containing ON DUPLICATE KEY UPDATE, that gets passed directly to db_query().

I may be wrong, but I'd assume that's as good an indication as any that a raw SQL string along with db_query() is the way to go.


When should I use behaviors? Can I attach them to any DOM node? I was using Drupal behaviors during a commerce project that ran some simple code after a select list changed product value.  In my head though I was thinking how is this any different than a 'change' event.

I went through Google to find out a bit more, but could only come across some things that provided very little insight, including the documentation itself.

So I am curious as to why and when to use Drupal behaviors, and if I could get a practical example. And does it only work on Drupal rendered nodes that have asynchronous functionality attached to them? Or can I attach it to anything like a regular div element? If so what would that look like?

I also noticed in the Drupal behaviors object tree, you can see all the behaviors, and are able to run them if you get all the way down to the attach object ( i.e. Drupal.behaviors.myBehavior.attach() ). Can you manipulate those?

Thanks for the insight in advance.

The attach function of all registered behaviors (all properties of the Drupal.behaviors object) will be invoked when behavior should be added to elements, either when the DOM is ready (ie. page load) and when elements are added to the DOM. The detach function will be called when behaviors should be detached from elements: just before elements are removed from the DOM, moved in the DOM or a form is submitted. The context parameter will always be a parent of the added/removed/moved/submitted elements, the single added/removed/moved/submitted element itself or the whole document element. The settings parameters will be the settings for the context, usually the Drupal.settings object as set by calls to drupal_add_js() from PHP. For detach, the trigger parameter will contains the kind of event that triggered the call: 'unload' (elements removed), 'move' (elements moved) or 'serialize' (form is being submitted).

The attach (and detach) functions of a behavior can be used multiple time over the same portion of the DOM tree. So the same element could be processed multiple time by the same code. It is up to the code itself to avoid processing (ie. binding event handlers, altering CSS styles, etc.) multiple times for the same elements. The easiest solution for this is to use the jQuery Once plugin (which is provided by Drupal 7) like this:

$(selector).once('behavior-name').doSomething();
$(selector).once('behavior-name', function(){ /*do something*/ });

Since a behavior is being attached/detached to/from a context, the context object can be used to restrict your jQuery queries to only the affected element or DOM subtree, like this:

$(selector, context).doSomething();

Putting all this together means the base pattern to process and add behaviors to elements on the page should looks like this:

(function($) {
  Drupal.behaviors.doSomething = {
    attach: function(context, settings) {
      $('div.something', context).once('do-something').doSomething({
        param1: settings.something.param,
        param2: 'something else'
      });
    }
  }
})(jQuery);

You can manipulate thhe Drupal.behaviors object tree, but be careful to avoid breaking other behaviors. I common usage is to use your behavior object (ie. Drupal.behaviors.myBehavior) to store information extracted from the elements during attach and consumed by event handlers.

If you write code that dynamically add or remove elements to the DOM, you should invoke Drupal.attachBehaviors or Drupal.detachBehavior on the (closet) parent element of the added/removed elements.


How to add user role as a class while rendering a username I'd like to style the username of certain roles differently (mainly admin roles) and I think the way to do it is to append the user roles in the class of the username.

I'd like your help with this because I've tried this but it doesn't work:

function THEME_username(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

You need to preprocess the theme function, and add to the attributes array or link options, depending on context. Currently you're overriding the theme function and reducing its output to an empty string.

function MYTHEME_preprocess_username(&$vars) {
  foreach($vars['account']->roles as $role) {
    if (isset($variables['link_path'])) {
      $vars['link_options']['attributes']['class'][] = 'role-' . drupal_html_class($role);
    }
    else {
      $vars['attributes_array']['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}


How can I check if the author of the current node is the current logged in user? I am trying to execute a Rule based on the condition of whether the currently logged in user, is currently viewing their node (a node they are the author of), or viewing someone else's node. The Rule event/trigger I am using is "User saves a Status" from Statuses module. Next I have used the Rules condition "Execute Custom PHP code", and set an if statement that checks whether the current node uid (the uid of the node's author) equals the current user uid:

if ($node->uid == $user->uid) {
  return TRUE;
}
else {
  return FALSE;
}

This is causing a bunch of "Trying to get property of non-object" errors, as both the $node and $user variables are not being recognised. I'm not sure why this is the case, do I need to use the node_load() and user_load() functions before using these variables? If so how?

I have managed to work it out! Below is the code for checking whether the current user is viewing content they are an author of:

global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

Hope this is helpful to someone.


Add fields to entity in module update I'm using Drupal 7 and I have a module which has working implementation of the Entity API module.

In my_module.install file there is a hook_schema() in which I defined table columns:

$schema['my_subscription'] = array(
'description' => t('The base table for subscriptions'),
    'fields' => array(
      'sid' => array(
        'description' => t('Primary key identifier for an subscription log.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'email' => array(
        'description' => t('Email of a users subscription.'),
        'type' => 'varchar',
        'length' => '250',
        'not null' => TRUE,
      ),
      'name' => array(
        'description' => t('Full name of a user subscribing.'),
        'type' => 'varchar',
        'length' => '250',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('sid'),
);

return $schema;

In my_module.module there is a hook_entity_info():

 /**
 * Implements hook_entity_info().
 */
function my_module_entity_info() {
  return array(
    'my_subscription' => array(
      'label' => t('Subscriptions'),
      'base table' => 'my_subscription',
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'fieldable' => FALSE,
      'entity keys' => array(
        'id' => 'sid',
      ),
      'bundles' => array(),
      'module' => 'my_subscription',
    ),
  );
}

Records are created from the module like this:

    $values = array(
      'email' => $email,
      'name' => $name,
    );

    $subscription = entity_create('my_subscription', $values);

It's all working good, and there are couple of hundred subscriptions at the moment.

Now I need to expand the table with one more column, I'll call it 'test' for simplicity. I added a hook_update_N() to the my_module.install, added

 db_add_field('my_subscription', 'test', array(
    'type' => 'varchar',
    'length' => 64,
    'not null' => FALSE,
  ));

and ran update.php which added the column as expected.

Now, when I try to pass new column value in the $values array like this

    $values = array(
      'email' => $email,
      'name' => $name,
      'test' => 'lorem ipsum'
    );

    $subscription = entity_create('my_subscription', $values);

record is made, but the newly added 'test' column has the value of NULL no matter what.

I suppose I need to tell Entity API that there is new field that needs to be populated as well, but I don't know how.

Using the API to add a column is the right thing to do, but it can't/won't update the code in your hook_schema() definition for you.

Drupal relies on that definition to map values to columns, so if you haven't explicitly declared the 'test' column, entity API doesn't know it exists, and so discards the value.

To solve, you should declare the new column in hook_schema():

$schema['my_subscription'] = array(
  'description' => t('The base table for subscriptions'),
  'fields' => array(
    'sid' => array(
      'description' => t('Primary key identifier for an subscription log.'),
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'email' => array(
      'description' => t('Email of a users subscription.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => TRUE,
    ),
    'name' => array(
      'description' => t('Full name of a user subscribing.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => FALSE,
    ),
    'test' => array(
      'description' => t('Test field.'),
      'type' => 'varchar',
      'length' => 255,
    ),
  ),
  'primary key' => array('sid'),
);

After you clear caches things should start working.


Adding Image for banner I want to add the banner image from the Admin page. The banner is slider. The slider contains text, Read more link and Images.

These three options user have to add from the admin page. The slider appears only in the home page.

Is there any plugin or Content type is advisable.

When i Google drupal image sliders the second result leads me to this.

Available modules

There are many modules that provide some sort of slideshow / rotator functionality.

Views Slideshow Liquid Slider - A fully responsive, HTML5 jQuery content slider for both web and mobile devices.
Content Glider - Another jQuery plugin for image slider, very easy to use.
Flex slider - provides a client-side automatic adaptation of the slides size according to the window size (Responsive). Can work with the Views module. Poor documentation.
jCarousel - This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Dynamic display block - Enables you to create and present blocks of content in a dynamic and attractive way. Uses the jQuery Cycle Plug-in.
Views Nivo Slider - a Views style plugin using the Nivo style slider.  Drupal 6 version requires imagecache, imagefield and jquery update.
Views Slideshow - a Views style plugin using jquery cycle. Provides an extensible API that allows other cycles, rotators, and carousels to plug into the module, so they don't need to recreate the Views functionality.
Views Slideshow: Dynamic display block - a Views slideshow plugin which enables you to present slideshows in an attractive way.
Views Slideshow Xtra is an enhancement module for Views Slideshow, providing the ability to create animated slideshow overlays.  This module can also help automate the creation of any Drupal 7 Views Slideshow, using the Views Slideshow Xtra Example sub-module, which creates a Slide content type, a default Slideshow View, and example Slide nodes.
Views Slideshow: ImageFlow - offers an ImageFlow option to Views Slideshow, similar to Apple's CoverFlow.
Slideshow Creator - adds an input format filter to allow you to add slideshow creation code to the body of a node and other text fields.
Featured Content Slider - select nodes based on content type and create up to 3 blocks of featured content.
Slider - create a "slider" content type with a multi-value nodereference field to create carousel-style sliders of the referenced nodes.
Ajax Slideshow - Sequential presentation of any of the site nodes, using various effects. The slideshow is ajax-based which means the page load-time is agnostic to the amount of content included.
Media Nivo Slider - Provides the ability to expose the content of a Media Gallery to a Nivo Slider block.
Nivo formatter - Nivo formatter is an image field formatter that transform any image field
    to awesome Nivo Slider image gallery.
Nivo Slider - Nivo Slider is a stand-alone solution for creating a simple slideshow for your website.


Superfish menu with user id as a parameter My question is how to get the user id on a URL path when creating a link in a superfish menu.

Checkout this module Menu token

  Menu Token module provides tokens, that could be used in title or in
  path of menu items (links). For example, if you create a menu item
  with path: "user/[current-user:uid]", the url will be changed "on fly"
  to: "user/1" (assuming you are user 1).


Convert a static query to dynamic one, with a having clause i am writing a patch for ubercart 3, for a attribute ignore module i am building.
For this module, i need to be able to query alter the query for the uc_product_adjustments_form.

I need to convert the static mysql query to a dynamic one.

This is what the static query looks like:

$result = db_query("SELECT pa.nid, pa.aid, pa.ordering, pa.display, a.name, a.ordering, ao.aid, COUNT(po.oid)
    FROM {uc_product_attributes} pa
    LEFT JOIN {uc_attributes} a ON pa.aid = a.aid
    LEFT JOIN {uc_attribute_options} ao ON a.aid = ao.aid
    LEFT JOIN {uc_product_options} po ON ao.oid = po.oid AND po.nid = :po_nid
    WHERE pa.nid = :pa_nid
    AND pa.display <> :pa_display
    GROUP BY ao.aid, pa.aid, pa.display, a.name, pa.ordering, a.ordering, pa.nid
    HAVING count(po.oid) > 0
    ORDER BY pa.ordering, a.ordering", array(':po_nid' => $nid, ':pa_nid' => $nid, ':pa_display' => 3));

And this is what i got so far:

$query = db_select('uc_product_attributes', 'pa');
  $query->leftJoin('uc_attributes', 'a', 'pa.aid = a.aid');
  $query->leftJoin('uc_attribute_options', 'ao', 'a.aid = ao.aid');
  $query->leftJoin('uc_product_options', 'po', 'ao.oid = po.oid AND po.nid = :po_nid', array(':po_nid' => $nid));
  $query->fields('pa', array('nid', 'aid', 'ordering', 'display'));
  $query->fields('a', array('name', 'ordering', 'aid'));
  $query->fields('ao', array('aid'));
  $query->condition('pa.nid', $nid);
  $query->condition('pa.nid', $nid);
  $query->groupBy('ao.aid');
  $query->groupBy('pa.aid');
  $query->groupBy('pa.display');
  $query->groupBy('a.name');
  $query->groupBy('pa.ordering');
  $query->groupBy('a.ordering');
  $query->groupBy('pa.nid');
  $result = $query->execute();

So everything works, except for the HAVING clause, which i don't understand to be honest.

Many thanks!

-- Tom

If I understand you right you just need to use the having() member function of the SelectQuery:

$query->having('count(po.oid) > 0');

FYI you have this line twice:

$query->condition('pa.nid', $nid);

I don't think it'll make a difference to the query result but it's probably best to remove the duplicate line.


How do I find (or create) a File Template override in Panels 3? So I'm using Panels 3 and Drupal 7 and it makes it damn easy to override the default templates for a taxonomy term template, a node template, even the front page template.  However, I don't see anything on the default panel page admin list that allows me to override the default FILE template.  When I try to Add a New Page and use the file/%file path, the system forbids it, as this URL structure already exists.  How do I harness the power of Panels for other page templates that the Panels module does not offer an override out-of-the-box?

As Adam Friedman points out, there is Page manager existing pages, which can do part of what "real" Page manager support can do, but it will not have the same capabilities as say the node/%node template has.

There are two issues that work on "full" support for this. First, and Second.


Commerce add product attribute without adding new product variations I have found this Commerce manual: Product Attributes & Variations, which explains the differences and connections between fields, attributes and variations, where in the end they assign a different product to each product display.

The situation I am in is as follows. Let's say I sell lunchboxes. The same model is available in 5 colors and the lid is always white. But now I want to add an option to the shop where people can order a lid in the same color as the lunchbox. My SKU's are as follows:

lunchbox_red
lunchbox_blue
lunchbox_...

I was hoping this could become a simple product attribute (a checkbox?), but it seems I will have to add a second version of my 5 products with the extra costs of the lid:

lunchbox_red
lunchbox_red_lid_red
lunchbox_blue
lunchbox_blue_lid_blue
lunchbox_...

I initially wanted to let people choose the color of the lid, but that would require me to maintain 25 different products for each box-lid combination!?

lunchbox_red
lunchbox_red_lid_red
lunchbox_red_lid_blue
lunchbox_red_lid_...
lunchbox_blue
lunchbox_blue_lid_red
lunchbox_blue_lid_blue
lunchbox_...

Since I don't really care about the photo (I would definitely need a product for each lid combination in that case), I was hoping for a smarter way to implement this.

Can I add a general attribute (with added costs) to all product variations without adding all the products? The price for the coloring of the lid will be a fixed price, not depending on the color used.

It appears I have been looking for Commerce Pricing Attributes. There is one SKU with a base price and I can manage the attributes and add a price modifier for each of them.

This screenshot from the module page explains it all:


Caching Blocks with Context Module I am using the Context module with the Block module disabled and noticed that blocks are not being stored in the cache. How do I get Context to cache blocks? Does it matter that much that blocks are not being cached?

The block module is turned off because I don't see why it is needed with the Context module enabled. The block module loads every block on every page load. So I imagine that it would be a boost to use Context without it. However, I'm curious if it would make sense to also have the Context module cache each block that it loads and check the cache first before it loads the block.

How do I get Context to cache blocks?

Anyway a lot of block don't use cache by default. You need to use http://drupal.org/project/blockcache_alter to improve the control of what you want to cache. Sadly block cache alter is not compatible with context but a small glue module make it works :) http://drupal.org/project/context_blockcache_alter . But need a port on D7.

So using block cache alter going to do a real performance boost.

To not use block module the answer from Adam S is correct.


Render module block programmatically I know I can render my custom block programmatically with

$block = \Drupal\block_content\Entity\BlockContent::load(2);
$vars['contact_us_info_block']= \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
$vars['contact_us_info_block'] = drupal_render($vars['contact_us_info_block']);

Now I want to render SimpleNewsletter  Block programmatically,I tried

$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block =  $block_manager->createInstance('simplenewssubscription', $config);
$vars['newsletterblock'] = $plugin_block->build();

but faced with following message in output

This block is broken or missing. You may be missing content or you might need to enable the original module.

SimpleNewsletter module is enabled,how can I render contributes modules block programmatically?

I render it with following snippets and work correctly

$block = \Drupal\block\Entity\Block::load('simplenewssubscription');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$vars['newsletterblock'] = $block_content;


Views block link defaults to target="_blank" using rewrite output My client is using d6 and views 3.  They want to be able to display a box containing a random static image with an internal link to display in the same browser tab or an external link that would display in a new tab.  I created a content type with a field to upload an image, a text field to include a url, and (for simplicity's sake) a text field to include the target (either _self or _blank).  Then I built a views block to display each image using the 'rewrite the output of this field' option on the image field.  The text for the rewrite looks something like this:

[field_image].

The problem I'm having is even when field_target_value has target="_self" in it, views or something is ignoring it and the a tag is always showing up in firebug with target="_blank".  Another weird thing is that when I display the page source, the target doesn't appear at all.  When you click on the image, it does in fact bring the page up in a different tab as expected.

I've looked in the views code and did not see anything in there that seems to be the cause.  There is some custom code and theming on the site but I have not been able to find anything in there either.

Anyone have any clues why or thoughts on the strategy I am trying to use ??

Print the results from the views template.you can rewrite the views template for that specific field and check the link that whether its external or internal using the drupal function url_is_external and you can add the attribute target="_blank" to those views fields that are external urls.

Off topic suggestion : if you want all external links on your website should open in new tab then you can use the extlink module to open all external links in new tabs.

  External Links is a small module used to differentiate between
  internal and external links. Using jQuery, it will find all external
  links on a page and add an external icon  indicating it will take you
  offsite or a mail icon  for mailto: links.


Update drupal modules without updating core in one drush command Is there a way to update all contrib modules without updating core in one drush command.  For example:

drush up updates all modules and core.  Is there a way to ignore core and just update the modules without having to list out each module name?

You can use the --no-core flag.

drush upc --no-core

https://drushcommands.com/drush-8x/pm/pm-updatecode/


Product category filter on the /products page I've been looking for a while but I can not seem to find the correct way to tackle the following problem.

On my products page, where all the products are, I have the standard drupal commerce kickstart filters. One of those filters lets me filter the shown products depending on which category they belong to. Now, I have somewhat of a hierarchy

Term
-child Term
--"grandchild (child of child)

(see image below)

now I'd like to be able to show for example the "Kastanje" product when i click on "Vloeibaar". Show the child product when clicking on the parent.

So far, i have had no idea how to do this and have tried pretty much everything i can think of in the "configure facet display" option.

Anyone who has an idea on how to do this?

You need to add a new filter to your view and remove the default category filter.

You should choose: Content: Has taxonomy term ID (with depth)

This filter / argument will also return content assigned to child terms of any given taxonomy term.


How do I include data from the order item type fields in the order receipt email? I have created an "Event Registration" product type and order item type. In the order item type, I added fields for the registrant's name and job title. How can I print the submitted values for those fields in the commerce-order-receipt.html.twig?

Figured it out! Took a few steps:

I created a View of type: Order Item. Added my custom fields to that view (Job Title, etc).
Added a Contextual Filter "Order item: ID".
Provide Default Value: Content ID from URL.
I created a Viewfield on
each of my Order Item Types, using the View I created in the
previous step.
I went to
/admin/commerce/config/order-item-types/default/edit/display and hid
all the fields except for the Viewfield. Repeat for the other Order
Item Types. In commerce-order-receipt.html.twig, add this code
(which was found in commerce-checkout-order-summary.html.twig):

{{ order_item|commerce_entity_render('summary') }}

Style the output as you like in the receipt twig. Here is the
pertinent portion of mine in case anyone finds it helpful:

            {% block order_items %}

              {% for order_item in order_entity.getItems %}

            {{ order_item.getQuantity|number_format }} x
            {{ order_item.label }}
            {{ order_item.getTotalPrice|commerce_price_format }}

          {{ order_item|commerce_entity_render('summary') }}

              {% endfor %}

            {% endblock %}

Clear cache, and that's it!


drush sql-dump skip extended inserts? Does drush have an option in its sql-dump command to skip extended inserts?

I am looking for a particular value in the database, and having shorter lines would be a boon for my task.

Yes, it has, just add --ordered-dump parameter to the sql-dump command, e.g.

drush sql-dump --ordered-dump

Tested under Drush 8.x.


image hover with views I have created 2 image-fields in my content type image-main and image-hover.
The image-main is an album display and when you hover the album cover it must change to the image-hover.

How can I get this working.

yes, this is sounds good, you can nicely use the replacement pattern for the views, and there is nice tutorial for css3 hover effect you can use this. Click here
After adding two field to your view hide the first image field and use the replacement pattern of the next field.In that replacement pattern you can put the variables as like bellow..this is just an example

<div id="cf">
 [fieldone]
 [fieldtwo]
</div>

then this two image will wrap with a div now you can add class name to the image tag as shown in the example.Hope this will help you.


Webform default validation message altering I am working with drupal8 site.Here i want to override the default "The email address %mail is not valid" email format validation message.I have checked with hook_form_alter to implement this.But no result.Is it possible to alter this message?

For Drupal 8, Webform uses Drupal's default Email Form Element. You'll have to override this element info and add your own validation message there.

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_element_info_alter/8.5.x


Catchable fatal error: Object of class stdClass could not be converted to string includes/theme.inc on line 2742 I did noting ,when try to clear cache I see this error
Catchable fatal error: Object of class stdClass could not be converted to string includes/theme.inc on line 2742

foreach (array_keys($regions) as $region) {
    // Assign region to a region variable.
    $region_content = drupal_get_region_content($region);
//  $tmp = (array) $variables[$region];
    //ym(empty($tmp));
//  if(empty($tmp))
    isset($variables[$region]) ? $variables[$region] .= $region_content : $variables[$region] = $region_content;

I google this error but didn't find anything, anybody know what is the  reason of this error and how can I resolve it?

Clearing your cache goes through all of your code looking for hooks, so something you have installed or updated or written since the last time you cleared cache has this error.

The error technically means that you are trying to use the wrong type of variable in a particular function.  In my limited experience, this usually means you have passed the wrong type of variable to the function before it.

In your case, it looks like you are trying to add a stdClass object $region_content to a string, which is why it is trying to convert it.  You will likely need to dig into $region_content to find the markup you are looking for before adding it to your string.


How do I create relevant keyword search? I created a view and fetched the content from a content type. I created an exposed filter with two fields (title and body) using contextual filters.
Search works for exact match keywords, but it doesn't work with similar keywords. For example, for timesheet and application it works fine, but if I search using the wrong spelling (for example, timeshet or appliction), it doesn't work.
How do I create a keyword relevant search?

You would need Search API and Search API Solr for this, along with a Solr instance to get relevancy scoring and support for fuzzy searching (e.g. iphone iphane etc).

https://www.drupal.org/project/search_api
https://www.drupal.org/project/search_api_solr

It is mostly configurable from the Drupal UI.


Back to views search result View search results gives node list based on exposed filters applied when making the search.

After user picks a result (node) and reads it there is no easy way to get him back to search results.

Exposed filters are "remembered", but the option to click back in browser does not seem user friendly, so i am looking for a module to do this. Is there any ?

Maybe you could check the selected answer here How to provide back link to page? just to confirm if you really want this kind of functionality and it also suggests some options that you can do and it's "non-recommended" level.

Hope that helps.


Global $user object isn't always "Fully Loaded" I have a Drupal 6 module that implements hook_user() to add a custom property on op='load';

mymodule_user($op, &$edit, &$account, $category = NULL) {
  $account->external_id = mymodule_get_user_external_id($account->uid);
}

In modules, I access the global $user object. What I find is sometimes it has my ->external_id property, and sometimes it doesn't.

As a result, I end up having to check to see if my custom property is set, and if not, call user_load()

if(isset($GLOBALS['user']->external_id)) {
  $account = $GLOBALS['user'];
} else {
  $account = user_load($GLOBALS['user']->uid);
}

Yuck! Is this a known problem, or does it sound like I'm doing something wrong?

Nope, you are doing it right as this is a known issue/behavior.  Check out http://api.drupal.org/api/drupal/developer%21globals.php/global/user/6 for a lot more information on it.  A link from there, http://drupal.org/node/57287, talks to your point directly (it is for D7 but is germaine to D6).


Feeds import dynamic author change I use Feeds so that logged users can upload data. I need to keep track of which user uploads what.

In Feeds importer 'Settings' you define the author, but in my case it should not be static but defined dynamically by the system.

How can I dynamically change that? thanks

You will need to make sure that users import content by creating a node. You can then map the author of that node to the author of the feed items that get created.

Make sure your importer is attached to a content type. Users can then import content by creating a node of that type. If you use the standalone import form, you cannot track which user uploaded what.

Map "Feed node: User ID (parent:uid)" to "User ID (uid)". This will make sure that the author of all nodes that get created will be the same as the author that is set on the feed node.

If you are using the CSV parser, manually enter parent:uid instead as source.


Need help defining IE specific stylesheet with Zen Starter-kit and Conditional Stylesheet Module I need help defining a conditional IE stylesheet in my .info file.

I am using the Zen starterkit as my base theme, and I have the conditional stylesheet module installed and enabled. I have added an ie.css file added to my css directory along with my other stylesheets. In that ie.css file, I have changed the background to an obnoxious color to confirm when the stylesheet is being used appropriately.

However, I have been struggling with what I need to put in my .info file. I have researched as much as I could and read the help.txt file multiple times.
I just want this stylesheet to target IE. I do not want to create one for each version. This site will not support ie6 and ie7 anyways.

Here is what I currently have defined in my .info file for it:

stylesheets-conditional[if IE][all][] = css/ie.css

I have also tried this that just results with that stylesheet loading for all browsers:

stylesheets-conditional[!IE][all][] = css/ie.css

So far with all of my attempts, I can either get it to act as a normal stylesheet, having it override my other styles, or not having it load at all. Is there something I need to add in my page templates that I am overlooking?

I have this in the head of my html.tpl.php as well (I have my actual theme name in there):

<!--[if IE]><link rel="stylesheet" type="text/css" href="sites/all/themes/THEMENAME/css/ie.css" /><![endif]-->

Other resources that I have used:

1) Conditional Stylesheets Set-up: Using the Module

2) Add conditional stylesheet CSS for internet explorer only (not trying to use this method)

If this link is in your head it is like if the css file is in a folder under the currrent one. You need a first backslash: <!--[if IE]><link rel="stylesheet" type="text/css" href="/sites/all/themes/THEMENAME/css/ie.css" /><![endif]-->

As you can see in the answer you linked the definition in .info file has to look like

stylesheets-conditional[IE][all][] = css/ie.css

not

stylesheets-conditional[if IE][all][] = css/ie.css

(I just have it from this answer - never used this module). Honestly I would not install a module just to add conditional comments for IE. It is easier and saves performance eating module to put them simply into the html.tpl.php - you just have to keep the right paths.

stylesheets-conditional[!IE][all][] = css/ie.css

Makes absolutely no sence - I do not know if this module could interprete that. But at least no browser in the world would read a css file in such a conditional comment: every browser except IE ignores conditional comments. So you tell the only browser who reads them that this file is notfor it to use... you got it :)


Drupal 7 Views filter between two dates Looking for a little assistance. I have Drupal 7 up and running with the View and Date module. I'm attempting to build a content type where the only additional fields other than Title and Body are, Post Date and Expire Date. Setting up the view is easy but I can't seem to figure out how to make the view only appear with values between Post Date and Expire Date. Does anyone have any experiance setting this up this type of view?

First of all if you have date module you do not need to add two fields "Post" and "Expire". You can add a date field with a start and an end date. Other than that the rest is simple. Go to your view and add two filters.

First filter will be your start date where the field is "less than or equal to" -> "now" (you can write that only if you select "enter a relative date" )

Second filter as you may have guessed will be your expire date field where the field is "is greater than or equal to" -> "now"

If "less than or equal to" and "greater than or equal to" don't appear as options, make sure you've enabled the Date Views module. (It is installed as part of the Date project.)


How to add paragragh information under hovered menu item? Hi all,
I want to add descriptions under my menu items like above (Eg. Home (ADD my description) Products (etc)?
Do I have to create children under these menu items and enable these????
Any advice would be appreciated.

Drupal 7

I think you're going to need to do a little (code) preprocessing of the menu in your theme layer.

To achieve this, I would put my description text in the "Description" part of my links (which is actually the title attribute) and then add a theme_menu_link() function to template.php (https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7).

Most people overload this function to add attributes to the menu links (like classes or ID's) but you could also adjust it to pull out the text you have placed in the title attribute, then mark it up however you want (span, div, etc..) and then return it in the Menu Link Title.

I see that you have also tagged your question with Superfish so you may need to review the theme superfish function as well (http://api.drupalhelp.net/api/superfish/superfish.module/function/theme_superfish/7).


"Preview before submitting" based on user role So, you can make "Preview before submitting" optional or required for a node type.
I would like to make it optional based on the user who is creating the node.

So, for example, a authenticated user has to view the preview of a node before he can save it, whereas a administrator user can save the node without previewing it beforehand.

Is there a module for that?

I tried it myself, hiding the submit button in hook_form_alter, depending on the current user's role:

$form['actions']['submit']['#access'] = false;

But i can't let the submit button appear again in hook_node_validate by doing:

$form_state['complete form']['actions']['submit']['#access'] = true;

Any help would be appreciated!

You have to unset the button:

unset($form['actions']['submit']);

This will delete the submit button from the array, thus it won't show up. Be carefull bacause above code will hide your submit button. You will have to check the key for the "preview" button.


How to implement 'phonetic typing' for performing a language conversion of a field (using CKEditor)? I am using CKEditor in a Drupal website. I am looking for a technique to convert (not translate) words from English to some other language (say Telugu), while typing those words.
Below are 2 examples to illustrate Phonetic typing (during the creation of a node):

If I start with typing "What" in a text-area (long text), then it should suggest something like so:

If I then continue typing "oka" in a text-area (long text), then it should suggest something like so:
 ... 2

How can I achieve (implement) this while using CKEditor?

Finally I found a module called Indic Script.

  This Module enables IME (Transliteration Input Method) for Indian Languages in Drupal Text Fields and Text Area Fields So that users can create their content in their own Language within Drupal without installing any additional software.

  6.x-3.0 and 7.x-2.x version has the integration for CKEditor (CKEditor.module and WYSIWYG.module)

  Indic Script module supports Type writer (TW) as well as Phonetic typing
  for the following languages.

  Tamil, Tamil Tw, Tamil 99
  Hindi, Hindi Tw, Hindi Remington Tw
  Malayalam, Malayalam Tw
  Bengali, Unijoy, Bengali Tw
  Gujarati, Gujarati Tw
  Kannada, Kannada Tw
  Oriya, Oriya Tw
  Punjab, Punjab Tw
  Telugu, Telugu Tw & Telugu Apple Tw

I've tested this module. Here is the screenshot of this module usage with CK field

I hope it helps someone.


Show related Content type content in block filtered by category I have a Content Type called "All Documents", this uses a Category called "All Categories". Within "All Categories" I have multiple sub-categories eg "Sales", "Parts" and "Service".

I have a block that displays the related content of "All Documents" but this shows everything in that Category. How do I filter so if I am viewing "Parts" it will only show content related to that sub-category?

At first, category and sub-category should be in Drupal-terms. Taxonomy vocabulary, taxonomy terms etc.

Assuming your related content block is created with contextual filters.

You can add these contextual filters to your views:

Content: Has taxonomy term ID (with depth)

Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.

Content: Has taxonomy term ID depth modifier

Allows the "depth" for Taxonomy: Term ID (with depth) to be modified via an additional contextual filter value.


Using a template for a custom admin page made with hook_menu I have developed a module in Drupal 7.

Now, I want to add a custom themed-page in the admin panel of Drupal.

I have added a page using admin_menu():

function newsletter_menu()
{
    $info = array();

    $info['admin/reports/newsletter'] = array(
        "title" => "Number of Registered Users for Newsletter",
        "description" => "",
        "page callback" => "newsletter_admin_content_block",
        'page arguments' => array('newsletter_admin'),
        'access arguments' => array('administer newsletter settings'),
        'type' => MENU_NORMAL_ITEM
    );

    return $info;
}

It works all well. But my problem is:

I have a template file newsletter.admin.tpl.php which I want to use a the template for this page. But I don't know how should I achieve it. Can anyone help?

Have a look at this question on stackoverflow: https://stackoverflow.com/questions/5305114/drupal-7-how-to-load-a-template-file-from-a-module

It basically comes down to this:

Implement hook_theme()
Create the template file
At the end of your newsletter_admin_content_block call theme() with your template key (as defined in hook_theme()) as first argument and any additional variables that you need in your template as an array.

Example:

function hook_theme($existing, $type, $theme, $path) {
  return array(
    'newsletter_admin_content_template' => array(
      'variables' => array('var1' => NULL, 'var2' => NULL, ...),
      'template' => 'newsletter-admin-content-template'
    ),
  ),
}

And at the end of your menu callback:

return theme('newsletter_admin_content_template', array(
  'var1' => $var1,
  'var2' => $var2,
  ...
));


Gmap cluster different marker types seperatly I created a Gmap with the Gmap module and views. There are two different marker types, based on different Gmap marker fields in the used node types.

The markers are clustered with GMaps Utility Library MarkerClusterer. And I added a MarkerClusterer styles in JSON. This results in clustering all markers regardless the marker type.

How to get each marker type cluster separately?

Is this something for OpenLayers?

The Comparison of mapping modules includes this:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


People Permission: View own unpublished content do not work I want let anonymous user can visit unpublished content, So I enable View own unpublished content for anonymous user.

But I open other browser to visit the url of unpublished content. But it alert me:

Access denied

I clear the cache, but above problem again

So, It is a bug?

Drupal 7

  In Drupal 7, users are not allowed to view any unpublished content by
  default, not even content created by themselves. By enabling 'View own
  unpublished content', you grant users access to their own unpublished
  content.

  The only way to allow users access to all unpublished content in
  Drupal 7 (without using a contributed module), is to enable the
  permission 'Bypass content access control'. Use this permission with
  extreme caution as it has far more consequences than just allowing
  access to unpublished content. In combination with Organic Groups for
  example, this permission allows access to private group content
  regardless of whether the user is a group member.

https://drupal.org/node/1106606

On that page are some contributed modules to set permissions you need...


I can't translate the text  in a form select list I just can't translate the text  in a form select list.
I need it to be translated in spanish lang.
I tried to translate it using the translate interface but I couldn't find it.
Please take a look a the capture:

There seems to be a problem translating strings with "<" and ">" in them, which is odd, but anyway:

http://drupal.org/node/348130
http://drupal.org/node/663156

If it's a Views related problem, at admin/build/views/tools you can change Label for "Any" value on optional single-select exposed filters: to - Any - (instead of <Any>) and translate that.


Search multiple fields from one text box in a View I have a database of articles with some taxonomies to classify each article. I also have a view that also contains a faceted search and uses filters to create dropdowns for the taxonomy fields using Views (see the image below). The search results will show facets in the sidebar and a user can click on them to further refine results (such as facets like Doc Year, Doc Author, etc.) The problem is that I really only need one text box to search a group of 3 text fields in this View.

For example, each article contains these three separate text fields:

Article Title
Article Title in French
Article Body

I want one text box on the search form to search these three fields without having to create three fields, one for each database field. The rest of the dropdowns to search each taxonomy can exist in the form to appear like below.

Thank you to everyone helping think how to accomplish this. I am sure it has been done before many times.

You achieve it by using  Global: combine field filter.
For details and get familiar with it take a look at

https://swsblog.stanford.edu/blog/views-exposed-filters-multiple-field-search


Show field label when using tokens in "Global Custom Text" field in Views? How can I show the field label when using tokens in Global field in Views.

To reproduce:

In a view:

1) Add field: title-field and enable to "Create a label" with value "My title".

2) Add field: Global Custom Text. In this field I use the token [title_field] for the text.

In the result the label is not shown. The token just print out the value but not the label. Even when I checked  "Create a label" with value "My title" for the title-field

Can I get this? I know that this can be done with the views_php module but, I don't want to enable this module just to workaround this.

A workaround would be to just create your own label by typing it in.

ex 1: Title: [title_field]

ex 2: Title:
[title_field]


How to add multiple images to a node using node.save service? I am using the services module along with the json server module to add a node to my drupal web site from an external application.

One of the cck fields is an image field which can accept multiple values. In my javascript application I'm calling the node.save service with node object like:

node_obj.field_image = [{ "fid": fid }];

This successfully adds the image value to the cck field. But how do I add another image value to this field? Calling the service again overrides the old image vale with the new one.

[{ "fid": 1 }, { "fid": 2 }];

have you tried this?


Best way to store custom commerce pane form data as part of an order? I have a custom checkout pane that only loads if there is a product of type 'Event' in the cart. For each product of type 'Event' in the cart, the pane prints out two custom fields: 'Ticketholder's Name' and 'Ticketholder's Email'. Further depend on the event there are upto another 8 extra fields such as 'Dietary Requirements' and 'Arrival Time'.

In the past, if I have a custom value that I want sent through with the order, I have created a custom field within the order fields, and then set the value in the following way:

$order->field_my_custom_field['und']['0']['value'] = 'my custom value';
commerce_order_save($order);

Now this seems fine for custom values that need to be set for all orders. However with this custom checkout pane, these custom fields only appear for 'events'. Further it is dynamic, so if there are 2 tickets for the same event (i.e one product of quantity 2) in the cart, it will need to store Ticketholder's Name & Email etc. for both ticket 1 and ticket 2.

So is there a more appropriate way to set the custom values and display them when you go to Store > Orders > View Order? Can I programmatically attach the custom fields to the order?

In the past I have looked at adding custom line items to checkout to store this kind of data but have been unsuccessful in getting them to display within Store > Orders > View Order. Further the same event, with quantity 2 will just be one line item in the cart so I'm not sure how you would attach the data for both ticketholders in this way.

What is the best way to store this data as part of the Order, so that it is accessible at Store > Orders > View Order?

Thanks for your help!

I have had the same issue for some time with field collections and simply switching the panes on and off in the order entity was not doing the trick.  I ended up being able to work up a solution using order types.  http://drupal.org/project/commerce_order_types

In addition I want to mention that we used the following patch: http://drupal.org/node/1887812 so that commerce could recognize panes from different order types.  At this point your already there, its a simple process of switching order types and subsequent panes based on the order type.


Replace file button missing I am missing a button to press when replacing a file.

Go to admin/content/file and edit a file.

For example: i am on file 778 at /file/778/edit

If you look at the Replace File field, there is no Replace/Upload button! So, yes, I can only upload an image but not replace the image.

The actual replacement does not happen until you save the entity. There is no fancy AJAX-based form manipulation here (unlike a core file field), so there is no specific "upload" button attached to that "replace file" field.

You just need to specify your replacement file (populate that field) and then save the full form ("Save" button at the bottom) for the replacement to happen.