How to hide paragraph items based on permission I am trying to limit access to each item in a paragraph field. My goal is to only let the creator of each item change the specific item. I installed and enabled the Field Permission module and this is almost exactly what I am looking for. I have configure custom permissions for each field in the paragraph. The only problem right now is that each paragraph item is still visible even though none of the fields are showned:

Is there a way to hide or disable a paragraph item for all users except the owner?

Field permissions is not what you want, that only does permissions for fields, not for the entire entity like you want.

There's a hook called hook_ENTITY_TYPE_access, you can use it as hook_paragraphs_item_access(), that would let you alter permissions (Look at the paragraph_bundle_permissions submodule for an example).

As others have said paragraph items don't actually have the owner on them - neither does field collection. They aren't really mean't to be separated like this. You can add the property yourself if you want to.

I recommend changing the Paragraphs to not be paragraphs and be something like Nodes instead. If they have permissions and are owned by someone, paragraphs aren't really the right thing. You can use Inline Entity Form if you want to embed a form for it. Since they are nodes you should be able to have more control on permissions.


How to set advanced views setting in code? Specifically disabling SQL rewriting with webform_select_options So, I'm having trouble with a little custom module that places a list of flagged items in a webform with: webform_select_options_info, views, and anonymous flag.

The issue I'm having is that the select list generated by my custom module doesn't appear for anonymous users. I suspect this has to with the issue of showing views to anonymous users by disabling SQL rewriting. I suspect this  because I'm using a view generated in code via the custom module and that the advanced settings aren't set and the function isn't being shown to anonymous users.

So, how do I set advanced options like disabling sql rewriting in code?

here's my custom function minimally adapted from drupal steve's tutorial:

<?php
function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
       $options[$item->product_id] = '<a' . $attributes . '>' . render($item->field_field_image[0]['rendered']) . ' ' . $item->field_title . ' (' . $item->commerce_product_title . ')' . '</a>';
     }
   }
   else {
     $options[0] = t("Nothing");
   }
   return $options;
 }
 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
  foreach($view->result as $item){
      $options[$item->product_id]= $item->field_field_image[0]['rendered'];
      }
return $options;
 }

I have a block view which shows the flags of the current user, I can confirm that each anonymous users flags work and generate unique flag lists on a per user-agent basis.

So, how do I diable sql rewriting for this view in code? or is there another reason this is happening?

Thanks

So this approach let's you edit the view through the Views UI. I thought the view was created on-the-fly by the module, but the module loaded the view into the db and exposed it to the views UI. Though this doesn't address the question directly.


Associating a user with a particular form submit/click In my web site i have created a custom content type Challenge which contains a list of tasks that the user has to do. I have created the custom content type from the CMS itself through admin/structure/content type. I have created a custom form, , and when the user clicks submit i have made a query which insures that the node id of that challenge and the user id is associated in a Challenge table (the code is below). It works fine. Now i need to create a view which shows the challenges accepted by the user, i.e., when the user logs in and clicks on a tab(i am using quicktab) then a view appears which shows the challenges undertaken by the user. Here my code for the query:

function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_my_form($form_state) {

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Accept Challenge',
    '#submit' => array('my_module_action'),
    );

  return $form;
}

function my_module_action($form, &$form_state) {

 if ($node = menu_get_object()) {
  // Get the nid
   $nid = $node->nid;
    }
 global $user;
 if ( $user->uid ) {
 $query = db_insert('challenges')
    ->fields(array(
    'cid' =>$node->nid,
    'uid' => $user->uid
    ))
    ->execute();
}

Well, thats it then. Now how do i create a view to show a user their accepted challenge.

Thanks

For node you should load challenges data in your custom module, using next: hook_node_load and/or showing next: hook_node_view. See examples module for it: nodeapi_example.
For Views you should define connection with your custom table and node, there nice example for it.
For Views also you can use Data module.


theme hook and rendering I am trying to get my head around the drupal 7 render() function but there is something I can't get straight.

The data source that I want to render looks like this:

Array
(
    [id] => 3315539862007
    [name] => Some Name
    [picture] => some-facebook-image.jpg
    [link] => http://www.facebook.com/some-page

I pass it to a $block['content'] like this (I also tried changing '#children' to '#element', but with no success):

$block['content'] = array(
  '#theme' => 'opengraph_company',
  '#children' => $data
);

but inside my custom theming function the data that is passed looks really weird

function theme_opengraph_company($variables) {
  $element = $variables['element'];

  return 'hello';
}

if I debug the $variables inside the theming function I get something like this

Array
(
    [element] => Array
        (
            [#theme] => opengraph_company
            [#children] => Array
                (
                    [id] => 3315539862007
                    [name] => Some Name

which to me looks really weird. The MYMODULE_theme function looks like this

function opengraph_theme() {
  return array(
      'opengraph_company' => array(
      'render element' => 'element',
    ),
  );
}

I would expect access to the data based to the theming function to easier, something like

function theme_opengraph_company($variables) {
  $element = $variables['element'];

  return $element['name'];
}

Am I passing the parameters wrong to the theming function?

When you use render element, the element which you apply the theme to is passed into the theme function in the $vars array...the index in the array will be whatever you've set render element to in your theme function, which in this case is element; hence the element you've asked the theme API to pass in is available in $vars['element'], which is a carbon copy of the original render element.

To get the effect you're looking for you would normally use variables instead of render element:

function opengraph_theme() {
  return array(
    'opengraph_company' => array(
      'variables' => array(
        'id' => 0,
        'name' => '',
        'picture' => '',
        'link' => ''
      ),
    ),
  );
}

Then you'd build your render element like this:

$block['content'] = array(
  '#theme' => 'opengraph_company',
  '#id' => 123,
  '#name' => 'Name',
  '#picture' => 'Picture',
  '#link' => 'Link'
);

Or, if you want to use your current $data array, you can pass it directly to the theme function:

$block['content'] = array(
  '#markup' => theme('opengraph_company', $data)
);

Bear in mind with that second method any modules whose hooks might be run after yours will no longer get the chance to alter the theme output, as you're converting it down to a string.

Using either of those methods though, when your theme function is run you will have access to the variables like this:

function theme_opengraph_company(&$vars) {
  $id = $vars['id'];
  $name = $vars['name'];
  // etc...
}


How to hide purchased commerce product with Panels visibility rules? Goal:

I want to hide the panel pane containing a view (containing a product display) when the user has purchased the product.

Set-up:

I have a commerce product entity (not display) which is flagged using Rules on behalf of the user who purchases the product. I've created a view to verify the rule and it works, linking the Prod ID to the User ID correctly.

I then have a view:

View type: 'Content Pane'
Filtered on: 'Content type: Product Display'
With a field 'Content: Product Reference' with 'Add to Cart line item type : Commerce node checkout'

The view is displayed in a panel pane and appears as a standard 'add to cart' button. This is also ok and users are able to purchase the product, (which then provides a link to some premium content).

The problem:

In panels, I have a visibility rule on the pane containing the 'add to cart' button. The visibility rule looks for the flag attached to the product and shows it only if the flag is NOT there.

However, the product is always visible.

I've also tried the same procedure, but flagging the 'product display' instead, but with the same result.

I think it's probably that I'm not using the right context or relationship, either in views, panels or both. I've tried a few, but am now at the stumbling in the dark stage. I'm pretty stumped as I thought panels visibility rules would only offer options that were available/in scope. Any help/guidance much appreciated!

EDIT after comment #1 below:

I've added some screen grabs of the panels settings and output.

1 Panels content screen. Top-right panel shows two ways I tried to put the "add to cart" button in. The views method works, the direct panels method does not.

2 Relationships in Panels. I thought this would make the correct entities available to visibility rules, etc. but apparently not.

3 Panels output. The main content (overriden node type) is at the bottom. The "add to cart" button is on the right, and should only appear before purchase, but is always there. The contact details (left) should, and does, only appear after purchase.

4 Very brief diagram of entity relationships.

Further to the orginal description, the following might be useful:

Content access module with per-node access control is used to control access to "Contact details" content.
There is an option in visibility rules that can base visibility on access of current user to a particular bit of content, which I have tried, and seemed to target the correct content, but didn't work (so obviously wasn't).
This suggests to me that it's a matter of getting the correct vars in scope using panel contexts.

I solved this by using the flag module and rules.

In summary: When the customer buys access to the hidden content, a rule is triggered that flags the content author on behalf of the customer. Panels can set visibility of a pane based on whether this flag exists between author and current user viewing the page.


How to: Multilanguage site, but single language backend? I have almost completed my first Drupal 7 multilanguage test site. As long as I'm not logged in, I can browse through all pages and switch languages. When logged in, my first issue was that the backend language would switch, when switching the frontend language. I.e., the admin menus are translated, but should stay English (or whatever the editors preferred language is).

Then I found that in Configuration > Languages > Detection and Selection, I can select how the language is chosen. So: User first, then the backend stays in the user language. Fine.
But then, the frontend stays in that language, too! So when logged in, I cannot browse all pages anymore, only the English ones ...

There must be a way to select front and backend languages independently.
How?

I know this post is getting old and the OP probably has this sorted by now but I came here looking for the same answer and thought I'd post a follow up for anyone looking for details. I've made this as easy and basic as possible in case you're new to Drupal.

My version is 7.21.

Ok, here's what I just did to get the back end in English and the site content in Spanish. I'm assuming you have all the translating modules installed and set up, etc.

Go to your admin profile and set your languages, for me its this:

Administration Language = Default administration language, currently English

Language Settings
Language = English

Then go get the Administration Language module that Patrick linked to. (its currently the Dev version but works fine for me, look in the red area for the DL). Install and enable.

Then go to Administration > Configuration > Regional and language > Languages:

Scroll to the bottom and you'll have an option of "Use administration language in the administration menu".
Set that to Enabled

Save it and now everything should show in what ever language while the back end stays in the language you set for your admin profile.

I hope this helps!


How to group view by field and display row results below? We have a content type Basic Page that is supposed to be grouped by a taxonomy term field Page Type that has the following values below in a view.

How can we setup the view so that the view will display the Page Type in one group and the results in another group? Is this even possible without a hook_preprocess_hook() or custom twig template?

View Setup:

Display: Block (`block_1')
Format: Unformatted
Format Setting: Grouping field nr. 1: Page Type, User rendered output to group rows = true
Show: fields
Show Settings: Inline fields --> Page Type
Fields: Page Type, Title, field_description
Filter Criteria: Published = true, Content type = Basic Page
Sort Criteria: Page Type (asc)

Page Type Values:

Blog
Press Release
Video
Document

Current results:

 Blog

 Page Title1

 Continually negotiate bleeding-edge materials through installed.

 Blog

 Page Title2

 Collaboratively disseminate global customer service for..

 Blog

 Page Title3

 Continually evolve enterprise-wide total linkage through..

 Press Release

 Page Title4

 Energistically productize competitive sources after standards..

 Video

 Page Title5

Professionally implement principle-centered portals without efficient..

 Video

 Page Title6

 Uniquely fabricate high-quality testing procedures with..

Desired results:

 Blog

 Press Release

 Video

 Page Title1

 Continually negotiate bleeding-edge materials through installed.

 Page Title2

 Collaboratively disseminate global customer service for..

 Page Title3

 Continually evolve enterprise-wide total linkage through..

 Page Title4

 Energistically productize competitive sources after standards..

 Page Title5

Professionally implement principle-centered portals without efficient..

 Page Title6

 Uniquely fabricate high-quality testing procedures with..

What you're trying to achieve isn't grouping by a field, it is displaying the same node list twice, showing different node information in the two instances.

You can achieve it by creating two Displays in your Views where one is showing only Page Type field, and the other is showing Title and field_description while sharing the same Filters.

If your original View is a Page Display, it makes sense to use Attachment Display for the other. You adjust the Attachment to appear Before or After the other Display results, depending on which you created first. You could also make one or both of them Block Displays and place them one below the other in the Content region of your theme.

You could also render one View Display into another Display Header, with the help of an additional module Views Field View.

Your HTML won't be exactly the same as in your question, but it will be close enough, and you can override the templates in your theme for those particular views displays to achieve exactly the output you want. Attachment views usually show with their own class and view-rows outside the .views-content of the Display they're attached to, but if you really need to you can override them and set your own classes.

Drawing from Drupal 7 solution

I posted an answer to a similar question for Drupal 7: Filter a view by clicking on a link on another view. It doesn't completely mirror to D8 but with Better Exposed filters you can make an exposed filter behave similar to tabs, if you use Autosubmit optin and hide the Submit button.

Taxonomy summary through a Contextual filter

One additional way of listing only the terms used on nodes in Views results is by creating a Summary through a Contextual filter.

On your Content Views Page add a Relationship to the Page Type field, you may require it since none of your results will have it empty.
Then add a Contextual filter Term ID from Taxonomy term Category and set it to use the Relationship from above, and these options:
When the filter value is NOT in the URL
Display a summary
Descending
Number of records
Base path (if this is not the first Page Display in your Views)
Add Attachment View Display to this Page, keep all the options the same as in Page, only override the Contextual filter and remove it from Attachment.

This way you get the original list of nodes, after the terms relevant to the results.

The terms are already sorted by the number of results tagged with it. To make the nodes in the Attachment sort the same way use Aggregation on it.


Drupal 8 Metatag and Media Entity modules to set meta image tags On a Drupal 8 content type, I have a field with an entity reference field to a Media Entity field.  I would like to use the Metatag module to set the image that is on this Media entity in the og:image meta tag.

Featured Image - [node:field_im] - Returns the entity name
Featured Image type with delta 0 - [node:field_im:0] - Returns the entity name
Media - [node:field_im:0:entity] - Returns the entity name
Media ID - [node:field_im:0:target_id] - Returns the entity ID

In Drupal 7, the following token was available:

[node:field-fimg:0:file:url]

But I don't see anything like it in D8.  Could someone point me in the right direction?

If I understand your question correctly you'll need to do the following:

Check on your modules page that the "Metatag: Open Graph" submodule
is enabled.
Go to metatag config page (Configuration > Search and
metadata > Metatag).
Add a new "default metatag" and select your
content type in the "Type" selectbox.
Fill in the rest of the fields similar like following picture (just don't forget to use your own field names:

Here are some things you need to know about my tokens:

field_teaser_img: is the fieldname of my media entityreference on my
content type.
field_me_img: is the fieldname of my image field
on my media entity type.
facebook: is the imagestyle name I
created for these metatags
height, mimetype & width: are
property fields of the media entity type yet I didn't create those
fields but it does seem to work.

I hope this helps.


How to display JSON returned (from external REST API) in a Block? [my code attempt inside] I am trying to display the data from a REST API (URL: 'http://api.kivaws.org/v1/loans/38239/lenders.json') to display in a block. Below is my code. It is not working, any hint on why will be sincerely appreciated.

/**
 * Implements hook_block_info().
 */
function restapiexample_block_info() {
  // This example comes from node.module.
  $blocks['kiva'] = array(
  'info' => t('Kiva Test Block'),
  'cache' => DRUPAL_NO_CACHE
);

return $blocks;
}

/**
 * Implements hook_block_view().
 */
function restapiexample_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
  case 'kiva':
    $block['subject'] = t('Kiva Example');
    $block['content'] = array(
    '#theme'  =>  'page',
    '#markup' =>  kiva_list_loans(),
  break;
}
return $block;

}

function kiva_list_loans() {
  $request = drupal_http_request('http://api.kivaws.org/v1/loans/38239/lenders.json');
  return drupal_json_decode($request->data);
}

You can try the URL, good JSON data is being returned. Error I receive is several instances of the following text in the $messages area: "Warning: Cannot use a scalar value as an array in drupal_render() (line 5859 of /home/drupalpro/websites/example7.dev/includes/common.inc)"

UPDATE 1:
With help from comments/answer below, I made some progress. from my function "kiva_list_loans()", I am able to see the response in my $page array. I changed the '#theme' in my "$block['content']" in hook_block_view to 'page' - but still I only see the word "Array". How to get this to render?

$block['content'] should be an array, like in the example for hook_block_view:

$block['content'] = array(
    '#theme' => 'feed_icon',
    '#url' => 'rss.xml',
    '#title' => t('Syndicate'),
  );

For more examples, see Examples for Developers project, block_example module.

If you are putting array there, it must be a renderable array. If it's not, then either:

Implode it into string. With nested arrays, it can get a bit complicated.
Put it as an element in $block['content'] array, and set $block['content']['#theme'] element to something that can theme it. More complicated, but also more versatile and cleaner solution.


validating the Uploaded Image name in Image field of Content type I need to validate the Image Name uploaded via Image field in Content type.How can i validate the Image name.

Any Help is Appreciated

Thanks,

function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "YOUR_FORM_ID"){
        $form['#validate'][] = 'myvalidation_function';
    }
}

function myvalidation_function($form, &$form_state) {
    $file_fid = $form['field_your_content_type_image_field']['LANGUAGE_NONE'][0]['#value'][fid];
    $file = file_load($file_fid);
    $file_name = explode( '.', $file->filename);
    if($file_name[0] != $form['type']['#value']){
        drupal_set_message('your validation error');
    }
}

Hope this works. I have tested on my system :)


Theme are different between different user I grant permission of menu ['node/add'] to a certain role of users (which was only accessible by admin previously). Turns out that, these two types of users have different views of this menu (As you can see from the following two screen shots).

How can I theme the page for these two users in the same way? Or How can I change the theme for the non admin user?

-----------update-----------

If I don't want to use admin theme, where should I add my own theme?

Go to /admin/people/permissions
Enable the "View the administration theme" permission for the appropriate role.
Save the form.

Users with that role will now see the admin theme (as set at /admin/appearance) wherever applicable.


how to make a content type that ties to the user and user can only add one? Drupal 8

So I want users to add a actor profile or crew profile or both.
I am thinking both would be content types.  The user should only be able to add one of each and it ties to the user.

Anyone know how I would do this?

Instead of creating content types, I think you're better off using the profile module.

For Drupal 8 use the Profile Module

  The Profile module provides configurable user profiles.

  Multiple profile types may be created via the UI (e.g. a general
  profile + a customer profile), whereas the module provides separated
  permissions for those. Optionally, profile forms are shown during user
  account registration. Fields may be configured to be private - thus
  visible only to the profile owner and administrators. Profile types
  are displayed on the user view page, and can be configured through
  “Manage Display” on account settings.

Formerly known as Profile2 in drupal 7. Here is a video tutorial. Perhaps it's similar in Drupal 8?


How can I have a nested slideshow with paragraphs and views? Initial situation

I have a node type with a paragraph field. Each paragraph of the paragraph field is rendered among themselves.

What I want to achieve

The paragraph field inside the node should render all the paragraphs as a slick slideshow.
The node containing the paragraph field and all the paragraphs should also be part of a (second) slick slideshow (via a view filtered by the content type).

In short, the user will have finally a slideshow (with the single paragraphs) nested in a second slideshow (with the nodes).

Problems

The module slick views allows it to display the nodes of the node type as a slider.
That's fine to realize the node slider.

The module slick paragraph only allows to create slideshows as a paragraph type, but not rendering the paragraphs of a node themselves as part of a slideshow.
They are still rendered among themselves inside the "node slider".

So here i struggle a bit - any idea?

Thanks in advance,
Phil

You could achieve this with more control by overriding node/field/paragraph templates in your theme to get the required markup, then creates the Slick sliders via custom JS code.

If you never worked with templates, you should start here https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates


Libraries shared by more than one installation? I am working with several Drupal 8 installs On a shared hosting environment.
I've got them up and running and they are looking great thanks to the MoreThanThemes themes I'm using. I'm at the stage of adding modules that require libraries.

It would be great if I could simply maintain libraries in a folder like  /Home/[accountname]/Libraries outside of the Drupal root folder. In this way several installs could rely on a common set of libraries, and these wouldn't have to be maintained per site (as would be the case if they were stored in /Home/[accountname]/[sitefolder]/Libraries for example).

An equivalent would be storing private files in a folder like /Home/[accountname]/Files.

Would this be possible?

I know that many are very strong advocates for using Composer, but I am interested in answers that do not require using that tool.

Sometimes different module versions use different library versions. For example an upgrade for a module comes with supporting the next library version.

AFAICT if you're after simplifying your maintenance, and the sites you're hosting are similar in their features, it makes sense to also set the modules to also be shared.

That is, the entire Drupal installation. This is called a multisite installation and I've been satisfied with that type of a solution when having a cluster of smallish Drupal sites that use the same modules (and libraries) but different themes.

Multisite Drupal

This way you only maintain one Drupal folder on your host (or at least one Drupal for more than one site, you can still have more Drupal folders for more sites if you like, independent of the multisite one).

Each site has its own database.

Advantages are that when you need to update the modules or core you do it only once on that folder, but don't forget to perfom database updates on all the sites that use that Drupal folder, so they will all have to be in Maintenance mode at the same time.

The downside is that when you need to update, you have to do them all.

Each site usually has a special theme, so themes are placed under the specific sites' folder, not under themes/ where the shared themes are.

You can still have individual sites use a special module that you don't want on other sites in the "cluster", just put it under the site's folder and not in the general one.

Libraries will be shared across all sites, but if the modules used across the sites are also of the same version, you win because you've simplified your maintenance.

To clarify, you don't need to enable all the same modules for all sites within a multisite "cluster". The enabled modules don't even need to overlap! One site can use modules a, b, and c, and the other site can use modules d, e, and f. It's only about keeping the versions the same across the sites to simplify the maintenance.


Generate one-time-use custom links for emails and interact with them to accomplish tasks Is there a module that would auto-generate custom unique  one-time-use URLs that timeout after a set time, and can be used to accomplish tasks and progress workflows in Drupal 7?

Use Case 1

User must click link in email to verify their address is valid.

Use Case 2

As part of a workflow process users must confirm they wish to complete an action by clicking on the appropriate link in an email message and depending on the link chosen the node would progress to a different state in the workflow

You can copy function "user_pass_reset_url" and form "user_pass_reset" and customize it for your needs. With first you create custom link and with the second you can get "one-time-link" logic.


Import configuration in CI/CD script does not work I have a Drupal 8.9.13.
I wanted to install a new module, for example the google_tag. But in my case I do that in my CI/CD process. So to do that I did the following actions:

edit the composer.json in a way to contain the new module
the composer.lock is updated for the same reason (by enabling the module using drush)
updated the core.extension.yml in a way to contain a line
generated the *.settings.yml by exporting the configuration.

During the deployment, first of all the code source is get from the git repo and then a 'composer install' is called.
After that a "./vendor/bin/drush config-import -y" is called to import the configuration of the new module (event the module wasn't configured, there is a default config).
And here I have the following error:
Unable to install the google_tag module since it does not exist.
Does someone have any idea what might be the problem?
I saw also that in Drupal's database in the table config for the value of core.extension I have a value which usually describes the activated modules and the one I am trying to activate is not there.

After running composer install, you need to add a drush cr before you run drush cim. All together:
composer install
./vendor/bin/drush cr
./vendor/bin/drush config-import -y


Drupal.behavior unexpectedly triggered by Ajax callback I work on a sandbox project which provides a Responsive Tabs to Accordion Panel style. Everything works fine except that once the page loaded, any Ajax callback (i.e add to cart or colorbox) seems to trigger the js function of my module.

The way js function is set in plugins/styles/reponsive_tabs.inc

function theme_responsive_tabstoaccordion_panels_style_render_region($vars) {
  //...
  $element = array(
    //...
    '#attached' => array(
      'js' => array(
        drupal_get_path('module', 'responsive_tabstoaccordion_panels') . '/plugins/styles/responsive_tabstoaccordion_panels.js' => array('type' => 'file'),
      ),
      //...
    ),
  );
  //set the wrapper id to give to responsive_tabstoaccordion_panels.js
  drupal_add_js(array('responsive_tabstoaccordion_panels' => array('tabstoaccordion_panel' => '#'.$tab_id)), array('type' => 'setting'));

Drupal behavior in responsive_tabstoaccordion_panels.js

(function ($) {
  $.fn.extend({
    easyResponsiveTabs: function (options) {
      //the main js function which is triggered
      //...
    });

    Drupal.behaviors.responsive_tabstoaccordion_panels = {
      attach: function (context, settings) {
        $(settings.responsive_tabstoaccordion_panels.tabstoaccordion_panel).easyResponsiveTabs({
          //Set options
          type: 'default',
          //...
        });
      }
    };
})(jQuery);

I guess it has to see with the way I attach my function to Drupal.behaviors ?

All Drupal behaviors are called when an AJAX call is performed. This allows modules to attach its 'behaviors' to new loaded content.

There are much cases where the behavior should be attached just one time. For this cases the once function is recommended:

   Drupal.behaviors.responsive_tabstoaccordion_panels = {
      attach: function (context, settings) {

    $(settings.responsive_tabstoaccordion_panels.tabstoaccordion_panel).once('rttap', function () {
      $(this).easyResponsiveTabs({
        //Set options
        type: 'default',
        //...
      });
    }
  );

This way the anonymous function that calls easyResponsiveTabs is called only one time for each element. If new elements are loaded the behavior is applied.


Default Redirect after login based on destination I have custom routing and a user controller in a module that redirects authenticated users to a private area on a site.

It works fine when users are coming from the login page - redirects them to a dashboard at a custom user page - but I would like users to continue to the page they are requesting if they come to the site from a link.

It is common for users to share links to internal content and they are then having to log in and get to the link from their dashboard which is causing some annoyance.

I have reasonably simple routing for the user page and a controller in my module that redirects users to their userPage. Is their a way to have this not redirect depending on the link they are requesting?

You mite need to add 'destination' query parameter for shared link.

For example: https://www.drupal.org/user/login?destination=search/site/destinations


Hashing function for session I need to verify the users session of Drupal on a Node.js server. The session ID has been hashed and it is stored in the Drupal 8 database. How can I hash the browsers session ID to compare it with the one stored in the database?

I see that no one has put up an answer for quite a while, so I will put it up here. This has been correctly answered by RaisinBrainCrunch above.

Drupal 8 hashes its session ID before it puts it in the database. The hash function used is hashBase64($sid) under Drupal\Component\Utility\Crypt.

Therefore, I am guessing you will have to write the same function in Node. This is the full function:

public static function hashBase64($data) {
  $hash = base64_encode(hash('sha256', $data, TRUE));
  // Modify the hash so it's safe to use in URLs.
  return str_replace(['+', '/', '='], ['-', '_', ''], $hash);
}


How can I create correct breadcrumbs when using Views arguments? I have a custom CCK content type for blog posts and I’m using Views to display the posts in an archived list. I use two arguments—Node: Created year and Node: Created month—to generate the monthly and yearly archive pages, which allows me to build URLs like http://example.com/blog/2011 and http://example.com/blog/2011/08. This is pretty standard stuff and really easy to do with Views.

While the actual archive list pages are working just fine, the breadcrumbs that views generates are not. With the URL http://example.com/blog/2011/08, instead of creating this kind of trail (which seems correct):

Titles = Home > Blog  > 2011       > August
URLs   = /      /blog   /blog/2011   /blog/2011/08

… Views generates this incorrect breadcrumb trail:

Titles = Home > Blog  > 2011  > August
URLs   = /      /blog   /blog   /blog/2011

The URL generated for the year argument points to /blog rather than /blog/[yyyy], and the generated URL for the month argument only points to the year, not the month.

Going down one level (to http://example.com/blog/2011) creates a similar problem:

Titles = Home > Blog  > 2011
URLs   = /      /blog   /blog

In both cases, none of the arguments' URLs are output correctly, while their titles are.

My settings for each of the arguments in Views are pretty standard: Month settings and Year settings. The path for the page display is just "blog".

What is causing this strange breadcrumb behavior and how can I fix it?

Thanks!

Check out the Custom Breadcrumbs module which has support for Views. Here is a quote about it (from the module's project page):

Custom Breadcrumbs 1:
Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
Custom Breadcrumbs 2:
Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.
In addition to breadcrumb visibility, this version provides an option permitting PHP code snippets to be used in forming the breadcrumb titles and paths. Multiple languages are also supported.


Views filter depending on the number of node references I have a content type A that has a node reference to a content type B.

How can I create a view that show A nodes, and either filter by or sort by the number of references to the content type B? (Let's suppose the node reference to B field in A is named field_reference_b)

I'm interested in both filtering and sorting by that criteria.

Edit:

I could do this using the module Views PHP Filter, but I'm trying to avoid using it as much as possible.

I don't have enough points to leave a simple comment. I haven't tested this yet. However, I think that you need to select in the 'Relationships' section the node reference. This will join the two tables and give the view access to all the fields in both. Then add an argument and when configuring the argument use the relationship you choose. I'm not sure which argument is best to choose but I think that node title is a good one for the summary and then select the Summery, ascending or desc. This actually creates a list of all the possible titles of A with the number of node B attached to each with a number next to is. When the title of node A is clicked in the block or page view it opens the page with node A's title as the big page title and all of fields of B as long as you selected the relationship under each fields setting.

I wish I had time right now to test it. It's only a theory but I'm sure it's the general direction of solving this.


What data type is "Date" in Postgres? I don't have access to a client database, but need to know how a "Date" CCK field stores its information.
I'm using MySQL, and this easily found in the structure of the table. Anyone use Postgres and can check?

Is it a timestamp or a date?

Why do you need access to the database for this information?

Have you looked here?
http://drupalcode.org/project/date.git/blob/b7502f3a86628e5c4995c01f20ac64d5cee5888b:/date.install

/**
 * @file
 * Install, update and uninstall functions for the Date module.
 */

/**
 * Implements hook_field_schema().
 */
function date_field_schema($field) {
  $db_columns = array();
  switch ($field['type']) {
    case 'datestamp':
      $db_columns['value'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    case 'datetime':
      $db_columns['value'] = array(
        'type' => 'datetime',
        'mysql_type' => 'datetime',
        'pgsql_type' => 'timestamp without time zone',
        'sqlite_type' => 'varchar',
        'sqlsrv_type' => 'smalldatetime',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    default:
      $db_columns['value'] = array(
        'type' => 'varchar',
        'length' => 20,
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
  }
  // ... more stuff

The answer to your question is that depending on the Drupal "Date" value you're storing it -- for Postgres it is 1 of the following values:

(drupal field of) datestamp = int DBMS field
(drupal field of)datetime = timestamp without time zone DBMS field
(other drupal field of) date = varchar DBMS field analyzed by Date module on save and usage

EDIT

My answer is for Drupal 7. The same module API can be referenced for Drupal version 6 if needed. You didnt specify what version of Drupal you are using and "CCK" can be apart of both.


How do I let users with a certain role add nodes but use the front end theme (not the admin theme) I have a role that allows users to create nodes themselves. What is the standard practice way to let them add nodes but not see the administration theme (I am using adminimal), and rather use a different theme on the node/add page.

Role Theme Switcher seems to be what you need:

Useful Drupal module to assign separate themes for different roles (including anonymous) in your system.
Often you want to separate Drupal administrative interface from frontend. You can do this assigning appropriate theme for you as user. What to do if you want to show different theme for non-authorized user?


I added a new module and it breaks Javascript from my theme. How can I fix? I have recently installed a new module, "Views Nivo Slider", and it is breaking the javascript on my web site that I have added via my theme.  I'm at a loss as to what I should do to fix the issue.

By Break, I mean that the code from my theme no longer executes. It also throws no errors. It just acts like the code no longer exists

In my custom theme, I add javascript by adding this line in the theme:

scripts[] = js/js.js

I had added the code by using the onready event:

$(document).ready(function() {

Now I read online that perhaps this was not the best method to add code and that I should bind with drupal events. I tried to change my code to use this method to see if it would make a difference:

Drupal.behaviors.addMenu = function (context) {

My code always works IF this module is not being used.  However, whenever I turn this module on, it breaks all of my javascript. I've spent about 2 hours looking around and searching for articles and I have had no luck so far.

The articles I was looking at to learn more about behaviors were:

http://www.phase2technology.com/node/663/

http://mydrupalblog.lhmdesign.com/drupal-theming-jquery-basics-inc-drupal-behaviors

The javascript code being used by this module is:

// $Id: views_nivo_slider.js,v 1.1.2.5.2.2 2010/06/18 15:04:17 pedrofaria Exp $
Drupal.behaviors.views_nivo_sliderBehavior = function (context) {
  $('.views-nivo-slider').each(function() {
    var id = $(this).attr('id');
    var vns = $(this);
    var cfg = Drupal.settings.views_nivo_slider[id];

    // Fix sizes
    vns.data('hmax', 0).data('wmax', 0);
    $('img', vns).each(function () {
      hmax =  (vns.data('hmax') > $(this).height()) ? vns.data('hmax') : $(this).height();
      wmax =  (vns.data('wmax') > $(this).width()) ? vns.data('hmax') : $(this).width();

      vns.width(wmax).height(hmax).data('hmax', hmax).data('wmax', wmax);
    });

    vns.nivoSlider(cfg);
  });
};

The only error on the page is from jqeuery reading the minified javascript. I don't think this is causing the issue b/c the rotator (what uses this) still works.

Can someone please provide me with some guidance?

The screenshot in your question shows an error regarding the jQuery live() function, this was added in jQuery 1.3 and Drupal 6 comes with 1.2.6.

If you want to use a newer version of jQUery (needed by some modules), you can user the jQuery update module or see this tutorial: Using Newer Versions of jQuery with Drupal 6.


How to get text from radio option value How do I get the option text from the submitted value of the radio field in Drupal 8 webform submission? I have written a rule action condition on webform submission where I am storing data in a middle table.

Based on screen I am looking for Option Text from webform field.
Current version: Drupal 8.6.15 & webform 8.x-5.2

Assuming Drupal 8 (since you didn't give a version), there are two parts to this.

Imagine this element in the form:

$form['some_field'] = [
  '#type' => 'radios',
  '#options' => [
    'option1' => $this->t('Option 1'),
    'option2' => $this->t('Option 2'),
  ],
];

The submitted value can be retrieved from $form_state in your submit handler:

$radio_value = $form_state->getValue('some_field');

You can then use the value to get the text of the radio, from the $form element:

$radio_text = $form['some_field']['#options'][$radio_value];


Hide view when node's taxonomy value is empty I have two taxonomy vocabularies: departments and categories.

I created a block view to display related pages (other pages in the same department and category) using contextual filter. All works well when a node has both department and category selected. But when I leave the category empty on a node, the view still shows other pages from the same department.

Is there any way to make the view not show up on the nodes with no category?

Here is what my contextual filter looks like:

With the help of my co-worker, we were able to make it work by adding two contextual filters: one for category and one for department taxonomy:

All other check boxes unchecked.


How can I translate those translatable texts defined in t() in contribute/custom modules? I wrote some custom modules, follow the Drupal standards, put all interface texts in t() function, make them translatable. Module enabled.

I enabled Locale module, added new Language under admin/config/regional/language:

However, under admin/config/regional/translate/translate
I cannot see those text I defined t('xxx') in my custom modules. (cache cleared)

How can I make Drupal aware of them? Thanks.

You can use the Translation template extractor module to extract all the t() calls you've done.

Another option is to get the t()processed, by viewing the pages where they are defined and then translate them in the interface you mention. (New strings will only be added once they have appeared once).


book module navigation horizontal submenu I am using the book module navigation block to display links to book pages. I was wondering if it was possible to alter it so rather than the children links appearing below the parent, they would appear to the side. This is because I want a horizontal navigation

Thanks

EDIT:
For anyone wondering, the way to get book links to appear on the same level, you just need to make sure the child pages are pointing to the same parent, then just display that level of links to get a nav bar, styled this gives you a horizontal nav bar.

You can override node.tpl.php and customize where to render $content['book_navigation'].

Have also look at book-navigation.tpl.php and template_preprocess_book_navigation().


How do I build a dynamic query in Drupal 7 equivalent to this SQL query? I want to make this SQL query into a dynamic drupal query:

SELECT name, u.uid, COUNT( n.nid ) AS total_written
FROM users u
LEFT JOIN node n ON n.uid = u.uid
GROUP BY u.uid
ORDER BY total_written DESC

I do not know where i should append the COUNT. This is what I tried:

$query = db_select('users', 'u');
$query->leftJoin('node', 'n', 'n.uid = u.uid');
$query
  ->fields('u', array('uid', 'name',))
  ->fields('u', array('COUNT(n.nid)', 'total_written')) # Wrong
  ->groupBy('u.uid')
  ->orderBy('total_written', 'DESC');

How do I append the COUNT to the dynamic query?

$query = db_select('users', 'u');
$query->leftJoin('node', 'n', 'n.uid = u.uid');
$query
  ->fields('u', array('uid', 'name',))
  ->groupBy('u.uid')
  ->orderBy('total_written', 'DESC');

// Add the COUNT expression
$query->addExpression('COUNT(n.id)', 'total_written');
$results = $query->execute();


I am creating my own shortcut bar but can't manage the user access I am creating a shortcut bar something like below, but unfortuntly it show up despite my wish that I could hide it for anonymous and administrator users/role. I want to display it for editor roles only. How do I achieve this? Thanks

function shortcat_permission() {
  return array(
    'administer shortcat' => array(
      'title' => t('Administer shortcats'),
      'restrict access' => TRUE,
    ),
  );
}

function shortcat_page_alter(&$page) {
       $page['page_top']['#pre_render'][] = 'shortcat_toolbar_pre_render';
   }

function shortcat_renderables() {

  $shortcut_set = array();
  $shortcut_set['my_list'][] = array("#markup" =>"
");
  $shortcut_set['my_list'][] = array("#markup" =>"
".t('Add Content')."
");
  $shortcut_set['my_list'][] = array("#markup" =>"
".t('Find Content')."
");
  $shortcut_set['my_list'][] = array("#markup" =>"
");
  return $shortcut_set;
}

function shortcat_toolbar_pre_render() {
  $links = shortcat_renderables();

  $links['#attached'] = array('css' => array(drupal_get_path('module', 'shortcat') . '/shortcat.css'));
  $links['#prefix'] = '
';
  $links['#suffix'] = '
';

  return $links;
}

I know you can make use of:

global $user;
  if ($user->uid)  {
display it here...
{

but this won't make the user access right accesible in People > Permissions

Since you're defining a permission you can make use of the user_access() function to check that the user is allowed to access the shortcut menu. You can actually then use the #access key on your render array to denote whether or not it should be shown:

function shortcat_toolbar_pre_render() {
  $links = shortcat_renderables();

  $links['#attached'] = array('css' => array(drupal_get_path('module', 'shortcat') . '/shortcat.css'));
  $links['#prefix'] = '
';
  $links['#suffix'] = '
';

  $links['#access'] = user_access('administer shortcat');

  return $links;
}

That code will deny access for anyone who doesn't have the administer shortcat permission. All you need to do is make sure the permission is ticked for the editor role in the admin permissions page.

It's worth bearing in mind that user_access() wil always return TRUE if you are logged in as the super user (ID:1). If you need this to be different then the easiest way would be to check that the user physically has the editor role assigned to their account:

global $user;
if (!in_array('edit', $user->roles)) {
  $links['#access'] = FALSE;
}

Hope that helps.


Views managing fields with style in Drupal7 i have created a view

having three fields   as image , title and  body

i want to show image on left and  on right hand side title and below title body .

i don't want to customize view template file. is there is any option so i will get desired results .

Thanks in advance

Exculde From display first and second field  and in third field  use rewrite output  something like this

[field_movie_image]

[title] [body]

it is working for me. itself in a view


Rebuild Form Element with new property after Ajax I want to rebuild a Form Item with new property after Ajax triggered on page, I try following codes
<?php

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
        $form['langcode']['widget'][0]['value']['#ajax'] = array(
            'callback' => 'MYMODULE_language_change',
             'wrapper' =>'edit-field-trends-wrapper',
            'event' => 'change',

        );

        $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>'test');
        $form['field_trends']['#prefix'] = '
';
        $form['field_trends']['#suffix'] = '
';
    }

}

/**
 * Ajax callback.
 */

function MYMODULE_language_change(array $form, FormStateInterface $form_state) {
        $form_state->setRebuild(TRUE);
            $form['field_trends']['widget'][0]['value']['#title'] = "New Title After Ajax";

        $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>'onajax');
        return $form['field_trends'];
}

Update : in order to find the problem I change the code to simplest manner,

The Problem is  when ajax triggered  autocomplete replaced but changing on #autocomplete_route_parameters to applied !!!
Update 2 Strange things is I try to change field title on ajax callback handler it applied and after ajax new title is New Title After Ajax but  autocomplete parameters not changed. I confused

Finally I achieve it with following, Change autocomplete parameters prperty in form alter on rebuild event INSTEAD of changing property worked for me,

    use Drupal\Core\Form\FormStateInterface;
    use Symfony\Component\HttpFoundation\Request;

    function zeytondev_form_alter(&$form, FormStateInterface $form_state, $form_id) {

        if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
            $form['langcode']['widget'][0]['value']['#ajax'] = array(
                'callback' => 'zeytondev_language_change',
                'wrapper' =>'mtrend-wrapper',
                'event' => 'change',

            );

            //kint( $form['field_trends']);
            $form['field_trends']['#prefix'] = '
';
            $form['field_trends']['#suffix'] = '
';
            $langcode = $form_state->getValue('langcode');
            if($langcode) {
                $langcode = $form_state->getValue('langcode');
                $langcode = $langcode[0]['value'];
            }
            else {
                $langcode = 'en';
            }
            //var_dump($langcode);
            $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>$langcode);
        }

    }

    function zeytondev_language_change(array &$form, FormStateInterface $form_state) {
        $form_state->setRebuild(TRUE);
        return ($form['field_trends']);
    }


How to flag a product variation on a commerce website? My products have multiple variations as enitities (size, color etc). I want to display a flag link on a product display page. When a visitor uses it, I want them to be able to flag the selected variation, not the node. Is it possible? Here is a related discussion on drupal.org: http://drupal.org/node/1050872

I wrote a way to use Flag for product variations here: http://drupal.org/node/1911568

Here is my solution:

Add a flag "add to wishlist" for commerce_product entity type.
Install computed field module.
Add a computed field to the product (not the display content type)
In Display Code (PHP) area of the field:

$entity_id = array_shift(entity_extract_ids($entity_type,$entity));
$display_output = flag_create_link('add_to_wishlist', $entity_id);

(Computed Code (PHP) part can be left empty, we dont want to store anything in database)
5. Go to Manage Display of the product and set the newly created computed field's format: "unsanitized" and make sure it is visible.
6. Go to Manage Display of the product display content type (not the product) and use your product's wishlist computed field there.

Now you can create a view to display a user's products in his wishlist. It is straitforward. You just add any field, add a relation: your flag and tweak the view as you like. You can also use view's menu system to create tabs on the user profile: http://drupal.org/node/326580


Views and Taxonomy Filtering I have a question regarding filtering in Views.

My setup:

• I have a content-type, for example: Cars
• I have a few different taxonomy term fields attached to that node, something like: Car brand, Car color, Car type, with the following terms:

  Vocabulary: Car brand

  Term:Car Brand A
   Term: Car Brand B
    Term:Car Brand C

Vocabulary: Car color

  Term: Blue
   Term: Red
    Term: Black

Vocabulary: Car type

  Term: Two seater
   Term: SUV
    Term: Sedan

I have a View that displays all the available cars, and I used Better Exposed Filters to display a block that displays those taxonomy fields as filters. Now: this is were I get stuck.

Say for example, that 'Car Brand A' only only sells Blue and Black Sedans. What I would like is that the color option 'red' and car types 'SUV' and 'Two seater' are hidden as selectable option, and re-added if a user selects other brands. How do I do that?

I really hope you can help me with this! :)

If I understand your question correctly, you need the functionality of the Views Selective Filter module.

Although I haven't used this module myself, I've written a similar Views handler in a custom module. This filter handler removes all options from select lists that don't provide any results (due to other selected values). If the Views Selective Filter doesn't provide the desired functionality, I can create a sandbox project of my code.


Tracking an authenticated user's first visit to a Panels page and forward them to another page on subsequent visits I'm looking to expose authenticated user stat information to CTools / Panels.  Basically, I need to have a Panel variant that says: If the user has never visited the page, display this variant, if they have, display this variant.

You want an access plugin. See What are Ctools plugin (content type, access, etc), and how does one create them? for an intro to how to build one.


Problem dynamically populating a select field based on the selection of another select field I have seen quite a few questions on here about the "Illegal choice has been detected" error when trying to load a select field with AJAX in Drupal 7. I have not yet been able to find an answer to solve my issue though. I have 3 select boxes Year, Make, and Model. When I select a year the makes populate fine. When I select a Make, I get the Illegal choice detected error and the models do not populate. But if I choose another make everything works fine. Can anyone help me figure out why the first attempt doesn't work? Here is the code that I have

function formblock($form, &$form_state) {
  $form = array();

  $form['year'] = array(
    '#type' => 'select',
    '#options' => _load_years(),
    '#ajax' => array(
      'callback' => 'formblock_make_loader',
      'wrapper' => 'make_div',
    ),
  );

  $makes = array('empty' => 'Select Make',);
  if (isset($form_state['values']['year'])) {
    $makes = drupal_map_assoc(_load_make($form_state['values']['year']));
  }

  $form['make'] = array(
    '#type' => 'select',
    '#options' => $makes,
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'formblock_model_loader',
      'wrapper' => 'model_div',
    ),
  );

  $models = array("empty" => "No Model");
  if (isset($form_state['values']['make'])) {
    $models = drupal_map_assoc(_load_model($form_state['values']['year'], form_state['values']['make']));
  }

  $form['model'] = array(
    '#type' => 'select',
    '#options' => t($models),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (isset($form_state['values']['make'])) {
    $form['model']['#options'] = _load_model($form_state['values']['year'], $form_state['values']['make']);
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function formblock_make_loader($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['make'];
}

function formblock_model_loader($form, $form_state) {
  return $form['model'];
}

function formblock_submit($form, &$formstate){

}

function _load_years(){
  $thisyear = date('Y');
  $years = array();

  foreach(range(1990, $thisyear) as $year) {
    $years[$year] = $year;
  }
  return $years;  // array
}

function _load_make($year) {
  $makes = array();

  // Make API call and get an array of makes

  return $makes;  // array
}

function _load_model($year, $make) {
  $models = array();

  // Make API call and get an array of models

  return $models;  //array
}

You're wrapping your model select options array in t()

i.e: '#options' => t($models) vs '#options' => $models

Try this instead, it might work:

  $form['model'] = array(
    '#type' => 'select',
    '#options' => $models,
    '#prefix' => '
',
    '#suffix' => '
',
  );


Combined Fields filters and missing custom search api fields Drupal 8

I am using Search API and Views to search several fields from several content and media types. For example, I have a custom "description" field for Media->files so users can add a searchable summary field to pdfs they upload to a website.

While I can get it set up to search all the fields using exposed filters and an "OR" filter grouping, this leads to an exposed filter for each field... which is not ideal. I would rather a single input box that allows several search terms to be passed to each of the filters.

I have tried to use combined field filter however it is missing a number of the fields passed from the Search API index. For example, below is a simple example searching only pdfs with a custom description field.

Media type and Name are available but not Description or even filename. Is there a way to make these available in the combined filter?

Any other method to achieve the desired result of a single search box for multiple filters would also useful. Just to re-iterate. The filters work, I just want them in a single search field.

It's kind of a beginner error here but in case it's useful to anyone the solution is you want to use the Search API Search filter rather than the combined filter.

It handles the search of the provided index all as a single input field by design.


How do I edit a block's default title? "Powered by Drupal" is a footer block I need to change to my name for my website.

How do I edit its default title?

In drupal6, you can go into the block admin screen for that block and change the title there.  If you are meaning the title/hover title for the drupal image itself, you can create a function in your theme's template.php file along the lines of:

function YOURTHEME_system_powered_by($image_path) {
  $image = theme('image', $image_path, t('Powered by Drupal, an open source content management system'), t('Powered by Drupal, an open source content management system'));
  return l($image, 'http://drupal.org', array('html' => TRUE, 'absolute' => TRUE, 'external' => TRUE));
}

and just change the t() functions in there to say whatever you want.

ADDITION:

A quick grep thru d7 suggests changing this...

/**
 * Returns HTML for the Powered by Drupal text.
 *
 * @ingroup themeable
 */
function theme_system_powered_by() {
  return '' . t('Powered by Drupal', array('@poweredby' => 'http://drupal.org')) . '';
}

in a similar way as described above would accomplish what you want, but yes, you would need to edit some code to do it in your theme.

If that doesn't work, or you aren't confident enough to do that, you could just remove/disable the powered by drupal block itself and create another one with your own created by link in it.


override views-view-fields.tpl.php in custom module Hi i want to Override views-view-fields.tpl.php in our custom module. kindly help me by example.

You need to define a theme hook for the field-template in your module and place a template in custom_module/theme/your-custom-template.tpl:

/**
* Implementation of hook_theme().
*/
function custom_module_theme($existing) {
  return array(
    'views_view_field__view_name__field_name' => array(
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
    'template' => 'your-custom-template',
    'original hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'custom_module') . '/theme',
   ),
  );
}

To narrow down which field-templates you want to replace you can name your return key to:

views_view_field__view_name: Override all field templates of the view named "view_name"
views_view_field__view_name__field_name: Override only this specific field

This example is taken from grayside.org


Comment count unpublished I want to display the number of unpublished comments in a template. I don't want to execute unnecessary queries on the database. Is there an already available function for this that I can use in page.tpl.php?

function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
    ':status' => COMMENT_NOT_PUBLISHED,
  ))->fetchField();
  return t('Unapproved comments (@count)', array('@count' => $count));
}

I don't think there's anything already in page.tpl.php but it really depends on what is happening in the preprocessor(s) of your theme. I don't know what theme you're using.

If you're worried about calling a function like comment_count_unpublished() multiple times in one page load why not statically cache the result with drupal_static()?

Have you actually profiled that query and shown that it will cause problems on your site? Drupal generally runs hundreds of queries each page load so I don't think counting the unpublished comments in that table would have a noticeable impact on most sites.


hook_schema is not creating database table The following function is contained in process_login.install as part of a custom module called process_login. The module works if I manually created the database table, but naturally I would like the table created automatically on install.

The function itself does not generate a schema error on installing the module. But neither does it create the database table process_login_register in the Drupal 7 MySQL database.

There are no other errors I can see, or problems reported by Site Report.

I have removed it completely and reinstalled numerous times. I have searched the web extensively, and consulted two books I have on Drupal development. I can't see anything wrong with this function (listed below).

NOTE: I have also tried defining 'id' as serial but get the same result (i.e. no table created).

I have run out of ideas. Does anybody know why this function isn't working?

function process_login_schema(){
  $schema['process_login_register'] = array(
        'description' => 'Register a specific computer with the system.',
        'fields' => array(
                'id' => array(
                    'description' => 'Primary identifier.',
                    'type' => 'int',
                    'unsigned' => TRUE,
                    'size' => 'normal',
                    'not null' => TRUE,
                    'default' => 0,
                ),
                'ip' => array(
                        'description' => "The user's IP address at registration.",
                        'type' => 'varchar',
                        'length' => 32,
                        'not null' => TRUE,
                        'default' => '',
                ),
                'user_agent' => array(
                        'description' => "The user's browser user agent string at registration.",
                        'type' => 'varchar',
                        'length' => 255,
                        'not null' => TRUE,
                        'default' => '',
                ),
        ),
        'primary key' => array('id'),
  );
  return $schema;
}

Use drush dre -y [module] which disables, uninstalls and then re-enables the module. The -y flag makes it even faster, avoiding you have to press y and enter three times.


Solr Search Custom search form template I have solr search setup on my drupal8 website.  I have a view setup that has two pages in it. I have the search box via an exposed form placed as a block in my header region.

What I want to do is to create a new search form that has different text in the submit button and submits the form to a different page than the search form in the header.

Is there a way through the view or display modes to expose a new template so that I can customize the button and action on the form?

More Details

I was able to create a new solr search form by duplicated the "page" in the solr search view.  I modified the name and machine name and modified the input-submit.html.twig template to remove the ID from the submit button.  I did that because I have a search form in the header region of my website and then adding another form to the page in a Layout Builder with the same id was causing a conflict and chrome was yelling about it. ID's have to be unique after all.

Layout Builder won't let me save the layout though. I had to revert back to the default and then rebuild my page layout in layout builder.  I have to add all of the blocks and then I get to save the layout once.  I can the form into the page now, but I won't be able to make any changes to the page in the future.

Well, I suppose i can remove the search form, save the layout, go back in and make my changes and then add the search form back to the layout builder.  That is not ideal.

Any trick to fix that issue?

Possible Solution, but not ideal

I added the view page block into the Block Layout and restricted to only the page I needed it on.  That should work for now, but I would prefer to be able to see all of the content blocks in the Layout Builder.

You can use view mode of all content types where you want to show in searching. Best things are

Create views modes for all content type
assign or enable view mode for that content type
create views and use render as the entity with that view mode.
Theme based on need or UI/UX
Custom form or create a template for search form so you can change the submit template with different UI.


Is there a way to create a sort option for search results that works together with facets? I'm using Drupal Commerce along with Search API and Facet API to create a search for my product dispays. Is there a way to create a facet that sorts products by price? I've tried using the exposed sort in views, but it doesn't work in unison with the facets. Any ideas? I'd prefer that the sort looks similar to the exposed sort criteria in views.

I'm using views to override a search provided by Search API. The view type is "Product display". I've added a "Search: Fulltext search" contextual filter to the view to override the search form. I'm also using Facet API to provide a faceted search to users made available using blocks on the search page. I've tried using the "SORT CRITERIA", which are available in views, to provide an option of sorting the search results by price and relevance. The problem I'm having with this is that the facets, which are provided by Facet API, don't work together with the sort criteria provided by the view.

Additional Information

If I select a sort criteria first, then apply a facet, the search results are narrowed down based on the applied facet and everything seems to work well.

If I apply the facet first, then select a sort criteria, the applied facet is reset and the search results that are shown revert back to how many there were before the facet was applied. For example, let's say that I sell 4 cars on my website, 2 red cars and 2 black cars. I search for "cars" and 4 items are shown in the results. I then apply a facet based on taxonomy terms for the color "red". There are only 2 red cars, so the search results are now only displaying 2 results. If I sort the results by "Price" the facet for the color "red" is removed. This causes the search results to revert back to the 4 items that were originally displayed for the search term "cars".

I want to be able to sort the results after a facet is applied and have the applied facet not reset itself.

Indexing the Price:

Go to Administration -> Configuration -> Search and metadata
Edit your Search Index and click on Fields tab.
Select Product->Price from the Add related fields drop down in bottom of form and click on Add fields button. It will add fields for Product -> price in index.
Enable check-box for the field Product » Price » Amount (decimal) and save the form.
Now, you will find Product » Price » Amount (decimal) (Min) and Product » Price » Amount (decimal) (Max) field in your list. Enable these fields and save the form.
Reindex your search.

Adding sorting in views:
Go to Administration -> Structure -> Views
Edit your view.
Add field Indexed Node: Product » Price » Amount (decimal) (Max) or Indexed Node: Product » Price » Amount (decimal) (Min) to sort view and save the view.


EditableViews without a table? I'm looking for the features of the editable views module without having to use a table (In Drupal 7).

I have a view that I use as an input form. I'm using the "editable views" module to expose those fields as editable. However, I would like to customize this beyond what a Table will provide. There's some CSS trickery I can do (e.g. moving cells around with CSS), but that seems very hackish. Are there any modules/methods out there to do what I'm trying to do?

(example)

I have...

 | Title | Description | Author | Feedback (Editable) | Rating (Editable)

I want...

 Title, Author
 Description
 Feedback (Editable) | Rating (Editable)

Thanks

You can use EditableFields instead, which will let you use Unformatted list instead of table.

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

Here is a video tutorial on how to use it.

Then you can use CSS to get the view to look how you want it.

.field-title { float: left; }
.field-feedback { float: left; }

Also, you will probably need to resize the edit button.

Else, if you do not want to use CSS then the following may possibly work:

1) Hide all your fields from display

2) In FIELDS, add a Global: Custom field

3) Use the replacement patterns on your custom field.

Ex:

[title], [author]

[field_description]

[field_feedback] | [field_rating]


Adding print friendly link on specific nodes (I have already posted this question on StackOverflow, but I then discovered this forum, which seems to be a more appropriate place for this question.)

I have also read all the similar questions on StackOverflow, without luck.

In my Drupal 7 site I use the Printer, email and PDF versions module. I want to show the printer link on some specific pages of a specific content type. So I have enabled the link in that content type, which include a boolean field (field_printable) where the admin should be able to choose to include the link or not. In my template.php file I try to figure out how to work this out. This is what I have got so far in my template.php file:

function mytheme_preprocess_node(&$variables) {
    if($variables['type'] == "mycontenttype"){
        // boolean field that returns 1 if checked
        if($node->field_printable['und'][0]['value'] == 1){
                 what to put here ...?
        }
    }
}

I should probably use print_insert_link(); to insert the link, but I cannot figure out how. Can anyone point me in the right direction? I have spent hours googling on similar questions, but I am stuck right now.

Any help would be very appreciated, thanks in advance.

Well If I understood your question properly, you want to show the print link only on specific nodes right? This is straightforward, by default if you enable print links for a content type, then the print links will be displayed on all the nodes of the content type.

For those nodes which you don't want the print links to be displayed, you can disable the print links option in the node-edit page itself.


using hook_form_alter on a same form from 2 different modules How will a predefined form behave if we have two different forms that implement hook_form_alter?

I would explain my question by an example, because currently I got a crash on it:

I have a predefined user_login form in user.module

I created two new blocks called author_login and creator_login. Each of these module using the form user_login and adding new validating properties for each form by using function hook_form_alter().

The new validating properties are:

For author_login block: if user doesn't have author role, user will not be logged into system, error: "you don't have author role"

For creator_login block: if user doesn't have creator role, user will not be logged into system, error: "you don't have creator role"

But the problem is: the new login block I created works fine if only one of two modules is enable. If I enable both modules, no user cannot log in to the system through these module.

For example, I have both modules enabled, I go to author_login block and log an user named Mark, who has role Author, to the system, an error message displayed: "the user Mark doesn't have creator role". And similar to creator_login block.

Why does this happen? I thought that the hook_form_alter will alter different properties to each new module we created, make each new form works separately. But from this case I encountered, it seem like the user_login form validate all new properties that I added by using hook_form_alter. And how can I avoid this as I want these two form to work separately?

Notes: I am really sorry to post this question here because I posted the question on drupal.stackexchange but there was only one answer that couldn't help me much in finding the solution. I really need help on this question. Many thanks!

All implementations of the hook_form_alter() will alter the user_login forms you embed in your blocks. As you observed, your author_login form alter will not be restricted to only altering the form in your author_login block.

If you want your form alters to only alter the form in the context of their respective blocks, you have to find a way to observe the block context from them. There is no easy way to properly implement this, you will either have to add additional non-standard arguments to your form builder (the arguments passed to drupal_get_form() after the form ID), or uses some sort of global states.

A cleaner solution is to use hook_forms to define new author_login and creator_login forms that simply re-use the existing user_login form as callback but have a different form id:

/**
 * Implements hook_forms().
 */
function author_login_forms($form_id, $args) {
  $forms = array();
  $forms['author_login'] = array(
    'callback' => 'user_login',
  );
  return $forms;
}

You can then simply implement a form alter specific to your author login form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function author_login_form_author_login_alter(&$form, &$form_state) {
  $form['#validate'][] = 'author_login_validate';
}

And finally embed this form wherever you need it with

drupal_get_form('author_login');

Repeat for the creator login form.


Bulk editing of Fields on multiple entities What is the best way to do the following?

Open up a page that does a form callback from hook_menu
Based on a URL arg, load all entities (probably with EFQ) with that argument
Present certain fields on the entities to edit, with one Submit button at the bottom
On Submit, each of these are processed and saved within their respective Entities

As a bonus, it would be great if the form output each set of fields in a tabular format, like editing a grid (without jQuery plugins needed).

The first two I can do, but I am not seeing seperation of entity data in the form submit data (knowing which data goes with which entity_id).

What I am trying to do is provide a quick way of editing game results line by line (Team A (score_home property) vs Team B (score_away property)).

The Multiple forms module might point you in the right direction.

Here is a quote from its project page:

  This is an API module which lets you put several forms into one <form>.


Cloning a Drupal website without content Drupal 8 ships with the new Configuration Management System. This system checks the sites UUID and only allows imports of configuration if the uuid is the same.

This means, your steps to create a new environment is:

dump db from existing environment
import db to new environment
import config in new environment

This however does not work in cases where one is not allowed to access Production data. How would one in this case then handle the creation of new environments?

Same goes for a new developer entering the project, he has to import a DB from prob/stg. But what if this db multiple GB's big. You are now running a multi GB website on your local machine.

In symfony we "solve" this with fixtures to create dummy data. this can then be used to create new environments from scratch on the fly. In Drupal 7 this was also possible with features.

So my question is, how does one do this in Drupal 8 if cloning the existing environment is forbidden? How do you sync configuration between these environments?

Have a look at Config Installer. It allows you to the initial install already based on your exported configuration and so replaces step 2 and 3.

One problem is that you might notice that there is more "content" or non-configuration stuff than you'd think (unfortunately). Menu Links created in the UI are content, aliases are content, translations are stored in a separate table too, Taxonomies/Terms as well (Fine for something like a free-tagging field, but they are often used to define fixed structures as well, like sections on a news site).


How Do i fix this in D8? there have been more than 5 failed login attempts for this account even flood table is not created in DB? I check my DB there is no flood table even found. But getting error There have been more than 5 failed login attempts for this account. It is temporarily blocked

What else could stop me to login?

Thanks

Drupal 8 still exited table flood. You can see here. Table flood created when use login failed. You can use the way in drupal 7. Simple

drush php-eval 'db_query("DELETE FROM `flood`");'

Full document.


Clean URLs are broken in MAMP I'm using MAMP on os x 10.6.

Until this morning clean URLs where working on about 20 different D6 and D7 installations without problems.

All of a sudden clean URLs are broken on all installations. I'm not aware of having changed something in the MAMP or apache configuration.

Things I already checked:

phpinfo() tells me that mod_rewrite is loaded.
I did not change any .htaccess files

Do you have any idea on where to look at?

Update: I think the .htaccess files are not loaded at all. I can write gibberish into the file and there are no error messages at all.

The .htaccess files are ignored if the AllowOverride directive is set to None.


Setting php E_NOTICE within my .module file I want to set E_NOTICE only within the .module files which I create. How can I do it?

I want to catch mis-spelled variable names which are difficult to catch.

I've never tried this, but if you don't mind modifying core on your dev server you can change drupal_error_handler(): examine the results of debug_backtrace(), decide if the error came via your module and act appropriately.


Changing url of exposed filter When I used an exposed filter the filter selection is passed as name/value pair in the url, for example:

members?field_a=valuea&field_b=valueb

How can I set it up to use more of a "pathauto" style url:

members/valuea/valueb

A colleague of mine created a module called path data a while back. His intentition was to solve this very problem. Unfortunately it has turned out that it conflicts with regular path aliases, so it will work on a site like drupal.org that doesn't use aliases, but will break links on a path-alias using site.

Currently, it's my belief that the only generic way to solve this issue is either manipulating the URLs at the httpd layer, or using hook_url_inbound_alter and hook_url_outbound_alter. You can read a bit more about the mentioned hooks at this question.

However, if I were to give this another shoot myself, I would attempt a Views specific solution instead, as this problem is common enough that it could be justified to have a module for this.

In hook_views_pre_build, one could take data from a url like "members/valuea/valueb", push these values into $_GET['q'], let views build it's query seeing the get arguments "in the url", then possibly remove them again in hook_views_post_build.


How do I translate a view page title? Is there a way to translate a view page title in Drupal 8? How can I achieve it, if it is possible?

Install the Multilingual modules in admin/modules

Go to admin/config/regional/language and add the new language

Go to edit your View and click in Translate

Then click in edit

And go to edit the title


How do I apply a patch with Composer workflow? I need to include a patch in my project. I have included cweagans/composer-patches in composer.json and added the following lines in the extra section (example is from when trying to enable distribution in the Configuration installer).

"patches": {
        "drupal/config_installer": {
            "Enable distribution for Configuration installer profile": "patches/config_installer_enable_distribution.patch"
        }
    }

Afterwards, I run composer update.

- Installing drupal/config_installer (1.5.0): Loading from cache
- Applying patches for drupal/config_installer
    patches/config_installer_enable_distribution.patch (Enable distribution for Configuration installer profile)

So I get no errors and the patch seems to have been applied successfully. Also the file PATCHES.txt is successfully created in the package's root directory. Still, the patch hasn't been applied.

I've tried this method with other packages which come from Github and it works, however every time I try this with a module or a profile from drupal.org then the patch isn't being applied.

Am I missing anything?

When I ran composer update -vvv, I saw the command which is running for the patch is indeed with Git.

git -C 'web/profiles/contrib/config_installer' apply '-p1' '/path/to/project/patches/config_installer_enable_distribution.patch'

I've tried running the command by itself; again, it didn't change the file.

The issue is that composer is applying patches using git apply which is not working for packages that are not installed from source.

Therefore the solution is to install the packages from source. This way the package will fetch the package along with its repository (when available) thus enabling it to be patched.

So...

How to install/update a package from source

For new packages:

Use

composer require vendor/package --prefer-source

For existing packages

If your package is already installed then you need to delete it so that you can re-fetch it with composer install (there is no composer reinstall command). Do so and then use

composer install vendor/package --prefer-source

Set it as the default behavior

You can also set it up as the default behavior for the project in the config section of composer.json:

"config": {
      "preferred-install": "source"
    },

Update:

Set it as the default behavior for a specific package

In case you don't want to set your entire project to install from source, you can do so for a specific package only. To do so you need to specify the VCS Branch in the Version constrain of the package.

"require": {
        "vendor/package": "dev-branch#branch-hash"
}


Update database after feeds' import Hello Drupal community,

I'm trying to develop a customized module that updates the database with some operations on some fields (geocoding an adress field) after an import using feeds. Any idea which hook I should use?

Thanks

There is a hook_feeds_after_import for this


Checklist(s) for simplifying upgrades from Drupal 6 to 7 or higher in the future? Is there any checklist to configure before upgrade for better deciding?

Is there any checklist for it after upgrade?

I have used the Upgrade status module on the past to better understand how much work will be involved in upgrading a site from a mayor version to the next.

Also, depending on how many modifications, or modules you have, it will also make the process easier.

One more tip: Check the Drupal documentation, and remember Youtube is your friend.


let user create content as another user My company has a website with a blog, and we have a virtual assistant.  Our process is that after writing the blog we have our virtual assistant proof read for grammar and spelling errors.  what we would like to do is to have our virtual assistant log into our site as herself but be able to post the blog article as one of us.

Is there a module that allows for this kind of ghost posting?

Using node hooks to set the user will work, but what you are suggesting is really what is normally called "workflow" in content management systems.

There are a few ways to do workflow in Drupal, but the most common for Drupal 7 is probably using the Workbench suite of modules.  In particular, Workbench Moderation would be the most beneficial module for your situation.

You would set up a few different roles (writer, editor, proofreader, etc) for your users.  You would then set up various workflow states (Draft, Pending, and Published are a good start).  Then, you define which roles can push nodes through which states of the workflow.  For example, you may say that only writes can push from Draft to Pending, and proofreaders can only push from Pending to Published.

In the long run, this will give you the most flexibility as your current situation evolves and changes.


Why are my users are being forced to reset passwords on almost every login? After logging out of my site, after about 30 minutes, each user's password is reported to be invalid -- that is, they cannot login with their existing passwords and are forced to use the reset link.

This happens almost every time and happens absolutely every time after a certain period of time.

This is an extremely frustrating problem to diagnose -- I'm not even sure where to start. Any suggestions?

I'm on Drupal 7.50 using a bootstrap 3 subtheme -- heartbeat controls some features.

Out of the box, Drupal does not have a way to force reset password automatically for users, I am guessing there must of use of any contributed module or there might be custom module written.

One of the contributed module which could do this is Force Password Change, can yu check if you have this module enabled? If so disabling the module or changing the configuration could help, also can you list down all the enabled non-core modules you have, you can get the list by running the following drush command, that will help in identifying if there is any such module used.

drush pm-list --type=Module --no-core   --status=enabled


How do I set the default value of a datetime form element? I have a requirement of developing a custom contact form in drupal 8. I am able add all the fields but coming to date time field unable to set the default value to current date.

This is my date field code

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#description' => date($date_format, time()),
  '#default_value' => time(),
];

use Drupal\Core\Datetime\DrupalDateTime;

and in form

$form['start_date'] = array(
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => DrupalDateTime::createFromTimestamp(time()),
);


How to avoid that a module encodes json puts out "\u0026" instead of "&"? I am using a module to encode to json, but it puts out "\u0026" instead of "&".

How can I avoid that?

Explanation:

Content as Json module simply returns the content by running it through drupal_json_output(), which in turn call drupal_json_encode().
Inside drupal_json_encode drupal ensures to have unicode conversion to special characters including '<','>','&'.

function drupal_json_encode($var) {
  // The PHP version cannot change within a request.
  static $php530;

  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }

  if ($php530) {
    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}

If you see if your php version is greater than 5.3 than json_encode() it self takes the argument to make sure all are unicode converted, it php is less than or euqall to 5.3, than drupal imcludes a helper json-encode.inc file which do the same.

Solution:

Way 1: The best would be to handle it on the client consuming the json data, have quivalent parser on the consumer side as well.

Way 2: Hook into contentasjson module to return json the way you want.Alter menu callback to register your own page callback

function mymodule_menu_alter(&$itmes) {
  $item['contentasjson/%/%']['page callback'] = '_my_custom_json_as_content';
}

//Copy the code as it from contentasjson module `contentasjson_get_data()` callback with a small change the json_encode function.
function _my_custom_json_as_content($type, $id) {
  switch ($type) {
    case "node" :
      $data = _contentasjson_get_node( $id );
      break;

    case "comment" :
      $data = _contentasjson_get_comment( $id );
      break;

    case "menu" :
      $data = _contentasjson_get_menu( $id );
      break;

    case "taxonomy_term" :
      $data = _contentasjson_get_taxonomy_term( $id );
      break;

    case "taxonomy_vocabulary" :
      $data = _contentasjson_get_taxonomy_vocabulary( $id );
      break;

    case "custom_data" :
      $data = _contentasjson_get_custom_data();
      break;

    default :
      $data = _contentasjson_get_error_message_type( $type );
      break;
  }

  // If false (no data object returned), generate return message
  $data = ($data == FALSE ? _contentasjson_get_error_message_id( $id ) : $data);
  // Here is the small change we are doing.
  json_encode( $data );
}


Convert view route parameter to entity Task: Create a view with link to it displayed among node tabs (View, Edit, etc.).

Solution: Create a view with page display and set its path to "node/%node/foo".

Issue: When the page "node/%node/foo" is visited, \Drupal::routeMatch()->getParameter('node') returns node ID instead of node object.

Is there a simple way to make it return the node object? (Currently I have to alter the view route and set the parameter type.)

Views doesn't use typed arguments as it doesn't understand them anyway. Why do you need that to work? You can just load it where you need it? And if you have code that relies on that being an object then that code is wrong and will also fail on node/N/revisions for example.

What might work is defining such a page with page_manager, that will allow to define the right type.. but on the other hand, page manager does not yet support defining local tasks.


What's the "Drupal" way of creating image links? I know that the correct way to create links in Drupal is to use l($text, $path, array $options = array()). But that only allows for text links. Is there a similar function for creating images that link, or is it OK to just write out the HTML?

l() allows for HTML too, you just need to pass it as one of the options:

$link = l($image_html, $path, array('html' => TRUE));

That'll stop the first parameter being passed through check_plain(), so the the full HTML you pass in will be wrapped in the <a> tag.

I'd advise using this method if the alternative is writing the link out manually, you get the benefit of automatic alias-translation and it's less prone to small errors in the HTML (of which I for one always make loads).


Turning on aggregration causes a SQL error I would like to create a view to display the number of nodes (later I'd like to also sum some numeric fields, but let's not run before we can walk).

In my view, I've turned on aggregation (under advanced settings), set the display type to fields, and added the title field with an aggregation type of "COUNT". However, in the view preview I'm getting the following error:

  SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause: SELECT node_field_data.nid AS nid, COUNT(node_field_data.title) AS node_field_data_title FROM {node_field_data} node_field_data WHERE (( (node_field_data.status = :db_condition_placeholder_0) )) LIMIT 10 OFFSET 0; Array ( [:db_condition_placeholder_0] => 1 )

What do I need to do to fix this error?

Aggregation can be sort of a pain in Drupal 8's Views implementation. Part of this is due to limitations in how MySQL handles GROUP BY.

As @Jonathan points out, for an aggregation function to work at all, you need to have at least one group by expression.  And if you want a function like COUNT or MIN to work as you expect, you only want the one group to be listed in the GROUP BY.

To get this to work right just now, you need to:

Under Advanced, you need to set Aggregation to "yes".
Under Format > Settings, you need to choose your Group by field.
You may not sort by anything other than the field you chose under Format > Settings, or your aggregation functions will give you bogus answers.

This is a bit limiting for some things you'll want to do, but as of 8.0.2, it's tricky to get better than this.

If anybody knows how to do better than this, I'd love to hear how :-)


Create a menu under a menu? I am wondering if there is a way to have a menu under another menu in Drupal 7. Let's say I have a new menu called Blah and I want it to appear under the main menu item Top.

So I would end up with

Main Menu

|- Top
|---Blah Menu
|------ Blah Menu Item

The obvious approach would be to have your main-menu built with sub-links.

If that doesn't work, you could:

edit your template to call the new menu right underneath the first.

or

add the new menu to the same block as your first menu (you may want to define new block areas for this)