Wrong path when moving from MAMP multisite to remote website I have different sites in MAMP, each of them being located in ../htdocs/
i.e. ../htdocs/site1, ../htdocs/site2, ../htdocs/site3, etc.
In some page of site1, I have something like

Petit retour aux sources : comment tout a commencé

Le golfe du Morbihan en 2008

En 2009, cap sur l'archipel de Glénan

Cette année (2010), c'est Bénodet !

Et pourquoi pas Stockholm en 2011 ?

2012, l'année des cairns du golfe du Morbihan

En 2013, tranquillement sur la Vilaine...

Golfe du Morbihan « agayne » en 2014

2015 : encore le Golfe mais en famille

Then, I move site1 to web provider and ../htdocs/site1 becomes www (root of the web site).
And, of course, URLs such as "/site1/node/36" don't work anymore :-(
How can I solve that?

It sounds like in MAMP you're using one domain, localhost, instead of three separate domains for three separate codebases.

You should set up three domains in MAMP and then you can use relative urls such as "/node/50" instead of "/site1/node/50".

Then your config would be in /sites/default/settings.php, with an included settings.local.php that is git excluded to use different database credentials between the local and production sites.

Multisite is a different set up.

You wouldn't have three separate codebases, such as "/htdocs/site1", "htdocs/site2" and "htdocs/site3".

You would have one codebase such as "htdocs/mymultisite".

With a non-multisite set up with three separate codebases, you would create three hosts in MAMP and then point each docroot to that site's docroot, for example, "/htdocs/site1", "htdocs/site2" and "htdocs/site3".

For a multisite set up, you would use one codebase (such as "htdocs/mymultisite" and create a sites folder for each domain.  First, you would copy example.sites.php to sites.php in the /sites folder of your repo. Then for each host, you would set up a folder with a separate settings.php, for example:

/sites/site1.local/settings.php
/sites/site2.local/settings.php
/sites/site3.local/settings.php

with the folder name corresponding to the domain set up in MAMP.

(With a non-multisite set up with separate codebases, you can just use the /sites/default/settings.php)

For both separate codebases and hosts in mamp, and for multisite with sites folders, it should work to visit each domain, such as site1.local in your browser, the urls will be relative to that URL.

If you are using multisite, when you want to go to production, you can set up a folder for production.  Set up a folder for production:

/sites/mysite.com/settings.php

There is a lot of information about setting up multisite Drupal.


Inherit/override core module I have made a single tiny change to a core module. I copied it into my site modules directory. I am curious as to whther I can simply override it's hook_menu() method in my copy so as not to carry over all the additional code which the core version provides?

Similar to theme inheritance, do modules support anything similar?

There's no inheritance for modules, but much of the functionality they provide can be altered using hooks (search this page for _alter and you'll see the ones core provides).

Specifically for items defined in hook_menu(), you can use hook_menu_alter(), e.g.

function MYMODULE_menu_alter(&$items) {
  // Replace the page callback for the foo/bar path
  $items['foo/bar']['page callback'] = 'MYMODULE_some_function;
}

If I've misunderstood and you mean you literally want to inherit from a module, like subclassing a class, and just change a couple of things, then unfortunately not. Copying the module is the way to go; you'll need to change the names of all the functions so they don't collide with those in the core module, and change paths/cache keys/variables for the same reason.


Warning: in_array() expects parameter 2 to be array, string given in _drupal_http_use_proxy() (line 1100 of /var/www/html/includes/common.inc) Whenever I add any content on my website, I get this warning.

  Warning: in_array() expects parameter 2 to be array, string given in
  _drupal_http_use_proxy() (line 1100 of /var/www/html/includes/common.inc)

I am not sure why it does that, and how do I solve it?
Can anyone help?

PS: I don't know what tags should I use for this question.

EDIT1: Executing

  dpm(variable_get('proxy_exceptions'));

This is the code for _drupal_http_use_proxy

function _drupal_http_use_proxy($host) {
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

The status message warns that $proxy_exceptions is not an array.

You can configure this setting on your settings.php file, this way:

$conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

Have you changed this variable to anything other than an array?

 $conf['proxy_exceptions'] = '127.0.0.1'; // For example

Maybe there is a contributed module which do this...

Try to insert a dpm on $proxy_exceptions or execute this on /devel/php  to show the value of this variable:

dpm(variable_get('proxy_exceptions'));

If you want to reset this variable:

variable_set('proxy_exceptions', array());

or

variable_del('proxy_exceptions');


Having a hover or mouseover effect in views for drupal 7 I am creating a staff page for a project, and I am putting an image (suing views) that links to the staff members page.  What I thought would be really cool is if when you scrolled your mouse over the image it turned into the name of the person.  I am not sure at all how to do this, and after several hours of searching I need some help.

Thanks in advance.

You can do a simple thing like this:

HTML

   John Doe

CSS

a.person {
    border: 1px solid #ddd;
    display: block;
    height: 100px;
    overflow: hidden;
    width: 100px;
}
a.person:hover img {
    display: none;
}
a.person span {
    display: block;
    text-align: center;
    margin: 20% 0 0;
}

Fiddle:
http://jsfiddle.net/fXnmr/

If you want fade effects etc you need to go the Javascript/jQuery route.


Full HTML Block Security I'm currently considering using a free theme for my a Website, they use bootstraps Carousel to render a slideshow/banner, and their advice on how to make that slideshow work is to embed HTML in a block an set it to Full HTML. Tutorial here

My question is if there are security risks attached to having a Full HTML block?

Or does Drupal (more specifically 8) inherently protects blocks with code/snippets in?

If so, to which extent should one utilize it, instead of e.g. building a custom block?

In general, you should probably only give Full HTML access to only your most trusted users (which may only be the site administrator).

Now the example you linked to was intended to be used in a block.  Block administration is also something that will likely only be done by your site administrators.  Every site needs an administration plan, so it's fair to ask, can the people entrusted with block creation also be entrusted with the use of Full HTML?  If so, no need to create a custom block.

Alternatively, the example code is fairly benign, so you could add a Text Format that allowed for the use of those tags & attributes (admin -> configuration -> content authoring -> text formats and editors).  I often create a Text Format called Advanced HTML that allows for most tags but I don't include any of the potentially problematic tags like script, object, style, etc.

To produce that carousel, looks like you would minimally need the following:

<div id class role data-*><ol class><li class data-*><img src alt><h3><p>


Are blocks a OK way to model a theme? I am trying to build a new theme. Are blocks a OK way to model a theme? Some sites seem to recommend them, others say that they should be avoided.

Blocks are an important part in Drupal, but you don't model a theme with them.
Blocks are implemented from modules, using hook_block_info() and hook_block_view() (together other hooks); what themes implement are regions where those blocks are rendered. A theme cannot decide not to implement regions, since there are some regions Drupal requires from themes.

Eventually, a theme can alter how a block is rendered, but themes are not modelled around blocks.


Drush make project versions when there is only dev available? Using Drupal 7.x.  If I specify a drupal module project in my make file with no version, for example:

projects[] = geocoder

and the project currently only has a dev version available (e.g. geocoder module as of November 29, 2011):

will make grab the dev version?  Or do I have to explicitly specify the dev version?

If the project has both a stable release and a dev version available, you can force usage of the dev version using something like

projects[geocoder][version] = 1.x-dev

You can also directly pull the project from its Git repository with

projects[geocoder][download][type] = git
projects[geocoder][download][url] = "http://git.drupal.org/project/geocoder.git"
projects[geocoder][download][branch] = 7.x-1.x


Create a user friendly workflow to create banners I'm looking for an easy way where my users can add banners on a page. There are many options here (View Slideshows, Rotating Banners,...) but what I want is a user to be able to do this as simple as possible.

The ideal scenario would be:
Create content - upload image - type a title and select the pages on which it should be displayed.

Basically, my (absolute n00b users) must be able to add a banner to any page available without any knowledge of views, panels,...

I've experimented with node references and templates, but no luck so far.

Is their anyone with the same situation and found out a great solution?

The simplest would be a content type with an image field and a text field. The image field would be the banner and the text field would be the path on your website where it should be displayed.

Create a view that filters on that content type and has the image as the field it displays.  Put the path field as an argument.  Configure it to return only 1 item.

In a block, call that view using $_GET['q'] as the argument.

Image is displayed in the block.  Display this block on your page where you want your banner.

Don't like blocks?  Put this in a page_preprocess() hook and assign the view output to a variable and put this in your page where ever you want it.

Get fancy?  Randomize the sort so if more than one of these content types has the same path a different image is displayed on each page load/reload.

Get fancier.  Use the views_nivo_slider module ( http://drupal.org/project/views_nivo_slider )


Rest login cookie token explanation When logging in via a POST to user/login?_format=json
I'm sent back a response that looks like this

{
    "current_user": {
        "uid": "233",
        "name": "test"
    },
    "csrf_token": "XXXXXR5HQwidW7CKIDL52tOg4JGKi7Pa-j87KKlr8Mg",
    "logout_token": "XXXX-G35feFznaapSggzlUQEhYKXqom6yYVDwCH5Zxc"
}

I'm also sent back a session cookie that looks like this

name: SESS95f37088bf4f23c4304d24270b7xxxxx

value: rqAupOwS2ieqwClBkwEaWj8-ywLqnQEcAL2xOG-xxxx

When I send a GET to session/token

I receive a seperate token that looks like this _XXXXXnX8k_prCNfdrHp6XeHOUx7DcuouqiLKBBn-Go

I understand that the logout token is used with /user/logout in order remove the cookie and log the user out.

My questions are as follows.

The Cross Site Request Forgery token doesn't seem to be required by any of my end points by default. Is this something I should have the backend require them on specific paths using _csrf_token: 'TRUE' (and be passing with each request using the X-XSRF-TOKEN header?) Is this automatically passed with the cookie by chance?

The same question goes for the session token from session/token should this be being passed with each request, or in general what is the purpose for this token? I've seen this token referenced in docs as another CSRF token. If this is the case why is it different than the one provided by the login POST?

You are logging in correctly by POSTing the username and password. After you've logged in, a Drupal session is created.

The csrf_token can be used to authorise future requests requests by sending it as a header:

X-CSRF-Token: XXXXXR5HQwidW7CKIDL52tOg4JGKi7Pa-j87KKlr8Mg

You can send this instead of a cookie if you've configured the backend to allow it. I've only used the CORS contrib module as CORS in Drupal core doesn't have the same flexibility.

  I understand that the logout token is used with /user/logout in order
  remove the cookie and log the user out.

Correct.

Also see my answer here: https://drupal.stackexchange.com/a/235712/34673


Views: What setting is available in Views to hide or skip the first entry in a multi-value field? (example skip first image) On my site, I have created an "Images" field with "unlimited" values. I have used "image delta=0" to show only the first image as the main gallery image. I then created a grid with a contextual filter of "content: nid" to display up to 10 of the images in that field. I would like to now hide the first image from the output, so that it isn't repeated with the first/main image on the page.

I have the contextual reference working well, but I haven't been able to figure out how to skip the first image. I tried a playing around with the Image Delta settings "=1", assuming that this means to increment by 1, but when I save, my view is empty.

I'm sure this is straight forward, but I have come up empty in my attempts (literally) and searches.

Thanks,
keb

I vaguely remembered doing this in a Views tutorial and remembered it was a control located within the center region of the Views interface.

Turns out it's under "Pager": Use pager: Display a specified number of items >> "You may also adjust the settings for the currently selected pager"

Click setttings and you'll be able to add an offset.


How can I prepopulate a field when creating a new node with the values from a field collection? I am creating an inventory management system in drupal. I have two different content types: and item and a purchase order.

An item has a name, style code, Colors (this is a field collection with a color name and color code), and a range of sizes (3 to 15 for shoes and XS to 4XL for shirts). Some items don't have colors and some don't have sizes.

In a purchase order, there is a purchase order number and any number of items ordered (a field collection with an entity reference to the item, a field for the number of items ordered, and field for the number of items received). Each item ordered will have one color (one of the colors that the item is available in) and any number of the sizes that was selected in the given item.

My question is how I can populate the color selection (probably a dropdown) with the colors that are in the field collection of the selected item (entity reference). I would also need to populate the sizes list with the sizes that were selected from the item, as well.

I am still pretty new to drupal, and I realize that I may be going about it the wrong way or that I may not have explained everything that someone would need to know to help me. But I am open to new ideas or different solutions. I haven't done much module development, but I would be willing to learn if needed.

You can try and look at this module. It allows to have corresponding node references and hence if you select something from one node, you can prepopulate the other node as well. http://drupal.org/project/cnr


Get all enabled viewmodes of a entity/bundle I need to get all possible viewmodes of a specific entity/bundle in D8.
Currently I have this:

$viewmodes = \Drupal::service('entity_display.repository')->getViewModes($entity_type);

This shows all viewmodes on an entity, it doesn't filter on bundle.
Also, the default viewmode is never included here.

Anyone knows a better way?

Cheers, Tom

What @googletorp said is correct. But there is a concept of "enabled" view modes, just not like you're apparently expecting.

Enabled view modes are view displays. Enabling a view mode for a given bundle creates a view display which then stores the formatter configuration.

Same for form modes and form displays.

And I think \Drupal\Core\Entity\EntityDisplayRepository::getViewModeOptionsByBundle() will kind of give you what you're looking for. The view modes for which the given bundle has a view display.


Number Slider for exposed filter using Drupal 6 I need to expose the number fields in views with the range slider, for example : Min- 421 and Max 780.

I found this slider Field module, but it support only for Drupal 7. any idea for Drupal 6 ?

I don't want to use Better Exposed Filter module, because the plugins mentioned in the documentation are not there and hard to configure the options. Looking for any other alternate way.

Better Exposed Filters has that functionality built in

  ...

  What else can I do with BEF?

  Use the jQuery Slider widget for greater-than, less-than or in-between types of filters

I've never used it for D6 but the project page doesn't mention the slider being missing from that version or anything so it should be there.


Profile2 taxanomy and views i have a problem considering drupal 7 and views.
i have a taxonomy view the lists al the terms:
http://conversal.w0p.be/feesten

Now i have used profile2 for tagging my profiles an made a second view that listens to an argument /feesten/%

But now if i want to get all the http://conversal.w0p.be/feesten/evenementen
profiles i et the page that gives the detail of that term and not the profiles.
Ive googled a lot and can't find any good answer related to this :s

THNX in advance !

Have it working now :)
made 2views 1taxonomy view and 1profile view and renamed the taxonomypath to something else.
and rewrite the taxonomy-name url in the taxonomy view


Loop through taxonomy parents How can i loop through taxonomy in drupal 8.
I found this static function but TID is required, how can i loop through all taxonomy without using TID?

Drupal::entityManager()->getStorage('taxonomy_term')->loadAllParents($tid);

I think you are using the word "parent" incorrectly.

The terms of a vocabulary can be sorted in a tree. And the parents of a specific term are the ones higher in that hierachy. So, if you want all parents of a term, of course you need so say, which term and give its id as $tid.

However, if you just want all terms of a taxonomy, you can use loadTree($vid) instead. $vid is the id of your vocabulary.

If you want to load all taxonomy terms, ignoring which vocabulary they belong to, then this is the best solution:

$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple();

Then, to access the term data do

foreach ($terms as $term) {
    $tid = $term->id();
    $vid = $term->getVocabularyId();
    $name = $term->getName();
}

If all you need is the ids of all the terms, this is enough:

$tids = \Drupal::entityQuery('taxonomy_term')->execute();


Change the error message "An illegal choice has been detected. Please contact the site administrator." When a user submits a content that has a taxonomy selection field and NOT make a selection, then the referenced error appears.

Now, I know exactly when, how and where the message appears, is there any way to change it so that it's actually useful for the user (i.e. "You did not select a category."), and not merely a cryptic error message that could potentially freak the user out?

This is to add onto Letharion's answer. Using the same principle, we can also check for error messages to replace in the validator.

function MY_MODULE_form_validate($form, &$form_state){
    $errors = drupal_get_messages(); // (dpm()'s has to go AFTER this line--they get cleared)
    foreach ($errors as $type => $id) {
        foreach ($id as $message){
            // Loop through individual messages, looking for ones to remove or replace
            if (test_for_invalid_error($message)===FALSE){
                drupal_set_message($message,$type);
            } elseif (test_for_invalid_error($message)!==TRUE){
                drupal_set_message(test_for_invalid_error($message), $type);
            }
        }
    }
}

function test_for_invalid_error($message){
    if (strpos($message, 'An illegal choice has been detected. Please contact the site administrator.') !== false) {
        return t('Please select a category!');
    }
    return FALSE;
}

This will not only add your own custom error, but replace the "An illegal choice" error. Isn't it neat? Yay!


Styling the layout of a content type I am using drupal 8 and I am trying to get the layout of my content type "jacuzzi" to go from this:

To this

As you can see, I am using bootstrap. What do I have to change (css or tpl or something else?) to group the text fields and add the right classes?

Thanks in advance

You can use node--(machine name of contenttype).html.twig to achieve this thing.

{{ content.field_machinenameofimage }}

{{ content.field_machinenameofotherfields }}

Replace the {{ content }} by the above code. And change the above code how you want to achieve.


How to hide set up database step in a installation profile? In a installation profile, how do I fill values for Set up database step programmatically and hide it so user doesn't need to fill the form?

How to do the above action for the Select language step?

You wanted an example -- which is basically showing you how to do it. From the docs I supplied and the help others that gave you cookie crumbs provided should have lead you towards a solution, Other than saying "show me" all the code.

A working profile example is in this GIST, you make a shortprofile directory in your /profiles directory and select "Short Profile" from the Installation screen. This is the "long way" to do this, there is a shorter way in-theory ... see my code comments.

Be sure to change the $databases['default']['default'] in line 47 of .profile to the existing database credentials that will work in your environment. Look for my comments in the code to change the db credentials and db password (line 125 of .profile).


Can Views output "raw" text field data? I have a view that shows the Body field of several book pages.  The text format for these pages includes the Markdown filter.

I want to export the body field data as the original markdown without processing it into HTML.  (This is an admin-only view that I want to use to collect the markdown-formatted text from several book pages to make an ebook.)

Is there an option within the Views module to output the "unprocessed" markdown?

Yes. Under the Rewrite results > Override the output of this field with custom text option, one of the Twig tokens you can use is {{ $FIELD_NAME__value }} (e.g. {{ body__value }}). This will have views render the field in its raw, pre-filtered, format.


How to include js library from /sites/all/libraries in twig template with attach_library? According to https://sqndr.github.io/d8-theming-guide/libraries/libraries-and-twig.html, you can include a library within twig template to only load it on specific pages using {{ attach_library('theme/library') }}. This appears to be for libraries included in mytheme.libraries.yml.

Is there a way to use this to include a library from sites/all/libraries? It seems silly to add a library to my theme folder when it is already available globally.

There was likely a module that required the files in question to be added to the sites/all/libraries folder.  You could review that module on how it adds those files as libraries.  Check that module for a .libraries.yml file or check to see if the module implements hook_library_info_build().  Once you know the how to reference the library, you should be able to use the same reference in your twig template.

As an example, the Easychart module (https://www.drupal.org/project/easychart) has both a .libraries.yml and implements the hook in it's .module file.  To reference one of those libraries you would use "easychart/easychart.render" or "easychart/lib.highcharts"


How to add a Rules Condition to only allow voting for users with at least 30 user points? I want to put condition when userpoints>=30, then user is able to vote.

For this, I did following steps-

ON event- "User votes on a node" the condition selected is "Compare current Userpoints" and in the condition part put ">=30".

I am using following modules: Rules, User Points and Vote Up/Down.

You should try to implement the hook form alter Drupal API: hook_form_alter

Within the hook_form_alter you can validate, if the current user has more then 30 Points and disable the voting widget if the value is below 30.


Possible to show 'Request new password' tab with LoginToboggan 403 login page? I'm using the LoginToboggan module to password protect a page.  A login area successfully shows on the page in question, but there are no tabs, only a username and password box.

Here is what it looks like:

This is what the I want it to look like (screenshot taken from /user on same site):

I can't see any option for it in the configuration (here is what I have currently as config under the login section):

I can't find anything relating to this in the LoginToboggan issue queue or via google.  Has anyone experienced this? Is there any way I can make the tabs display?

P.s. I was going to log a support request on the issue queue of LoginToboggan but I saw the following statement:

Support requests will only be responded to if they deal with the development of the
module, or possibly its use with another module. End users should consult the forums or
IRC chat rooms or hire a consultant for support.

When a page is forbidden, logintoboggan pulls the login form via the following code:

drupal_get_form('user_login');

For some reason, which I haven't figured out, calling user_login doesn't include the links to 'reset password' and 'create new account'.  I've submitted a patch to the module, which adds an option in the configuration to include the 'forgot password' and 'create account' links.  It uses user_login_block instead of 'user_login' to render the form with the 'forgot password' and 'create account' links.

Here is a screenshot of the admin area:

Here is a link to the issue that contains the patch: Add lost password link to 403 login form

Edit: I think the reason that the tabs for 'Request new password' and 'Create new account' aren't displayed, is that they are MENU_LOCAL_TASK's on the 'user' page.  Logintoboggan redirects to 'toboggan/denied', so the tabs aren't being pulled in.


Adding a "my messages (x)" link in the block template file I have installed Privatemsg, and I need to output the "My messages (x)" link programmatically in block.tpl.php.

I tried the following code, but it only prints "My Messages", when I need a counter for the new messages:

print l('My messages', 'messages');

The module already contains a block that does something similar: "New message indication". You can use that block and alter the output if needed by overriding the theme_privatemsg_new_block() function.


Dynamic view with a field matching a role of User in Drupal 7 On my site, the nodes are restricted based on user's role. Admin selects any number of roles in a field (field_role) when creating a node and if any logged in user's role matches one of the selected roles, he/she can access the node.

But this only works, when user clicks on the node and then either can see the node or see an access denied warning.

The problem is that I just don't wanna show the node, if the access is restricted. The nodes are shown through a view as a listing on home page and I am just not sure how to tell the view that if the logged in user doesn't have any of the role selected in  "field_role", then filter out the node from the listing.

Any help.

Add field_role in view and hide it.

Now create a custom php filter using Views PHP Filter

Get the current user role and compare it with field_role value. Following is the sample code.

<?php
  global $user
  $account = $user->uid;
  $roles = $account->roles;
  $field_role = $data[field_role]
  //$data is available in php views filter
  if(find user_role in field_role) {
    return false;
  else {
    return true;
  }
?>


drush cannot find omega help commands I've installed Omega 4 but drush cannot find the omega help set or the omega command set -- nor can I. Where are these supposed to be located? Without them, I cannot easily create a subtheme with drush, or do any of the drush goodies in omega 4.

Drush can only find additional commands in themes and modules if it knows where your Drupal site is.  There are several ways you can do this; cd to the directory that contains your settings.php file, or pass --root and --uri on the commandline to point at the Drupal Root and site uri (e.g. mysite.com), or define a site alias and pass @alias on the command line.  See the Drush README file on the github project page for more information.


Problem with aggregated CSS/JS on flush cache We are using Varnish and Pressflow (v6.30).  Every time we flush cache in Drupal, we encounter problems where browsers can not get requested CCS/JS aggregate files as they do not exist.  We have found that if we flush Drupal cache and then immediately flush varnish cache, problem is fixed.

Anybody else had this issue?   And is there a module (purge or similar) which automatically handles Varnish flush cache with Drupal cache?

https://drupal.org/project/advagg might be the solution you're looking for.

If you want to flush both caches this will help https://drupal.org/project/expire


How can I render multiple values which belong to the same field? I have a content type with a text field "Person", which assumes up to 3 possible options. I am trying to render a block, where I would display this field with three presons.

if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
  $node = Node::load(\Drupal::routeMatch()->getRawParameter('node'));
  if($node->bundle() == "people"){

    // CONTACT
    $render = array();
    if($field = $node->field_contact_person->first()){
      $field = $field->getValue()['value'];
      $render['#markup'] = '
'.$field.'
';
      $render['#prefix'] = '

'.$this->t('Contact person').'
';
      $render['#suffix'] = '
';
      $block['#markup'] .= render($render);
    }

  }
}

The issue is that it fetches only first value. How can I fetch all values and render them in the block?

Just don't use first() - that gets the first item.

if ($field = $node->field_contact_person) {
  foreach ($field->getValue() as $value) {
    $item_value = $value['value'];
  }
}


Avoid username output as a class of an article tag Drupal 7 generates a username class for the article tag, something like : class="node node-page node-published node-not-promoted node-not-sticky author-username odd clearfix".
I'd like to avoid to have the username output in the code for security reason.
I have tried the userone module, but it doesn't work for this.
I am thinking about some Jquery code, but a better way would be to avoid the username to be output at all.
I was looking in the core modules but I didn't find the php file that generates this author-[username] class.
Any help?

I think you can blame Omega for that one, in omega_alpha_preprocess_node() you'll find this:

$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name);

I think you've got two options:

Remove that preprocess function altogether, using hook_theme_registry_alter(), and duplicate it into MYTHEME_alpha_preprocess_node(), minus the offending line.
Implement MYTHEME_alpha_preprocess_node(), search through the $vars['attributes_array']['class'] array, and remove it from there.


Import content using the "Default Content for D8" module I am using Default Content for D8 to import content on my site.

After Profile installation completed, I enabled my custom default content module with contents sample json for node entity [my_module/content/[entity_type]/anything.json].

I get the following error:

  Symfony\Component\Serializer\Exception\UnexpectedValueException: Type
  /drupal-pro-8/rest/type/node/article does not
  correspond to an entity on this site. in
  Drupal\hal\Normalizer\ContentEntityNormalizer->getTypedDataIds() (line
  239 of
  \drupal-pro-8\core\modules\hal\src\Normalizer\ContentEntityNormalizer.php).

And the node isn't imported...

What have I done to try to fix it:

. Ensure I have the article content type;

. Flushed all cache;

. Tested in different browsers;

. In the module page it says all tests were passed with the following conditions: PHP 5.5 & MySQL 5.5, D8.5 6. I started to use the same version of PHP, MySQL and D8.

After all this, the same problem keeps on appearing and I can't understand why this happens. May I missed something. Any help.

Thanks in advance.

This will be probably resolved by setting the _links type href domain as http://drupal.org (the default links domain used by default_content module) in yor .json files to import, instead of drupal-pro-8 that was set form the site you exported?.


How to use traditional (national/native) dates and calendars? How can use non-Gregorian dates and calendars?

I adjust Drupal setting to my native language (fa) and native location (Asia/Theran) but month name and number of years also in Gregorian yet (however there are translated to my native language-persian).

I already use format_date() or date() in theme files, but this function is not locale-aware, which means that it always outputs English language data, such as day and month names and ordinal number suffixes.

I want to show the month names in the native language (e.g. Chinese, Islamic, Hebrew, Farsi/Persian) and use the national calendar (e.g. Irani, Shamsi, Jalali).

I want to understand is there any module or hardcoding solution in Drupal to show dates and calendars in other non-Gregorian calendars.

Any suggestions?

I'm hoping that someone else can Optimize this solution and make it better.
I'm ready to receive Any suggestion or criticism or any Other solution for this Challenge.

Features:

Does not requires any hacking or patching core /frontend solution
,display when dates are rendered
Does not change any date in database
Compatible and tested with PHP versions 5.3 and hereinafter
Supports Iranian/Persian/Shamsi/Jalali , Arabic/Hijri/Islamic, Thai, Hebrew...
Calendar systems
Better Performance becuse Doesn't outbreak the drupal core

Method 1, Using "IntelDateFormatter" Class:

First of all you must be sure that version of your php that installed is Newer than 5.3 and 'IntlDateFormatter' Extension was exist.
For use Traditional(National/Native) Date/Calender in Drupal 8 in nodes and Posted Comments with use of IntlDateFormatter class, add below codes to "THEME_NAME.theme":

For Nodes:

function THEME_NAME_preprocess_node(&$variables) {
    $locale = "fa_IR@calendar=persian";
    $dateType = IntlDateFormatter::NONE;//type of date formatting.
    $timeType = IntlDateFormatter::NONE;//if time format setting to none, will give you date itself
    $timezone = 'Asia/Tehran';
    $calendar = IntlDateFormatter::TRADITIONAL;//Non-Gregorian Calendar
    $pattern = 'y/M/d';

    $fmt = new IntlDateFormatter($locale, $dateType, $timeType, $timezone, $calendar, $pattern);
    $date = $variables['node']->getCreatedTime();
    $variables['date'] = $fmt->format($date);
}

For Comments:

function THEME_NAME_preprocess_comment(&$variables) {
    $fmt = new IntlDateFormatter(
    "fa_IR@calendar=persian",
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    'Asia/Tehran',
    IntlDateFormatter::TRADITIONAL,
    'y/M/d'
    );

    // Getting the node creation time stamp from the comment object.
    $date = $variables['comment']->getCreatedTime();
    $variables['created'] = $fmt->format($date);
}

Information about "IntlDateFormatter" Parameters:
locale: Locale to use when formatting or parsing or NULL to use the value specified in the ini setting, Link:http://www.w3.org/International/articles/language-tags

datetype:Date type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

timetype:
Time type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

timezone:
Time zone ID, default is system default,
Link:http://www.php.net/manual/en/timezones.php.

calendar:
Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.
The calendars ICU allows you to play with include:

Japanese (@calendar=japanese)
Buddhist (@calendar=buddhist)
Chinese (@calendar=chinese)
Persian (@calendar=persian)
Indian (@calendar=indian)
Islamic (@calendar=islamic)
Hebrew (@calendar=hebrew)
Coptic (@calendar=coptic)
Ethiopic (@calendar=ethiopic)

Link:http://userguide.icu-project.org/datetime/calendar

pattern:
Optional pattern to use when formatting or parsing. Possible patterns are documented at: http://userguide.icu-project.org/formatparse/datetime

METHOD 2,Using External Functions (like "jdf" for persian language):

First download this function form: http://jdf.scr.ir/download/
and then put downloaded file to your theme folder and add this code to above of "Theme_Name.theme"

include ('jdf.php');

and then add below code to appropriate place:

function Theme_Name_preprocess_node(&$variables) {
   $date = $variables['node']->getCreatedTime();
   $variables['date'] = jdate("l j F Y", strtotime($date));
}

I'm hoping that someone else can build on this and make it better.


Render an array in Block_view I want to render an array and print the output as Block[content]. There is either my Foreach or the way I use $item array or $row that is wrong. I will appreciate your help.

The result i get is the HTML I define in Block[content] without the values of $row->uri, $row->title, $row->body_value. They are empty. And it means I have done something wrong.

function produkt_block_view($delta = '')
{

  $block = array();

  $list = produkt_produkliste(1);
  $items = array();
  foreach ($list as $row) {
    $items[1] = $row->uri;
    $items[2] = $row->title;
    $items[3] = $row->body_value;
  }

 switch($delta) {
  case 'produkt' :
    $block['content'] = '';
    $block['content'] .= 'uri.'" alt="Se alle vores filter elementer her">';
    $block['content'] .= '
"'.$row->title.'"
';
    $block['content'] .= '
"'.$row->body_value.'"
';
    $block['content'] .= theme ('item_list',array('items' => $items, 'type' => 'ol',   'attribute' => 'produkt'));
    break;
  }

  return $block;
}

And I ended with this solution that get some results.

function produkt_block_view($delta = '')
{

   $query  = db_query("SELECT node.title,    field_data_field_kortbeskrivelse.field_kortbeskrivelse_value, file_managed.uri
    FROM node
    JOIN field_data_field_tilh_rsforhold ON
    node.nid = field_data_field_tilh_rsforhold.entity_id

    JOIN field_data_field_kortbeskrivelse ON
    node.nid = field_data_field_kortbeskrivelse.entity_id

    JOIN field_data_field_billede ON
    node.nid = field_data_field_billede.entity_id

    JOIN file_managed
    ON field_data_field_billede.field_billede_fid = file_managed.fid

    WHERE field_data_field_tilh_rsforhold.field_tilh_rsforhold_target_id = 30
    AND  field_data_field_billede.bundle = 'produkt_kategori'
    "

      );

    $rows   = array();
    foreach ($query as $row)
    {
        $rows[] = array(
        $row->title,
        $row->field_kortbeskrivelse_value,
        $row->uri
      );
            print_r($row->uri);

            $block['content'] = 'uri . '" alt="Se alle vores filter elementer her" />'; // assuming that anchor tag will wrap img
            $block['content'] .= '
' . $row->title . '
';
            $block['content'] .= '
' . $row->field_kortbeskrivelse_value . '
';
            $block['content'] .= theme ('item_list',array('type' => 'ol',     'attribute' => 'produkt'));

    }

  return $block;
 }

I don't think $block['content'] = ''; $block['content'] .= 'uri.'" alt="Se alle vores filter elementer her">';... will work, . is a string(concatination) operator. You should create render array and assign it to $block['content'], example:

$array = array('#markup' => 'SOME HTML');
$block['content'] = render($array);

EDIT:

After below comments, I played a little with hook_block_view hook, and I found out some information about it:

$block[subject] doesn't affect to its content even if you don't set it; content will be displayed without any subject (so, your missing subject doesn't cause any error here, as j.Reynolds mentioned);
$block['content'] can be string value and you don't need to render it, as Molot andj.Reynolds mentioned below, and you can concatinate it as many times as you want:)

So, if we return back to your snippet, you can try something like this:

$block['content'] = 'uri) . '" alt="Se alle vores filter elementer her" />'; // assuming that anchor tag will wrap img
$block['content'] .= '
' . $row->title . '
';
$block['content'] .= '
' . $row->body_value . '
';
$block['content'] .= theme ('item_list',array('items' => $items, 'type' => 'ol',   'attribute' => 'produkt'));

I don't know what $row->uri looks like in your code, but I assumed that it is something like public://FILE_NAME.EXT, if so you can use image_style_url function to generate image src..


hook_node_validate called on delete? Why is my hook_node_validate implementation being called when I try to delete a node through the node editing form (by clicking the delete button at the bottom of form)?  Validation fires and then my node doesn't get deleted which is not what I want.

I can delete without any problems when clicking on delete link at admin/content but not whenclicking delete button on node edit form since validation fires and fails.  What could be the reason for validation firing here?

You could check the Triggering element in the Form State for the button that triggers the Form Submission.

function MYMODULE_node_validate($node , $form_state , $form) {
  if ($form_state['triggering_element']['#value'] != 'Delete') {
    //Include the validations here
  }
}


What's the best practice way to test block Views with SImpleTest? I've created a block view, which I've positioned on the  page using the admin UI. I've exported my view using Features and fe_block for its block.

I'd like to write a SimpleTest to verify that content from the view is displaying on the front page.

I've written a test that creates some nodes (of the type being displayed by the view), then does a drupalGet('/') and some assertText() statements to verify the content is displayed.

However, these are currently failing. When I view the HTML of the frontpage as seen by SimpleTest, the view isn't there.

Have I missed something? Is there a better way to be testing this?

The simpletest code needs to place the block into a region. Then, you should see the content after doing the drupalGet('/').


Map subset of taxonomy terms to a content type I have a taxonomy called Writer and I have the terms added to it. I would like to maintain both active and inactive terms in the vocabulary and use only the active terms when mapped to a content type. In other words I would like to soft delete the terms instead of hard-deleting them. For this I added a custom boolean field for Writer vocabulary to indicate if the term is active or not. I am now not sure on how to apply the conditional mapping of taxonomy terms to the content type.

Appreciate help on this.

Achieved this using Taxonomy Publisher Filter which is part of Taxonomy Tools module


how to retrieve data for apache solr I am using apache solr 3.x .
Right now, I mixed the data from my two websites into one solr by mistake. I set one solr on the first website server and set another website's Apache Solr search to link to this server. I don't know they will mess up when I set this. But right now, the first website doesn't add any data into the solr, and all the data from the other website can add the data to the solr.

Is there anyway that I can retrieve each website data to make them show in the correct position?

Use Apache Solr Multisite search https://www.drupal.org/project/apachesolr_multisitesearch This is the proper way to have multiple sites sharing one index. You can search all sites or single sites.


How do I change the original language of a product type? On a multilingual site with commerce project I've created a product type while having one language selected as default but now I want to switch it to a different one. On /admin/commerce/config/product-types/producttypemachinename/edit/translate I see what the current original language is oviously but I can't edit it on /admin/commerce/config/product-types/producttypemachinename/edit. Is it ok if I edit it in the database? Does anyone have some ready SQL statements or at least know where it's stored?
I think product type is a Configuration Entity and I'm now searching where these are stored in the database.
I've found something in
SELECT * from `drupal_config` WHERE name LIKE "commerce_product.commerce_product_type%";
SELECT * from `drupal_key_value` WHERE collection="config.entity.key_store.commerce_product_type";

but the data columns there are longblob.
Update: with the next SQL I can confirm that original language is stored in the "config" table:
SELECT collection,name,CAST(data as CHAR) from `drupal_config` WHERE name LIKE "commerce_product.commerce_product_type%";

Update: even after editing the longblob value and setting langcode to en it's still not English original in the admin interface.
Update: just had to clear the cache, it's now changed.

Since I haven't found any easy way I had to edit it in the database manually and clear the cache after that.
Update:
It's easy with exporting at
/admin/config/development/configuration/single/export
and importing at
/admin/config/development/configuration/single/import


Using hook_form_alter() to add the "None" value in the select list of a required field When a field is required, Drupal removes the default "-None-" value.  However, also for a required field, "-None-" is very valuable as it requires the user to make a deliberate selection (put the first value on the select list as default doesn't force a sloppy user to make a selection).

I need to:

Have "-None-" as default value in the select list of a required field
Not accept "-None-" as field value when the form is submitted

How can I achieve this with hook_form_alter()?

By default, the label for the first default option is automatically set to "- Select -" for a required field and "- None -" for an optional field. To force the #empty_option to also show "- None -" for a required field, assign it with something like:

"#empty_option" => t('- None -'),

This will keep everything else intact and will do exactly what you want. See class Select.


How to modify user messages without hacking core user module? When "themeing" modules, especially core modules, as far as I know it is a good idea to take the module specific tpl.php files, duplicate the ones you need, and modify them once they're in the relevant theme directory.

However, what if I want to modify a .inc file? Is it the same process as with tpl.php files, or is there a better workflow? Basically what I would like to do is change some of the user status messages found in user.admin.inc in the core Drupal 7 User module. I'm not sure if editing this file directly is a good idea. Thoughts?

You can't override an .inc file by copying it to your theme, but you can override most of the function with your template.php; for example, any form can be altered using hook_form_alter(), or any function whose name starts with "theme" can be override by using  YOURTHEME_functionaname() in your theme template.php.


Markdown and Google Prettify I have been working on a site, that allows users to submit encryption algorithms, for other users to test and/or crack them.

The problem I am having is in the text editor that I want to use to do this with.
Being that I am now very used to, and comfortable with the Stack Exchange Markdown, I wanted to make my site use the same thing.

What I tried, was downloading the Markdown filter module, along with the Markdown Editor for BUEditor and Google Code Prettify modules.

I have been playing around with it for a little while, trying to configure it, and I noticed that there are several problems, that I can't figure out how to solve.

Block quotes don't work: When attempting to make a block quote, instead of making it correctly, it just looks like > this is pseudo block quote text.
Is there a library that I need to / can install to get this to work?
Google prettify is working, but not coloring the code.
Basically, I can get prettify to make the code look like this:

public static void main (String[] args) {
  System.out.println("this is a test example");
}

It is not highlighted.

public static void main (String[] args) {
  System.out.println("this is a test example");
}

What am I doing wrong? Is this just a simple css issue? Is it something bigger? Should I use a different module entirely, and if so, which one? (I am using omega as my default theme. You can see an example of this that I created for debugging purposes here.)

(Note: This is not a question about a module bug, I am wondering if there is something that I have forgotten to set up, or am doing wrong, not the module itself.)

I'm getting a 403 forbidden on your prettify.js. If you change the permissions of the sites/all/libraries/prettify/src folder to 777, It should solve your problem.


How do I add a node from a view to user profile field? I have list of courses of course content type in a view. I want to add "add course" button with every listing of node in view.
When a user is logged in he can add a course to its profile information. so that profile information shows all the added courses from view in the profile. For example: List of courses taken by user.
I have used entityreference module to attach nodes to user profile. But I have no idea how to do it from a view listing.

How do I add a node from a view to user profile field?

You can simply add a Global: text area in views header and input below HTML in the content.

Add Course


How do I use an entity reference field as a sidebar navigation on a view? I have 2 content types: category and project. On project, I have a reference field to category.

I would like to list all my nodes from project in a view and then use all the category nodes as links for filtering this list.

I know it is possible with a taxonomy term, but I'm trying to achieve it with a reference field. Is it possible with the view UI?

I'm using Drupal 8.8.2.

Yes. Doing this with content types is really no different than with taxonomies. You can leverage the reference value with a Views relationship.
You description sounds like it would use two Views, one for the block of navigational links in the sidebar, and the other for the lists of projects.

For the first you just want a view of the categories. I'd use fields and rewrite the output to link to each category title to a url like /projects/{{category_title}}. "Rewrite output" is an option available in the modal for the field. Alternatively, and perhaps more straightforward is to use the option to "output as a link."

The second page display View is based on the project type, and has a relationship to the category. Create a contextual filter to pull the category title from the URL, matching whatever you set up in the block.


Any way to override view_mode in twig directly? For some reasons, I need to render a content twice, the first one in default view mode, the second one with thumbnail view mode.

In field--paragraph--field-slide--gallery.html.twig I tried to use the following code, however, got a fatal error.

{% for item in items %}
  {{ item.content }}
{% endfor %}

{% for item in items %}
  {% set item.content['#view_mode'] = 'thumbnail' %}
  {{ item.content }}
{% endfor %}

Any another idea to get the similar output?

The fatal error is because Twig set is not able to manipulate arrays. This is only possible by using merge and then only on the top level of the array.

So first get the sub array where the key is placed and then merge the array key:

{% set item_content = item.content %}
{% set item_content = item_content|merge({'#view_mode': 'thumbnail'}) %}
{{ item_content }}

But I doubt that after you've solved the Twig issue this will work, because of how entities are rendered and cached. So you might have more success with Twig Tweak.


Default value of a 'managed file' field I created an edit custom form (of a node) via a custom module. From this form, I have a "managed file" field (for one picture) and I set his default value to a fid;
However, when my form is rendered, the "managed file" field doesn't show the image ratached. I don't understand why

My code :

$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => 10, //Set 10 for the test, the fid "10" exist, I checked
);

My form rendered:

As you see, no image is loaded whereas the default_value is set to an existing fid (10)

To render the existing image, please use the below code

$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => array(10),
);

You need to give the fid in array format. Please try it and let me know whether you got the result


Add paragraph domains to media View I'm using media and domain modules.
Nodes are assigned to multiple domains and there are image fields that link to media images on those nodes.
Some content types also use paragraphs and these paragraphs hold their own image fields, referencing media images.

The media view (/admin/content/media) provides some nice information out of the box and I have added a relationship to the image field used on nodes which allows me to add a field for Affiliate domains for the nodes that hold these images. This adds a list of domains for each media image (used on nodes) to the media View.

I need to display the same information for the image fields used in paragraphs. I can add a relationship to these paragraph image fields but that doesn't add an available field that would allow me to display the domains these paragraphs are assigned to. I guess that has to do with config entities not mixing very well with the domain module and Views.

What would the best way to add this field to the media view? A custom field handler seems to be the best bet but it seems that a query is needed to get the domains to which each node (holding a paragraph that holds an image field) is assigned to.

What's the best strategy to get this custom "computed" field into my view?

A newly developed module, Media View Addons, provides just that.


How do I enable CORS? I want to use services 3 module to create node of a content type in my Drupal 6 website.
I have enabled Services 3 module and configured the Rest Server properly.
But when I make a post call to it, the browser converts the POST method into OPTIONS and hence the response that is received is http 411 error. Further more, there is an error in that console about Access-control-allow-origin. This clearly means that this is a CORS issue.
I searched for a way to enable CORS in Drupal 6 and found out that we can enable CORS by adding headers in the .htaccess file. I added the following lines to .htaccess file :

Header set Access-Control-Allow-Origin "*" env=IS_CORS
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Allow-Headers "x-requested-with"

Is this the correct way to enable CORS in Drupal 6 site?
Thanks in advance. Please try to guide me through this. I am sure many people must have faced this situation, but I am currently not able to find  nice solution to this.

Doing this in an .htaccess should be OK.

Doing it in the Apache config for the host (main httpd.conf, include for the vhost, etc) is better.  When you upgrade Drupal, the .htaccess will be nuked.  Also, .htaccess is interpreted for every single access; Apache config (including Includes) is compiled when Apache starts.

You can also use drupal_set_header().  You just need to use the right hook for your situation (not terribly familiar with the Services hooks).

drupal_set_header('Access-Control-Allow-Origin: "*" IS_CORS');
drupal_set_header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
drupal_set_header('Access-Control-Allow-Headers: x-requested-with');

You may also want to check out the H5BP Server Configs project.  I use bits and pieces of this as Apache includes for my virtual hosts, and I am pretty sure they have some good CORS rules.


Drush: Update core from stable to dev I would like to upgrade from drupal core 7.7 to 7.x-dev, is this possible using Drush?

UPDATE:

Ok, looks like either I needed Drush 4.5, or the process of updating Drush from 4.4 corrected something with the installation, as drush up drupal-7.x worked, and I'm noticing that drush up now shows all installed modules everytime.

Yes it is. Navigate to your Drupal directory and run the following command:

drush pm-update drupal-7.x

Note you can use the same tactic to update any module to a development version from a stable version, as well as update a development version to a newer, stable version.


Registration form in a popup window (colorbox or jQuery ui)? How to embed a registration form in a popup window?

I would like to use Colorbox or jQuery UI:

drupal_add_library('system', 'ui.dialog');

There's already a module for that, Ajax Login/Register:

This module provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


Umami content not created I'm creating a new Drupal 8 site using Lando/Pantheon - and then installing the Umami profile. I've done this before with no problems.

This morning when I try, the site is created and it looks like the Umami theme is in place. However, the content is not created.

Is there any way to create the content after the profile is installed?

Note: Oddly, drush is saying that the demo_umami_content module is not found but is able to find demo_umami_tour. ~/Desktop/lando/lando-panth $ lando drush pmi demo_umami_content demo_umami_content was not found.

The Umami demo: Content module is not found from Drush, nor is it visible in the list of modules, because it is set as hidden in demo_umami_content.info.yml. If you change the hidden: true line in hidden: false, you will be able to uninstall the module, and re-install it. This will execute again demo_umami_content_install(), which imports the content.

/**
 * Implements hook_install().
 */
function demo_umami_content_install() {
  if (!\Drupal::service('config.installer')->isSyncing()) {
    \Drupal::classResolver(InstallHelper::class)->importContent();
  }
}

If that doesn't work, the alternative is re-install Drupal using Unami as installation profile.


Remove or hide the "View" tab on a node I know how to rename "edit" or "track" tab on user page and node page. Here's the code, it might help someone.

<?php

function MYMODULE_menu_alter(&$items) {
//    drupal_set_message('Menu Items: <pre>'.print_r($items, TRUE).'</pre>');
    $items['user/%user/view']['title'] = "Profile";
    $items['user/%user/edit']['title'] = "Profile edit";
    $items['node/%node/edit']['title'] = "Node edit";

}

...but I don't know how to remove or hide the "View" tab on created node.
my url page of the node is content/(node title).

What snippet should I use to remove the "View" tab on node page?

You should be able to do this using css, or try using the code below or the tab tamer module

function MYMODULE_menu_alter(&$items) {
  $items['node/%node/view']['access callback'] = 'MYMODULE_disable_node_view';
  $items['node/%node/view']['access arguments'] = array(1);
}

function MYMODULE_disable_node_view($node){
        return false;
}


How to attach external library in twig file with parameters? I have below code to share on LINE messenger

How to include JS using attach_library?

{{ attach_library('https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js') }}

How to attach async="async" defer="defer" ?

Tried using

{{ attach_library('https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js', { 'async' : 'async', 'defer' : 'defer'}) }}

But not working :(

In your theme.libraries.yml file add below lines

theme.social:
  js:
    'https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js' : { external: true, defer: true, async: true }

In your twig file

{{ attach_library('theme.social') }}

Clear cache & it works :)


Image file keeps getting deleted I'm using the Image Title module with Drupal 7. I can successfully upload an image to be used as a title, however the images keep getting deleted. It looks like the problem is similar to this question on SO.

Oddly, I've been using image_title for several years but never encountered this problem until now. And the module is basically abandoned, so there are no recent changes to it that would have changed the behavior - so has there been some change in Drupal itself that could explain this?

As a workaround I went into mysql and did update file_managed set status = 1 for the image file in question, is that likely to solve it?

To be honest I would forget about using that module and simply have a field that contains the desired image, and change your node template file to display that image in place of the title.

It is important to have a text title (even if it is not displayed) because it is used in search engine listings.


Remove language code from URL For example, with example.com/en/apple/12/article/11/23, in hook_init() arg(0) returns "apple," as I expect; in hook_boot() it returns en which is language prefix of English.

That is because hook_boot() is invoked too early in the bootstrap process, which means:

Not all the modules are loaded, including the Locale module that is the one that alter the path, and the reason why arg(0) returns "apple" in your example, when called in hook_init().
The language has not been set; it is initialized during the DRUPAL_BOOTSTRAP_LANGUAGE phase, while hook_boot() is invoked during the DRUPAL_BOOTSTRAP_PAGE_CACHE phase.
The call to drupal_path_initialize(), which alters $_GET['q'] with $_GET['q'] = drupal_get_normal_path($_GET['q']); is done during the DRUPAL_BOOTSTRAP_FULL phase, which is the last bootstrap phase.

Differently, hook_init() is invoked as last step done in the DRUPAL_BOOTSTRAP_FULL phase, which means all modules are loaded, the language has been set, and drupal_path_initialize() has been already called.

As side note, hook_boot() has been removed from Drupal 8; if you are using it, you will need to change your code. Using hook_init() is a possible alternative, since it is still used in Drupal 8.


Render a content type bundle in a custom module template How do I render/display an existing content type form in a custom twig template for a custom module in drupal 8?

I've tried using getform() function, but I dont think that is the correct function.

I have set a preprocessor variable in my custom module and can see the variable on my custom page via the twig syntax {{dump()}}. Just for simplicity, I would like to know, which class function will allow me to simply render the content type 'article' form , once I can see the article form, i can change it to my custom made form.

I'm not sure what you're exactly asking, but there are various modules that allow you to display entity forms in a block, for example Entityform block (Disclaimer, maintained by me).

Either use that, you can use form modes and/or form alters to then customize the form, or just look at the code to see how to do it.

One thing that this module doesn't support yet is editing existing entities, I'd love to add support for that using the plugin context system.


What's good form for calling views within a module (template, etc)? I have about three views that will be used; Here's Daniel Wehner's answer:

 $view = views_get_view();
 $view->set_display();
 $view->filter['foo']->value = 'bar';
 print $view->preview($display_id, $args);

I built this based off his code, which while works, could be improved if including views is going to be a regular activity throughout your project:

$view = views_get_view('nodequeue_3');
$view->set_display();

$content['raw_markup'] = array(
  '#type' => 'markup',
  '#markup' => $view->preview(),
);

I'm also thinking this might not be done that often, because if you can build a module, why use views?

The utility of views should not be overlooked, in combination with (or without) a custom module.

Thanks for the patience, this community is awesome!

I prever to use this small helper function:

function mymodule_embed_view($view_id, $display_id, $arguments) {
    $view = views_get_view($view_id);
    $view->set_display($display_id);
    $view->set_arguments($arguments);
    $view->pre_execute();
    $view->execute();
    return $view->render();
}


What's wrong with my sub-theme? I wanted to make some customizations to the "Seven" administration theme, so I started by installing the "Blossom" sub theme of Seven found here: http://drupal.org/project/blossom-admin .

This worked fine.  So then I copied /sites/all/themes/blossom-admin and named it /sites/all/themes/myadmin

In the .info file for myamin, I changed

name = Blossom
description = Drupal Gardens administration theme.

to

name = myadmin
destription = my description of this theme

And just to be safe, I also renamed any files that had the "blossom" name to "myadmin" in both the .info file and to the actual files themselves.  (Like renamed blossom.css to myadmin.css)

Now when I go to the Drupal admin and select myadmin as the administration theme, it works, but includes my main navigation and a footer region content at the top of the theme.  Does anyone know why this would happen to a straight copy of the blossom theme which worked fine?

Did you rename all the functions in the template.php file as well? These need to start with your theme name ;-)


Dependency Injection and the Url object I'm making the leap from Drupal 7 to Drupal 8 and am still fuzzy on some core concepts, particularly relating to dependency injection (DI). I've read plenty of tutorials and have a grasp on DI with services, but am unclear on using DI with something like \Drupal::Url().

For instance, I am using the following code in a class:

use Drupal\Core\Url;
...
$url = Url::fromRoute('<current>', [], ['absolute' => 'true'])->toString();

From what I can tell, there is no Url service. So, what I am wondering is: Is it possible to access Url via DI? And if so, how?

Bonus points: I intend for the class I am writing to be used as a service. Does this have any impact on the answer?

Edit: Fixed erroneous code.

Edit 2: I should also point out that the purpose of this call is to retrieve the current absolute URL so that I can determine if it is HTTPS.

You can inject the UrlGenerator as service and use UrlGenerator::generateFromRoute, but in the linked doc you are discouraged to do so:

  @internal Should not be used in user code. Use \Drupal\Core\Url
  instead.

So the code in your question to create an url object is OK for a service, but not the toString() method. Render the url only with this method when the page rendering process has started, for example in a theme.

In a service you usually don't know this and you should return an unrendered url object, so that it can be rendered later in the rendering pipeline.

$url = Url::fromRoute('<current>', [], ['absolute' => 'true']);

toString() in the wrong place generates ugly error messages about early rendering which are hard to debug when this happens somewhere in a service.


cout rows of a view for new content and comments I have made a view getting the new content added and new comments

But i need to get its count and so i usedthe following code

$view = views_get_view('new_activity');

$view->set_arguments(array(arg(2)));

$view->execute();

return l(count($view->result), 'new-activity/' . arg(2));

but i see untrue number related to the view page

how to fix it espicially using history_timestamp attribute of each row

the main problem is that the views gets , data and hide the viewed rows
and only shows the unviewed rows which gives me wrong count

please help or advice with a better scenario

thanks in advance

count($view->results) will only give you the number of the results on the current page if using a paged View. Try using $view->total_rows instead, which will give you the total number of rows returned by the View:

return l($view->total_rows, 'new-activity/' . arg(2));


How to display users with same select list value on a custom user profile page Firstly in my site, using Profile 2. i created a 'Select list field' that allows each user to choose his/her country.

I then created a custom user profile page using views by  following these steps:

1.Create a view and add a "page" display.
2. Use "user/%" as the page path.
3. Add a contextual filter "user uid" and select "provide default value" user ID from URL.

Now i want to add a block to each users profile page that displays all users from the same country as the currently viewed user profile

I have tried adding the "Profile Country" contextual filter and selecting "provide default value" user ID from URL but no results are displayed.

Is there a way to do this?

The problem is you're relying on your contextual filter to mean 2 things:

For the page it has to be the UID.
For the block it has to be the country select value that corresponds to the UID.

If you're wanting to configure it this way, you'll need your block view to derive the profile country value from a UID. One way you could do this is to use Provide default value > Type: PHP Code options with something like this:

if ($user = user_load(arg(1))) {
  $profile = profile2_load_by_user($user);
  return $profile['my_profile_machine_name']->field_my_country_field_name[LANGUAGE_NONE][0]['value'];
}

The actual code will vary based on your Profile2 configuration.


Continuing an interrupted batch I'm using a batch job in Drupal 8 to scrape pages from another site to import.

I'm using httpClient, and I have it wrapped in a try/catch.

try {
  $response = \Drupal::httpClient()->get($parts['scheme'] . '://' . $parts['host'] . $parts['path'], [
    'query' => $parts['query'],
    'headers' => array('Accept'=>'text/xml'),
    'verify' => FALSE,
    'connect_timeout' => 6,
    'CURLOPT_SSL_VERIFYPEER' => false,
    'CURLOPT_CERTINFO' => false,
  ]);
  return (string) $response->getBody();
}
catch (Exception $e) {
  watchdog_exception('scrape', $e);
  return FALSE;
}

However, from time to time the remote site times out, and the guzzle exception is not caught, which causes the batch job to end.

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /batch?id=44&op=do_nojs&op=do
StatusText: Internal Server Error
ResponseText: The website encountered an unexpected error. Please try again later.GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in GuzzleHttp\Handler\CurlFactory::createRejection() (line 186 of vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php). GuzzleHttp\Handler\CurlFactory::finishError(Object, Object, Object) (Line: 103)

This job imports a few thousand pages, so when the error happens in the middle of the batch, it's a major pain.

I am getting ready to write a queue for the batch processor, where the batch pops a set of items off the queue and then marks them as done, so that I can continue the job after an exception.

But then I wondered, is there already a way to tell Drupal to continue a batch from where it left off or was interrupted? I did some googling and didn't find anything indicating that this feature already existed. I don't want to re-invent the wheel if I don't have to.

Can I re-start an incomplete, interrupted batch job?

So I think there is no way to tell batch to restart when it's gotten an error response. What you could do is to not return a possible error but rather re-try the request using your own wrapper. So could do

try {

  $TestRetry = new TestRetry();
  return $TestRetry->test();
}
// And I think you won't need this but handle the exception in your wrapper class.
catch (Exception $e) {
  watchdog_exception('scrape', $e);
  return FALSE;
}

and in your wrapper, you could attempt to retry the request to avoid an error. So your wrapper may look like this:

<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

class TestRetry {

  public function test() {
    $handlerStack = HandlerStack::create(new CurlHandler());
    $handlerStack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
    $client = new Client(array('handler' => $handlerStack));

    $response = $client->request(
      'GET',
// @todo replace to a real url!!!
      'https://500-error-code-url'
    )->getBody()->getContents();

    return \GuzzleHttp\json_decode($response, TRUE);
  }

  public function retryDecider() {
    return function (
      $retries,
      Request $request,
      Response $response = NULL,
      RequestException $exception = NULL
    ) {
// Limit the number of retries to 5
      if ($retries >= 5) {
        return FALSE;
      }

// Retry connection exceptions
      if ($exception instanceof ConnectException) {
        return TRUE;
      }

      if ($response) {
// Retry on server errors
        if ($response->getStatusCode() >= 500) {
          return TRUE;
        }
      }

      return FALSE;
    };
  }

  /**
   * delay 1s 2s 3s 4s 5s
   *
   * @return Closure
   */
  public function retryDelay() {
    return function ($numberOfRetries) {
      return 1000 * $numberOfRetries;
    };
  }
}


Show last created node in views I'm using Drupal 7.
I have created two content types (A & B); content type B is referenced from content type A.
I want to create a view, I need to filter the nodes of content type B by showing the last node only (by date), for every node from content type A.

How can I achieve this?

You need to create a relationship in Views. Then filter by creation date descending, and limit results to 1. 'Relationship' is how Views does a SQL JOIN.

It's non-trivial to describe, so I'll just link to a tutorial: http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments


How can I use drupal_add_js() to include the following script? How can I use drupal_add_js() to include the following script?

<script src="http://example.net/script.js" data-config="{'skin':'skins/black/skin.css','volume':50,'autoplay':true,'shuffle':true,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'','url':'https://soundcloud.com/fosterthepeoplemusic/pumpedupkicks'}]}" ></script>

I recently came across this issue and was able to work around the limitations of drupal_add_js() with the following hack:

//this can be any string of js that's already wrapped in <script> elements
$my_script = '<script ...[all the things]... ></script>';

drupal_add_js('</script>' . $my_script . '<script>', array(
  'type' => 'inline',
  'scope' => 'header', //or 'footer'
  //...any other options you want to add
));

You end up with two empty <script> elements in your markup, which I find annoying, but they don't actually do any harm.


Get a list of field variables for template code For Drupal 7, how do I access (or generate) a list of all the field variables available for building a template (for a given content type)?

Some context: I used to rely on the (now deprecated) Contemplate module to write my templates. Directly within its interface, it would print a list of all of the available variables, like this.

It was quite handy. Now that I'm making disk-based templates and do not have this list generated by the Contemplate module, I'm confused as to how I might produce something similar for use as a reference.

Use Devel module and then with using get_defined_vars you can get a list of defined variables. then in you template file use the following snippet

<?php
 dsm(get_defined_vars());
// or even  dsm(get_defined_vars());
?>

and another solution is based on  hook_preprocess. just dumps the variables there.

on your template.theme file

mymodule_preprocess(&$vars, $hook) {
dpm($vars);
}

**Update*
if you want to see the $variables on node template try on your template.

copy/paste this snippet on your template.php then clear the cache
function YOURTHEMENAME_preprocess_node(&$variables) {
    dpm($variables);
    // you can add or remove whatever you want to it here
}

if your theme name is themetastic So

function themetastic_preprocess_node(&$variables) {
    dpm($variables);
    // you can add or remove whatever you want to it here
}

Ref: Read this to learn more about preprocessing


Access denied page for users without permission "View published content" My site access is only for registred users, then when you try to access drupal returns the "access denied" page. I want to customize my "access denied" page but the anonymous user doesn't have the "View published content" permission. Then they can't see a basic page node with my access node page customization.

How can I resolve this ?
-It can be a static html (but I don't know how to redirect when this error is raised). But drupal throws an error when I put in /admin/config/system/site-information because isn't a drupal path
-If is a node (my access denied page) how can I grant the anonymous users to view ?

I'm using Drupal 8

You can try Custom error module, It allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.


How do I group two nodes on the frontpage in a div? I want to have every two articles on the homepage within a div structure.

However, I can't get this done in my node.tpl.php file: if I use the zebra variable to print a  tag before the node when zebra is odd, and a closing  tag after the node when zebra is even then this only works when there are an even number of articles, or otherwise the last div won't be closed.

In code:

<?php if($zebra=='odd'): ?>

 <?php endif; ?>

 <div id="node-<?php print $node->nid; ?>" class="[..]">
 [rest of node here]

 <?php if($zebra == 'even'): ?>

 <?php endif; ?>

To make this work, I must be able to know when a node is the last one. But there isn't a variable $last in the node template file, neither is there a $count variable that hold the total number of nodes.

Does anyone has done something similar before?

The node template is not (usually) aware of the context in which it's been called; when you list nodes as teasers each node is themed individually, and has no awareness of the other nodes in the list.

What you need to do is find out what template/function is responsible for outputting the list of nodes in question and override that in your own theme/module to add the extra divs.

The Theme Developer module might come in quite handy here, it provides an in-page way of isolating which theme functions have been responsible for rendering which areas of the page.


How to create a Bean type programmatically? I'm building a module that creates set of blocks using Bean module. How do I can create a Bean Type programmatically in order to be able to create the blocks?

Bean uses ctools plugins for its types. Per the docs:

/**
 * Implements hook_bean_types().
 *
 * Beans uses ctools plugins to define the block types.
 * All plugin files must be registered in the .info file.
 */
function hook_bean_types() {
  $plugins = array();
  $plugins['plugin_key'] = array(
    'label' => t('Title'),
    'description' => t('Description'),
    // This is optional. Set it to TRUE if you do not want the plugin to be
    // displayed in the UI.
    'abstract' => FALSE,
    'handler' => array(
      'class' => 'ClassName',
      'parent' => 'bean',
      // This should be pointing to the path of your custom bean plugin module.
      'path' => drupal_get_path('module', 'example_bean') . '/plugins',
      // Class files should be named accordingly in order to support ctools
      // autoloading procedures.
      'file' => 'ClassName.class.php',
    ),
  );
  return $plugins;
}


How to use Field Collection in Webform? I want to use field collection module in Webform Component, How can I do that?

I did by using entity form + field collection.


Create dynamic text fields on form based on other entities I've created an entity which has fields that users need to fill out. As part of that entity there is a reference field back to a content type 'food'.
The 'food' content type has it's own entity reference called 'sections'.
When a user selects a 'food', i want to dynamically add each 'section' as a title with a textarea box underneath which gets stored against the original entity.
Considered using paragraphs as the 'sections' but they need to be reusable on different 'food' nodes. Also checked the dynamic fields module but this doesn't look like it's well supported.
Fallback approach is going to be to programmatically create a field for each 'section' item as they are added, but with this we could end up with hundreds of fields.
Any ideas on how else this can be done programmatically?

Paragraphs is what you want. What you are describing is Paragraphs' exact use case. We use Paragraphs as a staple of our platform because of its re-usability.
Assigning an existing Paragraph to an Entity Reference Revisions field on a node is as simple as:
// Note that the value will be a nested array, even if cardinality is 1.
$node->get('field_food')>setValue([
  [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ],
]);
$node->save();

// Another example: assigning multiple references to a single field.
$node->get('field_myfield')>setValue([
  [
    'target_id' => $paragraph1->id(),
    'target_revision_id' => $paragraph1->getRevisionId(),
  ],
  [
    'target_id' => $paragraph2->id(),
    'target_revision_id' => $paragraph2->getRevisionId(),
  ],
  [
    'target_id' => $paragraph3->id(),
    'target_revision_id' => $paragraph3->getRevisionId(),
  ],
]);
$node->save();

If you need to generate a paragraph programmatically, that is also easy:
// Note that I'm using the DIC for demonstration's sake.
// Be sure to use dependency injection and other best practices in your project.
$storage = \Drupal::entityTypeManager()->getStorage('paragraph');
$paragraph = $storage->create([
  'type' => 'food',
  'title' => 'A title',
  'field_a' => 'a value',
]);
$paragraph->save();

You can then assign this newly created paragraph to an Entity Reference Revisions field using the method I mentioned above.


What is the "u=" and "i=" class in CSS? I am trying to modify the CSS in a Drupal 7 theme from being statically coded to one which is generated by views.  The person before me, wrote the slideshow directly into the page--front.tpl.php file and this makes it next to impossible for users to change the slideshow without getting a Drupal developer involved.

In the "static" page, there are some tags which, due to my ignorance, I don't know how to deal with.  For exampe:

I know what the "id" is and I know what the "class" is, but I have no idea what the "u=" references.  I have also seen:

Can someone tell me the terminology associated with this tag so I can research it?  Typing in "<div u=" in Google is bringing up tons of unrelated results

Those attributes ("u" and "i") are not standard attributes. They seems from this JOSS slider or another slider.

Examine your Drupal modules and the View your want to modify to know which slider are you using. Then check the documentation for that slider.


Generating Url for a route I want to use drupal l() function, but Url doesn't work really well with a view with optional argument.

The view has a context filter, but it is optional. In the routes table it has path /knowledge-base. When I setup view's routing as /knowledge-base/% Routes table starts to receive /knowledge-base/{arg_0}, but it becomes mandatory.

Is it possible to add an argument to the route, so I would be able to construct route /knowledge-base/ID from the code (new Url('route.name', ['arg_0' => $val])), but leave it optional?

What you can do is to define the path as a non-routed path:

<?
$url = Url::fromUri('base://knowledge-base');

(The base:// stuff is a bit weird IMHO, don't ask me why it's named like that. @dawehner might know ;))

This has a few limitations, some methods will then not work (like getRouteName()), and the url will not be checked for access.

The only other way I can think of is to define two displays in your view, one without an argument and the other one that requires it.


logging into development instance of Drupal Ive rsynced the directory structure from mywebsite.com to mywebsite.local ( on my LAN)
and copied the DB .
the website mywebsite.local displays the website, but i cant log with the admin user/pw from the production site .
The DB tables look the same to me.  Its a single site and in sites/default/settings.php it points to DB host is 'localhost'
Tailing apache access.log and I can see the .local site is served from localhost

Do I need to change anything else  ?

You can try login with https://drushcommands.com/drush-8x/user/user-login/

drush uli admin

Which will give you a login link for user admin

If you invoke it without a username it gives you a login link for user 1

drush uli


Undefined error for field image I am using a custom image field in one of my content types, which I am accessing using the following code.

if ($content['field_heading']) {
  print render($content['field_heading']);
}

Everything is fine, except that in administrative area I am seeing this error message:

  Notice: Undefined index: field_heading in include() (line 4 of tridz7\sites\all\themes\tridz\node.tpl.php).

What could be the reason? Is there any workaround?

Probably you have nodes where the "field_heading" field has not been set, or you didn't enable the field in output tab on content type section.

Try this code:

if (!empty($content['field_heading'])) {
  print render($content['field_heading']);
}


Assigning OG group title to OG group image title field Every member of my site can create groups (OG.) Each group requires a title, an image, and a mission statement. The image Title field is enabled because in some parts of the site, the group images are displayed as thumbnails without the group titles.

However, most users don't bother to fill in the image title field so there is no indication of the group's title or purpose.

The idea here is to have the title of the group show automatically when the mouse cursor hovers above the group image after the group is created.

Any idea on how to accomplish this feast?

Your event should be after saving new content of type: your group content type.
Then add a condition, entity has field: node > your image field.
You should then be able add a condition to check if that field is empty.

Your action would then be to set a data value on the image using the node title.


Output array data on drush error when showing stack trace I'm trying to install a module, but its giving me errors during a drush enable. It shows the stack trace log and I can see it has something to do with the flag_lists_type during the install process. I can see there is an array in the output, but how do you print_r() this so I can get more debugging information?

You can use XDebug PHP extensions with the following suggested settings:

xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=1       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=256        ; int: Controls the protection mechanism for infinite recursion protection.

Since you're experiencing Exception type of error, enabling show_exception_trace will show a stack trace whenever an Exception or Error is raised (even if this Exception or Error is actually caught, so you can always disable it). Enabling collect_params, will display the parameters passed to functions when a function call is recorded (including content of the arrays).

See: Xdebug documentation page.

To verify your XDebug settings from CLI, run:

php -i | grep xdebug


How to cache a view for all users of a role? I have a view that displays a map. I need to display 7000 entries on the map.
I have installed solar search API to index the content and have created a view using that.
Still, the loading time for that view is around 1 minute for each user. After the first fetch, then it loads fast for that user since it fetches the data from the cache.
I was wondering whether I can cache the entire view for all users of a specific role.
I tried installing the "Views Custom Cache Tags" module.
But I am a bit lost on how to configure it.
Also not sure whether this will solve my problem or not.
Suggestions, please.

To answer the question title and the comment of @Leigh, without going into the details of the complexity of the specific View:

How to cache a view for all users of a role?

Views are cached like any other rendered content. When rendered a View bubbles up the cacheable metadata of Views plugins, like filter or sorting plugins and the rendered content itself.
Additionally there are the three default contexts, as defined in the service container:
core.services.yml:
  required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

The context user.permissions is a hash of all of the user's permissions, which is the result of the roles assigned to a user.
So in the end a View is cached for user roles by default.


How to add link (via php) to xmlsitemap I have a site where some pages are "virtual".

The path is :

internal_node/XYZ

where
* internal_node/% is defined in a hook_menu()
* XYZ is a number

my "internal_node" callback  call an external service using XYZ like argument, get soma data and display this data to the user. All works without problem. And all is legal.

Now I want to add all "interal_node" links to my google's sitemap.

I have installed xmlsitemap, but this module create a google sitemap for only all internal drupal node and my "internal_node" are not a drupal node.

So, how can I add link to xmlsitemap ?

Thanks.

you could put those links in a menu and have that menu included to your xmlsitemap.


How to merge more than one profile type within registration page? So I am using profile2 module to create different types of user profiles

for example

personal information profile
contact information profile
team profile - team role
member profile  - member role

contact information profile is a common profile (fields) between team user and member user

I created a registration page for each role using profile2 registration path module, in this module I can only create one registration path for each profile which will combine Drupal account fields with profile2 profile fields.

Current registration pages as follow:

team profile registration page
member profile registration page

Now I want to include/merge contact information profile fields with team and member profiles in the registration page without creating redundant fields for each profile.

Any helpful ideas

If you create fields for one profile, you can also use the same fields for another profile type.

When making the fields for the second type, rather than make new ones use the "Already Existing" Field to select the already made fields from a drop-down list.

This way both roles will fill in the same Contact Information since they both used the same fields for the task.


How to properly declare module settings with options list In my ConfigFormBase derived class I want to add select list to settings form.

How should I declare it in mymod.config.yml file?

I've tried:

mymod.config:
  type: config_object
  label: 'Settings'
  mapping:
    test_mode:
      type: checkbox
      label: 'Turn on test mode'
    country_code:
      type: multiple
      label: 'Action site'
      value:
        - 1
        - 22
        - 34
        - 56
        - 107
        - 168
        - 181
        - 209
        - 228

and can I specify list as key -> value pairs also?

Config schema doesn't know about allowed values. It's a about the structure of the stored configuration, not how it is displayed to the user.

It's up to you to implement the form for that, using e.g. a #type selection and #options.

For the config schema, it's type: boolean, not type checkbox. And type: integer, what you tried to use there doesn't exist.


how to enable workflow submodules in Modules administration page I am a very beginner to Drupal. In order to understand how Drupal-Workflow works, I try to install Workflow Module into my site. Following the installation guide on Drupal Documentation, i place the entire workflow directory into your Drupal modules directory, but when i go to the Modules administration page,  and try to enable the following workflow submodules, i get into the trouble, like this, i couldn't check the submodules. So, who can give me a hand, appreciate enough！

This page has suggested you the reason. You didn't install Entity module, you can get this module on Entity cache module.
This module has no user interface, if you enable it, entities will start being cached, if you disable it, they'll stop.


How to display data export icon on top of an admin view without views-view.tpl.php in admin theme? I want the XLS/CSV export link buttons of an admin view to be displayed on top of that view. If it weren't a admin view I'ld simply put a slightly changed views-view--NAMEOFMYVIEW.tpl.php into my default theme's template folder. But now I'ld have to put that template inside the core's themes folder to work on that certain view since this view has an admin path and is themed by a core theme.

I don't want to add anything custom to the core. Is there another way to bring that button to the top?

You can create

function MODULE_preprocess_views_view_NAMEOFMYVIEW(&$variables) {
  $variables['title_suffix'] = array(
    /* Renderable data or just string instead of array */
  );
}

it will render you content between view title and view content.


Determine if this should be a group When anonymous users are registering and creating a group - the field:

Determine if this should be a group.

Shows up on registration.

In the field settings on the content type I'm using I have the values checked to "Hide" this portion.  I've even hid the values on Manage Display.

Screen shots attached.  All I want to do with is hide the field to NOT show to users.  There's no reason for this field to be visible in my scenario.

I don't want to hide it with css if at all possible.

Any guidance is appreciated.

You could use hook_form_alter() to change the field type for the field you want to hide to "hidden". The code would be something like this:

mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case "user_register_form":
      $form["fieldname"]["#type"] = "hidden";
      $form["fieldname"]["#value"] = $form["fieldname"]["#default_value"];
      break;
  }
}

This function will get called for every form displayed, so the switch statement makes sure it's the right form. That being the case, the next line changes the type of the field to a hidden field. Finally, it copies the default value of the field into the actual value (hidden fields don't have a default value).

Unfortunately I don't know what the name of the field you want to change is, so you'll have to investigate that.

Hope this gets you on the right track.


How can I add more than one pointer to a map? I want to create a block which has search functionality for looking up locations. I want to be able to add a pointer to the map at the searched for location.

It should be able to add more than one pointer to the map based on what is searched for.

An example of pretty much exactly what I'm looking for the input of locations can be seen here:
http://www.mapcustomizer.com/

Does anybody know how to do this?

Thanks

You can use Get Location module for this functionality. It will create multiple location markers on a single map, with a popup bubble info and it comes up with inbuilt views. You just need to enable a block after installing it. Some more details about this module (from its project page):

... will provide Google maps API version 3 enabled maps on which to display markers of locations found in location-enabled content-types.
These can be displayed per node, eg "/getlocations/node/xxx" will display all the locations associated with that node. They can also be displayed per content-type, so if your content-type has a machine name 'venue' you can show them all with "/getlocations/type/venue" and it also supports paths like "/getlocations/user/xxx" and "/getlocations/users" for location-enabled users. These links have their own access permissions so control can be exercised on a per role basis.

If looking for custom thing, specify your complete requirement.