Dynamic weight for Blocks I want to change the block weight in sidebar for each page request, So the blocks position would be change for each request.

Is there any way to do it ?

Drupal 8 is providing a hook to alter the region template_preprocess_region, it would prepares values to the theme_region.Adding the following codes in THEMENAME.theme file would solve the problems,

function themename_preprocess_region(&$variables) {
  if ($variables['region'] == 'sidebar_second') {
    $variables['elements'] = shuffle_assoc($variables['elements']);
    $content = '';
    foreach ($variables['elements'] as $key => $value) {
      if (is_array($variables['elements'][$key])) {
        $content .= \Drupal::service ('renderer')->render($value);
      }
    }
    $variables['content'] = array(
      '#markup' => $content,
    );
  }
}

function shuffle_assoc($list) {
  if (!is_array($list)) {
    return $list;
  }

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key) {
    $random[$key] = $list[$key];
  }
  return $random;
}

For more details, check here


How to use different domains for multilingual sites and keep users logged in? I have a site that is in French and English. I am able to successfully setup so that users can switch back and forth between the two domains to view either language, however I cannot seem to keep users logged in. When they are logged into the english domain and then switch to the french domain they are required to login again. However if they switch back to the english domain they are still logged in.

As an example we'll use www.english-domain.com as the base (default) domain and www.french-domain.com as the secondary domain

In settings.php I have modified the following, however it doesn't seem to be keeping them logged in. Am I missing something?

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains.
 */
$cookie_domain = 'english-domain.com';

Note: That I have also flushed both site and browser cache as well as deleted any cookies left on my machine.

Update:

Here are my language settings:

A cookie can only be read from the same domain that set it. This is a fundamental security feature in browsers to prevent other sites from potentially stealing login sessions, and there is nothing simple you can do about it.

With that said, the comment in the settings.php file seems to contradict my statement, and I'm honestly not really sure how to intrepret that. Perhaps it's only meant to be relevant to sub-domains, which are allowed to share cookies, but if so the comment should probably be re-phrased.

There are a number of ways to work around this, where the easiest is to use language prefix sub-domains instead of separate domains.

Baring that, I believe the "best" one is to use a Single sign-on system. There's a comparision of different SSO modules here. This could be a Drupal based solution, which is the way that is most likely to "nicely" integrate with your current Drupal sites, but that's not really necessary.

The Bakery module which is used by *.drupal.org itself is relevant to mention, as well as this related DA answer How drupal.org single sign on works

More info about cross-domain cookies in a Stack overflow question.


How to override views title using values from several contextual filters? I have a view where the user can filter by using contextual filters in the URL, like this:

timeline/%year/%month/%day

I then use these contextual filters:

Content: node.field_daterange (year)

Content: node.field_daterange (month)

Content: node.field_daterange (day)

Users can use this path to get all events in a year, e.g:

timeline/1945

Or to get all events on a specific month in a year they can use

timeline/1945/05

Now I want to dynamically build the title of the view. If only the year parameter is used it should the title "Timeline YEAR" and if both year and month is set I want it to have title "Timeline MONTH YEAR".

In the contextual filter, there is an alternative named "Override title" (under the box "When the filter value IS in the URL or a default is provided")

It is written "Override the view and other argument titles. You may use Twig syntax in this field." But how can I now catch back the %year, %month or %day argument to use it in the title?

There is a Replacement patterns fieldset below it that you can copy the patterns from. You need to edit each contextual filter and override the title with the pattern that makes sense in each of those contexts.


Webform - Validating File Upload with PHP How can I validate, via Webform module (using Webform file upload in Drupal 7) whether the file has been uploaded or not?

How can I handle and reference those files?

Seems that normal FAPI calls don't work (e. g. file_save_upload('file1') returns a non-true value if I have a file field).

I see that Webform file fields upload the file BEFORE form submission (i. e. clicking "upload to server" adjacent button).

I don't know if that's the normal file-upload behavior or it's a specific behavior.

How can I handle the files in that way? I need to validate if at least one of those fields was uploaded (assume they are named foto1, foto2, foto3, foto4), and later I need to reference those files (e.g. getting a public link to them).

Found it -.-''.

$form_state['values']['submitted']['foto1'] returns integer 0, which is a "no file" id, instead of another value (webform for Drupal 7 currently returns a numeric string as id). File extension validation and other rules have been executed beforehand, and finally the obtained id can be loaded with webform_get_file($form_state['values']['submitted']['foto1']), obtaining a managed_file entity (actually, as a stdClass instance).

This is the result of DPM-ing the four fields using dev tools in Drupal 7, where foto4 is not filled. The four entries correspond to calls to webform_get_file($form_state['values']['submitted']['foto1']) to foto4-corresponding field path.


What is the syntax for using a token on webform confirmation page for Drupal 7 Webform 4 I have an Email field on my webform with the key email_address. On successful webform submission, I would like to display the confirmation message as.

Further instructions have been sent to xyz@yahoo.com [Email Address which is submitted on the webform]

I tried using

  [webform:val-email_address]
  [submission:values:email_adddress]

With no luck. The text format is Safe HTML. Not sure if this is causing that
This is on Drupal 7 - Webform version 4.1

Thanks.

Use Webform tokens module

  Webform Tokens provides tokens for user form submissions for forms
  created with the module Webform 3.

But Webform4 has this feature inbuilt, you might try this patch to fix it.

OR

You can try writing webform-confirmation.tpl.php to achieve the same.


How to convert objects into array using serialization API? I'm trying to convert entity objects into array but it's not working. Can you please help me spotting the mistake. I need to use `serializer.normalizer.content_entity' service. The code I have written is:

class ComplexMergeResolver implements ConflictResolverInterface {

  protected $serializer;

  protected function setUp() {
    $this->serializer = $this->container->get('serializer.normalizer.content_entity');
  }

  /**
   * {@inheritdoc}
   */
  public function applies() {
   return TRUE;
  }

  /**
   * @param RevisionableInterface $revision1
   * @param RevisionableInterface $revision2
   * @param RevisionableInterface $revision3
   *
   * @return array
   */
  public function merge(RevisionableInterface $revision1, RevisionableInterface $revision2, RevisionableInterface $revision3) {
    $r1_array = $this->serializer->normalize($revision1, 'array');
    $r2_array = $this->serializer->normalize($revision2, 'array');
    $r3_array = $this->serializer->normalize($revision3, 'array');
    $merge = new ThreeWayMerge();
    $result = $merge->performMerge($r1_array, $r2_array, $r3_array);
    return $result;
  }
}

r1_array is returned empty, which means normalize method is not being called properly. Any help would do great. Thanks in advance.

I tried serializer.normalizer.content_entity but got no success in normalizing the (node) revision entity, or even node entity for that matter. It always resulted in the following error:

  PHP Fatal error:  Call to a member function normalize() on a non-object in core/modules/serialization/src/Normalizer/ContentEntityNormalizer.php on line 28

For this I had to enable the serialization module. I also tried with the ContentEntityNormalizer provided by the "hal" module from core. Result same error:

  PHP Fatal error:  Call to a member function normalize() on a non-object in core/modules/hal/src/Normalizer/ContentEntityNormalizer.php on line 95

I had success with directly using the serializer service from the serialization module. The working code for serializing a node revision is given below. It was verified on /devel/php

$revision = node_revision_load(4);
$container = \Drupal::getContainer();
$normalizer = $container->get('serializer');
$normalized_array = $serializer->normalize($revision);
dsm($normalized_array);

Or combine line 2 and 3 above to get the serializer directly as

$serializer = \Drupal::service('serializer');

In your setup() function, you need the following change:

$this->serializer = $this->container->get('serializer');

P.S: I am still trying to figure out why serializer.normalizer.content_entity is not working and throwing the errors.


Drupal 7 Not Rendering HTML tags I have been trying to research this issue for about a week now but not having much luck as some of the similar postings do not make too much sense to me. Either way, I appreciate any help and guidance on this!

I have a custom module that utilizes the CKeditor and submits HTML tags to the appropriate column in the database table. Example tags:

I am using the views module to display results but instead of the HTML tags rendering, I am seeing:

This is a test:

test 1

test 2

test 3

When I inspect the browser I actually see:

&lt;p&gt;This is a test:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;test 1&lt;/li&gt;
    &lt;li&gt;test 2&lt;/li&gt;
    &lt;li&gt;test 3&lt;/li&gt;
&lt;/ul&gt;

What I want to see is:

This is a test:  test 1 test 2 test 3

Figured out a workaround.

With having the views_php module https://www.drupal.org/project/views_php , I went into the view I was working on and clicked "add" in the fields section.

I chose Global: PHP and the field that would be pulling my database (descr in this case).

For the field that would be pulling from my database (descr), I chose to "Exclude from Display" and in the Global:PHP field, I choose the available variable (which was $row->descr).

There are probably better ways to do this but after spending close to a week, this works for me.


How to make authored on field emtpy I have a content type with revision enabled, each time when I edit the node I can see authored on field has created date by default. I want this  field to be empty so that it uses latest updated time as created time. How can I achieve it?

You might want to use rules 'After updating existing content of type typename' in events and 'set data value' timestamp to created date will accomplish your task easily.


User field image deleted next day I have a strange issue with my drupal website. I created a image field to let users upload their own user galleries (like favorite images), this is not the profile image. The field works fine, users can upload their photos without limits, i can show it on each user profile (ex, if uid = 10 upload 3 photos, that 3 photos will appear on user profile with uid = 10, not on all profiles).

Now the issue is, in the next day (after the user upload the user photos), the photos disappear, i checked the file_managed table, and they no longer exist, but the entries on field_data_field_user_gallery exists. I tried to reproduce the error and this is what i do:

I log as user, upload some photos to my profile;
I visit my user profile page and everything work;
I change my computer date to next day;
I check table file_managed and files still exists;
I visit my user profile again, and no images;
I check again file_managed and the previous entries disappear;

Anyone has any suggestion for fixing this? I already tried to create a new image field, tried to put in different directory, but always end with the same :/ .

Thanks everyone for your help.

UPDATE

I did some tests with @arpitr and found new data. The error (image deleted from file_managed) only happens if i am logged in as VIP user (a role that i have on my site), so if i am logged and admin or "normal user" or even without login, the behaviour is correct, i can visit the (vip) user profile without any problems. Only VIP users can add and edit user gallery.

I temporarily found a solution using file_lock module, but i want to know and fix if possible why is this happening only with vip user role logged in.

Any ideas?

Thanks a lot.

Are you sure the files are not temporary? It does sound like the files are being deleted because they are not yet permanent as Jayendra suggests.

Are you handling the file uploads yourself? Like through a custom form, because I've forgotten to save files permanently before, and I remember wasting a lot of time on it figuring it out :)

The temp files are cleaned with cron I believe, so I find it weird that altering your computer date would trigger the issue. They might however also be automatically cleaned up when you try to render an image that's not yet permanent, and that has passed it's 'lifetime'.


Host has switched to fcgi Our hoster informed us, that he has switched to fcgi. Therefore he had to switch of this part of the .htaccess file and move it to a central part of the server configuration:

<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

Is fcgi ok to host Drupal? Are there any objections against moving this part of .htaccess to an other part of the configuration?

FastCGI should be fine, however...

Your .htaccess may be replaced each time you upgrade Drupal, depending on how you upgrade files.  If you do it manually, you need to diff the new one with old one, and determine if there are any changes and merge the changes.

In actually think all of those settings should be the defaults now in the stock PHP php.ini-dist, but I am not positive about the mbstring ones.

It is very probable that your permissions of your files directory (eg, sites/default/files) is messed up.  Double check that Drupal can read, write, add, and remove files.  The status page should show any problems, but you need to test all cases.

But, one common configuration with FastCGI with shared accounts is that Apache runs as your account user.  This would mean that the site files and the files directory would be owned by the same user.  This is a security consideration to keep in mind.  Preferably, the site files should not have write access by the webserver; write access should be as limited as possible.  You can "solve" this be revoking write access from your user account (ie, make files 444 and dirs 555) except for sites/default/files, but this is a major hassle.

If a host did that to me, I would be EXTREMELY upset.  The provider should have warned you ahead of time so you could prepare, and also given you a test account so you could properly test things out.

Personally, I always recommend true VPS accounts to clients who want to run Drupal.  The only time I would consider shared hosting are cases where the provider specializes in shared Drupal hosting.


make more rare content type appear in result I've made a view that pulls together results from two different content types - "blog posts" and "resources." This resources content type also has a field to further break down resource type (white paper, webinar, case study, etc.)

The problem: There are far more blog posts than resources. So resources get buried, several pages deep in results. How can I ensure that there's a better mix. I considered adding a weight field and grouping by it, but that doesn't seem like it would solve the problem so well. I don't want one weighted over the other. Just a better mix of the newest content, to always include those more rare resources.

I want each results page to show at least one latest 'white paper' resource, one latest 'case study' resource, one latest blog post, etcetera. Something that breaks up blog posts so they don't overpower other needed content.

Or maybe there's a way to force 'for every 2 blog posts, show a resource' ... anything that organically gets results to appear. I can't/don't want to do this manually.

Maybe something 'groupwise' but I'm not sure where/how to accomplish that.

AFAIK you'll have to manually modify the query to get such advanced conditional sorting.

You could group by the type (under Format), and set the Pager to such a high number that you can always be sure there will be at least one Resource there, so the second group will appear for it. But it's not a very reliable method if you can't predict the longest range of blog entries without Resources.

Usually, this is handled by creating two Views displays, one for blog entries, and the other for resources. You can set the Resources one to be Attachment type, and attach it to the blog one so they display one below the other. In that case you will be able to override the number of items in the Pager to show less Resources than Blog entries, to show Blog entries are more frequent.


How Best 301 Redirect in Drupal 7? How can I best redirect the following in Drupal 7?

stuff/bookA.pdf
stuff/bookB.pdf
stuff/magA.pdf
stuff/magB.pdf
stuff/...
stuff/magn.pdf

to

books/booka.pdf
books/bookb.pdf
mags/maga.pdf
mags/magb.pdf
mags/...
mags/magn.pdf

There are only a few Books (which can be redirected individually). There are hundreds of Mags.

I cannot find a module which does this.
I could write a custom module which checks the URL and redirects along these lines.
I am lost writing redirects in .htaccess.

Is there a noticeable performance improvement using .htaccess over the module solution?

If using .htaccess what would the rules be?

If you directly edit .htaccess (at the root directory of Drupal), I suppose you may as well be very careful, because any update of Drupal may delete it.  For that reason, as I understand it is not recommended in general.

I have been using Redirect module for that purpose and am content with it.
With the module, you can manually set the redirection for each path in its configuration panel.  But as you have hundreds of paths, perhaps you want a programmatical way.
An article by Dale McGladdery is concise and helpful for how to do that, using the module (It uses the Migration module; in your case ignore that part and set "From" and "To" URLs to suit your requirements).  Basically, you use redirect_save($redirect) function, where $redirect is the stdClass object, definining the paths and type of redirection.

A potential trouble in his example is, if the same redirection exists, it raises an error.  Therefore if you ever rerun the process to set up the redirections, you will have a trouble.  To overwrite the existing redirection, you need to appropriately set rid of the object to pass to the funciton redirect_save().
I have done that in my migration, and you can have a look at the source code at GitHub (complete() section), if you want to have a look at an example.


How to stop the jquery element being added on ajax requests I've added a toggle for my superfish menu, it works fine but for every ajax load or colorbox trigger the span is created multiple times. How to fix it???

(function ($){
Drupal.behaviors.customjs  = {
attach: function (context, settings) {
$(document).ready(function(){

$("#superfish-1").before("Menu");
$('#superfish-1').toggle();
 });

The better way would be to use the context of the behaviour along with .once() as mentioned here ( https://www.drupal.org/node/1667874 ), something like below:

(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      // Add context along with .once something like below.
      $("#superfish-1", context).once("CLASS-NAME").before("Menu");
    }
  }
})(jQuery);


Drupal 7 - When to use template suggestions? I always found it difficult to work with template suggestions in Drupal.
I'm trying to override those files (html.tpl.php, page.tpl.php, region.tpl.php) for a given url (mysite.com/user-export). So I found this function:

function MYTHEMENAME_process_page(&$variables) {
if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit', '', $_GET['q']));
    if ($alias != $_GET['q']) {
        $template_filename = 'page';
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '__' . $path_part;
        }
        $vars['theme_hook_suggestions'][] = $template_filename;
    }
}
}

That seemed to work pretty well, I created a file named page--user-export.tpl.php to override the page.tpl.php file and it worked.
However, at some point I removed that function, and the template overriding was still working!
So I guess in some cases we need to create a function in template.php, and in some other cases, the overriding is done automatically without having to create a function.

So my question is: When to use template suggestions ?

Thanks in advance!

page--internal-path is already defined by Drupal core as a theme hook suggestion, so adding your own version of it won't really have any effect (just as then removing that version won't have any effect).

You can see a full list of the core-implemented hook suggestions on the Drupal 7 Theme Hook Suggestions page.

The simple answer to the question is that you need to provide your own template suggestions when you require that functionality, and Drupal's core system, or a contributed module, haven't already provided the overrides for you.


Strip HTML from trimmed body before it is trimmed Teaser display has been set to display "summary or trimmed" at 200 characters but the auto generated trimmed body comes through with image tags, links and all.

I have tried the following in THEME_preprocess_node, but it results in a short trimmed version as it counts the html as characters -> trims to 200 -> removes tags:

if(isset($variables['content']['body'][0]['#markup']) && $variables['teaser']) {
    $variables['content']['body'][0]['#markup'] = strip_tags($variables['content']['body'][0]['#markup'], '<p> <br>');
}

This seems like surprising behavior, is trimmed not normally clean? PS this should ideally not be done in the template file.

You might want to take a look at the Smart Trim module. It gives all sorts of options for customizing trim functionality, including stripping HTML.


Where does a theme hook come from? I know I could use something like hook_theme_suggestions_HOOK_alter() to add a suggestion, which would allow me to get a template rendered, but I wish someone would explain where the original ones come from in the first place.

For example, in the Twig debugging html, I'm seeing this:

<!-- THEME HOOK: 'page' -->

...but I don't know where that 'page' hook came from.  I can't exactly grep for 'page' in core.  Could anyone give me an explanation the order in which these things happen, and how they're connected:

Something creates a list of possible templates to use (How?)
Drupal grabs/renders the files specified from this list, from the theme or parent theme
Something adds new suggestions to existing template names, allowing for specificity
You can add your own template names to elements, which causes it to look for those files

Even a good direction to look in core would be appreciated.

The hook page comes from a hook_theme implementation in system.module:

/**
 * Implements hook_theme().
 */
function system_theme() {
  return array_merge(drupal_common_theme(), [
    ...

which calls the function drupal_common_theme() in theme.inc:

function drupal_common_theme() {
  return [
    // From theme.inc.
    'html' => [
      'render element' => 'html',
    ],
    'page' => [
      'render element' => 'page',
    ],
    ...

The hook name is the top key of the array in hook_theme. See the documentation in D8 Theme API. The theme suggestions are built in core the same way as in custom code.


Getting literal ampersands from summary field in a view of fields I have a view where we are using the Body Summary field. I got a bug report that an HTML entity, &amp;,  displaying, where they wanted a literal ampersand.

When I updated our existing view, based on fields, to use the Body Summary field instead of a trimmed body, I did not find the Body Summary field by itself in the list of fields. So, I added another Body field to the view, and re-wrote its results: {{ body__summary }}.

Thinking that the problem was from our site's configuration, I repeated the same steps on a fresh Drupal install: using the Article content type, I added content in the Summary field, and created a view of fields of the Article content type. I got the same behavior on the fresh install.

I posted a question here, but I did not include information about what kind of view I created. I made a mistake from neglect; I did not include all the information needed to understand the situation and answer the question.

A helpful user went through the trouble of creating a fresh install, with two different versions of Core, and reported that he did not get the same behavior, but nonetheless gave a helpful and relevant answer.

That answer got me thinking, and I created a second view of teasers instead of fields. That view has literal ampersands, which is what I want. I concluded that leymanxx, when he did his testing, created a view of teasers, because I neglected to mention what kind of view I made, and thus, he did not see the same behavior that I did.

So now it looks to me that the body field re-write is the origin of the problem. I'm not sure the best way to address it:

Did I overlook the summary field in the list of fields somehow? Is there a "right way" to add it, and I simply did it a wrong way?
When I inspect the field with the escaped ampersand with theme debugging, it tells me this: <!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' --> When I look at that theme file, apart from the comments, I see only this {{ output -}}. Should I override this template? I'm not sure I know how to fix only the HTML escaping issue while ensuring that I'm not creating unwanted side-effects for all my other views. It appears that all views with fields get processed by this template.
Edit just make a new field, this is too much bother. See edits below.

How do I get a summary field displaying literal ampersand characters in a view of fields in Drupal 8?

Edit According to his comments, laymaxx didn't create a view of teasers, but added the body field and set the formatter to "summary or trimmed". We can't use this in our situation, because we never want the trimmed body; first, Drupal does a bad job trimming, and second, our wording in our summary will almost always be different from the first few lines of the body text. We want to use the summary and the summary alone.

At this point, I'm thinking just to add a new field and use that. However, I am curious as to the "right way" to do this, in case I am ever faced with a situation like this in the future.

Override the template and use the twig filter "raw":

Add template file to your custom theme. E.g. /themes/custom/MYTHEME/templates/views-view-field.html.twig
In the above template file add {{ output|raw }}
Clear cache and refresh

  The raw filter marks the value as being "safe", which means that in an
  environment with automatic escaping enabled this variable will not be
  escaped

Source: https://twig.symfony.com/doc/2.x/filters/raw.html


How can I call 2 functions in the same custom module? In my template file I have 2 links like

if(mytest){
  print l(t('Action 1'), 'my_first_link/'.$id);
}else{
  print l(t('Action 2'), 'my_second_link/'.$id);
}

In my custom module I have

function myModule_menu() {
  $items = array();
  $items['my_first_link'] = array(
    'title' => 'First function',
    'page callback' => array('myModule_first_function'),
    'page arguments' => array(1,),
  );
  $items['disableproject'] = array(
    'title' => 'Second function',
    'page callback' => array('myModule_second_function'),
    'page arguments' => array(1,),
  );
  return $items;
}
function myModule_first_function($url_argument){
  print('url_argument = '.$url_argument);
}
function myModule_second_function($url_argument){
 print('url_argument = '.$url_argument);
}

My first link works fine but my second doesn't!

It gives me a 404 error!

How can I solve it?

Thank you

You need to add 'access arguments' to your call:

$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access arguments' => array('some permission'),
);

Or you can add a custom access callback:

$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access callback' => 'some_access_callback_function',
);


How to create a Sub-theme based on a Zen Sub-theme I would like to modify the CTI Flex theme but would prefer to keep my changes as maintainable as possible. CTI Flex is already a Zen (7-x.3-x) sub-theme.

I have used the Zen starterkit in the past to create a Zen sub-theme, but never a sub-theme of another sub-theme.

How do I create a sub-theme of using another Zen sub-theme as a start point?

It shouldn't be too hard ... I have a live site running a sub-theme of an AdaptiveTheme sub-theme (Sky). The only thing you have to is create your theme folder and copy the existing zen-sub-theme.info to your own zen-sub-sub-theme.info and rename the base theme value to the zen-sub-theme.

See this page, some magic inheritence occurs with CSS if you define 1 stylesheet for your theme:
http://drupal.org/node/225125

By creating your own .info file you are defining regions / ccs files and theme specific variables. You will also probably want to copy the zen-sub-theme's template.php file as well (renaming the functions to your themes name).


IE fix for Omega theme? In the past, I have used the Fusion theme for designing web sites. Recently I started using the Omega theme, and realized a big problem with it. I went to look at it in IE, and it looks terrible. In Fusion, there is an IE fix in which, there is a separate css file for ie. I can't seem to figure out how to do this in omega. I know that there has to be a way, because the acquia site is themed in Omega, and it looks fine in IE. how is it that I go about fixing this problem?

As dddave mentioned it is probably because you have on your site more then 31 css files. Ie will use only 31 first files - other will be left alone.

What can you do with it? On live site - turn on standard drupal css aggregation. I will make creating theme painfull - you will need to clean cache(admin/settings/performance) after every css file change. So you can use the IE CSS Optimizer module:

Then there will be more option for css aggregation. It will make possible to aggregate all module's css, and having all theme's files included directly. Hopefully total number of files will be below 31.

For making easier adding condition styles for IE try the Conditional Stylesheets module:


Getting field from code I have difficulties with getting a render Date (ISO) field from code. The field has machine-name field_date. By default, the Date field has three formatter: "long", "medium" and "small". The default formatter for node is set to "medium". (I've checked that, if the field is displayed in usual node's view, it's formatted as it should be)
 Here's the code:

$node = node_load($nid);
$field_date = field_get_items('node', $node, 'field_date');
$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0]);

But the output I get is in "long" variant. Drupal.org says that by default it uses "default_formatter" which is defined in date_field_formatter_info() (having inspected the code, I figured out that that 'default_formatter' actually means 'long'). Well, I want it to be formatted in "medium" way. I write these lines:

$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0], array('type' => 'medium') );

but it's still in its "long". What is wrong with the code?

Solved that! I should have gone a bit deeper in the Date source code.

The solution is this line:

$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0], array('type' => 'date_default', 'settings' => array('format_type' => 'medium') ) );


How change "user menu" to current username I'm looking for a way to change the label "user menu" to be the current user's username. I am using the default Drupal 7 theme, Bartik, if that makes any difference.

You could do that with hook_preprocess_block

e.g, in template.php

function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->subject = check_plain($user->name);
    }
  }

}

Clear theme registry cache after adding new preprocess function.


Which module can be used to get the number of logged in users per day and supports views? I need to get number of users logged in a site / per day.

For ex :

May 1 : 123 logins

May 2 : 140 logins

...

May 30 : 400 logins

I've looked into few modules like login_history and counter. Login history tracks this data, but does not support Views. Is there any module which does this out of the box ?

Thanks

Couple of options (haven't tested either one):

This sandbox project seems to track login time and provides Views integration: https://drupal.org/sandbox/AshishThakur/1614582
Login History also tracks login time, but does not have Views integration yet. A patch was started for this, but looks like it isn't complete: https://drupal.org/node/1402266


How to make a Custom Field available as View Relationship? I'm trying to match the data of a field to a contextual value but I cannot find my desired field in the relationships list.

Do I have to something special to this field to get it to show up under relationships?

I'm trying to have a filter that shows content where the name of
  logged in user is equal to the value of custom field.

Add your custom field as a Contextual Filter.

Select Provide a default value then for Type select PHP Code

PHP Contextual Filter Code

  global $user; // gets current logged in user object

  if (isset($user->name)) {
     return $user->name; // gets user name
  }


Views options in UI not working Options aren't working in my views UI.  JavaScript is enabled.  Example, if in views, if I want to re-write output, and I click the checkbox, I don't get more options.

I just had a similar issue (June 2014) with Views UI. The ajax interactions on the 'style settings' simply stopped working so click on 'customize field HTML' and nothing happened. Hence finding this post/tip. I went to the Modules/JQuery configurations screen (http://website.co.uk/#overlay=admin/config/development/jquery_update) and instructed the Admin Pages to use JQuery v 1.5 (instead of the current 1.10). All View UI interactions then worked fine again.

Adding this extra note for anyone that might find that handy. Thanks to Vintorg and other repliers for the solution.

Q.


4095 Selectors Limit on IE. How to split the Drupal 7 CSS compressed files? Here is my problem. Using Sass (from Zen theme) and on top of that Brunch, our compressed css file has over 4095 Selectors and is then compressed by Drupal (and still has over 4095 selectors in one files).

Do you know if there is a way to tell Drupal to compress files in smaller files in order to avoid the 4095 selector limit per files ?

Lets say your my_theme.info have

stylesheets[all][] = css/my_theme_1.css
stylesheets[all][] = css/my_theme_2.css
stylesheets[all][] = css/my_theme_3.css
stylesheets[all][] = css/my_theme_4.css

And you don't want to aggregate these files in a single one (exceed IE limit 4095 selectors)(also I assume that is already minified by Brunch)

Remove the above lines from your .info or comment out.

Then add an html preprocess function (on the main template.php or if you have an html.preprocess.inc file)

function my_theme_preprocess_html(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'my_theme') . '/css/my_theme_1.css', array('preprocess' => FALSE));
}

The drupal_add_css will add the css but 'preprocess' => FALSE will prevent Drupal to aggregate them.

(It's a bit hacky but it works)


How to get a backtrace in Drupal, without problems like out-of-memory when huge objects are in the trace? I often have problems with the standard backtracing functions when working with Drupal:

debug_print_backtrace(); often seems to get lost between pages and never prints,
Drupal's objects and classes are often so big that debug( debug_backtrace(), "Backtrace", true ); can kill my server with out of memory errors, and debug( debug_backtrace() ); almost always fails with a "Nested dependency" recursion error.

Is there any alternative to the above approaches that can be used reliably, ideally as a drop-in function without needing to set up any framework?

I find this useful as a less memory intensive Drupal-friendly way to backtrace PHP as a one-off code snippet to temporarily drop into a troublesome location without installing modules or server-side tools:

  $trace = debug_backtrace();
  $backtrace_lite = array();
  foreach( $trace as $call ) {
    $backtrace_lite[] = $call['function']."    ".$call['file']."    line ".$call['line'];
  }
  debug( $backtrace_lite, "TRACE", true );

It gets the backtrace into Drupal's debugging system, but strips it down to the essentials to avoid failures when massive objects are involved.

For handy reference, the other keys within each row of the debug_backtrace() object are:

class
object
type
args

Note - this answer was first posted in the now-deleted too-broad question How do I debug Drupal?


Content type within content type? I have such a situation:

I have 4 content types:

city (name)
cinema (name, city_ref, hall_count)
movie (name, description)
session (movie_ref, cinema_ref, hall_number, date_time)

city_ref, movie_ref, cinema_ref are connecting content types with Node Reference module.

After that with Views and EVA I can aggregate some movie listings, etc.

What I want to do is to make site content manager register multiple sessions while entering a movie description, i.e.:

there are number of cities and cinemas created and fixed. But the number of movies may change and content creator opens the form and enters name of the movie, description and then has something like multiple sessions: in the same form content admin can enter session, which automatically has reference to this movie, add reference to the cinema, hall number, date AND (if needed) he could ADD additional session with the same duplicated info, but maybe different hall number/cinema and date.

How could it be solved? Is there any way to connect those content types to make it a bit easier to enter all the data and still have all the relations working?

This sounds like the kind of thing to Node References and the Node Relationships module in D6 or the References module for D7.  Both of those suggest other related modules that might helpful as well.


how to display the suffix of the field? Display the suffix for the field 'price', i use:

<?php
print $node->field_price['und'];
?>

but only it render the value without the suffix ($)

You should ideally be using the render functions to output the stuff in content and node arrays in Drupal 7, the reason you are not seeing the suffix is that you are simply pulling out a value and not rendering.

So the following should work for you:

<?php echo field_view_field('node', $node, 'field_price'); ?>

Take a look at Drupal's reference on field_view_field and this article too


Is there any way to create validation function in system_settings_form Creating a form having two file type element, i want to check that if user uploaded file any file, then user must upload both file, so is there any way to add a validate function in system_settings_form.

The system_settings_form should be used to set simple variables for your module, see the approved answer and related comment here:

Is "system_settings_form" voodoo?

If you want to be sure both form fields are filled out during submission you don't need a validate function -- you can set both fields as being required when you create your form array:

$form['SOMETHING']['#required'] = TRUE;

where something is your form field key.

If you have complex logic and your form isn't simply setting a configuration variable you will call with variable_get or variable_set later -- then implement a custom form_validate and form_submit function for your form as your form is not simply a variable settings form.

See the Form API Handbook. Also of use is this drupal $form lifecycle or workflow illustration. Lastly form validation helpers and submit handlers are touched on briefly on this page of the handbook.

EDIT:

Just to complete my answer, hook_form_alter can change many aspects of a form used by drupal.

EDIT 2:

You can add a custom validator on the form you use to build return system_settings_form($form); for an example see the Commerce Admin include file here: http://cgit.drupalcode.org/commerce/tree/includes/commerce_ui.admin.inc

They set:

$form['#validate'][] = 'commerce_currency_settings_form_validate';

in their form builder function then they provide a validation function:

/**
 * Form validate handler for the currency settings form.
 */
function commerce_currency_settings_form_validate($form, &$form_state) {
  // Ensure the default currency is always enabled.
  $default = $form_state['values']['commerce_default_currency'];
  $form_state['values']['commerce_enabled_currencies'][$default] = $default;
}


How to show the node delete tab and put a view in it? I would like to show a 'Delete' tab near the 'View' and 'Edit' tabs in the node page and insert a custom warning message and a view in it. If I create a view tab page with path /node/%/delete it works fine, but the submit button is missing and I can't figure out how to add it. Any idea?

By creating a view with path /node/%/delete, you have completely replaced the existing page (the delete confirmation form). According to Drupal logic, this is normal behavior.

What I would do is:

1) Do not use the page display of your view, but add a block display to the view. Add your message as view header. Place that block above the main page content and restrict it to the node/*/delete path.

2) Create custom module, implementing hook_menu_alter with one line of  code (credits):

function MODULENAME_menu_alter(&$items) {
  $items['node/%node/delete']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

Of course you need to replace MODULENAME with the actual name of your module.


Node Post Date equals to selected date only not time? I created a view and exposed a Post Date filter. I select a date and I want to show the post of that date. But it searching based on "YYYY-MM-DD HH:MM:SS". I just want to show full day data. I set the operator is equal to.

Install the date module and enable the "Date Views" module, which is a sub-module of the date module.
To your view add the filter "Date: Date (node)".
For the "Date selection form element" option set it to whatever you like.
For the "Filter granularity" option set it to "Day".
Set the "Starting year" option to whatever is relevant.
For the "Date field(s)" option select "Content: Post date"
For the "Method" option, generally leave it set to "OR"
Click the apply button, then continue to configure as you would normally.


Optimize image that does not have an image style We are using the imageapi_optimize modules with the imageapi_optimize_resmushit. We are able to flush the caches for all the image styles and see an improvement. However, there are images that are loaded with background-image attribute that do not get optimized and their image styles are set to Original Image under Manage Display for the image field.

How can I set up the image who use the Original Image Styles setting under Manage Display to be optimized as well?

What we tried:

Enable imageapi_optimize
Enabled imageapi_optimize_resmushit
Setup image optimize pipeline and set it to resmushit
Clear all caches and especially the image style cache using drush if all
Observe all images where an image style is used other than Original Image is optimized after cache.
All images where image style is set to Original Image is not not optimized.

Assuming background-image refers to the example: <img src="" style="background-image: url(path/to/image);" />.

Background images are different when written as: style="background-image: url(path/to/image);", they do not necessarily use Drupal's render service.

A couple of options to try depending on your use case:

• Try preprocessing your image field URI and then printing out the Image Style image path.

use Drupal\image\Entity\ImageStyle;

$imagePath = 'public://images/image.jpg';
$variables['imageStyleURL'] = ImageStyle::load('style_name')->buildUrl($imagePath);

url({{ imageStyleURL }})

• Change the output format of the field to "URL to image", then just print out {{ image_field }} in the url().

url({{ image_field }})

The problem to your question, is how would Drupal (or contributed module) know that an image URL should be processed by an image style? It would not seem an issue with the modules, more they don't have a chance to do their thing.

Also, Twig Tweak, beyond being a great module for many cases, provides a Twig method for applying an image style in Twig:

{{ field_image_path | image_style('image_style') }}

*Note, manual image URL's that contain an image style path will use that image style: /sites/default/files/styles/image_style/public/pictures/2019-03/file_name.jpg_11


Recommended taxonomy/structure for destinations site I am building a site with the primary goal of capturing detailed information about different destinations around the world. What is the recommended site structure for something like this using drupal 7?

So far I envision: my nodes would be a custom location type with the location's details expanded out using fields. I would then replicate the location hierarchy into a hierarchical vocabulary (Continent > Country > City, etc.) so users could search for a specific location. Should the hierarchy be flat (one vocab for Countries, another for Cities, etc.)?

Think of Drupal as an interface to a database (it is one) and vocabularies, when used as the basis for fields associated with your content items, as a means for filtering for values in a table.  If the terms in a hierarchy would have 1-to-many or many-to-many relationships, then you will want to have separate tables and therefore separate vocabularies so that you can use relationships to make selections.  In your case, the relationship between continent-county-city is one-to-one (with occasional duplicates such as two cities with the same name) so a single vocabulary, using a hierarchy, makes more sense.

The Views module is basically a UI for queries to the database, so you will use Views to make selections from your table, and menus can be structured as hierarchies to present selections to users using the same multi-level logic of your location vocabulary. You may choose to create content by defining a new content type article that has a field attached to it associated with the location vocabulary and perhaps a second vocabulary to identify the type of information it contains.  This second vocabulary would have terms such as geography, government, cuisine, hotels, restaurants, etc.  When creating an article about hotels in Paris, you would label the two fields from the vocabularies so that the articles can be filtered accordingly.  This is, in simple terms, how Drupal assembles sites.


Search & replace serialized data after moving the files directory A drupal 6 content_field_video table holds serialized data with URLs pointing to the old site location - sites/default/files/thumb.png. Moving to the otherwise amazing Aegir-based omega8 hosting platform, we moved to a new files directory,  sites/MYSITE.COM/files/thumb.png,  so we need to convert to URLs to a new scheme. Most of the URLs are corrected by the omega8 import process, but video thumbnails are hardcoded.

What's the easiest way to do it?

The scanner module scans all CCK fields - Since this is a CCK field, it should correct this kind of problem, if this is a small database. But for large database it may suffer from performance issues.

You can also do it with PHP or SQL.


Help understanding Drupal form creation/content creation I am fairly new to Drupal 7.9 and still trying to get a hang of it. Understandably it has a learning curve which I am trying to scale at the moment.

My challenge here is to basically create a page that has some backend processing to it. The front page consists of form elements (mostly textboxes) arranged in a tabular format.

A little bit of exploring and I reckoned I might need to create a kind of content type and then add content. But I got nowhere with this.

Then I discovered the webform module that lets me create form elements and provides a bunch of operations. But it doesn't necessarily allow me to display my form elements in tabular format.

So before exploring on my own again, I felt it would be right to ask questions from you guys.

Anybody with any leads on this ?

Thanks much !!!

Parijat

You probably need to explain what you mean by "background processing", i.e. are you looking to save content or do something else?

At any rate, if you really need to template your form to be table based, this is possible by implementing hook_theme. An example entry for a form with an id of example_search_form (this is the argument passed to drupal_get_form() or can be found by looking at the id of the generated form by viewing source) and a template file called example-search.tpl.php looks like:

  $hooks['example_search_form'] = array(
    'arguments' => array('form' => NULL),
    'template' => 'example-search',
  );

  return $hooks;

Then in your example-search.tpl.php you can render individual form items however you would like.


How to let site member to access vertical tab? How to let site member access the picture above?

It depends on which tab you're talking about. The highlighted one, Menu settings, is controlled by the Administer menus and menu items permission. Many of the vertical tab items is granted by the Administer content permission.


Load theme tpl after form submit From a custom module in Drupal 7 I am trying to load a template after I submit and process my form.

I can load the theme fine from a page callback:

function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'arguments' => array(),
    ),
  );
  return $themes;
}

function mymodule_menu() {
  $items = array();
  $items['reports/performance'] = array(
    'title' => 'My Module Performance Report',
    'page callback' => '_mymodule_report',
    'access arguments' => array('mymodule_client'),
  );
  return $items;
}

function _mymodule_report() {
  return theme('mymodule_report');
}

All of that works fine (e.g I can go to www.mysite.com/reports/performance and my tpl loads.).  The problem is when i submit a form, after I process the form I want to pass the form data to the template, and load the same template page.

I modified the hook_theme like this:

function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'variables' => array('parameters' => NULL),
    )
  );
  return $themes;
}

And in my submit handler for my form after I gathered all my form values into an object ($submission), I added this at the end:

 return theme('mymodule_report', array('parameters' => $submission));

All that happens is my form reloads...what am I missing?

So I found a solution that works...of course if there's another or better way, I'd love to know.

I added this to my form:

  if (!empty($form_state['nnjob_mtbf']['mtbf_results'])) {
    $form['result'] = array(
      '#markup' => $form_state['nnjob_mtbf']['mtbf_results'],
    );
  }

And then to my form submit handler:

  $form_state['nnjob_mtbf']['mtbf_results'] = theme('nnreport_client_perf_report', array('parameters' => $submission));
  $form_state['rebuild']=TRUE;

And voila, template loads like a champ.


How to generate content to Drupal 7 with a PHP-script? I have been given the task to generate a couple of thousand of pages in drupal that should contain text generated by a php-script. After that is done, I'm supposed to perform searches on the generated words and play with the settings in Drupal to make the searching as fast as possible.

I have the php-script that generates the text but what I am asking for is the php-script that generates the pages and for each one calls my php-script to put a mass of generated text on the page.

I know that there is a file in Drupal that I can use since I read this page https://api.drupal.org/api/drupal/scripts!generate-d7-content.sh/7, but that one generates text that I can't perform my searches on. I think I need to modify it to call for my own text generator but I'm not sure of how?

Is there someone out there that maybe could help me? It would be most appreciated!

You can use contrib module for that purpose

Devel

  Generate content

  Accelerate development of your site or module by quickly generating
  nodes, comments, terms, users, and more.

Dummy content

  DC allow your custom module to provide demo nodes as soon as the
  module is installed - this helps with populating blocks, views, and
  generally showcasing your module's functionality. This is very useful
  when showcasing a module's functionality to a client. For example,
  rather than installing the Forum module and having to manually create
  forum nodes, the DC API can be used to pre-populate the site with
  forum-type nodes as soon as the Forum module is enabled. Additionally,
  rather than having purely Lorem Ipsum-type content, you can define
  relevant pieces of text and images, giving the content a more complete
  & realistic look & feel.

Note:  Both modules will create random content.


What Hook to Use to Execute a PHP on Header and Footer in Every Page? I have the following code that needs to be executed at the top of the page:

<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
?>

The code above should be used in my module:

<?php
/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function site_visitors_help($path, $arg) {
    switch ($path) {
    case "admin/help#site_visitors":
        return '<p>' . t("Displays links to nodes created on this date") . '</p>';
        break;
    }
}

/**
 * Implements hook_init().
 */
function site_visitors_boot() {
    site_visitors_insert();
}

/**
 * Custom visitor function.
 *
 * Insert IP Address, URL to the database
 *
 * @return
 *   A result set of the targeted posts.
 */
function site_visitors_insert(){
    $tracker = array(
        'database' => 'c1tracker',
        'username' => 'c1tracker',
        'password' => 'mypass',
        'host' => 'localhost',
        'driver' => 'mysql',
    );

    Database::addConnectionInfo('tracker', 'default', $tracker);
    db_set_active('tracker');

    //This code requires the code above to compute the start time. This will compute the total page load.
    $time = microtime();
    $time = explode(' ', $time);
    $time = $time[1] + $time[0];
    $finish = $time;
    $total_time = round(($finish - $start), 4);
    $t = $total_time;
    //$url = $_GET['url'];
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $current_ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $date = date("Y-m-d");
    $time =  date("h:i:s");

    function is_bot()
    {
        $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
        "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
        "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
        "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
        "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
        "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
        "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
        "Butterfly","Twitturls","Me.dium","Twiceler");

        foreach($botlist as $bot)
        {
            if(strpos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
            return true;
        }
    return false;
    }

    if (is_bot())
        $isbot = 1;
    else
        $isbot = 0;

    db_insert('ap_visits')
        ->fields(array(
            'id' => NULL,
            'length' => $t,
            'url' => $url,
            'current_ip' => $current_ip,
            'user_agent' => $user_agent,
            'date_start' => date("Y-m-d H:i:s"),
            'is_bot' => $isbot,
            'is_logout' => 0
        ))
        ->execute();

    db_set_active();
}

I'm wondering how can I put the first code to be called at the very top of the page and the second code (module) to be called in the footer. My purpose here is to compute the page load and put it in length variable.

BTW, I'm using drupal 7.

hook_init() is run at the beginning of the page request. So this is where you should start your timer.

hook_exit() is run at the end of most regular page requests. And it's here you should stop your timer.

I did a search on similar modules and found Arooga, maybe you can find some ideas there. Also Devel has functionality to log page execution time, slow queries etc.


How do I add a CSS class to a p tag in CKEditor? The standard center button only applies a in-line style to the HTML.
But how can I add a class 'text-center' to a paragraph or selection by clicking the following icon? I went ahead and created a custom button on CkEditor.

(function($) {
CKEDITOR.plugins.add( 'center', {
    icons: 'center',
    init: function( editor ) {
        editor.addCommand( 'center', genCommand());
        editor.ui.addButton( 'center', {
            label: 'Align text on center',
            command: 'center',
            toolbar: 'center'

        });
        if ( editor.contextMenu ) {
            editor.addMenuGroup( 'centerGroup' );
            editor.addMenuItem( 'centerItem', {
                label: 'Change link',
                icon: this.path + 'icons/center.png',
                command: 'center',
                group: 'centerGroup'
            });
            editor.contextMenu.addListener( function( element ) {
                if ( element.getAscendant( 'center', true ) ) {
                    return { abbrItem: CKEDITOR.TRISTATE_OFF };
                }
            });
        }
        CKEDITOR.dialog.add( 'centerDialog', this.path + 'dialogs/center.js' );
    }
});
function genCommand( name ) {
    return {
            exec: function( editor ) {
                editor.insertHtml('
' + editor.getSelection().getNative() + '
');
            },
    };
}
})(jQuery);

What it is doing is nothing. In the case there is a selection, it deletes the selection and markup.

What I need:

If there is a line saying "text", I need
text

In the case there is a selection, make 1 out of the selection

Using WYSIWYG/CKEditor in Drupal, you can add classes in the UI and they will show up in the Style drop down.

In the CSS tab of the WYSIWYG Profile you are editing:

You need to have the "Font style" plugin checked off in the config.

Now any element you add here can have it applied, so you would add:

Center P Tag=p.text-center

line to this config.

Then, add some text in the editor, and highlight the text (CKEditor should automatically wrap regular text with a p tag). You should then see the option in the drop down as "Center P Text". You will only see these options available when you've highlighted elements that are applicable. It will then apply the class to the highlighted element, the p tag.

I use this all the time to add classes to various elements just as you are trying to do.


Ensure registered users can publish nodes only after paying some money Is there a way to charge registered users who publish a node in a Drupal 8 site?

If I'm not wrong, the pricing process should be easier as Web services are now part of the core in Drupal 8.

Pricing should be through Paypal.

The pre-existing solutions ( Commerce Node Checkout,   UC Node Checkout, Pay-per-node) for this problem haven't been ported into D8.

If one of the pre-existing solutions covers your use case well, you could help port it to D8 (Commerce 2.x is likely to have a stable release this year). Otherwise, you're looking at some sort of custom solution involving involving modifying the node form workflow and PayPal integration.


Taxonomy child terms as Select options in CCK form I have a vocabulary with parent-child terms. Every user is linked to a parent term in their profile field. And, I have CCK that the users fill in.

I need to add a Select Field with options as Child terms of a parent term that the User is linked to. (and save as term ref preferably)
How do I achieve this?

Vocabulary: "Sites"
ONE
 -a
 -b
 -c
TWO
 -d
 -e
THREE
 -f
 -g

User1 => profile field term ref => "ONE"
User2 => profile field term ref => "TWO"

CCK type: "Study"
node/add/study  =>  select field (term ref) => "Select Site"
for User1 => Select site options => a, b, c
for User2 => Select site options => d, e

For this you can add a term reference field and use the full vocab. Then you will need to do a form alter hook in one of your custom module and filter out options based on logged in user.


Drupal 8, very simple hierarchical form doesn't work In a custom module, I create a new form. In the buildForm function, I define my form :

$form["planet"] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('planet'),
  '#maxlength' => 64,
  '#size' => 64,
  '#tree' => TRUE,
);

$form["planet"][0] = array(
  '#type' => 'textfield',
  '#title' => '0 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

$form["planet"][1] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

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

There are 3 fields, but this is the result :

Why there only first field displayed ?

You need change type $form["planet"] to fieldset or container. Don't use text field in this case:

$form["planet"] = array(
  '#type' => 'fieldset',
  '#title' => '1 : '.$this->t('planet'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);


Add Rating Widget to a custom full content layout in drupal 7 Can anyone know how to add a rate widget to a custom full content layout in drupal 7.

Let say I have a content type article.A have customized the layout with the help of Ds module for the full content.I have added my the field to my choose.Now I need a rating in the full content page with that the user can vote the article whether they like it or not.For that I added a module called Rate widget.With that I try to add a Thumb up/down to the full content page of the article but it is not showing me.Can any one know how to add rate widget to the custom full content.

You can use below function to print rate field

rate_embed(&$node, $machine_name, $mode = RATE_FULL);

Like print rate_embed($node, 'rate', $mode = RATE_FULL);


how to add attributes of the parent taxonomy in the DOM? I am displaying a taxonomy "category" on a node, a view of that node ,and a search facet.
This taxonomy has 2 levels.
How can i add to the rendered HTMLs, i guess using preprocessing hooks, an attribute indicating the taxonomy parent id ?
I would need to apply CSS differently to the taxonomy buttons depending on the parent.

You can add the relevant Taxonomy parent Field to your Views, make it display the term ID. This way you get that information available as a token.
You can hide that field with Exclude from display and position it above all the other fields, so you can use it as a token in all of them without worrying about the position.
Then edit the Style settings of your "Parent" field that you want to style and enable the Create a CSS class option. You can enter the token for your parent TID in there.
Since css classes can't start with numbers make sure to enter a safe start for the class, for example: myclass-{{ tid }}
To find the list of tokens you'll have to temporarily enable the option Rewrite results > Override the output of this field with custom text > Replacement patterns.
You may need to Customize field and label wrapper HTML and/or Use field template depending on your particular configuration and output to get the class to show up.

Alternatively, you can construct the output of your field on your own with the Override the output of this field with custom text and enter what you want the HTML to show:

{{ field_output }}


How do I enable and use the password module for Drupal 6? I've uploaded the module to my site, but it doesn't appear in the list of modules so I can't enable it. Does this module work differently than other modules?

https://drupal.org/project/password

No, this module works as any other module. See my screenshot as I can see it in my module listing -

Are you sure you have it in sites/all/modules/ ? Are the permissions correctly set?


Download a File Outside of Web Directory I have a scenario where certain files are stored outside of the Document Root directory, like this...

/home/user/public_html/{drupal files are in here}
/home/user/data/{special data files are in here}

I would like to allow users with special permissions to download files from /home/user/data using Drupal's built-in file wrapper, but I'm not sure how to link to the files.

Addendum: Most of my files are stored in the usual location:

/home/user/public_html/sites/default/files

It is only some of them I need to store in the external data folder. For security reasons I do not want to change the sites/default/files/ directory to /home/user/data.

Drupal 6 doesn't support having both private and public files enabled, but there are some modules that provide this, for example http://drupal.org/project/private_download.

If that modules doesn't do what you need, you can also write your own, see file_download() for inspiration. This is the page callback that serves private files through PHP by checking access with hook_file_download().


What to do when you can't upgrade modules? I have some old sites running "dead" versions of modules in my drupal (I made the upgrade to the last current Drupal core version).

But some of the modules used in this site are not longer supported or they need a "major" upgrade. This will break my site for sure, because some of them are used.

What do you think it's the best approach to fix this ? Because this represents a serious risk for the security of the website.

Major upgrades of modules should not be a problem if the module is still supported. Just do drush up moduleshortname in the CLI (or replace the old code in the module directory with the new if you don't have drush). Updating a module is integrated in Drupal. If you do this manually (drush will do it automatically) just make sure you run Update on your site after updating the module (Update is linked to on Reports->Status Report page if you need to run it). Update should take of all incremental updates of the module, its schema, and the data in the schema, automatically. Unless there are a bug in the code to update the module, there should be no data loss.

Modules that are no longer supported, especially if they're unsupported because they have security vulnerabilities the maintainer did not fix, are a problem.

The first thing to do is to review the unsupported module and the features it brings to your site.  Is this features your site cannot live without?  If the answer is "no", just disable and uninstall it.

If the unsupported module provides functionality you need, try to find some supported replacement for each unsupported module.  If you find a replacement, you need to migrate all data from the old unsupported module to the new one.  If you're not a developer, you may need to hire a consultant to help you with migration.

If you don't find a replacement, and you are a developer, you may consider fixing the insecure module.  If you follow the process for dealing with unsupported projects, and work with the security team, you should be able to fix the problem. The security team is a helpful bunch and may provide some guidance.

As a last resort, you may hire a consultant to fix an insecure module you absolutely need, forking the result as a custom module for your site.

As already described by Darvanen, you need to do all this on a development server first and only repeat the procedure on your production server when you're sure the update did not damage anything. And make a backup before you start, just in case.


Text format filter for embedding links and videos into body copy I would like to get a functionality similar to Facebook: when you include any link in a status update, post or comment it will replace it with a thumbnail, link and short description of the page.

The emfield module has that functionality but it requires an extra field and can't do the replacement within a body copy.

Video Filter does it for videos but it requires a special syntax [video:url] that a user would have to learn. It does offer Wysiwyg integration.

Is there any way of achieving a seamless (Facebook-like) experience?

A quick hack in Drupal 6 for the links would be:

<?php

function MYMODULE_filter($op, $delta=0, $format=-1, $text='') {
  switch ($op) {
    case 'list':
      return array (0 => t('MYMODULE Open Graph Link Maker'));

    case 'description':
      return t('Changes links into Open Graph Link Blocks with a thumbnail, title, and description');

    case 'no cache':
      return FALSE;

    case 'process':
      return _MYMODULE_og_block($text);

    case 'prepare':
      return $text;
  }
}

function _MYMODULE_og_block($text) {

  $text = preg_replace_callback("`(<p>|<li>|[ \n\r\t\(])(www\.[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+~#\&=/;-])([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '_MYMODULE_link_to_og', $text);

  return $text;

}

function _MYMODULE_link_to_og($match) {

  $all = file_get_contents('http://' . $match[2]);      // alas get_meta_tags() only finds tags with name=, not property= like og: uses so we need to do this ourselves...
  $title=_MYMODULE_get_og_meta('title', $all);
  $image=_MYMODULE_get_og_meta('image', $all);
  $description=_MYMODULE_get_og_meta('description', $all);

  if ($title && $image) {
    $content=$match[1];
    $content.='
';
    $content.='';
    $content.='' . $title . '
';
    $content.=$description;
    $content.='
';
    $content.=$match[3];
    return $content;
  } else {
    _filter_url_trim(NULL,72);                       // these might be different in D7
    return _filter_url_parse_partial_links($match);  // but all it does is the default behavior of changing it into a link
  }

}

function _MYMODULE_get_og_meta($meta, $text) {

  $foo=explode('<meta property="og:' . $meta . '" content="', $text);  // I am sure someone out there can do this better with preg_replace_callback :)
  $bar=explode('"', $foo[1]);
  return $bar[0];

}

which looks for www.__ and creates a simple facebook like div from the facebook og: meta tags.  If you wanted to get fancier, of course you could look for the first image etc in the html in a similar fashion if they weren't present.

Now, I know you said you are using drupal 7, and I think that would be just changing MYMODULE_filter() to MYMODULE_filter_info() and changing up the arrays in the return as the filtering code itself should be the same.  Obviously, css style it how you want, I just threw in some quick stuff.

Also, this obviously doesn't do any of the fancy facebook ahah stuff but for something coded while watching Hawaii Five-O, I hope it helps you out a bit :)

Oh, somewhat obviously, to turn it on, you would go into your input filters and add/enable it for filtered_html, for example, and turn off the original one that changes www.__ into links so you don't refilter it again.


How do I get raw urls with contextual filters to work with views in Drupal 7, when i'm using panels, and panels everywhere? I've scoured the site for solutions, and I have no idea what's going on. I have drupal 7 running off a local installation (mamp), and my site is structured with Panels and Panels Everywhere. I have a view that is in the sidebar, and I want it to pull up anything tagged with the name of the page. (for example walldamp/drupal/architecture would pull up architecture, or walldamp/drupal/acoustics would pull up all nodes tagged with acoustics).

The preview works just fine when I type in a tag, but it just won't work with the sites. If anyone could help, I'd really appreciate it.

I'll post a picture as soon as I get more reputation, but currently my settings are as follows for the contextual filter.

Configure contextual filter: Content: Has taxonomy term ID
Provide Default Value
Raw Value form URL
Path Component: 3
Exception Value: All
Specify Validation Criteria
Validator: Taxonomy Term
Filter Value Type: Term Name converted to Term ID
Transform dashes in url to spaces in term name filter values
Action to take if filter value does not validate: Display a summary.

It's just displaying the summary in my sidebar, no actual blog posts or images like in the preview. Any help would be appreciated.

Try using argument 2 (URL arguments start at 0 not 1) as opposed to argument 3. A Failing that, disable the validation, oftentimes the validation is screwy and excludes valid content.  Start with as little filtering, validation, exclusion, etc. to make sure you're getting data and tighten the parameters from there.


How to get a certain header on FunctionalJavascript tests Since Drupal 9 is around the corner I'm working on puhsing some contrib modules (and a couple of my own) to be Drupal 9 ready. That involves on updating my tests to use replace deprecated code. Currently I'm working on this issue from Devel module, which replaces \Drupal\FunctionalJavascriptTests\JavascriptTestBase with \Drupal\FunctionalJavascriptTests\WebDriverTestBase but since this I cannot get headers during FunctionalJavascript.

My question what is the proper way to get them. I've checked tests in core but I just can't figure it out.

The code I'm working on is like so:

/**
 * Wait until the toolbar is present on page.
 */
protected function waitForToolbar() {
  $session = $this->getSession();
  $token = $this->getToken();
  $page = $session->getPage();

  $toolbar = $page->findById('webprofiler' . $token);
  $this->assertTrue($toolbar->hasClass('sf-toolbar'), 'Toolbar loader is present in page');

  $session->wait(1000, 'null !== document.getElementById(\'sfToolbarMainContent-' . $token . '\')');

  return $token;
}

/**
 * Return the Webprofiler token.
 *
 * @return null|string
 *   The page token
 */
 protected function getToken() {
   $token = $this->getSession()->getResponseHeader('X-Debug-Token');

   if (NULL === $token) {
     throw new PHPUnit_Framework_AssertionFailedError();
   }

   return $token;
 }

As shown the header is required in order to get an element that is generated using Javascript. Perhaps theres another workaround than fetching the header, but not sure how right now.

Thanks in advance.

I was getting all wrong. This is the key, copied from https://www.drupal.org/node/2857562

  All assertions within these tests must be done by checking the UI. Assertions that don't relate to UI should be added to other types of tests, a BrowserTestBase for example.

I should break this test in two one Functional to check proper header setting and the other pure FunctionalJavascript to check the element (whereas the token is set or not) is present on the page. Also does not make sense in this specific case to have two Webprofiler bars present on the page so a simple document.querySelector('[id^="sfToolbarMainContent-"]') should do the trick.


how to display entity references as numbered list? I'm selling music albums in Commerce. The product type has an entity reference field with unlimited values for the content type 'tracks' which I'm using to display the tracklist of an album. I'd like to output this field as a numbered list so the track I reference are displayed like this:

track title
track title
etc.

I also need to be able to export the track number from a View via Views Data Export.

Any ideas as to how achieve this?

Its pretty simple, in this example I will use title instead of an entity reference field, but it's the same process.

Step 1) add Global: View result counter as a field.

Step 2) Uncheck create label, and checkmark hide from display.

Step 3) Re-arrange so your counter is above your entity reference field.

Step 4) Re-write results and use replacement patterns to format your title field.


Configure/Override EU Cookie Compliance I've installed eu_cookie_complience module (eu_cookie_compliance 8.x-1.9). The documentation is nearly non-existent, but as much as this module is used, I'm hoping to find someone that has solved these issues.

The big one: how does one set the eu_only parameter to true? Crazy, but there does not seem to be any option in the Admin panel. I could hack the contrib yaml or worse the module and force things. But that's a bad idea.
How can I hook into or override eu_cookie_compliance and specify my own IP lookup. Though it isn't documented, apparently there are three ways to check to see if the user is EU (the smart_ip module, the geoip module, or geoip_country_code_by_name())  We already use IPSTACK and I want to leverage that.

The settings form is hard-wired to only display the config field on the form if one of the following is installed: the Smart IP module, GeoAPI module, or the PHP geoip extension. Outside that you'll have to bypass the config form; if you're version controlling your config, make the change in the eu_cookie_compliance.settings.yml file; or use drush cset to make the change directly.
The hooks are documented in eu_cookie_compliance.api.php. You're wanting to use hook_eu_cookie_compliance_geoip_match_alter() that lets you alter the results from the eu_cookie_compliance_user_in_eu() function. The parameter $geoip_match is a keyed-array with country & in_eu keys that drive the logic.


Drupal 7 Field Performance I've created a Content Type that will have >50 fields. I've noticed that each field has a corresponding table. Is Drupal joining 50 tables in order to load the page with all of the designated content?

Would a high amount (but not an unnecessary) amount of fields cause a noticeable decrease in performance?

Thanks in advance for your answers.

Answer really depends on your database backend. If you're using something like MySQL 5.6 or MariaDB 5.5 I would say probably not http://www.mysqlperformanceblog.com/2012/04/04/join-optimizations-in-mysql-5-6-and-mariadb-5-5/. If you're using a different database backend, it will be hard to tell without testing.

If using something like MongoDB for the field backend then it shouldn't cause any performance issues.

If you don't want to go with MongoDB or bleeding edge MySQL you can also look into using something like the Entity Cache if you find that all the fields is causing performance issues.


How to create a clickable area on the whole block view? I created a block view of my articles. The display format is grid bootstrap.

How to create a clickable area on the whole block view?

I want all my block (not just the fields, but the whole block) to be clickable and dirrige to /node/nid

"Additional attributes" can it be useful to create the link ?

Use CSS and custom template structure...

Markup:

    // Your various markup.
    {{ content }}
    // Link contains no text and is absolute positioned to cover the entire markup area.

    // The span can be absolutely positioned as well so it is on top of the link.
    This is a flag

CSS:

.views-row {
    position: relative;
}

a.link {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
}

span.flag {
    position: relative;
    z-index: 200;
}

With this approach, you will avoid having a link that contains a lot of text and markup that makes no sense to browsers and screen readers.


Send a form to twig template How I can pass a form to twig template in Drupal 8?

For example, I get this:

a form: mymodule/src/Form/MyForm.php

Then on my Controller:

public function myController() {

    ??????

    return [
        '#theme' => 'mytemplate',
        ??????
        ];
}

mytemplate.html.twig

{{ ????? }}

Well, I did it, for anyone that needs this:

public function pageAction() {
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  // If you want modify the form:
  $myform['field']['#value'] = 'From my controller';

  $build = [
    '#theme' => 'mytemplate'
    '#form' => $myform,
  ];
}

In twig:

{{ form }}


Jquery not working on node edit page Added jquery library, it works fine, but when i click on node edit, jquery does not work for this page. I need to style some inputs inside this edit page. I am using theme zen.
For example i want to change color of edit-title

(function($) {
$(document).ready(function(){

    $('#edit-title').css('color', 'red');

  });
})(jQuery);

not working. Its loaded i see in firebug. But any code does not work(only inside edit or admin menus).

In the firebug(any) console, try jQuery('#edit-title').css('color', 'red'); it should work or something with the css is wrong.

For Drupal you're really supposed to use something like this to do on document load:

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
})(jQuery);

Check out Managing JavaScript in Drupal 7, and search for "behaviors".

@ krister.. The code is a function where the $ variable is jQuery. So in most languages you create function and declare variables that you want passed into it. Well in JavaScript you can create that in one line.

function some_function(tmpVar){ alert(tmpVar); }
some_function("Woot!");

You can wrap the function side in ()s and it still works
( some_function )("Woot!");

Now you can put an anonymous function block instead of some_function

( function(tmpVar){ alert(tmpVar); } )("Woot!");

and finally the jQuery

(function($){... the $ = jQuery ...})(jQuery);


How do I correctly setup caching for my custom block showing content depending on the current node? I have this very basic block which just shows the current node's ID.

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\ExampleEmptyBlock.
 */

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * @Block(
 *   id = "example_empty",
 *   admin_label = @Translation("Example: empty block")
 * )
 */
class ExampleEmptyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    $build = array();

    if ($node) {
      $config = \Drupal::config('system.site');

      $build = array(
        '#type' => 'markup',
        '#markup' => '<p>' . $node->id() . '<p>',
        '#cache' => array(
          'tags' => $this->getCacheTags(),
          'contexts' => $this->getCacheContexts(),
        ),
      );
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $node = \Drupal::routeMatch()->getParameter('node');
    return Cache::mergeTags(parent::getCacheTags(), ["node:{$node->id()}"]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['user.node_grants:view']);
  }

}

But once cached, the block stays the same, regardless which node I visit. How do I correctly cache the result per node ID?

This is full working code with comments.

namespace Drupal\module_name\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * Provides a Node cached block that display node's ID.
 *
 * @Block(
 *   id = "node_cached_block",
 *   admin_label = @Translation("Node Cached")
 * )
 */
class NodeCachedBlock extends BlockBase {
  public function build() {
    $build = array();
    //if node is found from routeMatch create a markup with node ID's.
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $build['node_id'] = array(
        '#markup' => '<p>' . $node->id() . '<p>',
      );
    }
    return $build;
  }

  public function getCacheTags() {
    //With this when your node change your block will rebuild
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      //if there is node add its cachetag
      return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    } else {
      //Return default tags instead.
      return parent::getCacheTags();
    }
  }

  public function getCacheContexts() {
    //if you depends on \Drupal::routeMatch()
    //you must set context of this block with 'route' context tag.
    //Every new route this block will rebuild
    return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
  }
}

I tested it; it works.

Just put the code in a file named NodeCachedBlock.php in your module folder, change its namespace {module_name}, clear the cache and use it.


What's the latest in the page lifecycle a module can send an HTTP header? For CDN purposes I am collecting the modified times of various pieces on the page and want to set the Last-Modified header to them. What's the latest during a request a Drupal 7 module can call drupal_add_http_header?

I know the answer but I think this is a very interesting question and I somehow doubt most people would know the answer, so I will leave this open for a few days and then post the answer.

Note

To avoid insane answers like using runkit or doing your own request cycle, I will say the answer is userland PHP only, and less than 10 line of code.

Headers can be sent anytime up until the content is sent to the page which happens in drupal_page_footer(). The whole page is output buffered: _drupal_bootstrap_page_header has the ob_start and drupal_page_footer has the ob_flush.

Headers are also overwritten by default so there is no reason why you can't re-send the Last-Modified header at any point.

So, how about hook_exit() (called from drupal_page_footer just before the ob_flush).


Getting "Additional uncaught exception thrown while handling exception" I tried to install module Commerce Event Ticket, added all the requirements, then enabled Commerce Event Ticket and got an error message:

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;base.owner&#039; in &#039;field list&#039;: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.owner AS owner, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] =&gt; reaction rule [:db_condition_placeholder_1] =&gt; 1 ) in EntityAPIController->query() (line 187 of /home/content/q/u/a/quaa7882/html/sites/all/modules/entity/includes/entity.controller.inc).

Additional

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;base.owner&#039; in &#039;field list&#039;: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.owner AS owner, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] =&gt; reaction rule [:db_condition_placeholder_1] =&gt; 1 ) in EntityAPIController->query() (line 187 of /home/content/q/u/a/quaa7882/html/sites/all/modules/entity/includes/entity.controller.inc).

Now, this message also appears on the page without admin rights i.e. my page is  Offline now! How can I fix this?
Thank you!

Okay after this error, I ran www.mysite/update.php it applied a few updates after which I was able to access the admin pages but if i wanted to access my front page, I'd still get

Fatal error: Call to undefined function field_info_field_map() in /home/content/q/u/a/quaa7882/html/sites/all/modules/addressfield/addressfield.tokens.inc on line 92

instead. I then removed the module addressfield by ftp manually and my site was back up and running so that I can care about my module(s)  separately.


Let the user set the target of the link in a link field Link module has been added to core in Drupal 8, but it doesn't seem that all its features has been ported.

For example, letting the user choose the target of the menu. In Drupal 7, the module would let me create a field and in its configuration set an option to let the user choose the target. In Drupal 8, I don't see that option.

Is that option present in Drupal 8?

You can use https://www.drupal.org/project/link_attributes for that. No, it is not in core.


Drupal 8:How to add tags for custom content types Newbie here!

I go to Structure > Content types > Add content type and create a new content type.

But how can I add tags to my new content type, just like when you go to Content > Add content > Article, you get the option to enter a title, tags and body.

How can I add the capability to add tags to my new content type?

Thanks

Go to /admin/structure/types and press on manage fields of your custom content type

Press on the +Add field button, and use Re-use an exiting field (the drop down on the right) to select the existing Entity Referenc: field_tags

Then go to manage form display, for tags change the widget to autocomplete (Tags style)

PS: I suggest you install admin toolbar if you haven't already.


Only display profile edit button on personal profile page I'm using the profile module and am trying to display a profile edit button on your personal profile page.

my profile.html.twig:

{% if is_current_user %}

        {{ "Edit profile"|t }}

  {% endif %}

          {{ content|without('field_image', 'field_extra', 'field_tags') }}

{{ content.field_extra }}

      {{ content.field_image }}
      {{ content.field_tags }}

The a-container div may only be displayed if the current user id is equals to the user id of the user linked to the profile that's being displayed.

I'd like to make this check in a preprocess function and return a bool 'is_current_user' to profile.html.twig but I'm stuggling to find the right hook for the profile page.

I'm on drupal 8.7.1.

Thanks in advance!

Found the answer in access the user associated with a profile.

It was simply THEME_preprocess_profile.


Why we use dependencies keyword in {theme}libraries.yml ? and not just include the file? in the {theme}.libraries.yml why we need to declare the jquery js or any other library as a depedency :
  js:
    assets/lib/bootstrap-4.0.0-dist/js/bootstrap.js: {}
    assets/script.js: {}

 dependencies:
     - core/jquery

an not just include it for example as a simple js, before all other js that depends on it :
  js:
    assets/jquery.js: {} # load dependency library before the dependent libraries.
    assets/lib/bootstrap-4.0.0-dist/js/bootstrap.js: {}
    assets/script.js: {}

in the 2nd scenario the js file ex: jquery will be loaded before the other js files.
so what is the difference?

A library is a set of files (CSS or JavaScript) which could be local or loaded from another site. Declaring a dependency from another library has the vantage of not requiring to know:

Which files need to be loaded
Where those files are located
Which dependencies that library has

Using a library and declaring its dependencies also means that:

A file is loaded only once
There is only a copy of a file for all the modules
A module that depends from a library doesn't need to update the list of files (which are part of that library) when the library changes its files


How to alter auto-complete exposed filter programmatically? I created a views to show parent and child term together using autocomplete expose filter .. but its show only one child. I have same child for two different parent.but its show only one child.
how to change this programmatically using view query alter. I need such type:

Parent . Parent-1
           locality-1
           locality-2
         parent-2
           locality-2
           locality-4

I need such type of result on autocomplete expose filter.

Here is a possible answer to this problem.
First of all, a litte visual.

To get this working you need the following:

Configure your View to display the exposed taxonomy filter as a dropdown. autcomplete will not work because you cannot have multiple entries with the same key in the generated JSON array.
Optional: Install and configure the Chosen module [https://www.drupal.org/project/chosen] to get your dropdown to render nicely and offer autocomplete options.

You will also need this JS library for Chosen to work => [https://github.com/harvesthq/chosen]

Optional: You can finally use some custom code for formatting the presentation of your list, here is a sample minimal module that adds the special arrow that you see in the screenshot.

define('YOUR_CUSTOM_TAXONOMY_AUTOCOMPLETE_PATH', 'mycustompath/1');
define('YOUR_EXPOSED_FILTER_MACHINE_NAME', 'field_tags_tid');

/**
 * Implements hook_form_alter()
 */
function se_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'views_exposed_form' ){
    if(isset($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]) &&
    $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#type'] == 'select'){
      $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options'] = _custom_update_options_for_taxonomy($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options']);
    }
  }
}

/**
 * Function that update select options for taxonomy filter
 *
 */
function _custom_update_options_for_taxonomy($options = array()) {
  $current_parent = '';
  foreach( $options as $i=>$option ) {
    if( is_int($i) && isset($option->option) && is_array($option->option) ) {
      $option_arr = $option->option;
      $tids = array_keys($option_arr);
      $tid = reset($tids);
      // is this a child of the previous parent
      if( strpos($option_arr[$tid], '-') === 0 && $current_parent != '') {
        $option_arr[$tid] = preg_replace('/^-/', ' ⤷ ', $option_arr[$tid]);
        $option->option = $option_arr;
      }
      // this is a parent node
      else {
        $current_parent = $option_arr[$tid];
      }
    }
  }
  return $options;
}

Hope this help some!


hook_form_alter execution order Is there a way to change the order of execution of hook_form_alter in Drupal 7 without changing a module's weight or hacking Drupal Core?

I am trying to alter the element added in translation_form_node_form_alter from the translation module. When debugging the form I can't find the element so I assume my hook is being executed before the one in the translation module is.

Also worth mentioning, there is a new drupal 7 API called hook_module_implements_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.

Sample code from the API docs showing how easy this is to do:

<?php
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'rdf_mapping') {
    // Move my_module_rdf_mapping() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}
?>