Menu Block shows both languages I'm using the i18n module for translating nodes and menu items.
I have a bunch of menu-items and am now trying to put that into the header with a menublock.

But unfortunately all menu-items in all languages appear instead of just the items in the current language and language-neutral.

Does anyone know how to fix that.

The only solution I have is to create a menu for every language.

Okay sorry ... it took some time, but I found the solution.

First I had the themed menu within the template, now I have the main menu direct as a block.

The solution was to edit the main menu and set the following option:

Translate and Localize. Menu items with language will allow
translations. Menu items without language will be localized.

That's it.


Is there a core method in views that can pad numbers with leading zeros? Setup
I am building a view that outputs human usable id's. These ids would look best if padded to 3 characters. For example the episodes of a tv show may look best if they are formated:
01-01 (Season 1 episode 1)
10-05 (Season 10 Episode 5)
03-22 (Season 03 Episode 22)
Problem
In my node I'm storing a simple integer (1-100). I want to keep the value as an integer not a string. How do I pad the integer with leading zeros on output.
Using simple php would be a simple str_pad($value, 2, '0', STR_PAD_LEFT); but I do not want to execute php in my views or even enable the php module/filter.
Solution
The solution must:

Use a core ability of views
Not require me to execute php stored in the database (not enable php module or anything equivalent)
Must allow me to maintain the field as an integer input/storage

I could probably write the views plugin for this but I was hoping their was already something available like a views integer format or something like that.

Go to /sites/all/themes/yourtheme/ folder and in template.php add the following code:

function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $vars['fields']['field_example']->content = str_pad($vars['fields']['field_example']->raw, 2, 0, STR_PAD_LEFT);
  }

}

replace yourtheme with the actual name of your theme
replace view_name with the name of your view.
replace block_1 with the machine name of your view.
replace example with the name of your field (2 replacements).

Lastly, in Drupal, clear/flush your cache to see the changes.


Create custom theme for module I've creating an intranet module for Drupal 8 and I want to use a custom theme for it, like an admin theme(with page/node/field templates) where I can map region like menu, header, footer... but only for my module.

I didn't find any specific doc about this.

Thanks for your help!

You cannot specify region on your module, but you can custom your page or your block.
Regions are specify into main theme.
First, you need to create a folder on your module root directory :

myModule/templates

Inside, you ll put all your custom template.
For example :

page1.html.twig
page2.html.twig

Then you need to declare all your templates :

In myModule.module :

/**
 * Implements hook_theme().
 */
function myModule_theme() {
  return [
    'page1' => [
      'template' => 'test',
      'variables'=>array('test'=>NULL),
      'render element' => 'children',
    ],

      'page2' => [
          'template' => 'page2',
          'render element' => 'form',
      ],

  ];
}

And after, in your controller or your form :
return $build +  [
  '#theme'=>'page1',
  '#test'=>"its content for my variable inside my template",
];


Site Access control through a particular user field I am trying to only grant user the access to the site if one of the user fields have a particular value.

If not, the site should show an access denied.

Is there an efficient way to achieve this?

Let's say there is a specific path you want this rule to apply to, e.g. /special

<?php

function my_module_menu()
{

    $items['special'] = array(
        'title' => 'Special Page',
        'page callback' => 'special_page',
        // Permission in next line will be overridden by the check inside the page callback function.
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
        );
}

function special_page()
{
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user');
    $query->propertyCondition('uid', $user->uid, '=');
    $query->fieldCondition('field_special_field', 'value', 'required_value', '=');
    $query->range(0, 1);
    $result = $query->execute();

    if (isset($result['user'])) {
        // User meets the condition
        // Do whatsoever, show special content ..

    } else {
        // Deny access
        drupal_access_denied();

    }
}

?>

Make sure to download and enable the Entity API module to use the above code.


How to search and replace content type (system)name in database for product types Using Commerce kickstart, I wanted to replace the existing example content type names with other names.
I downloaded the database, applied a search and replace, and after uploading the database and clearing caches, the website now shows new content types plus the old ones.
It appears that the website has recreated the old content types..but I have no idea what does that and how to prevent that.
Any ideas?

It appears that commerce kickstart uses features in order to create the demo store, and that the content types cannot be deleted. Apparently they are recreated by features when the machine name of the content type is not present any more.

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


Single Drupal installation with multiple websites Currently, I have two static HTML folders: 1 for English webiste , and 2 for Thai website. They have the same look and feel but different menu and content. To be precise, the menu and content
in the www.example.org/th are not translated versions of the English site, they are totally different.

URL for the English website is http://www.example.org and http://www.example.org/th for the Thai website.
I want to switch to Drupal 7. So, here's what I have in the to-do list:

Theme:

Create a parent theme (www.exaple.org)
Create a sub theme for (www.example.org/th)

Panel:

I will create a Panel with "th" path for www.example.org/th and then make it use the subtheme (not sure if this is the correct approach)
Create a different menu and will put it in the Panel (not sure if this will work out that way)

Should I create Panel and different menu or Should I go with single Drupal installation that can be used to power multiple websites to get the same result as I currently have with static HTML sites?
If so, please show me some tips or sample to get started.

Thank you.

Yes, if these two sites are really separate and have nothing in common, I would go with a multi-site setup and a single Drupal installation.

This is supported out of the box, see the Multi-site documentation on drupal.org for more information.


What is the syntax for setting 404 fast paths on all Drupal pages in D7 > 7.9 D7.9 introduced 404 fast paths which don't fully bootstrap drupal on 404's for certain file types if it's enabled, thus saving some bandwidth / computation. More info is available here: http://drupal.org/node/1296384

By default this excludes only certain file types such as .jpg, .txt., etc., looks like this:

$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpeg|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

I want to use this for all paths. Are there any repercussions to that?

I tried changing it to

$conf['404_fast_paths'] = '/*$/i';

However, this returns a warning:

  Warning: preg_match() Compilation failed: nothing to repeat at offset 0 in drupal_fast_404() (line 2484 of /cms/main/includes/bootstrap.inc).

So what should the syntax look like up there to both work and not generate a warning?

Alternatively, if there isn't a solution to this specific question, is there a way I can speed up 404's for all Drupal pages, would it better to use the Fast 404 contributed module for instance?

You used "/*$/i" as regular expression, but there is nothing before the asterisk; in other words, you are not saying what can be repeated zero or more times.
Valid regular expressions expressions such as "/.*/i", "/[a-zA-Z]*/i", "/(foo|bar)*/i".

drupal_fast_404() is called by drupal_deliver_html_page() when the result of menu_execute_active_handler() is MENU_NOT_FOUND, which means Drupal is asked to look for a path without any menu callback associated.
drupal_fast_404() first checks that $_GET['q'] doesn't match the regular expression contained in the "404_fast_paths_exclude" Drupal variable; if it doesn't match that regular expression, then it checks $_GET['q'] matches the regular expression contained in the "404_fast_paths" Drupal variable. The default value for that variable is '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i' which means the fast 404 page is returned when the request is for a file with the following extensions:

.txt
.png, .gif, .jpg, .jpeg
.css, .js
.ico, .swf, .flv
.cgi, .bat, .pl, .dll, .exe, .asp

If you want the fast 404 pages be used in any case, I would not touch the value of the "404_fast_paths_exclude" Drupal variable, and change the content of the "404_fast_paths" Drupal variable to '/.*/i', which would match any path that causes a 404 error, excluding the ones containing "styles."


How to insert the title of the group in a message? I created a custom module using the example in:

https://www.drupal.org/project/message

When a node is created, it is associated with a group:

https://www.drupal.org/project/group

Here is my module. I created in my template a reference field to the group field_group_reference

How to insert the title of the group in the message ?

Thank you

<?php

/**
 * @file
 * Holds hook implementation for the Message Activity Stream module.
 */

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\message\Entity\Message;

/**
 * Implements hook_group_insert().
 */
function message_activity_stream_group_insert(Node $node) {
  $message = Message::create(['template' => 'mas_create_node', 'uid' => $node->get('uid')]);
  $message->set('field_group_reference', $node);
  $message->set('field_published', $node->isPublished());
  $message->save();
}

For this, you need to know that a node can be in multiple groups and there is also a midlevel entity between a node an a Group called a GroupContent entity.

To retrieve the Groups for a given node you can use this code:

 $plugin_id = 'group_node:' . $node->bundle();

 // Only act if there are group content types for this node type.
 $group_content_types = GroupContentType::loadByContentPluginId($plugin_id);

  // Load all the group content for this node.
  $group_contents = \Drupal::entityTypeManager()
        ->getStorage('group_content')
        ->loadByProperties([
        'type' => array_keys($group_content_types),
        'entity_id' => $node->id(),
  ]);

  /** @var \Drupal\group\Entity\GroupInterface[] $groups */
  $groups = [];
  foreach ($group_contents as $group_content) {
    /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
    $group = $group_content->getGroup();
    $groups[$group->id()] = $group;
  }

You can see this code in action in gnode_node_access() which works out access permissions for a node by checking the Groups it is attached to.

Now you have a list of groups, you can load the first one from the list and use its title.

  $group = reset($groups);
  $title = empty($group) ? '' : $group->label();


How to use FULL Jquery.com files in Drupal content item? I can use JS Injector and link to JS files through the info file, but what if the script is quite complicated with a lot of files and dependencies?

This accordion script has over 20 files...how to link all this and make it work?

Script is over here:

Download Builder

All you need is to enable the jQuery Update module, which provides support for all jQuery UI versions for Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x, 2.1.x and jQuery UI 1.10.2.


How to show Checkboxes with Fulltext Search Filter Exposed? I have created a simple search with three filter options of "Contains any of the word", "all of the words" and "none of the word", as shown in the figure below.

I used Search API, and later created a view out of it.

For an exposed filter, I just chose "FullText Search" and exposed it as follows:-

It shows me a page likes this:-

Now, it works fine, but I want checkboxes instead of the dropdowns. For that I installed Better Exposed Filters, but it doesn't show me the option to show checkboxes ... as shown:

What am I missing that this is not allowing me to show Checkboxes :(. I will be very thankful for your help. I just need to convert them to checkboxes.

Currently BEF doesn't support tweaking the display of the filter operator, only the filter itself. But this would be a great addition -- feel free to post a feature request in the BEF issue queue.

Thanks.


Is there a way to strip identifying data from commerce tables? I am interested in stripping personal addresses out of the  commerce_customer_profile and commerce_customer_profile_revisions database tables to sanitize the database for development purposes.

The site is using Drupal 7 and Drupal Commerce 7.x-1.13.

Has anyone come up with a way to do this?

There's nothing special about sanitizing Commerce.  When I sanitize the db, I simply delete all the info in SQL:

TRUNCATE TABLE commerce_customer_profile;
TRUNCATE TABLE commerce_customer_profile_revision;
TRUNCATE TABLE field_data_commerce_customer_address;
TRUNCATE TABLE field_revision_commerce_customer_address;
TRUNCATE TABLE field_data_commerce_customer_billing;
TRUNCATE TABLE field_revision_commerce_customer_billing;

NOTE: This is just an example.  You need to check your database and make sure you get all the relevant tables.

If you want to use dummy data instead of deleting the data outright, you can use a statement like this:

UPDATE users SET users.name = users.uid WHERE users.uid > 0;

If you don't have a tool like PhpMyAdmin for accessing your database easily, I would use Sequel Pro on macOS or MySQL Workbench on Windows/Linux.

Drush has a sql-sanitize command but I have encountered several issues with it over the years.  I don't want to risk accidentally exposing anything before handing off a db to another developer, so I check the db anyway; in that case, there's no real speed advantage to using Drush vs. running the SQL myself and since I'm checking it with my own eyes I can be confident the job got done.


How to specify entity reference fields when programmatically submitting to user_register_form You'd think this would be easy. I'm calling drupal_form_submit('user_register_form', $form_state)
to automatically register users after they have completed filling out a Webform.

But I have some Entity Reference fields in my user profile and form_validate is not happy with what I am submitting for them. All of the ER fields are references to taxonomy terms. Some of them are single-value fields, some of them are unlimited value fields. They have various widgets attached such as Select List, Autocomplete, Checkboxes and Radio Buttons. Some of them are Required fields, others are not.

I've tried setting all of the following in $form_state['values'] before submitting the form:

$form_state['values']['field_foo']['und'] = $tid;
$form_state['values']['field_foo']['und'][0] = $tid;
$form_state['values']['field_foo']['und'][0]['target_id'] = $tid;

But Drupal still throws out 'An illegal choice has been detected' when it comes to validate the field, or sometimes a 'Field is required' error.

What am I doing wrong and how do I go about figuring out the right way to specify each of the fields?

I think form might be expecting in proper format that is "[entity-title] [entity_id]", so field array should look like.

'field_foo' = {
    'und' = [
        0 = {
            'target_id' = 'Title of entity ($tid)'
        }
    ]
}

Just to make sure you can form alter user form, add a custom validate and do a dsm($form_state);


What does the "Vary: Cookie" header actually do for serving pages from Varnish? According to the documentation in default.settings.php, and I've seen similar descriptions elsewhere, "Without "Vary:Cookie", authenticated users would also be served the anonymous page from the cache."

However $conf['omit_vary_cookie'] = TRUE; is recommended with Varnish in Drupal 7 and doesn't seem to keep users from being able to switch from anon to authenticated sessions. Is this a header that Varnish doesn't actually care about?

To answer my own question. I've found that with $conf['omit_vary_cookie'] = TRUE;, users who visit a page as anonymous users and log in will see the cached version of the page until they click "refresh" on their browsers. It is a subtle difference that I didn't notice at first as  admininistrator user.


Aggregated javascript contains binary data, breaks site Today I noticed a site's javascript was broken. One of the aggregated javascript files contained a bunch a binary data that (obviously) caused a syntax error;

‹EAk1…ÿŠæ”°!«Ð–¢Á¶]¤µ'³³6â&K2ºÑßÞ,J{3ï½éWgÈzÇAn¤ç#„^)QVãR³ù¬X³ìzåÜaÛ{B¡¶H[#ùóÓ>
Ë

After deactivating the js aggregation the site works fine, and none of the javascript looks off.

Turns out the problem was caused by an external javascript file that had been added through drupal_add_js without specifiying it being external. In my case specifically the pinit module for Pinterest was the culprit.

The external server had recently enabled http gzip compression, so the end result was gzipped data being straight up being concatenated into the js aggregation.


How to add "rel" attributes to all external links throughout the website? I'm trying to add attributes for external links such as the rel="noopener noreferrer" for all the external links where target="_blank". I've tried using modules such as the noreferrer and sel, but neither affect the links in my views.
How can I add rel="noopener noreferrer" to all links globally where target="_blank"?

By implementing hook_link_alter in either a custom module or your theme.
The code (untested) would be similar to:
/**
 * Implements hook_link_alter().
 */
function MODULE/THEME_link_alter(&$variables) {
  if (isset($variables['options']['attributes']['target']) && $variables['options']['attributes']['target'] == '_blank') {
    $variables['options']['attributes']['rel'] = 'noopener noreferrer';
  }
}


Adding CCK field to solr index We have a cck field called "keywords". We need to add this field to the solr index so we can search on it from outside of drupal. How are CCK fields managed in the solr index?

UPDATE:

I created a module "apachesolr_search_additions" and the following function:

<?php
function apachesolr_search_additions_apachesolr_update_index(&$document, $node)
{
  if (isset($node->field_keywords_raw) && !empty($node->field_keywords_raw))
  {
    $document->addField('sm_keywords', $node->field_keywords_raw[0]['value'], '2.0');
  }
}

I then ran cron and went to:
admin/reports/apachesolr

it does NOT show the field name in the search index. How can I verify it is in the index?

Adding Custom Fields to Apache Solr Search Results appears to have the instructions.

  To do this, we will use the two hooks used in the last example: hook_apachesolr_update_index() and hook_apachesolr_modify_query().  To start, we need to add the data to the Solr index.

Modified the code to work with a field_keywords_field (note: field_keywords_field[0]['value'] is what I'm using, you may need to debug this if your keyword field is multi-value or something)

/**
* Implementation of hook_apachesolr_update_index()
*/
function mymodule_apachesolr_update_index(&$document, $node) {
  // Index field_keywords_field as a separate field
  if (isset($node->field_keywords_field) && !empty($node->field_keywords_field)) {
    // addField($key, $value, $boost), change $boost to give this field a higher score
    $document->addField('sm_field_keywords_field', $node->field_keywords_field[0]['value'], '2.0');
  }
}

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',sm_field_keywords_field';
}


How come images with image styles are blurry? We have noticed that images that are displayed using Image Styles are blurry. Below are the settings we have enabled.

The original images look fine and scale accordingly when using those on the pages, but not the Images with Image Styles. How can this be resolved?

GD2 Image Manipulation Toolkit settings: JPEG set to 100%
ImageMagick module but the results are the same.
We also tried to use JPEG and PNG

View mode (field setting):

formatter = image
Image style: Banner Image

Banner Image Image Style settings:

Scale 1600px (W) by 900px (H)
Allow Upscaling = false

CSS and HTML used:

<div class="banner__image" style="background-image: url('/sites/default/files/styles/banner/filename-banner.jpg')";>

.banner__image {
  width: 100%;
  height: 100%;
  background-position: center;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

I've delt with this issues on many sites. The cached version from the image style always renders poorly. I'd recommend removing it and using CSS to adjust the sizing.

In some cases, removing existing upload size limits on the image field has helped resolve this.


Facebook share in drupal7 sharethis module picking wrong thumbnail image I using ShareThis module in a drupal7 website for a certain content type say 'news'. When a user hits a Facebook share button, the title and links are fetched correctly but the thumbnail image it chooses is wrong.  I want my fbshare to pick my news image as its thumbnail image. Pls help.

thanks.

Update: i got it worked using MPD's comment. i explicitly added og:image in my header. Below is my code. Hope it helps someone.

$element = array(
            '#tag' => 'meta',
            '#attributes' => array(
                 "property" => "og:image",
                 "content" => $imagePath,
                  ),
            );
drupal_add_html_head($element,'fb_share_image');

Did you test the page with the Facebook Debugger?  Remember that Facebook caches page info, so changes don't appear immediately.  A side effect of the debugger is that it clears the cache when you test a URL, so changes get picked up.

If you wan to use a specific image, you need to be sure it explicitly has an og:image element in the header.  I am pretty sure this is something that the Meta Tags module can do this for you.


How to set context by url argument for node preprocess I have a View of nodes, rendered using a Display Suite view mode.  I need for users to either view the page with or without an argument in the path.  If they don't enter an argument, I want the nodes in the View to render normally, but if they do, like someview/10, I simply want to add a CSS class for that node in preprocess.  I have the Context module installed, so I'd like to be able to use that, but it doesn't seem like I can specify path arguments that I maybe set a context for that I can check for in the node preprocess.  Or if I can do it in Views somehow, that would be great, but I can't seem to figure that out.

This functionality is for a nojs user.  For js users, I just send the ajax commands back and set the CSS, but for nojs, I need to route them (I guess with drupal_goto())  to the View with the nid as an argument.

Here's a sketch of what you could do, using a custom module:

Define a menu entry for someview/%node.
Define a callback function for the menu entry with a node argument.
Store the node ID for later use. This could be done using drupal_static or the context API.
In your preprocess function, retrieve the node ID and add a CSS class if required.

You could also use Panels to achieve a similar end, I think, but this is a fairly lightweight, if specific solution.

Let me know if you need a fuller explanation. I realise not everyone is familiar with Drupal APIs.

So your menu callback might look like:
function mymodule_callback($node) {
 context_set("mymodule", "active_nid", $node->nid);
 return views_embed_view((... ...);
}

and in the preprocess:

$active_nid= context_get("mymodule", "active_nid");
 if($active_nid==$node->nid) {
 ...
}


How to restrict content access within a site? In a community site. I want to restrict users to have some private parts of the site like forum, groups and discussion board with their scope (should not be visible to others).

That is a specific forum should be available to a specific set of users who belongs to a specific group.

Eg: Let's say there are multiple groups of users like cricket players,  football players. I want to restrict the visibility and access to cricket forum only to cricket players and Football forum respectively. And there is a third forum called sports which should be visible to both.

The question can split into two:

How to create a specific set of users?
How can I restrict the specific set of users to the forums, groups, etc...

1) How to create a specific set of users?

That's what you typically do by creating appropriate "roles" in your site, and then for each user, you assign appropriate "roles".

  2) How can I restrict the specific set of users to the forums, groups, etc...

Combine this with granting "Permissions" to "roles" (which are then inherited by all users with the appropriate role). E.g. you grant access to (selected) forums.

When it comes to "groups", there are typically these modules that get used for that:

The most commonly used is Organic Groups, for which there is a set of amazing video tutorials to Learn Organic Groups. Especially the video about "Basic Organic group setup" should help to get you going with it. Here is what you'll learn from it (quote from that link):

  How to create a content type that is used as groups – meaning containers for other stuff (content and other entities)
  How to modify a content type (Articles) to allow it to be posted to selected groups
  That the user creating a group by default will be the group manager
  How to add more members to a group
  That there is an example feature shipped with OG
  That groupness and group contentness is actually managed by special fields
  That group membership is actually also managed with a field (of the same type that tells what group a content piece belogs to)

For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the (fairly new) Group module as a possible alternative. Some more details about it (from its project page):

  Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).

  Groups instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.

The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

  ... you can already use Rules to:

  Add a new Group
  Create a new GroupMembership and save it (the equivalent of $group->addMember())
  Add or remove a GroupRole from a GroupType
  React on new GroupMembership or Group entities
  …

  What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.

  Useful Rules we may add could be:

  E-mail all members of a Group, optionally filtered by GroupRole
  Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"

  ...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

Note:
It seems to me that "a particular school" (as in your comments below) would be a perfect with a "particular group" (no matter which of the 2 modules above you would use).


Site is slow when visiting admin pages I turned on Devel query log and at the bottom of my pages it shows the log with the number of executed queries and ms. When i visit any admin page for example /admin/appearance i have following entries in my query log:

 _update_cache_clear 73ms DELETE FROM cache_update WHERE (cid = :db_condition_placeholder_0)

DrupalDatabaseCache::clear 81.9ms DELETE FROM cache_bootstrap WHERE (cid = :db_condition_placeholder_0)

As i know, it shouldn't be more than a 5ms. I am using Xcache on my server with 16gb RAM. What's the culprit?

PS when i am visiting non-admin pages they all are loading very fast.

by default drupal cache pages for anonymous user, and it is usual that visiting page bye anonymous user be faster than login users,also in admin page we have more load that front-end page
The is a property of durpal. admin pages have more forms and more proccess.


SearchAPI + FacetAPI: How to add a facet programmatically Using SearchAPI and FacetAPi with Solr I have a facet block filled by one Solr indexed field i.e. "region".

Example:

  Region A
  Region B
  Region C

I need to programmatically combine two of the active facets to show the accumulated results, while keeping the original facets untouched.

How to achieve this?

  Region A
  Region AB <= new facet which accumulates Region A + Region B
  Region B
  Region C

There is a similar use case described in How can I merge or combine facets?

The difference in my use case is that I need the "combined facet" as an additional item, not replacing an existing facet item.

Any idea or hint is highly appreciated. Thank you.

The above use case may be an exotic one but I post my solution in case anybody else has a similar one and maybe it's a motivation for a more elegant solution.

Versions used:
- Drupal 7.38
- facetapi 7.x-1.5+1-dev
- facetapi_bonus 7.x-1.1+7-dev
- search_api 7.x-1.15
- search_api_solr 7.x-1.8

Steps in short

Add a new facetapi plugin to filter active facet items, using
hook_facetapi_filters() [1]
Plugin method execute(): Add the additional facet items to
the $build array of the active facet items
Alter the Solr query for the newly added facet items to combine the
two with operator OR, using hook_search_api_solr_query_alter() [2]
Activate the new plugin in the index facet configuration

Steps in detail

Add a new facetapi plugin with hook_facetapi_filters()

Documentation see facetapi.api.php and class FacetapiFilter [3]. Note the programmers comments in the docbloc of FacetapiFilter where another solution is suggested by adding an "alter callback". Unfortunately I couldn't get the alter callback to do what I like to do.

/**
 * Implements hook_facetapi_filters().
 * Define the plugin class to add additional facet items to an active facet.
 */
function mymodule_facetapi_filters() {
 return array(
   'add_items' => array(
     'handler' => array(
       'label' => t('Add facet items to facet "region"'),
       'class' => 'MyModuleFacetapiFilterAddItems',
       'query types' => array('term'),
     ),
   ),
 );
}

Plugin method execute(): Add the additional facet item to the  $build array of the active facets

Sample plugin code.

/**
 * Plugin that adds additional facet item(s) to an active facet.
 */
class MyModuleFacetapiFilterAddItems extends FacetapiFilter {

  // Execute active facets.
  public function execute(array $build) {
    // Taxonomy term ids of the facet items to combine into a new facet item.
    $tid1 = 1;
    $tid2 = 2;
    // Create the additional facet item. Check that the original facet items are
    // available.
    if (isset($build[$tid1])  && isset($build[$tid2])) {
      $add = array();
      $add['#markup'] = 'Region AB';  // the label of the new facet item
      $add['#path'] = 'search';  // your base search path
      $add['#html'] = FALSE;
      $add['#indexed_value'] = $tid1;  // @see comments below
      $add['#count'] = $build[$tid1]]['#count'] + $build[$tid2]['#count'];  // accumulate the #count of the two combined facet items
      $add['#active'] = 0;
      $add['#item_parents'] = array();
      $add['#item_children'] = array_merge($build[$tid1]['#item_children'], $build[$tid2]['#item_children']);  // merge the item children
      $add['#query'] = array(
        'f' => array(
          0 => 'field_region:' . $tid1,  // add both term ids in the #query f parameter
          1 => 'field_region:' . $tid2,  // leads to URL parameters like this: f[0]=field_region:1&f[1]=field_region:2
        ),
      );
      $build[] = $add;
    }
    return $build;
  }

  // Adds settings to the filter form, here only used for users' documentation. Inspired by facetapi_bonus.
  public function settingsForm(&$form, &$form_state) {
    $form['add_items'] = array(
      '#title' => t('Add a facet item for facet "region"'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
      '#suffix' => t('
        By enabling this filter, an additional facet item is added to facet "region".

        At the moment this list is hard coded and consists of

        - Region AB (combines Region A + Region B, with operator OR)
      '),
    );

    // TODO
    // - add UI settings to avoid hard coding stuff in code
    // - would be nice to be able to specify the operator (conjuntion) OR or AND in the $form array to pass it to the Solr query
  }
}

So far is achieved that the new facet item in facet "region" shows up. But it has zero results.

  Region A  (10)
  Region AB (0)
  Region B  (15)

As the operator (conjunction) for the facet "region" in my case is configured with "AND", the result of the newly added facet item "Region AB" is zero. So I need to combine the two filters with OR in the Solr query.

Alter the Solr query for the newly added facet items to combine the  two with operator OR.

Sample hook_search_api_solr_query_alter() code.

/**
 * Implementation of hook_search_api_solr_query_alter()
 */
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  // Only alter queries on the node index.
  if ($query->getIndex()->machine_name != 'node_index') {
    return;
  }

  // Facet query params array.
  $fq = $call_args['params']['fq'];

  // Get the key of the query that we need to alter. Depending on the active facets and if the
  // visitor is logged in or not, the fq array contains more or less queries in our environment.
  // The code below assures we modify the correct query.
  //
  // In this demonstration we use taxonomy term ids: tid1 = 1, tid2 = 2 for Region AB.
  // If both facet queries are present in the fq array, combine them to one query with operator OR.
  // Afterwards unset the second query.
  if ( (false !== $key1 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"1"', $fq))
  && (false !== $key2 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"2"', $fq))
  ) {
    $call_args['params']['fq'][$key1] = '{!tag=facet:field_region_ref}im_field_region_ref:"1" OR im_field_region_ref:"2"';
    unset($call_args['params']['fq'][$key2]);
    return;
  }
}

Now the counter of the newly added facet item shows up correctly.

  Region A  (10)
  Region AB (25)
  Region B  (15)

That's it about the coding. Of course "mymodule" has to be changed to the name of your module.

Remains just the last step to active the new plugin.

Activate the new facetapi plugin in the index facet configuration

In the Drupal administration UI visit "Configuration" > "Search and metadata" > Search API
- edit the Solr node index, visit tab "Facets"
- find facet "region" and select the "configure filters"
- active the new plugin "Add facet items .."
- store the changed settings

Note some drawbacks with this solution

1) Hard coded facet item properties
2) Facet item property: #indexed_value: can only specify one value. Don't know if this has implications on the counters when dependent facets are clicked. So far everything seems to be fine in my implementation.
3) Kind of complicated code to alter the query of the newly added combined facet items. It would be much more elegant if I could specify the operator as a parameter of the #query property when creating a new facet item. Or even easier: specify the fq query right in the wanted way like this: fq[0]=tid:(1 OR 2) -- only possible right now in module "ApacheSolr".

Links

[1] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!facetapi.api.php/function/hook_facetapi_filters/7
[2] http://www.drupalcontrib.org/api/drupal/contributions!search_api_solr!search_api_solr.api.php/function/hook_search_api_solr_query_alter/7
[3] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!plugins!facetapi!filter.inc/class/FacetapiFilter/7


Changing generated html of a module. (Search API) I need to change the generated html (twig) of the search API module ( https://www.drupal.org/project/search_api ). The Module generates a form having 2 divs with input tag in each of them. I need it to be a form with one div having an input tag and an anchor tag!

What the module generates (in short)

<form>

  <input>

  <input "submit-btn">

</form>

What I want it to be

<form>

  <input>

</form>

So basically, I need to be able to change the submit button to an image so I can place by "position:absolute" at the end of the first input field.

The search API module doesn't have the templates folder or any .twig files than I can overwrite. AND if I do overwrite the base theme form twig files that are used by the module, I cannot do it so that it changes only for this module and it doesn't change all other forms.

I am using drupal 8 btw.

I finally got around to do this using the MYTHEME.THEME file, I used this function:

function nestle_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#id'] == 'edit-submit-search-content') {
    $suggestions[] = 'input__' . $element['#type'] . '__' . 'mainsearch';
  }
}

Basically, it gets the element by its ID then changes its twig suggestion to kinda force twig to ditch the normal method of choosing the twig template based on naming conventions, Instead, it gives it a twig template to use!


add captch to registration modal box I have a modal box for login and registration for my site.

example.com
I want to add the captcha with the registration process.I added the captcha module in my site. But the captcha only work with the drupal's default registration page but not work with the modal box's registration.

How can I add the captcha with the modal box.

Try something like the following:

$form['my_captcha_element'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

More info here :https://www.drupal.org/node/743056


Change style for the reply link in comment.tpl.php How could I style the "reply" link in comment.tpl.php?

I have this line of code inside:

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

With this I get something like the following:

reply

I manage to get the exact URL with <?php print render($content['links']['comment']['#links']['comment-reply']['href']) ?>, but for some reason it doesn't work perfectly: It loses the "/?q=" part.

Just use the following code:

<?php print url($content['links']['comment']['#links']['comment-reply']['href']); ?>

If you pass node/1 to url(), it will  return /?q=node/1 when clean URLs are not enabled, and /node/1 when clean URL are enabled.


Get node bundle (content type) from EntityInterface trying to find if node is bundle article (node bundle = content type) before executing the rest of the statements in the following example

I can test if the entity is node but I can't figure out how to test if content type is article

<?php

use \Drupal\Core\Entity\EntityInterface;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    //if content type is article
    if ($entity->getEntityType()->id() == 'node') {
        //do wonderful stuff ...
    }
}

I did manage to find it after all $entity->bundle() it was pretty easy ...

 if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article') {


Support integer or float values as an attribute on a Drupal Commerce "Add to Cart" form I have created a product type which has integer and float fields. I would like to store my data as the correct data type and allow users to make decisions about which product to buy based on those fields. These are ineligible to become part of the commerce "Add to Cart" as defined by the following commerce function:

function commerce_cart_field_attribute_eligible($field) {
  // Returns TRUE if the field is single value (i.e. has a cardinality of 1) and
  // is defined by a module implementing hook_options_list() to provide an array
  // of allowed values structured as human-readable option names keyed by value.
  return $field['cardinality'] == 1 && function_exists($field['module'] . '_options_list');
}

It looks like the concept of implementing hook_options_list is hardcoded into a few places, including the field config forms:

if ( ... && function_exists($form['#field']['module'] . '_options_list')) {
  // Enable this field to function as an attribute field on Add to Cart forms.
}

By looking at how this has been setup, it seems reasonable that if you want commerce to cooperate with a field type, it must implement the hook.

I have considered implementing this hook for the "number" module and returning the entire dataset of values defined on the website for the specific field (this seems to work without any issues from what I can tell with 5 products).

I'm not sure if this will cause issues with Commerce or core down the track, perhaps with:

Too much data grinding things to halt.
The core "options" module not playing nicely with float/int fields.
Other modules assuming the field is a list of data?
The weirdness around implementing another modules hook.

Looking for some advice on the best way to move forward with the problem.

I ran into the same problem (and asked a similar question which I ended up answering myself  here)

Basically with the knowledge you gave I was able to implement a new module which installs a widget for the "list integer" and "list float" types that uses a textfield for input and on POST it sanitizes and adds the value of the textbox to the "allowed_values" setting on the field allowing it to pass the standard list field validation and use the standard list field storage.

This allows you to enter and display a "number" and use the value as a product attribute.  Best part is I did not have to alter another modules code, which addresses the majority of your concerns as:

  The core "options" module not playing nicely with float/int fields.

The options module defines the widget, since you are doing this, you don't need to worry about it.

  Other modules assuming the field is a list of data?

Since you defined your own widget and are not using the standard "options", other modules will not know it exists so you don't have to worry.

  The weirdness around implementing another modules hook.

Again, by adding the sanitized field into the allowed_values setting on POST you pass validation and this allows you to use the "LIST" modules standard implementation of hook_options_list and you don't have to modify someone else's code

As far as your first point on too much data, this is possible that you will have a problem here if you have a multitude of products OR if you are added and removing products all the time (which would continuously add to your "allowed_values" list). For the first point, you could probably also implement a field type in your module and do your own implementation of hook_options_list to follow your logic and just return all the values in your database (i don't have that much so didn't bother).  For the second point, you could implement hook_cron and clean up on the allowed values setting based on the values for the field in the database.

hope this helps and if you have any questions let me know!


Get Menu Items in Custom Module I'm creating a custom module block that will sit in the sidebar on certain levels of my site template.

The site structure is: Home > Level 1 > Level 2 > Article.

I want Level 2 to echo out all of the child links (basically a menu tree).

I want to achieve this with hook_block_view(). How can I get the page's child links in the main menu, and put them in an array?

Have you tried using Menu Block?

  provides configurable blocks of menu trees starting with any level of any menu.

It does exactly what you're looking for. If you still want to write a custom module I reckon looking through the code for that module would be the best place to start.


How do I clear a specific cache entry? I saved a cache entry using cache_set(). How can I clear this entry using Drush?

You can create a custom drush command to call the cache_clear_all function or just use:

drush ev "cache_clear_all('my_module', 'cache', TRUE);"

You can read more about cache_clear_all in A Beginner's Guide to Caching Data in Drupal 7


Passing variables from hook_mail to cutom twig template Custom twig template into hook_mail()

$body_content = array(
    '#theme' => 'mail_body_content',
    '#node' => $node,
);

I would like to access to node Entity and display value into the twig

myfield_name: {{ node.get('field_myfield_name').value }}

Render code

$renderedContent = \Drupal::service('renderer')->renderPlain($body_content);

Only myfield_name: is display.
How to get / pass the variable to twig ?

Rather than using node get to print a value just use this in twig.

  node.field_myfield_name.value

Otherwise preprocess your twig and get only required fields over sending complete node object to twig.

function theme_name_preprocess_mail_body_content(&$variables) {
  $variables['myfield_name'] = $variables['node']->field_myfield_name->value; //$variables['node'] will be render $node from your hook_mail() function.
}

And in Twig myfield_name will work


Making a REST AJAX call from Basic Page The following successfully calls a REST Services Module endpoint when contained in a module but I cannot get it to work within the script tags of a basic page.

(function ($) {

  var myapi = {
    'apiPath': '/api/award'
  };

  // REST functions.
  myapi.create = function (award) {
    $.ajax({
      type: 'POST',
      url: 'http://localhost/testsite/api/award',
      data: JSON.stringify(award),
      dataType: 'json',
      contentType: 'application/json'
    });
  };

  myapi.create({ award : 'The Award' });

}(jQuery));

I am wondering if it is even possible to embed AJAX calls in a Basic Page.

Thanks for any help,

Orville

It turned out to be a 401 error that only occurred when the user was not logged in. Changing the 'access arguments' string in the hook_services_resources array fixed the problem.


Inline labels for exposed filter forms in Views 3 How do I make labels inline for exposed forms in Views 3?

Might be worth checking out the Better Exposed Filters module, and Better Exposed Filters (the handbook). I haven't used this module.


Creating output files from Drupal 6 I need to produce PDF/HTML output from my Drupal 6 app; is there a "Drupal way" to create a template with variables and then substitute them when the output is rendered or do i have to realize it by hand?

EDITED

Data is not on a node, but need to select from a non-drupal table

If you're using Views, you could try the Views PDF module.

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.

Or perhaps the Print module if you're just creating a PDF from a node.

  This module allows you to generate the following printer-friendly
  versions of any node:

  Printer-friendly version (webpage format) (at
  www.example.com/print/nid)
  PDF version (at
  www.example.com/printpdf/nid)
  Send by email (at
  www.example.com/printmail/nid)

Edit:

If you're willing to do a little legwork, you can use the Data module to expose your non-Drupal table to Views, and then use the previously mentions Views PDF


Twig: How to show static text in the template to the Anonymous User? On a Drupal 8.9.13 website, I've removed the permission "View published content" from the Anonymous user.
By default, when someone visits the front page, Drupal will then display:

Access deniedYou are not authorized to access this page.

I want to replace this with some other text, e.g.

Please create an account to see our content.

To do this I try to create something like this in page--front.html.twig.
{% if not logged_in %}

Please create an account to see our content.

{% endif %}

However, I am stuck .

I am not able to get rid of the "Access denied" text for the anonymous user.
I can't get the the text "Please create an account to see our content." to show for the Anonymous user.  (If I remove "not" from the if-test it shows up as expected on the front page for the Authenticated user).

The site's theme is an otherwise unmodified subtheme of Bootstrap Barrio 5.1.4, but I don't think the problem is theme-dependent. Rather, the problem is that I don't understand the interplay between Twig and permissions (IMHO, there should be none).

Add a page--403.html.twig template to your theme.
See this change record: https://www.drupal.org/node/2960810
If you only want to change the default message you don't need a template. You can configure a node as access denied message in /admin/config/system/site-information.
Caveat for the non-template solution (as commented by @FreeRadical): If you restrict access to all nodes you have to find a different type of content. Could be a small module providing a custom controller which returns the static text.
BTW the themed page--403.html.twig is built in a subrequest which only job is to return a themed page with blocks. It's too late to make decisions on what to do with a 403 exception at this point. If you want to replace the core handling of a 403 exception (returning a themed subrequest) use an exception subscriber with default priority. See https://drupal.stackexchange.com/a/245211/47547


Combining two columns in Views table I keep on having different requirements and I always get stuck in Views. This time the requirement is to combine the two columns/fields of a views table but display it in different rows.

The eg: fields I currently have: (Below is the added Picture)

The output of the View in Table (Nickname Multivalue separated by comma)

While Putting the Multiple value field in different rows

In the table settings I did combine two fields like

i.e. Name and Nick Name  but that only gives result like:

(Here Nick Name is displayed after Name)

But the requirements I need to display is: (Name and Nick Name in Separate Row but at the same column). The Column needs to be sortable like normal Views Table Sort function.

Is there any settings in Views which lets me perform this? Or How can I accomplish this ?

Edit: If this is not possible and anybody could guide me to build custom query for this then I'd be very thankful.

Edit 2: SQL Query from Views Log is: (This query outputs the 2nd Image from above)

SELECT node.title AS node_title, node.nid AS nid, field_data_field_nick_names.delta AS field_data_field_nick_names_delta, field_data_field_nick_names.language AS field_data_field_nick_names_language, field_data_field_nick_names.bundle AS field_data_field_nick_names_bundle, field_data_field_nick_names.field_nick_names_value AS field_data_field_nick_names_field_nick_names_value, field_data_field_nick_names.field_nick_names_format AS field_data_field_nick_names_field_nick_names_format, node.created AS node_created, 'node' AS field_data_field_nick_names_node_entity_type, 'node' AS field_data_field_ages_node_entity_type, 'girls:page' AS view_name
FROM
{node} node
LEFT JOIN {field_data_field_nick_names} field_data_field_nick_names ON node.nid = field_data_field_nick_names.entity_id AND (field_data_field_nick_names.entity_type = 'node' AND field_data_field_nick_names.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('girlss')) ))
ORDER BY node_created DESC

You've structured your data in such a way that this can't be done with a single SQL query. You'll always be asking the database for two separate things: (1) a list of people based on their real names, and (2) a list based on their nick names.

But it doesn't have to be this way.

The easiest way to accomplish Picture 4, by far, is to always represent a person's "Name" as an additional "Nick Name".

So "Daina" should have 4 Nick Names: "Kristi", "Rita", "Sweetie", and "Daina". Then, all you need to ask the database for is a list of nick names.

This probably isn't the answer you're looking for. But I would argue that it's a more correct way to store your data. Think of the "Nick Name" field not as a list of alternate names, but rather as a list of all names that the person is known as. Based on the requirements of your situation, that's what it sounds like you're really after, anyway. It's a more complete model for your name data.


How to make all webform types collapsed by default? I just installed a Weboform Conditional module as per @PreritMohan recommendation.

Is there a way to make Textfield, textarea, select option, email, number, date, file types Collapsed by Default ?

I am running Drupal 7.19, webform 7.x-3.18 and webform_conditional 7.x-1.0-beta1

Also, what values should I put in the Options text area? (Key-value pairs MUST be specified as "safe_key|Some readable option". Use of only alphanumeric characters and underscores is recommended in keys. One option per line. Option groups may be specified with . <> can be used to insert items at the root of the menu after specifying a group.)

SImilarly, what should I put in the Values field under the Conditional Rules section? (List values, one per line, that will trigger this action. If you leave this blank, this component will always display.)

Firstly, let me recommend you use Weform 7.x-4.0-alpha6. It has conditionals built into it. Webform Conditional is a great module but I had problems with it.

Options, for select components, take the following format:

mr|Mr
ms|Miss
mrs|Mrs
doc|Doc

The in-built webforms conditionals are very simple and intuitive. Just add a condition and it will display an interface enabling you to hide/show a component when another component is/is-not a certain value.


What security should I double-check before opening my site to being multi-user? I've been using my D7 installation as a single-user blog, and operated assuming that would always be the case.  In the process, I may have been sloppy with permissions in various places, such as viewing, authoring, input formats, etc.---I'm no longer sure.

Now, however, I am going to open my site to subscribers (for a mailchimp mailing list), and possibly allow another content author.

Before I undertake these, what should I go over to make sure I'm safe, and ensure my site stays secure and is well permissioned?  Can someone help me construct a security checklist for all items I need to verify to move from single-user to multi-user?

Mittenchops, here is a suggestion

Create a role for the new users
Guarantee that this role doesn`t have permission to use PHP Filter
Check all the "administer " permissions to see if the new role is not
having access to certain areas that it should not have
Create a new user for you with this new role and test the site.
During the process of creating the new user check if you are able to choose the role (you shouldn't be)
You should also try to access pages like http://yousite.com/admin which a common user should'n have permission

I think you would be safe with this.


How do I show a submenu when hovering over a menu item? I have a Drupal 7 site. I need to create menu and sub-menu. I am using the Mega Menu module for this.

This is my menu structure.

Sub-menu not showing up when hovering over a menu item.

Mega Menu module will create a Block in Blocks section(admin/structure/block).

Enable that block in a particular region and see it in action.


How do I allow custom .php files to be accessable? I have already looked at the How do I call legacy PHP files? answers and they didn't fix my problem.

I have a custom php file in my Drupal site (Hosted on Acquia Cloud and I am working on a local version of the site using Acquia Dev Desktop) that needs to be accessable, I added these lines to my .htaccess file trying to allow access to the php file

RewriteCond %{REQUEST_URI} !^/learning/
RewriteCond %{REQUEST_URI} !^/learning/sales/[^/]*\.php$
RewriteCond %{REQUEST_URI} !^/learning/sales/index.php
RewriteCond %{REQUEST_URI} !^/learning/sales/ajax/[^/]*\.php$

But I still get this response trying to go to the index.php file.
"Forbidden
You don't have permission to access /learning/sales/ on this server."

How can I fix this?

Note: if I change the file to be index.html it works just fine (well my ajax call in it doesn't work but it atleast loads) but if it is index.php it returns with the 403 error.

This should do the trick:

 RewriteCond %{REQUEST_URI} !/learning/[^/]*\.php$

For more info please look at this thread, unable to run custom php script inside drupal.


Views module error after migrating to new server After putting my website (in drupal 7) online today, I got a few strange errors from the 'View' module. On my local machine everything is working fine, but online I just keep getting those errors! I already checked the php version, php limit, hosting space, .. etc, everything is fine. I tried deleting all my views and adding new ones aswell, but this doesn't work either; when I try to save, nothing happens. These are the errors I'm talking about:

Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).

After checking my serverlogs, I also found this:

[Thu Oct 10 13:08:17 2013] [error] [client 213.224.29.86] ] [notice] EACCELERATOR(12762): PHP crashed on opline 3689348415265695042 of form_execute_handlers() at /home/kvclinke/public_html/includes/form.inc:1465, referer: http://www.kvclinkeroever.be/admin/structure/views/view/test

Anyone knows a fix for this or what the cause of this problem is? Thanks in advance!

Are you sure all the modules are same in your local environment and live site?..There might be cases, if one of such module is missing, views will show missing handlers and will through these kinds of errors. Please try and see if some required module is missing.

This seems a database migration issue. Did your database migration go smooth?..It is strongly suggested you use Backup & Migrate module to deploy database to produciton. You can try to migrate your database through the module once. In the past this had helped me in fixing similar issues.


Why is the Pressflow Last-Modified header not like plain Drupal? The Last-Modified header is set in includes/bootstrap.inc. Plain Drupal uses

header("Last-Modified: ". gmdate("D, d M Y H:i:s") ." GMT");

which yields

Last-Modified: Sun, 27 Jan 2013 21:52:57 GMT

Pressflow uses

$default_headers = array(
    'Last-Modified' => gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']),

which yields

Last-Modified: Sun, 27 Jan 2013 21:52:57 +0000

'+0000' is incorrect according to RFC 2616, and is flagged as an invalid date by http://redbot.org/

What gives? Is this a Pressflow performance technique, or an error, or what? Do browsers care?

We're trying to nail down some load issues on our site, and want to be sure we are not getting more repeat requests than is appropriate.

Drupal 6 sets the Last-Modified header with

header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

That was changed to

$default_headers = array(
  'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),

during the development of drupal7. Pressflow has backported the patch from drupal7 in 2009. That's the reason of the difference. As for the possible impact of this, in fact it can have bad effects on caching. At least squid 3.1.10 prints a warning about the header and refuses to store the page in cache

cannot parse hdr field: 'Last-Modified: Tue, 12 Feb 2013 14:35:43 +0000'
[snip]...[/snip]
refreshIsCachable() returned non-cacheable..

Switching to the "GMT" version resolves the issue with squid.

rfc2616 (HTTP/1.1: Protocol Parameters:) specifies that "Last-Modified" header value can conform to rfc1123 (which looks OK with +0000) but all the examples use "GMT".

I think it'll be better to create a bug report in drupal issue tracker and see what the developers answer.


Is it safe to delete all revisions of a deleted node? I'm trying to import nodes from a Drupal 7 database to a brand new Drupal 8 one using the Feeds module.

I'v imported stuff and then deleted it (because I'm testing at the moment the best way to do it). I keep deleting nodes, but I've noticed that the revision tables are full of stuff.

Currently there is no node in the site, but the revision tables are occupying 50MB already.

Is it safe to empty all those tables?

I hope you are doing your tests on a test server. In that case, yes, they are safe to be emptied, even if it would be better to let Drupal and any third-party module to remove any entity data they have in their tables.

Rather than worrying to empty tables, I would find a quicker way to create a test server that is then destroyed when the test is done.


How to get field type from $form_state? How do i get field type (e.g textfield, option, etc.) from $form_state in below method.

public function validateForm(array &$form, FormStateInterface $form_state)

As said before, it is in

$form['fieldname']['#type']

You don't need the state for this because it is not a state, it's static.


What does "sanitized" mean (in api documentation)? Hi
I see the word "sanitized" quite often in Drupal API documentation.

For example, this page: theme_username($variables)

  $variables An associative array containing:

  account: The user object to format.

  name: The user's name, sanitized.

  extra: Additional text to append to the user's name, sanitized.

What does sanitized mean in the context?

'Sanitization' is the removal of malicious data from user input, such as form submissions
or maybe more simply...

The cleaning of user input to avoid code-conflicts (duplicate ids for instance), security issues (xss codes etc), or other issues that might arise from non-standardized input & human error/deviance.

Depending on the context, sanitization will take on a few different forms. Could be as simple as removing vulgarities & odd symbols from text to removing SQL injection attempts and other malicious code intrusion attempts.

You can get the idea of what Sanitization is generalized to drupal core by looking at:
http://api.drupal.org/api/drupal/includes--common.inc/group/sanitization/7

For instance, the check_plain() function will:

  Encode special characters in a
  plain-text string for display as HTML.

  Also validates strings as UTF-8 to
  prevent cross site scripting attacks
  on Internet Explorer 6.

or filter_xss() which:

  Filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.


How can I upload and read an unmanaged file? On a custom form I have a file field. Having chosen the file and clicked Submit, I'm trying to find how to access and read the uploaded file. I have no need to move or save it, I simply need to open it and use fgetcsv on it.
I've looked at the online examples I can find, but they seem to either deal with managed files or moving and saving unmanaged ones. The Examples module seems to only have a placeholder with regards to the file example.

Maybe have a look at the CSVimportForm.php in xurizaemon/csvimport sample module. I wrote the D8 version. There an unmanaged uploaded CSV file gets read line by line. This happens in a batch process to prevent a timeout when you process a CSV with let's say a million lines.
The file gets uploaded to the temp dir and will be added to the files table as a temporary file. We make a copy of the file to the public files dir and let the garbage collector delete the original upload. You need to put the file somewhere on the server to read it in PHP. You don't have access to the browser in PHP. You then can delete the file when you are done.


Easier way to get a field's value when given a node object from node_load I'm trying to get a CCK text field's value using node_load() - the code goes like $nodeObject->field_name['und']['0']['value'];

Is there a simpler built-in function like get_cck_field_value(node $nodeObject) that I can use, or do I write it myself?

You can use field_get_items() like this:

field_get_items('node', $node, $field_name);

Also see What's best practice when working with the language['und']?.


Render variables printed by {{ dump(user) }} in a template? I have the following code in node.html.twig.

{{ dump(user) }}

I get this output.

object(Drupal\Core\Session\AccountProxy)#523 (4) {
["account":protected]=>
object(Drupal\Core\Session\UserSession)#91 (16) {
["uid":protected]=>
string(1) "1"
["roles":protected]=>
array(2) {
  [0]=>
  string(13) "authenticated"
  [1]=>
  string(13) "administrator"
}
["access":protected]=>
string(10) "1513942493"
["name"]=>
string(5) "admin"
["preferred_langcode":protected]=>
string(2) "en"
["preferred_admin_langcode":protected]=>
NULL
["mail":protected]=>
string(18) "noreply@imi.org.uk"
["timezone":protected]=>
string(13) "Europe/Berlin"
["langcode"]=>
string(2) "en"
["pass"]=>
string(55) "$S$E7IRVipuFHHectBpj8GkGZGPHlFWNQKG9ydDoRpwBDcCbzklpVaj"
["status"]=>
string(1) "1"
["created"]=>
string(10) "1513920795"

I want to render value of ["created"]=>string(10) "1513920795" and ["uid":protected]=>string(1) "1". What is the syntax or code to output them from the template?

You can just get the user ID and when the account was created respectively with {{ user.id }} and {{ user.created }}. With {{ user.created | date("d F Y") }} you print the timestamp with the date format you specify.

Consider user as an object. You can access all the values the same way.

See also the Twig documentation.


Set default form values after AJAX callback OK I know this question has been asked multiple times from people in different ways but I haven't been able to pinpoint my exact use case or solution.

I have a registration form that I want to prefill the default values after the user selects an option from a select list. After they select an option, AJAX fires off to see if the user is in our CRM, and runs a series of code to look up information. I then want that found information to show in the various form fields on the page.

Couple key things to point out that I often find in other solutions that do not work for me:

The user is NOT submitting. They are still doing work on the form, the first form field sets up their experience going forward.
Setting the field info in $form_state['values'] doesn't work. Nothing is set.
Settings the field info $form_state['input'] does work, but then if a user changes any of the values in the fields, that new change isn't set.

Here is a stripped down example of what is being done.

function ces_user_registration_form_commerce_checkout_form_registration_alter(&$form, &$form_state, $form_id) {
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            $form['registration_information'][$name][$subname]['register_for']['#ajax'] = array(
                'wrapper' => 'commerce-checkout-form-registration',
                'callback' => 'ces_user_registration_form_register_for_ajax_callback',
                'method' => 'replace'
            );
            // run our code for comparing user values with CRM
            // return object with CRM data
            // below are example static value settings that I have

            // This works after AJAX is called, but the field isn't visually filled in for the user,
            $form['registration_information'][$name][$subname]['field_first_name']['und'][0]['value']['#default_value'] = "travis";

            // This works after AJAX is called, but changes to the field are not saved or recognized so we save their old value
            $form_state['input']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";

        }
    }
}

and the callback

function ces_user_registration_form_register_for_ajax_callback($form, &$form_state) {
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            if(!empty($form_state['values']['registration_information'][$name][$subname]['register_for']) && $form_state['values']['registration_information'][$name][$subname]['register_for'] == 'registration_registrant_type_me' ){

                // I tried moving the CRM code down here instead, but no changes
                // run our code for comparing user values with CRM
                // return object with CRM data
                // below are example static value settings that I have tried

                // doesn't work
                $form['registration_information'][$name][$subname]['field_first_name']['und'][0]['value']['#default_value'] = "travis";

                // doesn't work
                $form_state['values']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";

                // doesn't work
                $form_state['input']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";
            }
        }
    }
    return $form
}

I finally found a way to do this, though it appears this isn't the best way to do it - but it works.

You can not set #default_value for a field if the field is set in $form_state['input']['field_name'].

So before I try to set the field to the newly generated value, if I put this before then I can reset the default value.

unset($form_state['input']['registration_information'][$name][$subname]['field_name']);


Drupal caching prevents cookie read On one of my production sites I wrote a jQuery stylesheet switcher. It drops a cookie when a selection is made and uses php to select the corresponding stylesheet on pageload which overrides styles. All is great until I enable performance caching mode, whereby the cookie is ignored on each pageload. Obviously this isn't the desired effect and I can see why this is occuring: being that the pages are cached and no longer truly dynamic with respect to loading what's seen as a 'dynamically' changing stylesheet. You can change the stylesheet however upon returning to a page the initial style is applied. Just for reference I have coded the php into each page template (page-front.tpl.php and page.tpl.php) and the javascript is located in my scripts.js. The php is basically just a couple of if else statements.

Due to a large volume of traffic I have to enable caching on the site, however ideally would like to retain this style-switcher functionality. Is there a method of making an exception to the caching rule for this or will I have to disable the switcher? Would packing it into a module help?

Thanks in advance :)

I think you have have a hard time doing this with caching, since you want to create two versions of the same page.

I haven't tried this, but it should be possible to let your style.css not be an actual css file but a drupal callback that returns the styles based on the cookie. You would need to include the "stylesheet" as you would do styles for IE. You wouldn't be able to cache this, but if you really need to performance, you could do it in a php file and skip the drupal bootstrap.

An alternative option would be to let the js itself execute the styles, based on the cookie.

None of these options are ideal, but they should work.


How to use an external jQuery plugin with Drupal's no-conflict jQuery I'm using drupal_add_js() to load some external js:

drupal_add_js('http://jquery-accordion.googlecode.com/svn/trunk/jquery.accordion.js', 'external');

This produces 'TypeError: $ is not a function' errors because Drupal uses jQuery in no-conflict mode.

So I think the only solution is to copy the code, wrap it in this function and call it locally:

(function ($) {
  // Original JavaScript code.
})(jQuery);

I wondered whether there was a trick to still be able to directly use external js?

In Drupal 7, if you a certain that the external scripts are attempting to use "$" as an alias for jQuery, and you can't get the script author to patch their code, and you aren't loading any other JavaScript libraries, then in your template_preprocess_page, place the following drupal_add_js before the set of all drupal_add_js that reference external files. All scripts in the header region that use "$" as an alias will then refer to jQuery:

drupal_add_js('var $ = jQuery;', 'inline');

If your external javascript is added in another region, for example, the footer, then use something similar to the following instead:

drupal_add_js('var $ = jQuery;', array('type' => 'inline', 'scope' => 'footer'));


Is there a way to swap webform object between nodes? I have a weird situation.

Webform Localization module allows localization by string translation. That's good, that's what I wanted to use. Sadly, it treats all strings as if their "original" language was English. That's a limit/bug I can live with, but one of my editors created webform under node in another language. I can't simply change node's language, because it's title etc are set up OK. Or rather, I can, but I'll have enough work with Webform already that I want to avoid it.

Is there a way to connect that webform to English node, and connect empty webfrom from English node to this one? i only need to do it once, so it doesn't need to be pretty.

Simply swapping Node IDs in {webform} table does not help. It swaps confirmation messages etc (but these i would prefer to leave where they are), but does not swap actual webform components.

Simply swapping Node IDs in {webform} table does not help, but switching them in {webform_component} is.

The way I did it was to swap nids in following tables:

{webform}
{webform_component}
{webform_emails}

I didn't touch submission tables because I was planning to purge them anyway, but for test purposes I needed to swap:

{webform_submissions}
{webform_submitted_data}

That did it. Don't know if it is really enough, but I see no errors after a long time of use.


Custom content entity template preprocess doesn't contain any variables I've created a custom entity and a template for it.

path to template /modules/custom/my_module/templates.

My theme_hook()

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module' => [
      'path' => $path . '/templates',
      'template' => 'my-module',
      'variables' => [
        '#my_entity' => '',
      ],
    ],
  ];
}

My preprocess

/**
 * Prepares variables for My Module templates.
 *
 * Default template: my-module.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the user information and any
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_my_template(array &$variables) {
  // Fetch my_entity Entity Object.
  $my_entity = $variables['elements']['#my_entity'];

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

But all I get is the user object nothing else.

Did I miss something?

I needed to remove the #

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module' => [
      'path' => $path . '/templates',
      'template' => 'my-module',
      'variables' => [
        'my_entity' => '',
      ],
    ],
  ];
}

now i have my entity and can work on :)


URL & Geomap Lat/Lon fields are not showing in Target List during mapping in Feed? I am using the Feeds module. All the fields from node are showing in target list except URL field Type and Geomap Latitude and Longitude Fields. I can't figure out how to map values from CSV to them.

Any suggestions?

Finally I was able to import the data for lat/lon values from CSV file to geoField field lat/lon.

I required to use a patch in "geofield.feeds.inc" file in GeoField module which solves this issue.

You can get this patch from under mentioned URL:

GeoFiled Feed Patch File

Hope this patch will help more developers as it does for me too.


Unable to fetch paragraph's multi field values inside node twig I have a content type as "worker". I have a Paragraph "test" and I am referencing "test" paragraph inside my content type "worker". This allows multiple values to be saved.

How can I get the multiple "test" paragraph's field_name inside my node--worker.html.twig file directly?

I am able to get the single value of that field like below:

{{ node.field_test.entity.field_cdsfasdf.value }}

But, unable to fetch the multiple values for this field inside my node--worker.html.twig. I tried using for loop to fetch the multiple values like the code below:

{% for key, item in node.field_para %}
    {{ key }}
    <div class="item"> {{ item.entity.field_cdsfasdf.value }} </div>
{% endfor %}

But, I am facing the following error:

Exception: Object of type Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 465 of DRUPAL_ROOT\exp\core\lib\Drupal\Core\Template\TwigExtension.php).

Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 465 of DRUPAL_ROOT\exp\core\lib\Drupal\Core\Template\TwigExtension.php).

Off the top of my head...

For multiple value fields you either render out the paragraph field itself:

{{ content.field_paragraph_field_name }}

and let Drupal handle the multiple value rendering, or do your own loop:

{% for item in content.field_paragraph_field_name %}
  {{ item.your.array.keys.here.value }}
{% endfor %}

Try:

{% for item in content.field_paragraph_field_name %}
  {{ dump(item | keys) }}
{% endfor %}

to see what keys you need to follow to your value.

I do recommend doing this kind of theming in a paragraph--paragraph-name.html.twig file, and then just printing the field in node.html.twig.

For a paragraph template file, it would look something like:

{% for item in content.field_paragraph_field_name['#items'] %}
  <div>{{ item.value }}</div>
{% endfor %}

For the error, looks like you're cycling through the reference field, but you need to cycle through the values of a field inside the reference field. (I'm sure someone could explain this better, but entity holds the field values you want to loop)

Instead of:

{% for item in node.field_para %}
    {{ item.entity.field_cdsfasdf.value }}
{% endfor %}

try something more like:

{% for item in node.field_para.entity.field_cdsfasdf %}
    {{ item.value }}
{% endfor %}


Internal Server Error? Why is this happening? All normal to start my website, but to click on any of the links, menus, etc, I get redirected to this with the following message:

Internal Server Error
The server encountered an internal error or
misconfiguration and was unable to complete your request ...

Why is this happening?
What happens is that had risen another database project (one domain to another) I think it has a lot to do this.
There a way to fix it? Perhaps when exporting the database did wrong, what I want is that this database will serve me for several other projects. other domains.
I need your comments, help or suggestion

Q. Why is this happening?

This can happen if the .htaccess files in your Drupal directory use settings or trigger actions which are not supported by your Apache server config. If you're not running the server yourself, but are registered with a webhost, you can either ask your webhost to enable the options in question, or just comment them out in the htaccess files.

The options which are known to cause an Error 500 are:

Options -Indexes
It may also occur when setting very permissive file permissions (777) and your hoster added some security checks to avoid this. Try to lower permissions.
Another problem can occur if you're using .htaccess files using UTF-8 codification with Byte-Order Mark (BOM). Reencode your .htaccess files properly without BOM to solve this.
This error can also manifests itself as a PHP error. Try adding the code below to one of your PHP files such as local.php, then checking the error log file it generates.

ini_set('log_errors', 1);
ini_set('error_log', 'errorlog.txt');

Read:

HTTP Error 500 Internal server error

List of HTTP status codes


print all the titles of a content type by php I created a content type: "period".

Then, I created instances of this content type.

Now I would like, on a page tpl.php put the instructions, to print all the titles of the instances that I put on this content type. is it possible?

I think the "best" way (most future-proof etc.) would be to use an EntityFieldQuery:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'period');

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
  foreach ($nodes as $node) {
    // Do something with $node->title
  }
}

There are other options but they either involve deprecated methods or going directly into the node/revision tables, which can be a pain.

If you need this list in page.tpl.php make sure you don't put the code directly in the template file (it's bad practice and can cause problems with caching). The best place would be in a preprocess hook in your theme's template.php file, or a module file.


View listing element by date, exception for the first one I have a view which list a content type order by date.
I just want to add a simple condition : the first element of the list must the one with ID = X, even if it was created long time ago.
How can i do that ?

Add two sort criteria, the first one on that ID and the second on the date.
Please note that the "ID" must have the same value for all other nodes except the first to make this works.
So probably it will be necessary to use an extra field - boolean, or integer, depending how many nodes you want to fine control.
If you don't have a lot of content to order in that view you otherwise may consider Entityqueue or DraggableViews.


Commerce: How to skip checkout cart and redirect to PayPal How i have to set a rule to go direct to Paypal site? I use PayPal Express and i am not able to solve this. The only one rule i can set is to go to cart/checkout. But i´d like to go one step forward without to see the order and to have to click on the PayPal button. Thanks for helping

It's not possible without custom code. The customer either initiates the Express Checkout payment by clicking the button form on the cart page, or the Commerce PayPal module does it on a form submission when the customer chooses PayPal as a payment option on the checkout form. That requires sending an API request to initiate the payment and get the tokens that must be passed with the customer to PayPal to submit payment. With custom code you could simulate the customer choosing PayPal as a payment option on the checkout form and initiate the redirect, but there's nothing that exists to do that that I've seen.


Updating view content (in block) based on field data from page it's displayed on I'm struggling to achieve something in Views that would be quite simple in PHP itself - hoping for some pointers.

I have created a view, displayed as a block, which appears at the bottom of each page with a content type of 'article'.
This block shows the latest 4 articles added to the site based on publish date.
It shows max 4 items (provided at least 4 articles exist and are published).

This works - however I've been struggling to extend this functionality to meet two new client requests:

The view should exclude the currently viewed article if loaded on the page of one of the 4 latest articles added; [SOLVED THANKS TO ANSWER BELOW]
The client wishes to 'override' the items shown in this view in some cases. Here I've added a field to the content type named 'field_related_articles' which is a entity reference field. The admin can now select up to 4 articles from the database which should show in this view. However it is optional, and the default behaviour is to show the 4 latest articles still. If 1 article is specified the 3 latest articles should then appear. If 2 then those 2 plus the latest 2 articles make up the view.

I've been advised to have two views then use an 'attached' display to stitch them together, then remove the extra results (if applicable) in code in a template file. But I'm struggling settling this up.

---------- EDIT : to add some clarity to second point ----------

The view is intended to always show 4 article teasers.
In it's default state this should be the latest 4 articles added to the site. This is now working.

The complexity comes in that on each 'article' content page it should also be possible to specify up to 4 articles (using an entity reference field) to show in this view instead.
I've added the field to the content type 'field_related_articles'.

So when the view is included on an article page it needs to check if any values are specified in 'field_related_articles' - if so they should be the results in the view. If less than 4 nodes have been specified, the view should then show the latest X articles to make up to 4 in total.

To avoid the article you're on :

Click on the "advanced" tab.
Click on add under "contextual filters".
Choose Content:nid.
Under "when the filter variable is not available, choose "provide default value".
From the drop down menu select "content id from url".
Scroll all the way down to the bottom of the window and click on the "More" link.
Click "Exclude"

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

The second problem can be done by adding 2 Sort Criterias.   The first will be on 'field_related_articles'  - and then by date.  I find displaying the SQL output in admin really helps to see what is happening backend.


views pagination pager add | to the li How do I add "|" to views pager when you are displaying numbers. See the example
below

previous   1 | 2 | 3   next

There are couple of options:
1. Using the view's tempate file
2. The easiest and my favorite in that case - using css :after selector to add the '|' to the li's

Hope that helps.


views filter's identifier I'm using drupal 7.

I want to use $view->set_exposed_input(array('filter_identifier' => 'filter_value'));

How to know the filter identifier?

When you create the view exposed filter you can give it a name. You use the default name it gives you, or whatever you choose it to be. See attached image.


Setting values for custom display fields in Views thanks in advance for your help with this.

Firstly, the Basic Page type of my drupal build has a Title (as per usual) and a Subtitle custom field. The Title and Subtitle are then displayed in a header when viewing the node.

I then have a View which is producing a page displaying a list of Employees from the Employee content type. The Employee content type does not have the subtitle field.
When the view is displayed it uses the standard page.tpl.php which will display the subtitle field if it exists.

Since the View is displaying a page, it is not bound to any specific Basic Page node so there is no subtitle to pull in to the View.

Is it possible to add the subtitle variable into this View so I can fill it with a custom piece of text and have it display on the View page.

Thanks again.

EDIT: Updated text to clear up confusion

There are a couple of ways to go about this, if I understand your goals correctly:
1) If your view is set up to use Fields, you can customize the Subtitle field to include additional content along with what is coming from the Node's field.
To do this, Edit the view, Select the field, Expand "Rewrite results", and then you can use a Replacement Pattern token along with your additional text:

The subtitle is [field_subtitle], yes it is!

2) If your view is set up to display as a Node, you would create a Node template override, named like node-contenttype_with_subtitle.tpl.php, and you can format your layout specifically for your need here:

echo 'The subtitle is '.$node->content['subtitle']['#value'].', yes it is!';

Note that the 2nd approach would affect the appearance of that content type everywhere, not just in the view. So, if you want this special treatment of the subtitle only in your view, then the 1st approach may be preferable.

A third option would be a field-level override template, where you would create a file named something like views-view-field--subtitle--page.tpl.php and control your output there. Here is an in-depth look at that approach: https://drupal.org/node/352970

(Please let me know if I misunderstood your question, and I'll be glad to take another stab at answering.)


Format inline drupal form elements I got this:

As you see I already aligned label and input field inline with CSS, because they are both inside same container, but the button is outside. I was wondering if I could somehow move the button inside the container? So then I could format all elements into one line.

That's typical in Drupal. In this very moment, This is the CSS styling I use in scenario similar to yours:

.some-div-class label,  .some-div-class input[type="text"] {
  display:inline;
  width:auto;
  font-size:0.8em;
}

This will work fine on mobile devices as well.

Please do note your own CSS may need a bit more work.


Don't apply sort criteria by default I added sort criteria by price to my catalog view, and in the sort criteria I have only to option to use by default one of them - Ascending or Descending. But I don't want to use any sorting by price by default in catalog, I would like to apply it (one of the option Ascending or Descending) only after user chose an option and pressed button 'Apply' on the sort form. Is there any opportunity to do that?

What would be removed from the directory by default sorting, you need to remove from Sort criteria. And leave the possibility of the sort only Filter criteria


getting node items by taxonomy I can get a list of node items by content type, using the following query:

$query = db_select('node', 'n');
    $query->condition('n.status', NODE_PUBLISHED);
    $query->condition('n.type', 'slider');
    $nids = $query
        ->fields('n', array('nid'))
        ->orderBy('changed', 'DESC')
        ->range(0, 4)
        ->addTag('node_access')
        ->execute()
        ->fetchCol();
    $nodes = node_load_multiple($nids);

I want to filter this output further with taxonomy. How can I do this?

You need to use the EntityFieldQuery instead of the SelectQuery that db_select uses. You should do something like this:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->fieldCondition('fieldname', 'tid', $tid)
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

The results will be an array of objects containing the nid and vid.

Read more about the fieldCondition


Import multiple node reference from CSV using feeds I am trying to import multiple node references for one node using feeds. How should my CSV look like for that??

Will this work :

"title","description","status","code","details",("contact1","contact2", ..., "contactN" );

given that I have another content type named contact with titles contact1, contact2, ..., to contactN

I would recommend you the Node Import module for Drupal 6. It's very powerful and works great with references.


Fetch value from JSON I have a field in drupal "field_xyz". it stores json values. JSON looks like this:

{"Id_-_SiteWasteProductAction":"34638393224", "Postcode": "CSF 12CF"}

I want to fetch postcode value from this json using mysql query

i used

$query = $connection->query("SELECT @@sql_mode"); //for group by (php 7.0)
$query = $connection->query("set @@sql_mode=''"); //for group by (php 7.0)
$query = $connection->select('node_revision', 'n');
$query->fields('n', ['vid', 'nid']);
$query->fields('shad', ['field_xyz_value']);
$query->join('node__field_xyz', 'shad', 'n.vid = shad.revision_id');

i fetch postcode value from url-

   $filter_postcode_value = \Drupal::request()->query->get('filter_postcode_value');//postcode

and i use this condition

   if(!empty($filter_postcode_value)){
          $query->condition('an.field_xyz_value->"$.Postcode"', '%' . db_like($filter_postcode_value) . '%' ,'LIKE');
     }

output is coming out as-

    Column not found: 1054 Unknown column 'shad.field_sheet_all_data_value.Postcode

Please help!

If I recall, you need to use the json_ specific query functions to query within a tuple.

There is an example query on the JSONB module page demonstrating this. This module is not required, but does have an example of how to write a db_query:

  If you wanted to query for JSON records that were in the 2005-2006
  timeframe for high school graduates, you could do the following:

$results = db_query("SELECT point
      FROM (SELECT jsonb_array_elements(field_jsondata_value) point FROM {node__field_jsondata}) points
      WHERE point->'DataType' = :type
        AND point->'TimeFrame' = :frame
        AND point->'Education' = :education",
      array(':type' => '"Percent"', ':frame' => '"2005-2006"', ':education' => '"High school graduate"'));

  You would receive the fourth object only. The function
  jsonb_array_elements expands data at runtime to query data in this
  manner.

I don't think Drupal core supports the usage of these functions outright, maybe it does, but I accomplished this in both Drupal 7 and 8 with db_query.


Implement hook_node_access based on field value I need to implement hook_node_access based on field value, which I can get only via $form variable. At the moment I cannot do this because I only have variables ($node, $op, $account) available in hook_node_access. Could you please help me to find the way how to implement something like:

if ($form['...']['...'] == 'TRUE') {return NODE_ACCESS_ALLOW;}

You don't need the node form to access its fields to check for conditional access. Use the field data in your node object.

if($node->my_field_name[LANGUAGE_NONE][0]['value'] == 'TESTED_VALUE') {
  return NODE_ACCESS_ALLOW;
}