Pass Variable to Custom Block template file I want to create my custom block with custom content in Drupal 8,in start I create  Block with just simple text on it, and work correctly, my Problem is how can I pass my custom variable to it?
I saw some tutorial about it , my Module name is tcdev and this is content of .module file.

function tcdev_theme($existing, $type, $theme, $path) {
    return array('tcdev' =>
        array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
            'template' => 'block--sliderblock'
        )
    );
}

and my SliderBlock.php

    namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;

/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build(){
        return array(
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
}
}

and finally my template file block--sliderblock.html.twig

My Custom Block{{ title }}-{{ description }}

But Result is only "My Custom Block-" .
The problem is variables not getting passed to template file,where is my fault?

appreciate any help

Your return array doesn't contain a #theme key. So at the moment you aren't using a template file at all.

And you  probably have a mix up between the outer block and theming the content inside of the block. Your template inside has the name tcdev, because that is the name you defined at the top of the array in *_theme(), and tcdev.html.twig is where your variables will end up.

Your code would look like the following one.

function tcdev_theme($existing, $type, $theme, $path) {
  return array('tcdev' =>                  // this is the name of the template
           array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
        )
    );
}

SliderBlock.php

namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;

/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#theme' => 'tcdev',
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
   }
}

tcdev.html.twig

My Custom Block{{ title }}-{{ description }}

You wrote that you saw some tutorials about it. Probably this was about two different topics, and you are trying to apply them at the same time.

Create custom twig templates from custom module
Override Twig Templates

The custom template in the first link is tcdev.html.twig. What you are trying to do with the method in the second link is for block--sliderblock.html.twig.


Why am I getting empty input value on expose filter $form_state variables for taxonomy? I have created a panel. Inside the panel there is one content pane and one view expose filter present.

Normal exposed filter works properly but Simple hierarchical select does not works as expected: I am getting empty value after submit.

I have checked using views_exposed_form_alter hook.

$form_state['view']->exposed_input['shs_term_node_tid_depth']

Is there any alternative way to set or get the expose filter input?

Apply little trick and my issue solved.
Used default taxonomy search and hide it.

(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.


How to run the cron within specified timebound only? I have a requirement which needs to be done via cron.
Some of the jobs should run only in time frame of 9AM-7PM everyday. So how I can schedule a cron for this type of requirements in the crontab.I surfed around it, but didn't get any solutions so please anybody help me in this regard.

To run cron you have to have something that triggers the cron since php is a scripting language and only fires off when executed. What that means is you either need an outside resources to fire off the cron or you need to set it up server side.  You can set up a cron service on linux by following the guide on Drupal.org. If a scheduled cron task is not set up on the server side or some other mechanism then cron will simply run the next time a user goes to your site. This could have performance issues and unreliable cron runs.

Custom Module

If you don't want your cron task to run every single time cron runs then in your code you would set it up to check the current time and whether or not to run. This would require use of the date functions in php and allow you to decide whether or not to execute your code based off the time

Elysia Cron

Elysia cron will allow you specifically set which cron tasks run at certain times. This will require you to still set up a cron task so that cron can still fire.


"Uncaught ReflectionException: Class DOMDocument does not exist" error On Ubuntu 16.04, I installed Drush using Composer: composer global require drush/drush:~8. Installation succeeded, but running drush --version, I got this error:

  PHP Fatal error:  Uncaught ReflectionException: Class DOMDocument does
  not exist in
  /.../composer/vendor/consolidation/output-formatters/src/Transformations/DomToArraySimplifier.php:24

What do I do now?

DOMDocument is included in the extension php-xml.  To install it on ubuntu, run:

sudo apt-get install php-xml


Using a conditional OR in a view query alter programmatically I am trying to use an conditional OR in my custom module.

hook_views_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)

I get it to work with either one of these conditions set, but not together.

if (isset($query->alterTags['VIENAME'])) {
  $query->condition('draggableviews_structure.entity_id' , NULL, 'IS NULL');
  $query->condition('draggableviews_structure.view_name', 'view_display_name', '=');
}

How do I set an OR value between them, so if either is true?

Thanks

You can do this by using orConditionGroup():

$query = \Drupal::entityQuery('map');
  $group = $query->orConditionGroup()
    ->condition('attributes.color', 'red')
    ->condition('attributes.color', 'green');
  $entity_ids = $query
    ->condition('attributes.building_type', 'bikeshed')
    ->condition($group)
    ->execute();

Example from https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3AorConditionGroup/8.2.x


Drupal 8 block cacheing I have written a block, displayed on the right sidebar of my drupal 8 site. It reads the database, and shows today's reports. But the block's output is aggressively cached, so that it never shows the up-to-date details. The block's code is being called, and returns the correct data, but this is ignored. (Pages created by controller classes do similar work, but are not cached. What's the difference?).

After reading many help pages, I'm frustrated; I can't get the block to show up-to-date details. The solution seems to involve setting '#cache' on the render array returned, but I can't see how.

Help please!

It all depends on what you want to do exactly.  I have a block that is dependent on the user thats logged in, and it may also be changed from time to time based on some other code being run.

In this example

'#cache'=>[
        'contexts'=> [
            'user',
            'route',
        ],
        'tags' => [
          'Block:smn',
        ],
      ],

It gives it context for which to cache and the tag allows me to invalidate the cache for just this block if I run some other code that will affect what is rendered

in this example if some entity is deleted i use hook_entity_delete

function foo_entity_delete($entity){
    $cache = \Drupal::service('cache_tags.invalidator')->invalidateTags(array('Block:smn'));

}

and my block will be removed from cache and the next time I visit the page it will be rendered with new information.

for more info on tags, and contexts you can cache with:
https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x


How to allow users to login with a particular role they have selected? I have a multiple roles in my site, let's say I have role A, B, C, D.

I want users to be able to choose which role a user wants when logging in. And then the user should only be able to access the content for the selected role (even if the user has multiple roles).

Any suggestions about how to implement this?

Changing roles would probably require the permission "Administer permissions" so it could be hard. There's a module that does what you want, but it would probably require some modification: https://drupal.org/project/roleswitcher

There's also the Masquerade module (https://drupal.org/project/masquerade) which offers the ability to switch user account - which may be useful depending on your needs.


Pagination for Views RSS I'm using Views RSS module to generate a custom RSS feed. I want to be able to limit the results by adding ?offset=50&limit=50 . How could I achieve that? Is there any Views plugin I could use?

Thanks

Not sure if there is a dead simple solution. I know that by using Services and Services Views you can use offset and limit as arguments when calling the service.

So that the URL could look like: http://example.com/rest/views/articles?limit=5&offset=2


Adding comments at content creation? I'm on D7. I have a content type that I would like users to add comments to WHILE they create it. Basically the content type is a "how to" topic and the comments will be used as different steps to do whatever. Thanks for any suggestions.

In this case I'd have a look at the field_collection module. It may be more suited for your purposes.


What is the best way to add user points to existing users I have a dev and prod versions of my D7 site. On dev I developed some functionality based on User Points module and plan to roll out it on prod. But it requires some initial number of user points for every user.

What is the best way to add user points to existing users: SQL query, Rules etc?

One method here is to use the Userpoints API and execute a code snippet that will add the points for you. You can reference the userpoints API here. You can do something like this...

$initial_value = 10;
//@TODO: Build a list of all $uids in an array
foreach($uids as $uid) { =
  userpoints_userpointsapi(array(
    'uid' => $uid,
    'points' => $initial_value,
    'operation' => "Add Initial User Point Value",
  ));
}


How to make a slideshow of Views? i want to make a slideshow block of two views.

view 1 is 'most popular blog posts', showing 10 titles with date and no. of times viewed.
view 2 is 'most commented blog posts', showing 10 titles with date and no. of comments.

I'll put the slideshow block on the front page, it will show view 1 first then after 5 seconds, it will show view 2.

How?

By using the Views slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


Updating custom module I created custom module and I installed it on "Add Module" page. I've got that module in sites/all/modules. I changed that module (I went to that location and I recoded it). What should I do to update that module. It seems to me that only after recoding that module Drupal doesn't notice changes.

When you edit an installed and enabled module, Drupal will not notice you added new hooks, since the list of the hooks implemented by a module is cached from Drupal. In order to make Drupal notice you edited the module and added new hooks, you need to disable and re-enable the module, without uninstalling it.

The reason why this is necessary is that module_implements(), the function that returns TRUE when a module implements a hook, contains the following code.

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }


First AJAX request is working very well, next takes too much time I'm working on ajaxing my site, for a long time now.
I found a method that's working for me, but only the first AJAX request is working the right way; the next request takes at least twice the time.

I thought, that it behaves like that because I load the whole scripts from a template file with every request. I removed the print $scripts from that template file; the result is that the requests take the same time took before.

This is the content of the files I am using.

my_ajax.module

function my_ajax_init() {
  drupal_add_js(drupal_get_path('module', 'my_ajax') . '/my_ajax.js');
}

function acquia_slate_preprocess_page(&$vars, $hook) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $vars['template_files'][] = 'page-ajax';
  }
}

my_ajax.js

Drupal.behaviors.my_ajax = function (context) {
  $('#content-group-inner a').live('click', function (e) {
    $('#content-group-inner a').not('.my_ajax-processed').addClass('my_ajax-processed');
    var url = $(this).attr('href');
    $('#content-region-inner').empty().html('');
    $('#content-region-inner').load(url, 'ajax=1', function () {
      Drupal.attachBehaviors('#content-region-inner');
    });

    return false;
  });
};

page-ajax.tpl.php

<?php print $styles; ?>
<?php print $setting_styles; ?>

<?php if ($local_styles): ?>
  <?php print $local_styles; ?>
<?php endif; ?>
<title><?php print $head_title; ?></title>

<?php if (arg(0) != 'admin') { ?>

<?php } ?>
<?php  print $scripts; ?>

<?php print theme('grid_block', $tabs, 'content-tabs'); ?>

    <?php if ($title): ?>

<?php print $title; ?>

    <?php endif; ?>
    <?php if ($content): ?>

        <?php ?>
        <?php print $content; ?>
        <?php print $feed_icons; ?>

    <?php endif; ?>

<?php print $closure; ?>

I found a solution that's working for me.
I just changed that:

$('#content-region-inner').load(url, 'ajax=1', function () {
      Drupal.attachBehaviors('#content-region-inner');

into that:

var result = $('#content-region-inner:not(.my_ajax-processed)', context)
    .load(url,'ajax=1',function() {
               Drupal.attachBehaviors(result);

When using that, Drupal only fires up Drupal.attachBehaviors() once a time, no matter how much requests you do.

I hope this is working for you, too


How to get a field with a relationship in a view I have a design where a car belongs to a brand and let's say a brand belongs to acategory, using entity reference module I was able to display the brand in the car view, but I don't know how to display the category, I tried to set the relationship but it does not seem to work.

Follow this steps:

Add a relationship of brand to the view. This will get you to display the properties and fields of the brand entity.
Add another relationship for the brand field which references to the category entity using the entity reference field. This relationship should use the previous relationship (like nested relationships).
Now you should be able to display the properties and fields of the category entity as well.

Note: I've written this generically; it should work for any type of entities (e.g. Nodes, Users, Files, Taxonomy, etc.)


How do I add fields to a specific node? I want to create a Basic page that, in addition to its title and body, has a list of other nodes. The list of other nodes has to be entirely administered through the admin. However, I don't want to add the other node field onto all Basic pages, as it only applies to this one specific case. How do I do that?

To clarify, I'm asking about the backend portion of this. How do I get it so that, when I edit a certain node, only specific fields show up in the admin?

There are two main ways of doing this: You can create a second content type which is the same as the Basic Page content type except with the additional fields that you require, or you can just add those fields to the Basic Page content type and only fill them out on the single node you want them to appear on.

As for how to show a list of nodes on another node, I would highly recommend the Entity Reference module. This allows you to add a field that is just stored as a reference to another node.

Original answer (I am leaving this in because it is another way to accomplish a similar outcome):

Using Views you can create the list of nodes that you would like to display on the page. The new version of views makes it super easy to do that. From there you have a couple options, depending your level of skill with theming and how much control you need to have over where the list of nodes displays:

A Block - Create a block display for your view. Place the block in the same region as the main content block.
node--NODEID.tpl.php - You could add a template suggestion to your theme to override the specific node that you want to add the list to. To do that you would need to:

Create a node--NODEID.tpl.php file, replacing the NODEID with the nid of the node you want your list of nodes to show up on.
Embed your view in the node template using the following code:

<?php print views_embed_view('MY_VIEW', 'MY_DISPLAY', $node->nid); ?>

Where MY_VIEW is the machine name of the view you created and MY_DISPLAY is either "default" or the machine name of a specific display in your view.

Here is an example: http://api.drupal.org/api/views/views.module/function/views_embed_view/7#comment-32858


Local json migration: how to set the value of the urls variable? I'm currently really busy to get the migration work on my desk.
I want to import (migrate) a local json file into drupal8 using Migrate_Plus, Migrate tools.
For that I have the following migration yml configuration file

# Migration configuration for products.
id: product
label: 'Product'
migration_group: Products
# Here we define the migration source
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls: /modules/custom/migrate_products/data/data.json
  item_selector: /data
  fields:
    -
      name: uuid
      label: 'uuid'
      selector: uuid/value

    -
     name: name
     label: 'Produkt Name'
     selector: name/value

    -
      name: supplierName
      label: 'Anbietername'
      selector: supplierName/value

  ids:
    uuid:
     type: string

destination:
    plugin: entity:node

process:
  type:
    plugin: default_value
    default_value: produkt

  title: name
  field_uuid: uuid
  field_suppliername: supplierName

  sticky:
    plugin: default_value
    default_value: 0
  uid:
    plugin: default_value
    default_value: 0

migration_dependencies:
  required: {}
  optional: {}

dependencies:
  enforced:
    module:
      - migrate_products

Like you can see, the json file is located inside the custom module directory.

The json file looks like this:

{
  "data": [
    {
      "uuid": {
        "value": "7d51-4406-a7ef-3a7916b977a9",
        "patient": false
      },
      "name": {
        "value": "Product1",
        "patient": false
      },
      "supplierName": {
        "value": "User1",
        "patient": false
      },
.....

After enbaling the required migration module, when running:
drush ms
I get the following output:

file parser plugin: could not retrieve data from /modules/custom/migrate_products/data/data.json
 Group: Products (Products)  Status  Total  Imported  Unprocessed  Last imported
 product                     Idle    n. v.  0         n. v.

The data fetcher plugin can't find your JSON file because the format is wrong. The plugin is expecting Drupal's URI format (e.g. public://path/to/data.json or private://path/to/data.json) under its private/public file dir. For example, see the included example migration with the module:

  # The data_parser normally limits the fields passed on to the source plugin
  # to fields configured to be used as part of the migration. To support more
  # dynamic migrations, the JSON data parser supports including the original
  # data for the current row. Simply include the 'include_raw_data' flag set
  # to `true` to enable this. This option is disabled by default to minimize
  # memory footprint for migrations that do not need this capability.
  # include_raw_data: true
  # Flags whether to track changes to incoming data. If TRUE, we will maintain
  # hashed source rows to determine whether incoming data has changed.
  # track_changes: true
  # Copy the example JSON file in artifacts folder to sites/default/files folder.
  urls:
    - 'public://migrate_json_example/products.json'


Outputting multiple content fields all wrapped in a div I'm trying to wrap multiple field items in an HTML container.

So let's say I have "Blog" content type. I have field1, field2, field3, field4 and field5 for this content type.

I want to output field2, field3 and field4 wrapped together in a DIV.

I've been Googling and tinkering for the past 3 hours and I haven't gotten anywhere.

Any help out there?

Drupal 7, Zen subtheme.

I read this and didn't have any luck here either:
Wrapping multiple cck fields into a single div tag for theming?

Multiple ways to achieve this.

By creating a node tpl file for that particular content type.
By creating view.
But i think the best and easiest way is creating group in manage display. Check field group module.

Procedure to create group.

Go to structure->content types->content(ex-blog)->manage displays.
Add a new group of div type.
Drag the required field like field2 , field3 etc under it.

Print in tpl file.

It will be easy to find out if you will update the code snippet of node--case-study.tpl.php file.

I think you need to first check by printing

echo '
';
print_r($content);

and use this for

  <?php print($content['field1']); ?>

 <?php
    print($content['field2']);
    print($content['field3']);
    print($content['field4']);
 ?>


Sending two exposed filters fast I'm using auto submit in exposed filter and if I changing the form control twice and fast(Before I'm getting answer on the first change)
I will get wrong view list item.
(So it seems to be that the first ajax request overrules the second selection)
How can i fix it?

The problem is that because of the auto-submit, you submit an ajax request as soon as the first filter is changed. It then doesn't matter that you make a second change, and the answer to the first request is already being processed.

The only solution that I'm aware of, is to not use the ajax functionality in Views, and instead implement your own, that for example waits one second after changing the first filter before submitting the form, allowing several filters to be changed in one request.


How to delete a node with same specific field content and by same user when a more recent one is created in drupal 7? I have created a review system allowing users to make a review of a place. One of the fields for each review is the actual location which needs to be filled. If a user decides to create a review of 'the Red Lion' and it happens that she has already written one on that place, I want the old review to be deleted, and only the latest one kept.

I have tried to use Rules with the 'fetch entity by property' and a double loop, but it does not seem to do the trick. Here is the export of a test rule where I just flag the 'former review'. The current result is that it flags all reviews of the 'Red Lion' made prior to the current one being saved. Any suggestions?

{ "rules_delete_old_reviews" : {
"LABEL" : "Delete old reviews",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "flag" ],
"ON" : { "node_presave--review" : { "bundle" : "review" } },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "node",
        "property" : "author",
        "value" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched_author" : "Fetched node by author" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched-author" ] },
      "ITEM" : { "list_item_nodeauthor" : "Current list item" },
      "DO" : [
        { "entity_query" : {
            "USING" : {
              "type" : "node",
              "property" : "field_revlocation",
              "value" : [ "node:field-revlocation" ]
            },
            "PROVIDE" : { "entity_fetched" : { "old_review_item" : "old_review" } }
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "old-review-item" ] },
            "ITEM" : { "list_item" : "Current list item" },
            "DO" : [
              { "drupal_message" : { "message" : "This node \u0022[list-item:title]\u0022 is now flagged." } },
              { "flag_flagnode" : {
                  "flag" : "tagged_review",
                  "node" : [ "old-review-item:0" ],
                  "flagging_user" : [ "site:current-user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        }
      ]
    }
  }
]
  }
}

Here is how I achieved it in the end:

First, create a component rule 'Listreviews'. This component rule will filter nodes created by the current user and then

Component plug-in is set to 'rule'.
The variable is of type 'node' of type 'parameter'. Give it a machine name 'nodefromlist' and save.
Add a condition: data comparison. This comparison will be have the data selector nodefromlist:author:uid, and it needs to equal site:current-user:uid.
Add an action: 'delete entity', which will have the data selector value of 'nodefromlist'.
Save!

Then, create a rule 'Delete duplicate review'.

the event chosen is 'before saving content type review'
no conditions
Actions: 'fetch entity by property'

entity type 'node'
property: the field 'location' (in my example)
data selector: go down the arborescence up to: node:field-location
I put a limit of 10, but may need to be adjusted based on previous content available.
Add a label to the provided variables section
Add a variable name like: item_same_location

Then

Create a loop below the action above with the parameter item_same_location

call the current list item: list_item.

In that loop, create an action 'component' with the name of the rule component created above.

the data selector will be: list_item.

Save your rule!

This should now work. As a bonus, I added a 'display message' action in the component rule in order to let the user know that their previous review was deleted. I hope this helps someone in the future!


Add PHP code to block's content Is there a module that allows a php text filter in drupal 8? This was a possibility in drupal-7 but I can not find something similar to 8.

The PHP filter module was removed from core, because of the inherent security problems it presents.

It now exists as a separate contrib module, but beware that even the module description itself warns against using it:

  Warning

  Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site. There are better alternatives out there that do not expose such vulnerabilities on your site.


How to hook into fivestar_ajax_submit function? I have to add custom HTML element for rate stars and I tried to this with alter fivestar_custom_widget form and set:

$form['actions']['submit']['#ajax']['callback'] = 'MODULE_fivestar_ajax_submit';

I created MODULE_fivestar_ajax_submit function where I call original fivestar_ajax_submit.
My problem is that I can't instruct $form to use my function in place of original code.

-- edit --

In MYMODULE_form_alter() I'v got:

if ($form_id == 'fivestar_custom_widget') {
    $arg0 = arg(0);
    $arg1 = arg(1);
    if ($arg0 == 'node' && !empty($arg1) && ctype_digit($arg1)) {
        $node = node_load($arg1);
        $form['votes_counter'] = array(
            '#markup' => '
' . format_plural($node->field_rating[LANGUAGE_NONE][0]['count'], '1 vote', '@count votes') . '
'
        );
        $form['#submit'] = array(
            'MYMODULE_fivestar_form_submit'
        );

        $form['actions']['submit']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
        $form['#submit'] = array('MYMODULE_fivestar_ajax_submit');
    }
}

and submit function:

function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);
    $result['#commands']['data'] .= format_plural(100, '1 vote', '@count votes');
    return $result;
}

My friend helped me with this solution:

function MYMODULE_element_info_alter(&$info) {
    $info['fivestar']['#process'][] = 'MYMODULE_fivestar_process';
}

function MYMODULE_fivestar_process($element) {
    $element['vote']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
    return $element;
}

function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);

    $type = $form_state['build_info']['args'][1]['content_type'];
    $id = $form_state['build_info']['args'][1]['content_id'];
    $votes = fivestar_get_votes($type, $id, 'vote', $GLOBALS['user']->uid);

    $result['#commands'][] = array(
        'command' => 'insert',
        'method' => 'replaceWith',
        'selector' => 'span.vote-count',
        'data' => '' . format_plural($votes['count']['value'], '1 vote', '@count votes') . '',
        'effect' => 'fade'
    );
    return $result;
}

This code adds and change votes counter displayed after fivestar voting widget.


Multilingual- can non-English languages be used without a prefix if they are the main language of the site? I am trying to set up a multilingual web site, in English and Spanish. The way I want to setup the web site is:

  www.example.com: main page of the site in Spanish

  www.example.com/en:  main page in English

and

  www.example.com/productos/ejemplodeproducto: Spanish product page

  www.example.com/en/products/exampleproduct: English product page

Instead, for the Spanish pages, there is always a prefix as well:

  www.example.com/es/productos/ejemplodeproducto: Spanish product page

Is it possible to not have a language prefix in the URL for the main language? That's how our site worked with Wordpress. We are using Drupal 7.

Yes, just go to 'admin/config/regional/language', click the edit link of your main language (Spanish), delete the prefix and save your changes.

If you have issues (like links still having the old prefix in them) then clear the caches ('admin/config/development/performance').


Add a 'GROUP BY' in Views? How do I add the equivalent of GROUP BY using drupal 6 and views 2?

Views 3 supports grouping.

For views 2, aside of Views Group By, you can also write a custom module, implement hook_views_query_alter(&$view, &$query) and do something like:

function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name') {
    if ($view->current_display == 'page_XXXXXX') {
      // Tell the query constructor these fields must be used with the GROUP BY clause
      $query->add_groupby('field1');
      $query->add_groupby('field2');

      // hack to make the query constructor just ignore these fields (not adding them to the GROUP BY clause. It's needed to let it continue without problems
      $query->fields['fieldalias3']['aggregate'] = TRUE;
      $query->fields['fieldalias4']['aggregate'] = TRUE;
      // ... all but the grouped and aggregated fieldaliases must have this.

      // Configure the fields that perform the aggregation (SUM, AVG, etc)
      $query->fields['aggregatedfieldaliasA']['table'] = '';
      $query->fields['aggregatedfieldaliasA']['field'] = "SUM(fieldA)";
    }
  }
}

You now should be able to see the resulting query in the preview when editing the view and make sure it is correct. Field aliases in the code refer to "SELECT table.field1 as fieldalias1 ...", it's easy to get them just by checking the query shown in the preview.


watchdog truncate or delete Watchdog table has become so big that, truncate cascade or delete command in the table is not working at all.
The moment the server encounter a DELETE command in watchdog, it gets busy in executing that, all resources are being occupied by DELETE command and server gets very slow. The total functionality can be considered to be null.

Even vacuum full/ananlyze is yielding any result even after waiting for 1 or 2days.

You can use truncate command which is faster than Delete. And try using this command directly from Terminal rather than doing "clear log" option available in Recent Log Messages in Drupal 7.

You can find more details on Truncate vs Delete on here.

Hope this helps.


D7 - Multilingual in the admin, only one language for the users We have a drupal 7 with the following need :

When the user visit the website, we let drupal chose the best language for the user
He can then choose to chose another language.
We have a finite number of language (5 so far)
Unless he decide to change the language for the whole website, he should only see the content written in the selected language
all user (except admins) on the website are anonymous (no registration, no login)
we need the admins to see all languages.
contents can exist in one or many languages. There is no "reference" language that holds all the contents.

So far we have set the language switcher for all languages, but then on the website the menu for all languages are displayed (which we don't want). Also, search is made on content for all languages. If we set the language switcher to only use the selected language, everything works as intented on the website but then the admin can only see the content matching the current selected language. We need that he sees all content.

We've been looking into some options (including the Administration Language, but unless we overlooked some configuration, it doesn't seem to fit our needs).

Any ideas, hints or suggestion welcome !

We ended up writing various custom modules to solve that issue.


Install module that has an external php script and a couple of other files i want to develop a module that has some pdf modelling functionality. I have an external script I want to use and some javascript.
i wonder what is the best solution to get a module working from the drupal install routine.

1.) Do i have to add my external script to the drupal library...and remove it when my module is deinstalled?
2.) Can you recommend some good tutorials to get started with install scripts?

Any hints are welcome...

Thanks

You should use the Libraries module - it allows integration with external libraries and scripts.
This is the correct way of adding libraries and using third party scripts in Drupal. This way several modules can use the same library and same sources, which is better from maintenance and organization perspective.

You can define a dependency in your custom module using the hook_libraries_info() and then include the library when you need it with libraries_load()`.

As an example, take a look at Colorbox to see how the hook is implemented there.

Check out also the Print module.

In your particular case, you will probably use TCPDF for generating PDFs, so you should define a library dependency like so:

/**
 * Implements hook_libraries_info().
 */
function YOUR_MODULE_libraries_info() {
  $libraries['tcpdf'] = array(
    'name' => 'TCPDF',
    'vendor' => 'http://www.tcpdf.org/',
    'download url' => 'http://sourceforge.net/projects/tcpdf/files/',
    'version callback' => 'YOUR_MODULE_tcpdf_version',
    'files' => array(
      'php' => array(
        'tcpdf.php',
      ),
    ),
  );

  return $libraries;
}

And when you need it, just call libraries_load():

libraries_load('tcpdf');

Last thing - don't forget to add dependency for libraries in your module .info file.


How do I download/open a pdf file directly by clicking on lable/link I have created a view that displays in a bulletin format, which works fine. My challenge is when I click on the bulletin which has a pdf attachment, I want it to immediately download/open the attached pdf file. Currently it takes me to  second screen(see attached) which has a pdf attachment. I would like to get pdf attachment downloaded immediately when I click on the bulletin, National Arts Festival Grahamstown 27 June to 7 July 2013 from the first screen(see attached).

I have tried to use file force drupal module but seems not to be doing the trick.

Herewith an attachments.

If want to Download File, then use DownloadFile module.

  a module to direct download files or images.

If want to open PDF, then use PDF Reader module

  will render your entity file fields with the selected PDF renderer.

and PDF module.

  Use HTML5 to display PDF files if users don't have pdf plugin for
  their browsers.


limit order quantity in drupal commerce In my website I would like to limit product quantity to 1, meaning is that user can order only one of a product in one order. And my question is how to configure to set maximum quantity to 1 . Any suggestion is greatly appreciated.

Thanks.

You can achieve this using Rules by following steps given below:

  Event: After udpdating an already existing line item

  Conditions: 1/ data comparison: commerce-line-item:type = product 2/
  data comparison: commerce-line-item:commerce-product:type = Your given
  product type 3/ data comparison: commerce-line-item:quantity is
  greater than 1

  Action:
  - set data value: commerce-line-item:quantity 1
  - display custom message

Reference: https://drupalcommerce.org/questions/8066/how-limit-maximum-quantity-1-one-given-product-type


dreamhost VPS returns a lot of blank pages After upgraded from shared hosting to VPS (for more memory), my site returns a lot of blank pages, for example:

plain /update.php is OK, but returns blank page after clicking Continue and Update
plain /admin/reports/status is ok, but /admin/reports/updates/check?destination=admin%2Freports%2Fstatus returns blank space

php memory_limit is now 512M.

Any dreamhost user shares some experience?

I would check PHP error reporting on the server : usually, WSOD are caused by hidden PHP errors. A value of E_ALL & ~E_NOTICE is usually fine, at least for development.


How to pipe output of "drush sql-dump" without warnings When I do: drush sql-dump > somewhere/database.sql if there will be any warnings printed by Drush, they will be included at the beginning of the created database.sql file. Can we avoid it somehow?

I know there is the --result-file= option that ignores all warnings when creating the file, but is there any way to ignore warnings when piping the output? I would like to parse the output before actually saving it into a file if its possible.

drush 8

Seems -q should do the job.

$options['quiet'] = array(
  'short-form' => 'q',
  'description' => 'Suppress non-error messages.',
);

Source: function drush_get_global_options


How to pass PHP variables to Javascript/jQuery? I found this way to send variables from PHP to Javascript.

Inside the template.tpl.php file, I have the following code.

<?php
  echo '
'.json_encode($variables).'
';
?>

Within Javascript, I have the following code:

(function ($) {
  $(document).ready(function() {
      var variables = jQuery.parseJSON($('.drupal-vars').html());
      //Remove if youwant to clean the code.
      $('.drupal-vars').remove();
  });

}(jQuery));

I found another solution, but it's more complicated, although it may be better architectured.

Is there a better way to do it?
How ugly is what I am doing here?

The tutorial goes like:

  I'll start by creating a hook_menu() implementation to establish a
  page callback:

<?php
function helper_menu() {

  $items = array();

  $items['js-vars'] = array(
    'title' => t('Javascript Variables'),
    'description' => t('Javascript Variables'),
    'page callback' => 'helper_page_callback_js_vars',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}
?>

  Next, I'll define the page callback:

<?php
function helper_page_callback_js_vars() {

  // include module javascript file
  drupal_add_js(drupal_get_path('module','helper') . '/js/helper.js');

  // define variables you'd like to pass to the DOM
  $js_vars = array(
    'js_vars' => array(
      'message' => t('Hello @username', array('@username' => $GLOBALS['user']->name)),
      'an_array' => array(
        'color' => t('red'),
        'name' => t('Eric'),
      ),
    ),
  );

  // pass variables to javascript
  drupal_add_js($js_vars, 'setting');

  // generate some page output
  return "TEST";

}
?>

  And here is the contents of the javascript include file I stuck in my
  module directory:

$(document).ready(function(){

  // debug variables directly in FireBug
  console.debug(Drupal.settings.js_vars);

  // popup mesage passed from Drupal
  alert(Drupal.settings.js_vars.message);

});

You'd be better off using drupal_add_js() to pass your object in the JS Drupal.settings object:

// In PHP:
drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');

// In JS
var variables = Drupal.settings.myModule.variables;

Drupal handles all the conversions of objects/arrays internally and this is just a much cleaner way of doing it...at the moment you're including raw JSON as part of the page output which isn't great in terms of semantics; also bear in mind that search engines will pick up this text even though you're hiding it for users with javascript.

I'd also recommend separating this logic out from the template file itself and put it in a template_preprocess_ function in your theme's template.php file...again it's just cleaner. e.g.

function MYTHEME_preprocess_html(&$vars) {
  $variables = $your_variables;
  drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');
}

Have a look at the link to the drupal_add_js() function, there are quite a lot of options and you'll probably find them quite useful.


How we can make weekly calendar block with ajax? How we can make weekly calendar in drupal 7 module same as attach screenshot?

My R&D

I am using jQuery week calendar (https://github.com/themouette/jquery-week-calendar) .

Use calendar module (requires views module). Calendar module comes with bunch of blocks (block views) available and you can set for them to use AJAX instead of refreshing page. With views you can do a lot of customization.


Custom autocomplete form and autosubmit I've added an autocomplete function for my views_exposed_form (a text input) using this tutorial and it works (https://www.linkedin.com/pulse/implementing-autocomplete-drupal-8-custom-callbacks-waliullah-khan).

I'd like to add a "submit on click" behaviour, so when I click on a value of the autocomplete it changes the value of the input and then submit the form.

How should I do this?

Attaching below code:

custom.module

<?php

use Drupal\Core\Form\FormStateInterface;

function custom_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == "YOUR_FORM-ID") {
      $form['combine']['#autocomplete_route_name'] = 'custom.autocomplete';
      $form['#attached']['library'][] = 'custom/custom';
      $form_state->setCached(FALSE);
    }
  }
}

custom.routing.yml

custom.autocomplete:
  path: '/want/autocomplete'
  defaults:
    _controller: '\Drupal\custom\Controller\WantAutoController::autocomplete'
  requirements:
    _permission: 'access content'

custom.libraries.yml

custom:
  version: 0
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

js/custom.js

(function ($) {
    Drupal.behaviors.custom = {
        attach: function (context) {
            $("#FIELD-ID").autocomplete({
                select: function (event, ui) {
                    if (ui.item) {
                        var itemLink = $(ui.item.label).attr('href');
                        window.location.href = itemLink;
                    }
                }
            });
        }
    };
}(jQuery));

src/Controller/WantAutoController.php

<?php

namespace Drupal\custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Returns tree responses for nodes.
 */
class WantAutoController extends ControllerBase {

  function autocomplete(Request $request) {
    $db_conn = \Drupal::database();
    $matches = [];
    $string = $request->query->get('q');
      $alias = \Drupal::service('path.alias_manager');
      $db_conn = \Drupal::database();
      $query = $db_conn->select('node','n');
      $query->leftJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
      $query->fields('n');
      $query->fields('nfd',['title']);
      $result = $query->execute()->fetchAll();
      if ($results) {
        foreach ($results as $row) {
          $path = $alias->getAliasByPath('/node/' . $row->nid);
          $linkTonode = '' . $row->title . '';
          $matches[] = ['value' => $row->title, 'label' => $linkTonode];
        }
      }
    return new JsonResponse($matches);
  }

}

Here in the autocomplete we are building value with "a" tag. And while searching autocomplete field our autocomplete return with "a" tag also. We are also building js here to click on that value and redirect.


Why does my kernel test error with "Install profile will be a mandatory parameter in Drupal 9.0."? I've test classes based on KernelTestBase.

Previously everything was working smoothly, now I came back to the project and I'm hit by this error:

  Install profile will be a mandatory parameter in Drupal 9.0.

Drupal version: 8.3.5
PHPUnit version: 4.8.35

phpunit.xml:

<phpunit bootstrap="web/core/tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false">
<!-- TODO set printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter" once
 https://youtrack.jetbrains.com/issue/WI-24808 is resolved. Drupal provides a
 result printer that links to the html output results for functional tests.
 Unfortunately, this breaks the output of PHPStorm's PHPUnit runner. However, if
 using the command line you can add
 - -printer="\Drupal\Tests\Listeners\HtmlOutputPrinter" to use it (note there
 should be no spaces between the hyphens).
-->
  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value=""/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://vagrant:vagrant@localhost/vagrant"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
  </php>
  <testsuites>
    <testsuite name="mymod">
      <file>web/modules/custom/mymod/tests/src/Kernel/FooTest.php</file>
    </testsuite>
    <!-- etc -->
  </testsuites>
  <listeners>
    <listener class="\Drupal\Tests\Listeners\DrupalStandardsListener">
    </listener>
  </listeners>
  <!-- Filter for coverage reports. -->
  <filter>
    <whitelist>
      <directory>./web/core/includes</directory>
      <directory>./web/core/lib</directory>
      <directory>./web/core/modules</directory>
      <directory>./web/core/modules</directory>
      <directory>./web/core/sites</directory>
      <!-- By definition test classes have no tests. -->
      <exclude>
        <directory suffix="Test.php">./</directory>
        <directory suffix="TestBase.php">./</directory>
      </exclude>
     </whitelist>
  </filter>
</phpunit>

Test class:

class FooTest extends KernelTestBase {

  protected static $modules = ['foo'];

  public function testFoo() {
    self::assertEquals(2, 2);
  }

}

I'm launching it from PHPStorm via:

  vagrant:///Users/drupality/Develop/drupal/myproj/usr/bin/php
  /home/vagrant/.phpstorm_helpers/phpunit.php --group foo
  --configuration /var/www/myproj/site/phpunit.xml --filter "/::testFoo( .*)?$/" Drupal\Tests\foo\Kernel\FooTest
  /var/www/myproj/site/web/modules/custom/myproj/tests/src/Kernel/FooTest.php

UPDATE

I've updated PHPUnit to 5.7.21 (newest supported by PHPStorm) but still no success.

Your problem is that your test and/or code is relying on a deprecated feature.

In Drupal 8.3, there was a push to have deprecated featured generate E_USER_DEPRECATED messages, eg in Drupal\Core\Config\ExtensionInstallStorage:

  public function __construct(StorageInterface $config_storage, $directory = self::CONFIG_INSTALL_DIRECTORY, $collection = StorageInterface::DEFAULT_COLLECTION, $include_profile = TRUE, $profile = NULL) {
    parent::__construct($directory, $collection);
    $this->configStorage = $config_storage;
    $this->includeProfile = $include_profile;
    if (is_null($profile)) {
      @trigger_error('Install profile will be a mandatory parameter in Drupal 9.0.', E_USER_DEPRECATED);
    }
    $this->installProfile = $profile ?: \Drupal::installProfile();
  }

This is to provide early warning to developers to update their code.

If the code is hit in a phpunit test (which includes unit tests, kernel tests, and functional tests using BrowserTestBase), anything from trigger_error will generate a fail.

So, you either need to fix your code, or you can cause the test to not fail by using the @expectedDeprecation annotation on the test method until you can fix it.


Show step-by-step dialogs for helping user with using the site I built an app with Drupal, and I would like to add step-by-step dialogs to help users learn how to use the app.

I found some boostrap plugins, but I would like to know if there is already a Drupal module that has this functionality.

The modules chrischarlton suggested were fine, but those are unsupported and not maintained.

I recommend using the Boostrap tour module. With this module, you can show popups step-by-step, attach the popups to HTML elements in each step, save the progress of the user, and let the user add feedback to the tour. However, you need to have a boostrap based theme in order to make it work.


Site not working after the database update I cloned a repo of a site to my local computer, imported the database and ran "Composer install --with-dependencies" after the installation had been done I entered the local site and it worked, then I ran "drush updb -y" and it showed a couple of errors and warnings:

    The following module is missing from the file system: aspambot       [warning]
bootstrap.inc:268
The following module is missing from the file system: phpmailer      [warning]
bootstrap.inc:268

...

PHP  27. include() /home/www/sites/zb/web/vendor/composer/ClassLoader.php:444
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Interface 'Doctrine\Common\Reflection\ClassFinderInterface'
not found in
/home/www/sites/zb/web/core/lib/Drupal/Component/Annotation/Reflection/MockFileFinder.php,
line 14
The external command could not be executed due to an application     [error]
error.
PHP Fatal error:  Interface 'Doctrine\Common\Reflection\ClassFinderInterface' not found in /home/www/sites/zb/web/core/lib/Drupal/Component/Annotation/Reflection/MockFileFinder.php on line 14

I'm new to Drupal, so please help me get over these errors, I understand that the solution may seem straightforward to some, but I don't know what to do. Thank you!

Add "doctrine/common":">2.8" under conflict in your composer file and then run composer update.

"conflict": {
    "drupal/drupal": "*",
    "doctrine/common":">2.8"
},

See issue: https://www.drupal.org/project/drupal/issues/2986725


Show new navigation once user log in? I'm building a site using Drupal 7 and have a question regarding navigation and roles. My site requires that a lot of content be accessible only to members. I'm wondering how I can show a secondary navigation element on the site once a user logs in? Obviously this would be tied to an authenticated user role.

Any assistance is greatly appreciated!

This module might do the trick:

http://drupal.org/project/menu_item_visibility

I've not installed it myself, but it seems to do what you're asking.


How do I convert drupal_goto to 301? Right now I have a redirect in my code:

drupal_goto($path);

Per the documentation drupal_goto defaults to a 302 redirect. I want a 301.

However, when I put in:

drupal_goto($path, $http_response_code = 302);

It gives me an error:

  Argument 2 passed to drupal_goto() must be of the type array, integer given,

But if I try something like:

drupal_goto($path, array $options = array(), $http_response_code = 302);

...I get this error:

  Unexpected '$options'

How can I properly change drupal_goto into a 301 redirect?

Looks like you're mistaking the function definition for an implementation example.

The function definition describes the arguments to use, but it's not a literal example of how to call it.

So when you want to use the drupal_goto() function, instead of this:

drupal_goto($path, array $options = array(), $http_response_code = 302);

It should look more like this:

drupal_goto($path, array(), 301);


Need to redirect Parent Taxonomy Term page to oldest child I use the Views version of the taxonomy listing page.  For performance reasons, I can't use a depth of 1 on the 'Taxonomy Term (depth)' contextual filter.

Unfortunately, for one taxonomy, ALL terms are a child of this one set of six terms (think Publication / Issues of a magazine).  Is there a way I can, in my menu, link to the parent terms, yet have that listing page show only the nodes from the most recent child?

Otherwise, is there a way, in that View, to have an increased depth (1 vs 0) ONLY if there are no nodes for the particular term?

So I figured this out, wasn't too complicated at all.  Use hook_menu. I didn't write my SQL using the Drupal DB API, but it works:

function ain_custom_menu() {

 $items = array();

  // Item1
  $items['taxonomy/term/218489'] = array(
    'title' => 'Title1',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218489"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  // Item2
  $items['taxonomy/term/218500'] = array(
    'title' => 'Title2',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218500"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;

}

function MYMODULE_find_newsletter($mytid) {
  $tid = db_query('SELECT max(tid) AS tid FROM taxonomy_term_hierarchy t1
    JOIN field_data_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid
    JOIN node t3 ON t2.entity_id = t3.nid
    WHERE t1.parent = '.$mytid.' AND t3.status = 1')->fetchField();
  $latest = is_numeric($tid) ? 'taxonomy/term/' . $tid : '<front>';
  drupal_goto($latest);
}


Cumulative user ratings I am trying to set up a user to user rating system where users can rate nodes and the average is the users rating / total feedback.

I was thinking about using fivestar to create a field on the user profile, then create a fivestar reference (which doesnt exist to my knowledge) to that field so when a user rates a node they aren't rating the node, but the user's rating field attached to their user profile.

Is their a way to get users to rate nodes authored by a user and have it total up to give the user the average rating? I wanted something easy and light without having to create a feedback content type with a fivestar field and using entity prepopulate to pull the user in to link the user to the review content type. Or do it with entityforms/webform.

Would this be doable with flag since I am already using it pretty extensively?

Thanks.

Ok here is what you can do:

Attach a Five Star field to the user
Create Views block that shows the users. Select to show fields and only show the Five star field.
Use a contextual filter in the View to filter by User Id(uid). Select "Provide a Default Argument" -> "User id from URL" -> "Also look for a node and use the node author"
Place this block on the page. Restrict it by content type if you want.
When someone Views a node then they will see the Views block also and can rate the user.

You could put Header text area in text in the View to give the user instructions. You could also display the user name, picture or other information if you wanted.

This is way I could think of with the least amount of modules. If you were already using Panels you could use Panels to place the Five Star field on the node page but I won't suggest installing Panels just for this use case.


Drupal sites extremely slow due to cache SELECT-queries I have multiple drupal 7 sites running on my shared hosting. Suddenly almost all of my drupal sites began running very slow. After some searching I found that I had 132k slow queries of the 140M queries executes.

So I turned on de debug query option in the Devel module and got this:

Executed 230 queries in 18868.24 ms. Queries exceeding 5 ms are highlighted.
Page execution time was 21632.34 ms.
Memory used at: devel_boot()=2.61 MB, devel_shutdown()=47.54 MB, PHP peak=48 MB.

After looking at the SELECT-query list I noticed that there are a lot of cache-queries that run slowly:

SELECT cid, data, created, expire, serialized FROM cache_views WHERE cid IN (:cids_0)

Not only for 'cache_views' but also other cache-tables:

cache
cache_field
cache_filter
cache_menu
cache_bootstrap
...

In PHPMYADMIN I also notice that a lot of queries have been removed from the cache:

Qcache_lowmem_prunes: 35.2M (of 143M queries)

I already checked if there were modules enabled in the DB but deleted on the drupal site.

I hope this is enough info to get some help.

Sounds like MySQL needs to be tuned. I would start with the InnoDB Buffer Pool Size. This answer has info on innodb_buffer_pool_size: Do Drupal websites have bad performance or are heavy?

If the innodb buffer pool is a reasonable size and If MySQL is in ball park of doing 3k+ queries per second and your running MySQL version 5.1 or lower you might be affected by the query cache bug. At work I ended up disabling the MySQL query cache after reading this bug and verifying that the version of MySQL we are running (5.1) does not have this fix http://bugs.mysql.com/bug.php?id=43758 (available in 5.5). The bug is that a lot of queries get stuck in the “freeing items” state http://dev.mysql.com/doc/refman/5.1/en/general-thread-states.html#id770305 (The thread has executed a command. Some freeing of items done during this state involves the query cache. This state is usually followed by cleaning up). I issued this command SET GLOBAL query_cache_size = 0; and saw an instant improvement in query times.


Can I disable Toolbar in specific theme? I have two active theme, and switching between them by themekey on specific paths.

theme #one is my main theme, and some contents load in theme #two in a modal box (lightbox2).
I need disable Toolbar on theme #two because it's load Toolbar too and I don't want it there.

my question is how can I disable Toolbar in theme #two?

You'll have to use hook_page_alter from within a module to unset $page['page_top']['toolbar'] — you can't do it from within a theme.

There is a module for that: Toolbar Visibility.


Restrict content access by term reference in profile What I would like to accomplish is to have the following.  Please let me know if anyone is aware of modules that can accomplish this already or what direction I should take developmentally to accomplish this.  Thanks.

Nodes

All nodes are tagged with terms from a particular vocab through the use of a taxonomy reference field.  The nodes are only accessible to specific users that have permissions to view the tagged terms.

Taxonomy

I have one vocab that I am working with for all of this control and it is enabled for all content.

Users

All users are tagged with terms from a particular vocab through the use of a taxonomy reference field added to their profiles.  This field should only be editable by a certain administrative roles.  Additionally, the user will only be able to access content on the site that is tagged with the terms set in this field.

Turns out I went with Access by Terms module after finding that the Term Access module did not work for me.  Access by Terms also has permissions the make the field editable by certain roles in the profile and nodes, so that takes care of administration requirements too.


Altering Webform email %value before sending email I summon your wisdom on this day because I can't figure out how to alter submitted Webform values that are used in email templates.

Here's my situation:

I have a "contact us" form (set with Webform API) with first name, last name, email and message fields. Nothing spectacular. The submitted values are sent by email to the administrator.

In this webform setting > Email subject, I have this template:

[NAMEOFMYSITE | question from %value[first_name] %value[last_name]

Everything works fine. But my problem appears when the user forgets to put an uppercase in last name or first name value. It doesn't look professional in the email subject. And I want to force these two values with an uppercase as first letter to get something like:

NAMEOFMYSITE | question from John Doe

And never:

NAMEOFMYSITE | question from john doe

I tried to alter submitted values because I thought template's %value were based on it:

function pwe_webform_form_alter(&$form, &$form_state, $form_id) {
  [...]
  $form['#submit'][] = 'contactus_webform_submit'; // callback function on submit
}

function contactus_webform_submit($form, &$form_state) {
  $form_state['values']['submitted']['last_name'] = ucfirst($form_state['values']['submitted']['last_name']);
  $form_state['values']['submitted']['first_name'] = ucfirst($form_state['values']['submitted']['first_name']);
}

But even if I succeed to modify them, the %value in email doesn't change.

Of course, I dpm $form_state tree to see where the submitted values appear in it and where the template's %value could find its origin. It appears on several levels:

$form_state['input']['submitted']['last_name']
$form_state['values']['submitted'][2]
$form_state['values']['submitted_tree']['last_name']
$form_state['complete form']['submitted']['last_name']['#value']
$form_state['webform']['component_tree']['children'][2]['value'] (but always empty)

I altered every variable but the email value still the same. I'm about to ask myself if it is actually based on one of those variables... If not, on what is it based? And how can I alter it?

Please excuse the looooong post but I wanted it to be very clear. I hope you will help anyway :-(

In hook_form_alter, add a new submit function before the other submit handlers, like so:

pwe_webform_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
  case 'YOUR_WEBFORM':
       array_unshift($form['#submit'],'pwe_webform_form_submit');
       break;
  }
}

And then write your submit handler, something like this:

function pwe_webform_form_submit($form, &$form_state){
  $form_state['input']['submitted']['last_name'] = ucfirst($form_state['input']['submitted']['last_name']);
}

You can intercept the submit handler with dpm($form_state['values']) calls, to make sure you're using the right array keys, etc.


modules for building ajax application and friendly urls? I'm building an ajax application using drupal 7, i found a module with some help ajax_nodeloader, but also i need load panel pages, views, etc.

Until now i'm overriding template theme file (zen) for ajax requests, and trying to use jquery address for good seo.

Also i will use jQuery UI Layout Plug-in on my template.

Which modules do you recommend ?

You shouldn't need an additional module, Drupal's AJAX framework should provide the needed features. For instance, it can easily be used to ajaxify links.

See the AJAX Example, AJAX Graceful Degradation and AJAX Commands example modules for API usages.


Outputting different class other than default for status messages I'm trying to theme status messages, I want to change the HTML of the message.

Drupal default is

message!

What I want to achieve is

message!

I have used theme_status_messages to modify 'messages' but how can I modify the type (e.g. 'status'/'warning', etc)?

This is current code

function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

I've changed this line

$output .= "
\n";

to

$output .= "
\n";

as you can see in my code above, but how can I change the options for $type?? I want my types to be alert-success, alert-error, alert-warning, rather than status, error, warning.

Anyone got an idea?

thanks!

This is just some good old PHP logic, is this what you're after?

function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );

  // Map our drupal statuses to bootstrap classes
  $bootstrap_statuses = array(
    'status' => 'alert-success',
    'error' => 'alert-error',
    'warning' => 'alert-warning',
  );

  foreach (drupal_get_messages($display) as $type => $messages) {
    // Grab the bootstrap class that corresponds to $type
    $bootstrap_class = $bootstrap_statuses[$type];
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

You could even put the $bootstrap_classes and $status_heading arrays together. But I separated them for simplicity


With search_api_solr, how can I apply an significant field based boost when using solr 6.x? I am using the solr backend for search_api on a drupal 8 site.

I have added the value of a taxonomy term reference field (field_promoted_search) to the index.

If an item of content has field_promoted_search with value matching the search term, I would like it to get a significant boost (eg ^1000), pushing it to the top of the search results.

Adding a high 'boost' value at admin/config/search/search-api/index/content/fields worked as expected when the server was using solr <6, but since moving to 6.1.0, this does not work as expected. This may be because search_api_solr/solarium is using a multiplicative boost rather than additive. This is not seem as useful to me as this multiplies the relevance achieved by other fields, rather than solely privileging field_promoted_search, though I am uncertain of this aspect.

I have tried adding a boost query for this promoted search field to the solarium query using hook_search_api_solr_query_alter. This requires me to pass each search key as a boosted query, and the effect seem to be affected by the order of the keys (and also my result does not end up top).

$keys = $query->getKeys();
unset($keys['#conjunction']);
// Boost results where search term matches promoted search field.
$boost_keys = [];
$boost_value = 1000;
foreach ($keys as $key) {
  $boost_keys[] = '"' . $key . '"^' . $boost_value;
}
$solarium_query->getEDisMax()->setBoostQuery('ss_promoted_search:' . implode(' OR ', $boost_keys));

When I attempt to use a boost function instead, I get an error from back from Solr and the query does not run (I have tried several functions).

// Format is: "funcA(arg1,arg2)^1.2 funcB(arg3,arg4)^2.2"
$solarium_query->getEDisMax()->setBoostFunctions("ord(ss_promoted_search,1)^1000");

Any advice much appreciated.

My reference for additive vs multiplicative boost methods is this very helpful article.

None of the API function provided by Search API and Search API Solr Drupal work properly. You can either check solarium docs or switch back to Solr 5 or Solr 4. Boosts work properly with Solr 5.x. Data type indexed is also important. Try indexing it as Fulltext field.


Dynamic Form Generation I need to create a web form that functions as a skills checklist. The user will select a 'specialty' from a drop down and based upon that selection, a list (with as many as 50 radio selections) will be presented to the user. I'm trying to figure out the best way to do this in terms of performance and maintainability.

1) I can write the skills list as a huge single form and then use jQuery to to show and hide the elements based upon the drop down selection. However, this may lead to very long page load times since there may be upwards of 1000 fields in the form.

2) I could gather the 'specialty' information at an earlier time, then load it at run time and based upon that, run another query for all the fields I will need from the database and build the form in a foreach loop. This means that there will be upwards of 30 queries in the form and an extremely complex submit handler to insert all of the entered data into the database.

Any thoughts on the best way to accomplish this? This is part of a large web application with many different sections and performance and maintainability is a huge consideration.

Thanks

Do you know that Webform now supports conditional form items from the now merged webform conditionals module?

You can then manage this form like any drupal webform and show/hide child pieces of the form based on selection rules. If your form is huge good luck the conditional page/logic settings can get huuuge and cumbersome.

If you want to this in php code yourself I recommend this tutorial using the Ctools based Multistep Form. I've made multi-step forms using native drupal node forms -- just the stepping logic is very ugly. This is clear and precise using a multi-step ctools form.

You could even show/hide stuff I believe on 1 page of the form usig FAPI #states API. A tutorial explaining #states provided by Shane Graham is on this blog post. Also review this for more complicated XOR type logic in forms here on d.stackexchange:
Multiple Values to Trigger #states


How can I alter a query adding an OR clause for a relational field? I have an "Event" node type with a number of fields: title, date, location, description, etc.
Because a number of events are similar, we added a "Parent event" entity reference field. Child events inherit fields (e.g. location, description) from the parent, if set.
We have a block that displays all of the events for a location, using a contextual filter. The problem is that the child events have an empty location – it is inherited from the parent event when we render the event page.
How can I adjust the view query to select all events with either the contextual location ID, or with a parent that has the location ID?

My solution:

Add a relationship for content referenced from the entity reference field.
Add a contextual filter for the entity reference field, using the content ID from the URL as the value. This includes events that have the location set directly.
Add a contextual filter for the entity reference field, using the content ID from the URL as the value, using the relationship. This includes events are related to an event that has the location set.

Unfortunately, the contextual filter WHERE group uses AND by default, so no results are returned, so we have to change the type in the WHERE clause.
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(ViewExecutable $view, Sql $query) {
  if ($view->id() === 'events') {
    if ($view->current_display === 'block_2') {
      $query->where[0]['type'] = 'OR';
    }
  }
}

If there are more contextual filters, you have to create a new OR where group with the fields, and remove them from group 0.
$group0 = &$query->where[0];

// Create a new OR group.
$group_id = $query->setWhereGroup('OR');

// Copy the conditions to the new where group.
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][1]['field'],
    $group0['conditions'][1]['value']
);
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][2]['field'],
    $group0['conditions'][2]['value']
);

// Remove from group 0
unset($group0['conditions'][1]);
unset($group0['conditions'][2]);


Is there a way to tell if the current page is a node? Without checking the URL I would like to know if the current page is a node page.  We plan on using URL aliases so we would like to not rely on the '/node/*' structure.

Is there some page variable or something that will indicate a node page?

\Drupal::request()->attributes->get('node');

Taken from here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3Arequest/8

Now the docs say to never use this function, but I have used this to determine what kind of page I am on.

There is another function, but I am not sure it applies in your case:

https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_is_page/8

At the very least, if you do not have an entity, you could mimic that in your code:

  $route_match = \Drupal::routeMatch();

  if ($route_match->getRouteName() == 'entity.node.canonical') {
    return true;
  }


Include Lead Forensics code in all pages I'm trying to include the tracking code Lead Forensics gave me. The code is:

I've tried creating a block with only this in the body, but it doesn't render in the page (when I check the generated code with 'view source code' on the browser, it isn't there). I don't know if it's the correct way to do it. Any idea? Thanks!

The better way to do this is by placing the script in the code for the theme.

You may be able to pretend this is another script and use a Drupal module that adds a script to the theme.

An issue you may be having by using a block is that unless you have the right permissions and also are careful to preserve this code as source, Drupal may try to alter what you enter for security or because you don't have permission to add a script.

We are a user/partner of Drupal and LeadForensics.


How to make exposed timestamp filter accept human readable date I'm using Drupal 8. I created a new content type (title, body, image, date).
The date is a timestamp field.

I used the devel module and the Realistic Dummy Content module to generate a test content for my view test.

I created my test view and chose the date as an exposed filter.

Here is my configuration:

And this is my view:

When I apply my filter, I want to say all contents having a date greater than my input:

If I test with 01/31/2018 - 02:54, nothing was changed!

But If I test with the unix value: 1538323253, my filter works well!

Any idea please to make the filter with human readable value?

I ran into this issue on D7. I enabled the views query and noticed that the values were being passed as human date to the query rather than timestamp.

So what I did was use hook_views_query_alter and converted them to timestamp.

Example code (D7 code)

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'list_employers') {
    foreach ($query->where[1]['conditions'] as $con_key => $con_val) {
      if ((strpos($con_val['field'], 'node.created = ') !== FALSE) &&
        empty($con_val['value'])) {
        $date = $con_val['field'];
        $date = str_replace('node.created = ', '', $date);
        $date = date('m/d/Y', $date);
        $start = strtotime($date . ' 12:00 AM'); // convert to timestamp
        $end = strtotime($date . ' 11:59 PM'); // convert to timestamp
        unset($query->where[1]['conditions'][$con_key]['value']); // remove default condition
        $query->where[1]['conditions'][$con_key]['field'] = 'node.created';
        $query->where[1]['conditions'][$con_key]['value'][0] = $start;
        $query->where[1]['conditions'][$con_key]['value'][1] = $end;
        $query->where[1]['conditions'][$con_key]['operator'] = 'BETWEEN';
      }
    }
  }
}


How do I incorporate an if-statement within my array to hide/display a link? Using the coding snippet below, how would I write the code to display the "Change" link only when the value in status is "A"?

I think i'm making this harder than it has to be, but the use of both drupal module structure and php are throwing me, since i am just learning module development.

The link showing in the array below appears at the end of each of my rows. I only want it to appear when the status equals "A".

Because this link is within this array, i can't figure out how and where to implement it. I just want an [if statement] like this:

if (drupal_render($form['status'][$key]['status']) == 'A',)
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}

so when the html table is displayed, the 'Change' link will only appear in the last column when the value of status is "A"

Can't believe I got the module working, but can't turn this link on/off as i want. See code snippet below:

function team_room_available_form($form) {
    $output = "No space available.";

  if ($form['roomid']) {
    foreach (element_children($form['roomid']) as $key) {
      $rows[] = array(
        'data' => array(
          drupal_render($form[''][$key]),
          drupal_render($form['room_title'][$key]),
          drupal_render($form['username'][$key]),
          drupal_render($form['status'][$key]['status']),
          l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
        ),
        'class' => $form['status'][$key]['#value'],
      );
    }

You can use below code snippets:

$field = $form['status'][$key]['status'];

if (strip_tags($field) == 'A')
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}


Merge two view in one page I have create two view

[1] testimonial_image
[2] testimonial_text

Now i want to display this both view in custom created .tpl file
.i.e

page--alltestimonial.tpl.php

[1] testimonial_image -> display all images of testimonial

[2] testimonial_text -> display all text description of testimonial.

How can i merge in one page?

This is the way I would approach this. I would create the two views using a block display. And place the two blocks display on the page created. Then you can create the custom page file and theme it. You can add the blocks using the default blocks page (admin/structure/block), or the context module.

In case you do not know how to create a block display, on your views UI page,


Change menu link title dynamically? I'm trying to alter the text of a menu item dynamically based upon certain variables.

I'm using hook_menu_alter like this:

function mymodule_menu_alter(&$items) {
  $items['toggle-review-process']['title'] = 'asdf';
}

Problem is, it does nothing. That menu entry is in there, but it has no title normally, and adding the key isn't doing anything. How can I change the text of this menu item dynamically?

Be sure too understand how the menu system works. The menu structure is only build once every time the cache is cleared. It is at that moment that hook_menu_alter() will be called. The results are then stored in the database. So simply implementing this hook is not sufficient to create dynamic menu titles. You can use it though to add a title callback that will be called every time a link to the menu item will be rendered. For details have a look at http://drupal.org/node/140311 (D6, but basic logic still applies to D7).

From the top of my head:

function mymodule_menu_alter(&$items) {
    $items['toggle-review-process']['title callback'] = 'mymodule_title_callback';
    $items['toggle-review-process']['title arguments'] = array(1, 'some string');
}

function mymodule_title_callback($arg1, $arg2) {
    $title = 'create the title';
    return $title;
}


Override core permissions used for visualizing a page Is there is a way (without using any external module) to override the core drupal 7 pages access permissions , for example and by default you will not be able to access /admin/structure/taxonomy/tags page without having (Administer vocabularies and terms) permission , but I want the users to be able to access it if they have for example (Edit terms in Tags) permission

You can make it by writing a custom module that implements hook_menu_alter().

function mymodule_menu_alter(&$items) {
  $items['path/to/change']['access arguments'] = array('permission name');
}


Drupal 7 and views: Get results from two content types and their own individual terms Drupal 7 and views

My issue might be hard to explain but here goes:

What I want:

show all nodes from two content types, that is tagged with their own individual terms.

What I have done so far:

I created a view that should display nodes from content type"names", and content type "name_auto" that is tagged with "job" the two content types, has its own term but the name is the same. (so job and job, could be different, like: bike and carpet)

My filter looks like this:
is published AND
content type is names, name_auto AND
term is job OR
term is job

What the issue is now:

the view give me zero results, but, if I remove one of the terms in filter, I get results but only from one of the content types.

I need to get results from both tagged with job from names, and job from names_auto.

Issue simplyfed (bottomline):

This scenario could just as well be content type shoe, tagged with bike, and content type house, tagged with carpet. and then I need all nodes of bike and house, tagged with their own terms.

What i think is wrong:

I think the view looks for the term in both content types, and then when it only find it in the one, it dont display any of them at all. But why does it do that? I have tried to change the order of the filters and nothing works.

I know it would be easier if you could just see the view, but its on a local site, if the view query, or an export dump would help, please let me know :)

I hope I have explained this well and that you understand my problem.

Your problem is that your query is using INNER JOINs but you need to be using LEFT JOINS.

As you found in the thread I linked to the easiest solution is to edit your filter criteria and check the reduce duplicates checkbox.


How do I turn on theme_debug? I want to use theme_debug to check which elements of a site use which .tpl files.

I have tried turning it on by using the drush command:

drush @mysite vset theme_debug 1

Though I do get the response theme_debug was set to 1, this does not seem to work.

Would anyone know if there is a way to get this working?

(Drush it's self seems to be working ok as I can use drush @mysite cc all)

Drush commands to control theme debugging:

Drupal 7

To turn it on: drush variable-set theme_debug 1
To turn it off: drush variable-set theme_debug 0

Drupal 8

To turn it on: drush state-set theme.debug 1
To turn it off: drush state-set theme.debug 0


Setting up a download page requiring a user to fill a form before downloading anything In the Drupal site I'm setting up, there's a Download page containing several links to download softwares.

What is the best way to "bind" the softwares to the page, put them anywhere online and place a direct link in the page?
Does anyone know a module that would show a contact form when a user clicks one of the "Download" buttons, preventing him from downloading unless he properly completes the form?  Our goal is to receive the contact information of any person downloading our software.

There is Webform Protected Downloads. But it will result to quite a different structure from yours. Webform Protected Downloads allows someone to download a "protected" file after filling out a webform. You can add more than one file and have the download links expire after a certain time.

When also looking for something like your issue I also found another module (don't remember the name) that added a page before redirecting you to a node. So maybe you could add a webform page to send the user before reaching the download page. But if he knows the link he could bypass it of course.


List all nodes by logged in user in a custom module I am creating a module in Drupal 7, where I need to have a list of all nodes created by a logged in user of specific content type. How can I achieve this? It is easy to do it in view but I need to do it in a custom module. Can anybody help?

Thanks

There is module available https://drupal.org/project/usercontent still if you want to do it in custom module then here is the code:

global $user;
  $node_query = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition("type", "node type")
  ->condition("uid", $user->uid)
  $node_result = $node_query->execute()->fetchAll();


Custom submit button text I have a  classic contact form. I can add for example some custom placeholder like this :

function my_theme_form_contact_message_about_your_project_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // placeholder
    $form['field_contact_name']['widget'][0]['value']['#placeholder'] = t('Saisir votre nom');

}

It works very well and I can also easily modify wrapper, name, etc.

But for a reason I can’t understand, I am not able to modify the text of the submit button.

Here is what I’ve tried among a lot of things and I think it should be the right thing (as seen on other answers) :

$form['actions']['submit']['#value'] = 'hello world!';

Here is the html of the button :

<button data-drupal-selector="edit-submit" class="button button--primary js-form-submit form-submit btn-primary btn" type="submit" id="edit-submit" name="op" value="Envoyer">Envoyer</button>

I use a custom theme based on Bootstrap theme.

Of course, I can do it with jQuery :

$('#edit-submit').text('lorem ipsum');

But I would like to know how to do it the Drupal way.

EDIT :

The solution is :

form['actions']['submit']['#value'] = 'hello world!';

It works on a clean Drupal install but not on the website I am currently working on.

Do you know why it is not working ?

Because it seems to me that you're playing the guessing game.

How about installing the Devel and adding kint($form) to inspect the $form array?

You will see its

$form['actions']['submit']['#value'] = t('Post Comments');


How to install Social Auth LinkedIn PHP Library with composer for Open Social Drupal module? How to install Social Auth LinkedIn PHP Library with composer for Open Social Drupal module ?

I try to install Open Social (https://www.drupal.org/project/social) but I can't because I can find how to install the LinkedIn library with Composer.

I already installed successfully Google, Facebook and Twitter library with Composer.

"Social Auth LinkedIn module requirements
Not installed
Social Auth LinkedIn requires LinkedIn PHP Library. Make sure the library is installed via Composer."

Thanks.

According to the composer.json of that module, you need happyr/linkedin-api-client. So to install that with Composer, from the root of your Drupal project run:

composer require happyr/linkedin-api-client:1.0.0

Since that library has dependencies too, you probably need to install them too. Basing on the documentation, you could need to execute the following too.

composer require php-http/guzzle6-adapter
composer require guzzlehttp/psr7 php-http/message


How can I change the file system from public to private? I have been using public file system has the upload destination for file field. I want to change public file system into private file system. I cannot change it it showing below error.

  There is data for this field in the database. The field settings can
  no longer be changed.

I cannot select the upload destination. How to change the file system for file field in drupal 8

I have no idea why the UI prevents from doing that. It's not actually anything in the storage, it's just the default for new files.

What you need to do is edit the config file directly, which is named field.field.$entity_type_id.$bundle.$field_name, for example field.field.node.article.field_image.

You can do that using drush cedit, or single export and then import it again from the UI, or do a full config export and import it again after changing that file.


Is in Drupal the way to cache whole region? I have a region which contain several blocks, each of them is changed rarely. I want to cache whole region (for each user), but i can not find the solution. Watching into the sourses gives no result too. Is anybody who knows is it possible, and how to do that? Thank you for every answer!

Rather cache the individual blocks. There is a module for that: Block Cache Alter

  Alter cache settings per block. Cache settings per block are now set
  in code, but if you don't like the default - usually none - you can
  now easily change this. Install this to speed up block rendering for
  authenticated users.

It will give you the optioon in the Block UI to alter the cache settings for that block:


How do I provide a "delete" link for comments? For example, if I am posting a comment, how can I delete it?
How delete links should be given?

On Drupal 6, users with the permission of administer comments and create comments are able to delete comments. The code that adds the delete link for comments is contained in comment_links().

  if (node_comment_mode($comment->nid) == COMMENT_NODE_READ_WRITE) {
    if (user_access('administer comments') && user_access('post comments')) {
      $links['comment_delete'] = array(
        'title' => t('delete'),
        'href' => "comment/delete/$comment->cid",
      );
      $links['comment_edit'] = array(
        'title' => t('edit'),
        'href' => "comment/edit/$comment->cid",
      );
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/$comment->nid/$comment->cid",
      );
    }

Similar code is present in Drupal 7 and higher.

Third-party modules allows other users to delete comments.

Comment Delete allows the comment authors to delete the comment they created. The module is for Drupal 6.
User tweaks, a module I maintain, allows the comment's authors to delete their own comments; it also allows users to delete any comment, or any comment associated with nodes of specific content types. In both the cases, the user needs an additional permission, but not the permission to administer comments. The module is for Drupal 7.


Module to list menu_router / path debug info? Every now and then, mostly when looking at a new site, I find myself wanting to know

What's the source of this particular page?

Usually, I end up starting to dig in the menu_router table, and possibly also alias tables. Is there a module that will be helpful in finding and displaying this, and other relevant, information for me?

I'm not sure there's a module specifically for that, if anything I think it would come under the domain of Devel as you mentioned in the comments. I haven't seen anything like that in Devel before though.

Getting the router item for the current path itself is very easy:

$item = menu_get_item();
$callback = $item['page callback'];
// etc...

You could just wrap that in a hook_init() and dpm() it out for a quick solution, or maybe build a patch up for Devel.


How to invalidate cache contexts? When updating my module from Drupal 7 to 8 I bumped into the concept of cache tags and cache contexts. After reading both documentation pages, I have come to the following conclusions:

A cache tag is used to tell Drupal 'what is in the cache', so the cache can be invalidated once something in the cache is updated. This is mainly used for entities and configurations.

Cache contexts provide... context (duh), so the exact same set of tags (entities) can exist under multiple circumstances with a different cache. Examples for contexts are languages and themes, where the same set of entities need to be rendered differently.

Now I did find how to invalidate cache tags:

  Cache tags are invalidated using cache_tags.invalidator:invalidateTags() (or, when you cannot inject the cache_tags.invalidator service: Cache::invalidateTags()), which accepts a set of cache tags (string[]).

But I cannot find how to invalidate cache contexts...

The reason for asking this is because I am in the process of converting the white label module to Drupal 8. (This module allows the site name, logo and color scheme to be overridden initially based on a url token, but a session variable for subsequent pages.) So I thought such a whitelabel token would make up for an excellent cache context. However (probably on very low frequency) the parameters (name, logo, etc) could change. Thus I should invalidate the cache context.

Can I invalidate cache contexts? Or are there other options? I have thought of using a combination of both tags and contexts, but I am afraid the amount of combination will go through the roof...

Cache contexts cannot be invalidated.

Cache tags describe data dependencies. Data can change. When data changes, the associated cache tag(s) are invalidated, causing the cached results to get invalidated and then recomputed.

Cache contexts describe context dependencies, which means they describe variations. It's very much like HTTP's Vary header. Cache contexts usually describe input from the request (such as the URL or parts thereof, the requestor's IP address, the associated user, the associated session, or even the matched route), but could also describe some global state such as which day of the week.

You could create a custom cache context for your use case, but it'd be the combination of the url.query_args:whitelabel (assuming ?whitelabel=foo is what you meant) and session cache contexts. But it'd be much simpler to instead just associate those two existing cache contexts!

(Note that using the session cache context makes things extremely uncacheable, because it causes a unique variation per session!)


drupal.js is loading before jquery.js I have face this problem often in my drupal site. The drupal.js file is loading before jquery.js, so i get the "uncaught jQuery is not defined" error.

I have been using memcached also in my site.

But I can fix the error by the following steps

Restart memcached
Restart Apache
Cache clear
Run the cron

After doing the steps the jQuery is loading properly.

Now, i want to know the reason why the drupal.js loading before jquery.js?

FYI : This is happening, When I enable/disable any modules/features through UI

May be because of cache that might cause

Check if you installed jquery_update module
in themes info check if there you have declared jquery

3.check if in any module hook_init() you are adding your js with weight.

if you install jquery update module you dont need to add jquery plugin in info file

if you have any clarification regarding the js weight and so on read the following links will be helpful

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

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


How to get author_picture URL from a template? How to get author_picture URL from a template ? I know that I can use {{ author_picture }} to display the picture; however, all I need is the URL and not the picture. I'm trying to get this URL from the template node--article.html.twig

Here is a similar question but this is different because is base on the field_image. Getting the image URL from a field_image on a node and all I'm trying to get is the author picture.

URL FORMATTER module

This module add a url formatter for image field. Then you can output image url directly.

Once enabled, go to your user manage fields, and change the picture field formatter to url.
{{ author_picture }}  // will display url instead of picture

If you are using views, views will give you an option to change the format to url.


Show Colorbox or other Modal Window on page load I'm working on a module that shows a modal window of some sort (I've used Colorbox so far, but I'm not attached to it) upon page load. I've gotten to the point where I need to make it display on page load and am now a little bit stumped how I'd do that -- any ideas? Using D7, btw.

Thanks!

I figured it out, it's pretty easy. See below:

function popupmessage_init(){
    $colorbox_js = 'jQuery(document).ready(function(){ jQuery.colorbox({html: "
Your Message Here
"}); });';
    drupal_add_js($colorbox_js, 'inline');
}


How display node author roles at node.html.twig My user case is:

Extlink module can add exception classes to avoid processing some links.

I want some external url links on nodes whom author belongs to a special role (premium) can be mark with a class (for example with premium role name) to set an exception at external links module.

Well, at node twig template I can render node owner name, using this: {{ node.Owner.name.value }} but I don't know how render author roles.

You can get roles in twig using:

{%  for role in node.Owner.roles %}
    {{ role.entity.label }}
{% endfor %}

Update :
If you want to use roles in classes i recommended you to use clean_class filter to get the clean css class from roles instead of the code you post in comment use this:

   {% set custom_classes = [] %}
    {% for role in node.Owner.roles %}
      {% set class_role = role.entity.label | clean_class %}
      {% set custom_classes = custom_classes | merge([class_role]) %}
    {% endfor %}
    <div {{ attributes.addClass(custom_classes) }}>
      {{ content }}
    </div>