How to migrate password with hash I'm doing a user migration from Drupal 7 to Drupal 8 (the data is in json format)
Most of the fields have been imported to the new website. Now, I'm in the process to migrate the password; this field is, of course, encrypted/hashed (as far as I understood, Drupal uses SHA512 by default with a salt).
So far, I have found this answer and adapted my code like below:
$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach($users_array as $user){

    $values = array(
        'name' => $user["name"],
        'pass' => [
            'value' => $user["pass"],
            'pre_hashed' => TRUE,
        ],
        'status' => $user["status"],
        'mail' => $user["mail"],
    );

    $userStorage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $userStorage->create($values);

    $role = $user["roles"][0];
    $userEntity->addRole($role);

}

Now, my question is: Is it a good approach? How do I import this kind of field? Do I have to decrypt/de-hash the password?

You can follow document.

The $P$ is the so called hash type identifier which indicates that the
hash is a portable Phpass hash. The string after that consists of salt
and a hash. The portable Phpass hashes can be migrated to Drupal 8
as-is. When the user logs in to your Drupal 8 site for the first time,
Drupal will re-hash the password. The salted hash used in this example
is for a password 'test'.

If the source system was a PHP based application that used crypt() or
password_hash(), these hashes should work as-is and they can be
migrated 1:1 like in the Phpass example above. When the user logs in
to your Drupal 8 site for the first time, Drupal will re-hash the
password.

Here is my example convert old pass using md5
<?php

namespace Drupal\my_module;

use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\Core\Password\PasswordInterface;

/**
 * Provides custom password hash comparison for migrated passwords.
 */
class MyModulePasswordService extends PhpassHashedPassword implements PasswordInterface {

  public function check ($password, $hash) {
    // Check old pass is md5
    if (preg_match('/^[a-f0-9]{32}$/', $hash)) {
      $pwd_sercet = "pwd_sercet";
      $pass_hash = md5($pwd_sercet . $password);
      return ($pass_hash == $hash);
    }
    return parent::check($password, $hash);
  }
}


How to get the hard coded string as output in views_php module I am using quiz module.

I am creating a view which has field which shows the status of the quiz. If the user score is greater than pass rate, the field should display "pass" else "fail". How to achieve this.

I used views php module to do this. But, I'm confused between Value code and Output code.

Can anybody provide some pointers?

Value Code : The value of the Field.

Output Code : The php code that you wish to execute for getting the output for that field.


Views with multiple languages I'm building a multi-lingual site with drupal 7.  I see that you can "translate" a page.  How do I translate a view?  The url http://mysite.com/view is a view, but I don't see the "translate" button.

Since views are dynamic lists of content, you don't directly translate the view. Rather, you make the view select content of the current user's language. This can be done using the i18n module, and the i18n views module.

Once you have these installed, you add a filter to your view, under the node translation group.


How to split content for different target audience? We're having a bit of a difficulty finding the best way to solve the current issue: it's a multi-site and multi-lingual set-up for a customer that is active in different countries. For each country a separate database is uses (multi-site) and each country has an English + local language variation (multi-lingual).

The customer also has a split audience (private vs. business) and all pages have a one-to-one match, meaning if you are on a /en/private/foo page, you could go to /en/business/foo just by switching the target audience (same way the language switcher works).

The problem is you'll have two switcher blocks on the page that have to be in sync:

language (english/local language)
audience (private/business)

How would you split the content and keep the relation between the different nodes for different audience groups? This also has impact on other Drupal components, the menu for example.

We've been looking at two different approaches:

separation on content level (taxonomy or field to select the audience
group)
grouping the content (e.g. og module, or the new kid on the block group)

Any people out there that had the same issue and how did you solve it?

@max I am assuming that since there is a 1-1 relation between 'private' and 'business' content, you are probably just hiding (restricting) content in on of the two.  So if for example, your 'private' content is only available to authenticated users, or user who paid for the content, then essentially the other (business) content is a reduced version (teaser)?

If that is the case, then maybe you can consider using different display modes for the same node - in other words, you only have one node for both business and private, but with different view modes.  The one with restricted access (lets assume that is business) will show nodes using the 'teaser' view, while the other will render the node using the 'full' display mode.

It should be easy enough to change the display mode dynamically on load / render based on the user's status (logged in, paid for content, etc).

The other option, and you could even combine this, is to use content access modules, specifically field level access, to automatically control which fields will be rendered or not.  So in this configuration, you could always render the node using the same (possibly different) display modes, but based on the authentication level of the user, simply do not show the field: I can confirm that I have personally used this and it does work (http://www.startnetwork.org).

All things being equal, I would personally only have one node (as opposed to 2 implicitly related nodes) and then simply control what information (or how much) is shown.

If you have any questions - please let me know: happy to help.


Domain Access and mother website arguments I am thinking of creating a series of websites based on one mother website using the Domain Access module, like this:

www.domain1.com linking to www.motherwebsite.com/argument1

www.domain2.com linking to www.motherwebsite.com/argument2

www.domain3.com linking to www.motherwebsite.com/argument3

etc. Each child domain will show the content associated with this domain (but created on the mother website) depending on argumentN.

So, my question is how can I capture the argumentN data to deliver the corresponding content (in Views, Blocks, Panels etc)? I guess I won't be able to use the URL for that as the argument data will not be part of the child domain's URL...

Thank you

If you have installed the Domain Access module, you will have the Domain Access Views module available. First thing you want to do is enable that module if you haven't already.

Once you've done that, you can use the current domain as a filter:

Under Filter Criteria, add "Domain Access: Domain ID"
"Operator" is one of "Current Domain"

Now the view will only return nodes for the domain that the block/page is loaded from.


How to make drop down field as mandatory field in views exposed filter? I need to make one of my drop down field in views exposed filter as mandatory field.How can I achieve this?

In the Exposed Filter option check Required checkbox.. See attached screenshot below for select list field..


Open link as modal form or normal form based on user role I wish to have a link 'Post Ad':

For anonymous user: a modal login form will be displayed to request log in.

For logged in user: a normal ad posting form.

I managed to use the ctools for modal login form, but i have no idea how to get the normal form to display. (Exception happens when open the normal form, an ajax http error occurred.)

How to achieve this without create two links?

Thanks!

You can look at Menu per Role module, ie link to login form for anonymous users, and link to normal form for authenticated users. another alternative would be to add a hook into the menu in your custom module and change your link based on user's status that way. You can look at this post for info and examples.


When you recreate a Feature, do you need to uninstall and re-install it? When you recreate a Feature, do you need to uninstall and re-install it or is it OK to just delete the feature folder and paste the new on in its place?

Instead of deleting the folder just download the tar.gz file and extract it in the folder where the features folder is there. I would automatically merge the changes.


Are HTML strings translatable through admin/config/regional/translate? I'm on Drupal 7 and to easily add an image to a string, I did this:

<img src="/icons/icon_32.png" height="32" width="32" /> My text here

I used this technique in several places: field labels, views titles, field values, etc.

Now I'm translating the site.

As it turns out, using the standard translation interface and the i18n modules (views, fields, etc.), field labels containing these img tags can be translated, but field values cannot.  I'm also noticing other inconsistencies.  Should strings containing HTML not be used with t() or am I doing something else wrong?

After looking into this for a bit, here's what I've found so far.  t() runs everything through format_string(), which sanitizes/wipes out HTML such as the IMG tag.  Hopefully someone who understands this better is able to provide greater insight into how it all works.


Comment only once per node I'm trying to get my users to post only once on each Product node... I'm kind of new to hooks and I'm not sure what else should I use for this.

What is the drupal way to do this?

You can use the Comment limit module.

  Limits how many comments a user may post on a node.
  Adjustable on a per node type basis.

  This module can be handy for instance when comments are used as "Reviews" and "Ratings" for products and a user may only review and rate a product once.


Drupal 7.16 started sending duplicate account activation emails Could anyone help me debug why Drupal is sending two account activation emails when a new user account is activated?

I also see from the rules logs, that certain workflow rules are also sending two emails for each one.

I have looked in /admin/reports/dblog but there are no errors or warnings there.

Any idea where I can start looking?

thanks,
Darren

OK, not sure what was happening there! I changed the settings on admin/config/people/accounts and removed the need to confirm email address ("Require e-mail verification when a visitor creates an account.".

This didn't work - still duplicates being sent out when activated.

Then I de-selected "Notify user when account is activated." (Under "Account Activation" tab) and this stopped them being sent.

Then I re-enabled "Notify user when account is activated." AND modified the email template.

Now it's only sending the one email again!

For some reason, this also fixed the rule emails that were getting duplicated... Beezaaar!

Any ideas?


How to use presave hook to save a field value as node title? I have a custom date field in a node type 'day'.
When the node is saved (or edited then saved), I would like to get the field_date value (not the published date) and save it into the title field.

I would like to know how, perhaps using a module to:

hook_presave

GET FIELD VALUE
SET TITLE AS FIELD VALUE
SAVE NODE

You need to implement the hook_entity_presave()

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    // Here you modify only your day content type
    case 'day':
      // Setting the title with the value of field_date.
      $entity->setTitle($entity->get('field_date')->value);
     break;
  }
}


The drush command 'rets-import' could not be found I believe I have all the pieces of the Drupal RETS Real Estate Framework installed in my drupal 7 site.

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

But when I run:

drush -u=admin -d rets-import

I get:

The drush command 'rets-import' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.

What step might I have missed in my install of this framework?

The file that integrates DRealty with Drush drealty.drush.inc is kind of in an odd place within a drush folder of the module.

http://cgit.drupalcode.org/drealty/tree/drush/drealty.drush.inc

Drush will scan the root level of a module folder or your .drush directory for drush include files but I dont think it will randomly scan deeply into module directories. I recommend moving this file into your .drush folder and clearing the cache, then trying from your site folder again. Eg,

cp ./drealty/drush/drealty.drush.inc ~/.drush
drush cc drush
cd YOUR_DRUPAL_PROJECT/sites/all/modules
drush -u=admin -d rets-import


How can I remove 0 & negative values(-1 to -100) in weight module section? I want to remove 0 and negative values (-1 to -100),so need to display only 1 to 100 items only  in drop down list .

How can I achieve this?

Display weights 1 to 100 only case below code working good.
  path:sites/all/modules/weight/weight.module file 751 line

/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;

  $options = array();

  for ($i =1; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;
}

Before code:

/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;
  $min = $max * -1;
  $options = array();

  for ($i =0; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;


How to enable theme on profile installation I am creating a drupal 6 installation profile and I want to enable a specific theme on installation. How can I do that?

In your profile_name.info, add a new line with theme = mytheme.


ajax reload causes jquery issues i jquery applied to a exposed filter to force the look of a drop down with checkboxes which works fine until the ajax reloads the content and cause the slideToggle to open and close immediately. i switched it to just css height and the box wont open after ajax reload. Anyone have any ideas or options that might work after ajax reload.
 just css option

boxes1.css({"display" : "none", "background": "#f2f2f2", "border" : "1px solid #ccc", "padding":"5px", "margin-top" : "25px","position":"absolute","overflow" : "hidden"});
    title.live("click",function(){
        if(boxes1.is(":hidden")){
            boxes1.css({"height" : "300", "display" : "block"});
        }
        else {
            boxes1.css({"display" : "none"});
        }
    });

slideToggle option

boxes1.css({"display" : "none", "background": "#f2f2f2", "border" : "1px solid #ccc", "padding":"5px", "margin-top" : "25px","position":"absolute","overflow" : "hidden"});
    title.live("click",function(){
            boxes1.slideToggle('slow');
    });

this might have to do with behaviours

see jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module


Unable to display images after Drupal Update I recently updated my site to Drupal 7.34 using these instructions -

https://www.youtube.com/watch?v=_uDTyzE47pQ

After update, I am not able to see the images in the site. All I see is the placeholder for image, but not the image itself. I checked and its not a path issue.

This is how it looked before -

And this is how it looks after -

Also notice that the theme has changed. I was using bartik before. Can somebody tell me if I did anything wrong or how to get the images to display? Could this be an issue with image styles?

My guess is you didn't correctly copy sites/all and sites/default/ over during the update or the permissions on the files in those directories aren't correct so Drupal can only "see" core modules and themes.  The data in the database is still working, but any field, content type, or url that requires a module from sites/all probably doesn't work either.


Where are {image_style} and {scheme} coming from? I can't find much documentation on this subject other than https://www.drupal.org/node/2122201. This leads me to think that the subject is either much easier than I think, and doesn't have documentation because everybody knows it, or that there isn't much available.

I have been working with the last example on that page, but I can't figure out where {image_style} and {scheme} are coming from.

I need to create something pretty simple, where there's a path that links to a page that requests some data from an API. For example, if someone browses to mysite.com/example/johndoe, then the page requests data from example.com/users/johndoe and displays it. So, I need to also have access to the entry in the URL to forward it to the API with my module, not just routing a ton of pages with a certain URL pattern to a single page.

I've found plenty of documentation on static page routing, and I have understood that.

They are route parameters. See here: https://www.drupal.org/node/2186285


'print render($content['links']);' Which links is Drupal referring to in 'print render($content['links']? 'Links' is kind of general to me so I am wondering which links this php snippet is referring to.

I've looked at Drupal's theming references and saw only a list of variables for theming.

The links it is referring to are the comment links, statistics links and translation links of a node.

So in a situation where you want just the comment links, it would be

print render($content['links']['comment']);

For more information, see this page.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_pre_render_links/7


css and javascript aggregation. Can I still edit files? Am developing a site using drupal 7.15
I am having problems with displaying a ddblock in internet explorer and I think it may be due to too many css files.
If I aggregate them can I continue to edit them? Also, can I still use Firebug to view my css?
All the posts I read seem to refer to setting aggregation when you decide to "go live"
Sorry to ask such an elementary question.

You can still edit the original files as much as you like, but you won't see the changes reflected in the front end until you clear Drupal's caches.

You can absolutely still use Firebug to inspect your CSS, but keep in mind that the files have been aggregated, so you won't be able to pinpoint the original file and line that a rule comes from.

That's pretty much why it's recommended to keep aggregation off during development, unless of course you're testing the aggregation itself.


Preserve &nbsp in title I'm currently working on a French website. French formatting requires a space before question marks. For some of my titles, this results in the question mark appearing on a line by itself.

  Why does it do this

  ?

It looks like trash. How can I preserve the &nbsp; in the title to have the question mark on the same line?

You can use these two modules:

Title

  Do as follow:
  In content type field management, use replace button to turn title core into a text field; set up the field to be in a full html text format;
  In content type display management, show new title field;
  In file node.tpl do not print the core $title;

HTML Title

  It let you insert some sort of BBcode into the title. I've never used it and I don't know if there is a BBtag for


Database query with WHERE and ORDER BY Can't figure out why the following query executes directly through phpMyAdmin perfectly well:

SELECT id FROM `stats` WHERE type="load" ORDER BY id DESC LIMIT 1

but firing this:

db_query('SELECT id FROM {stats} WHERE type = '.$param.' ORDER BY id DESC LIMIT 1')->fetchField();

from a module outputs:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'load' in 'where clause': SELECT id FROM {server_stats} WHERE type = load5 ORDER BY id DESC LIMIT 1; Array ( ) in server_tab_stats_submit() (line 750 of /home/dev/public_html/sites/all/modules/custom/server/server.inc).

Column's name there is "type", I don't know why Drupal query thinks "load" is a column, it is just a value derived from $param variable.

Try This

$nid = db_query('SELECT id FROM {stats} WHERE type = :type ORDER BY id DESC LIMIT 1', array(':type' => $param))->fetchField();

Refer db_query for more information...


Do we need to update every release sequentially to get to the latest version? Drupal releases a minor release approximately every 6 months, and a patch release every 1 month. Do we need to update to each one of them sequentially in order to get to the latest version? E.g, if I'm on Drupal 8.5.0, and the current Drupal version is 8.6.1, do I need to follow the order and update each release in the order 8.5.0 -> 8.5.1 -> 8.5.2 -> 8.5.3 -> 8.5.4 -> 8.5.6 -> 8.6.0 -> 8.6.1, or can I directly update to 8.6.1 from 8.5.0 by replacing the core files?

If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?

You do not need to update Drupal sequentially. The Drupal update system will run all the needed updates so that you can go from (lets say) 8.3.0 to 8.6.1 directly.

Regarding your question about "If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?" ... If 8.5.4 requires a change to settings.php then 8.6.1 will assume that those changes are there already.

Note: its a good practice to update core (at least for minor versions) so that you are always in a position to quickly apply security releases. The Drupal security team has recently decided to support the most recent 2 minor releases, but still...

Check out this further reading and also this


Very slow cache processing: Is there any alternative? I have some Drupal sites and the one common problem on them: very large cache with very slow processing and therefore the sites work very slow. I have enabled all caches and set them to long lifetime. But the sites are still slow.
My server has 4GHz frequency and 4G RAM. DB queries log shows me that all queries takes 100-300ms summary.

When I perform profiling with xhprof I see that the largest part of wall time is used by serialize, unserialize and array_map functions. So i suppose it is because of large amount of serialized data stored in cache. So the data can be get from DB quickly but is processed by CPU very slowly.

So what should I do with the issue?
How can I reduce cached data amout or store not serialized data in cache?

If a large part of your time is spent with serialize then that might point to some broken code; as in things keep getting serialized to be stored in the cache/db but it keeps on having a cache miss, otherwise you should only see unserialize with heavy cache usage.

The pattern you're pointing to sounds like you have some code that is abusing the variables table. Inside variable_initialize() it runs array_map with serialize, and variable_set() calls serialize. I would check the max_allowed_packet value inside of MySQL; my preference is to set it to 32M.

If you can provide more details, I can give you a better answer. I will say that using PHP7 should give you a big speedup if you haven't done so.


db_merge() PDO error The Error:

 PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, value) VALUES ('1', '1', 'mydata', '35')' at line 1: INSERT INTO {mytable} (uid, tid, key, value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => mydata [:db_insert_placeholder_3] => 35 ) in MyClass->save_myData() (line 145 of /path/to/my/stuff/my.class.php).

My Code:

db_merge( 'mytable' )
    ->key( array( 'uid' => $this->user->uid, 'tid' => $data['tid'] ) )
    ->insertfields(array(
           'uid' => $this->user->uid,
            'tid' => $data['tid'],
            'key'      => $key,
            'value'    => $value
    ) )
     ->updateFields( array( 'value' => $value ) )
     ->execute();

I've tried this with just the basic ->fields() but my latest iteration here involves specifiying the inserted fields and updated fields separately (just ran across this while googling and thought it might help.  Same error though.

Originally I was trying to use

db_query( "REPLACE INTO goal_data(uid,tid,key,value) VALUES( :uid,:tid,:key,:value)", array(
                ':uid'      => $this->user->uid,
                ':tid'      => $data['tid'],
                ':key'      => $key,
                ':value'    => $value
            ) );

It too was throwing an error saying that there were in invalid number of placeholders or something similar.  There wasn't. The error was basically:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

Any thoughts on what I'm doing wrong?  I don't get it, trying everything here and just keep getting errors.

Here's my table structure (very simple).

CREATE TABLE IF NOT EXISTS `mytable` (
  `uid` int(11) NOT NULL,
  `tid` int(11) NOT NULL,
  `key` varchar(255) NOT NULL,
  `value` longtext NOT NULL,
  PRIMARY KEY (`uid`,`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The syntax error comes from key being a MySQL reserved keyword.
The best solution is to not use these keywords as identifiers.
 Otherwise the workaround is to enclose them in backticks.

It may work like this:

  [...]
  ->insertFields(array(
           'uid' => $this->user->uid,
            'tid' => $data['tid'],
            '`key`'    => $key,
            'value'    => $value
    ) )
   [...]

However this fails at cross-database compatibility since the backtick is a MySQL-only syntax. Better rename the column if possible.


hook_help() argument I don't see the second parameter $arg being use in the function.

function hook_help($path, $arg) {
  // ....
}

Why should I declare it? What is its use?

Take a look at the api. It states:

  $arg An array that corresponds to the
  return value of the arg() function,
  for modules that want to provide help
  that is specific to certain values of
  wildcards in $path. For example, you
  could provide help for the path
  'user/1' by looking for the path
  'user/%' and $arg1 == '1'. This
  given array should always be used
  rather than directly invoking arg(),
  because your hook implementation may
  be called for other purposes besides
  building the current page's help. Note
  that depending on which module is
  invoking hook_help, $arg may contain
  only empty strings. Regardless,
  $arg[0] to $arg[11] will always be
  set.

Example:

function hook_help($path, $arg) {
    if($path == 'user/%'){
        if($arg[1] < 10) {
            return 'one of the early users';
        }
        else {
            return 'foo';
        }
    }
}

Doing this without the $args would be ugly.


SQLSTATE[42000]: Syntax error or access violation in drupal views query When trying to preview a view containing references to three Field Collection module fields, I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS node_, node.created AS node_created, 'field_collection_item' AS field_data_fi' at line 1

Here is the full attempted query:

SELECT field_collection_item_field_data_field_obit_service.item_id AS field_collection_item_field_data_field_obit_service_item_id, node. AS node_, node.created AS node_created, 'field_collection_item' AS field_data_field_service_location_field_collection_item_enti, 'field_collection_item' AS field_data_field_service_time_field_collection_item_entity_t, '' AS field_data_field_service_type__entity_type
FROM
{node} node
LEFT JOIN {field_data_field_obit_service} field_data_field_obit_service ON node.nid = field_data_field_obit_service.entity_id AND (field_data_field_obit_service.entity_type = 'node' AND field_data_field_obit_service.deleted = '0')
INNER JOIN {field_collection_item} field_collection_item_field_data_field_obit_service ON field_data_field_obit_service.field_obit_service_value = field_collection_item_field_data_field_obit_service.item_id
WHERE (( (node.status = '1') ))
ORDER BY node_created DESC
LIMIT 5 OFFSET 0

I don't know sql that well, but it appears as though some of the references are being truncated due to length. Also there is a reference to an empty string ('') as a column name. Any idea what's wrong and how to correct it?

Removing the fields and then adding them back resolved the issue, though I'm not sure how.


Find the custom module responsible for a URL On a site I did not originally develop, I'm stuck having to fix display issues on an arbitrary page.

Is there a way to locate the custom built module responsible or the source of a given URL path?

You can use "hook_menu_alter" to list all routes and you can see the module via the module key.

function HOOK_menu_alter(&$items) {
    if(isset($items['yoururlpattern'])){
        drupal_set_message($items['yoururlpattern']['module']);
    }
}


Doubts on Marinelli Menu I'm trying to have submenus like the ones that can be seen on http://marinelli.netsons.org in Cameras menu item.

Could anyone point me on how can I achieve that? I don't know how to create the sections that can be seen in that submenu.

Megamenu might be of use.

  Mega menus are a type of menu drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:

  The information architecture of your navigation is made clearer and is visible all at once
  The amount of clicking, searching, and navigating is reduced


Linking to other nodes I'm looking to add a field to a content type that lists nodes. Basically, I need that users are able to choose the node they want to link to, and then (in the template) output the link to that node.

This seems like a basic thing to do; I'm using Drupal 7 but can't for the life of me work out what I'm missing.

In order to use the "node reference" field in Drupal 7, you need the References module.


How to convert cUrl code to drupal way? I have below code

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
curl_close($ch);

In Drupal 8 way we can use

$client = \Drupal::httpClient();

$response = $client->request('GET', $url, [
  // To add
]);

Not sure how to pass needed parameters/convert it to drupal way.

[UPDATE]

$uri = 'http://domain.com';

$client = \Drupal::httpClient();

$actual_uri = NULL;
$response = $client->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, \Psr\Http\Message\UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);

dump($response);
exit;

The only special thing I see there is getting the effective URL, which is actually something that was specifically added back to Guzzle 6 for Drupal: https://github.com/guzzle/guzzle/issues/1166

See \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher::fetch:

  /** @var \Psr\Http\Message\UriInterface $actual_uri */
  $actual_uri = NULL;
  $response = $this->httpClientFactory->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);


Changing the Title of a Blog How can I change the title of my blog? It's found on the main page of the blog above the previews of the posts. I am attaching a screen shot.
I want to change "The Scrapbooked Bible Study" (on the left above the first blog post preview) to "Winning the Victory." Thank you.

That page seems to be a Views page, but there is no way of telling from the screenshot if you're using a special module to build those page or simply Views.
If it's Views then you can Edit the particular View, it has the Title option for the Page, that's where you change it.
You can find list of all Views under Structure on the top menu.


How to hide label if field is empty? so I have a content-type X and some nodes of this type. If I go to the node page, I'd like to not see the label of an empty field. Where in the display options can I change that?

In my case ,the content of the fields are some check-boxes (from a vocabulary). I'm on D7.

Try the settings in /admin/structure/taxonomy/X/display (label settings)

but it should be done automatically if there is no content


How do I create a catalogue list that links through to my individual product nodes? I have taken Ryan Szrama's advice from a question I asked on how to display products and have now got that working. I have also built a catalogue list of all my products using views.
I now need to link the two up, so that if a user views the catalogue they can click through from there to the appropriate individual product node. How do I do this, or am I missing something?

To be specific: I have a view called 'catalogue' that is a list of books using a table, and I have a view 'book' that is an unformatted list that contains more detail on each book (like cover image, author etc). This view returns all books initially. I want the title in the list to link through to the book view and filter that view using ISBN (SKU) for an individual book. I can create the link, but I am not sure how to correctly format it. Currently the link looks like this: /book?isbn=123456789 (I have also tried /book?sku=123456789). This link just returns a full unfiltered list of the view.

Now, I'm not using D7 yet, but Views has settings to turn fields within a node (your product nodes) into links to the originating node. Just go to your View that is your grid of products, check out the individual Fields you use, in their settings some of them (if not all of them) should have an option to turn the field into a link back to the original node.


How to target specific sites with Drush when using Multisites? I have a Drupal Multisite set up. It contains two sites, but the core Drupal install has no site.

With Drush, I can use @sites to target all sites. For example:

drush @sites -y cc all - Updates all multi-sites
drush @sites -y en jqmulti - Install Jquery in all Multi-Sites

However, because I have no site installed in the core folder, I always get an error message  stating that the core site is missing. Is there any to use Drush to only update the sub-multisites and skip the core one?

I know I can run Drush from the sites directory of the sub-sites, but that isn't very convenient when I want to target all sites.

The reason I am using Multisites is because both sites share themes and user-logins.

When you say "core site", do you mean the site in sites/default?  Is it an option to just delete the settings.php file at sites/default/settings.php?

If you'd like to manage your aliases in an alias file, create a file ~/.drush/mysite.aliases.drushrc.php:

$root = '/path/to/root';

$aliases['site1'] = array(
  'root' => $root,
  'uri' => 'site1.com',
);

$aliases['site2'] = array(
  'root' => $root,
  'uri' => 'site2.com',
);

See this link for an example.

Then, to refer to one site:

drush @site1 status

or -

drush @mysite.site1 status

To refer to all sites:

drush @mysite status

Maybe you want to get more fancy than this, though.  If you have more aliases in your alias file (e.g. for 'dev' and 'live' sites, you can make your own lists:

$aliases['dev'] = array(
  'site-list' => array('site1', 'site2'),
);

Then:

drush @mysite.dev status

If you want, you may also store your alias file in /path/to/root/drush or /path/to/root/sites/all/drush, but if you do this, Drush won't be able to find your alias file unless you specify --root on the commandline, or change your working directory to be somewhere inside of /path/to/root.


Delete or unpublish content from old migration, if source rows no longer exist I am using Migrate API to import products from a CSV file that is updated every week or so.

Every time the CSV file is updated,

new products may be introduced
existing products may be modified
old products may disappear

Migrate currently does not seem to have a mechanism to remove or unpublish orphan content from the site, where the source record no longer exists.

See e.g.

Migrate module FAQ: "A negative number means the current source has fewer records than we have cumulatively imported from the source. This could mean that records have been deleted on the source side (there is no built-in support for deleting destination records based on the absence of the corresponding source record)."
Issue #2809433: Migrate support for deleting items no longer in the incoming data, an issue currently in "Needs work".

What kind of solution or workaround could be used to deal with this old content?

"Deal with" could mean one of the following:

Delete "old" entities from the site.
Unpublish "old" entities.
Have a property or field that tells us when an entity was last seen in a migrate source record. This would allow e.g. to filter such entities in Views.

Notes

Please consider that migrations do not always process the complete source data. E.g. you could use the --limit parameter, or manually stop the migration, before all source rows are processed. Of course the typical nightly or weekly migration will process the complete source data. But manual migration runs often do not.

Also consider that a migration will usually not update rows that are unchanged. If we would store a "last import date" in a field, this would cause a lot more entity_save() operations, so it would significantly slow down migrations.

Here is the solution that I came up with.

TLDR: Drush command to compare source data vs existing products, and activate or deactivate products accordingly.

Use case / goal

I am focusing on a specific use case, to make this easier to explain. Something similar could be done for other use cases.

Commerce products are imported with a migration. Both source and destination have one numeric primary key. The migrate map is MigrateSQLMap, so there is a migrate_map_* table in the database with destid1 and sourceid1.

Goal: Change the "status" property of commerce products which are no longer in the source data.

Considerations

A migration run can be incomplete. In such a case, we do not want remaining products to be deactivated.

Updating an entity (commerce product) in Drupal takes time. We do not want to update every entity just to change a timestamp.

We have to assume that the entire list of products can be quite big, so it can be problematic to have them all in memory at once. However, in this solution, I assume that having the ids (source id mapped to destination id) in memory is still acceptable.

Solution: Custom drush command

Create a custom drush command that does the following:

Query the database, join the commerce_product AS cp table with the migrate_map_MYMIGRATION AS mm table. For each row we want mm.sourceid1, mm.destid1 and cp.status. Load the complete list into an array as $maps[$row->status][$row->sourceid1] = $row->destid1.

Assign the two parts of the array to new variables $inactiveIdsMap = $maps[0]; and $activeIdsMap = $maps[1];.

Create two additional associative arrays, each with format $[$sourceid] = $destid:

$idsToActivateMap = [];. Start value: empty array.
$idsToDeactivateMap = $activeIdsMap. Start value: All ids for active products.

You may want to unset($activeIdsMap); to free memory. (We could have reused this variable instead of declaring a new one, but I like having variable names that are accurate throughout a variables's life.)

Iterate through the source data. You can get the migrate source from the migration. It is a bit tricky but it can be made to work.

For each source row:

If the id exists in $inactiveIdsMap, add the source + dest id to the $idsToActivateMap array.
In any case, unset this entry from the $idsToDeactivateMap array.

Now deactivate all to-be-deactivated products, and activate all to-be-activated products.

You ideally do this in chunks, so e.g. you load 20 products at once with commerce_product_load_multiple(), set each one's status, and save them individually with commerce_product_save().

This drush command can be executed after the migration.

Memory impact?

You can measure memory use with memory_get_usage() or memory_get_peak_usage(). If you use memory_get_usage(), you need to call it in the place where you expect memory usage to be highest. Memory pretty print: http://codeaid.net/php/convert-size-in-bytes-to-a-human-readable-format-(php)

The way to check for the impact of this specific operation is to run the command with a subset of data. E.g. put a ->range() on the select query for loading the migrate map. This should make all arrays smaller.

Why? Alternatives?

Another solution that I found tempting at first was to maintain a "lastseen" timestamp in a separate table.

However, this would mean either having to update each product on every migration run, or at least reindex the search index each time, because we would want to filter by "lastseen".

With the solution presented here, in the average case, only few products have to be updated.

It turned out that the memory impact was very manageable.


Why user's rights has that impact on my Views pages? I have two custom entities (Adhérents and Personnes) linked to each other and to User.

One 'Adhérent' is mainly a "family" and has these fields: label, adresse (postal address), Téléphone (landline phone number), date d'adhésion (Membership start date).
One 'Personne' is a "person" ;-)  and has these fields: Nom (Lastname), Prénom (Firstname), Portable (Cellphone number).

Each 'Personne' is linked to one 'Adhérent'. One 'Adhérent' may be linked to many 'Personne' (one of these 'Personne' being the 'contact').  Each 'Personne' is linked to one 'User'.

'Personne' is defined as entity_reference for 'Adhérent' (as the 'Contact'):

$fields['contactid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Contact'))
  ->setSetting('target_type', 'association_personne')

'Adhérent' is defined as entity_reference for 'Personne':

$fields['adherentid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Adhérent'))
  ->setSetting('target_type', 'association_adherent')

'User' is defined as entity_reference for 'Personne':

$fields['userid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Utilisateur'))
  ->setRequired(TRUE)
  ->setSetting('target_type', 'user')

I use Views to publish all these contents (see Screen captures below).

When I look at the output with a user with no specific rights (i.e. not Administrator), some of the data are not displayed:

In the 'Adhérents' view, the Contact column is empty (see capture 2) while there is a link to the entity (see capture 1).
In the 'Personnes' view, the link to the entity_reference 'Adhérents' is there but the link to 'User' that should display email address (see capture 3) is completely absent, the column header is not even there (see capture 4).

Any idea?

The Permissions as they are set:

I'm not sure if I understand your problem correctly but would say that if it works as planned for admin user then the issue is with permissions.

Check permissions like: view user profile, view [entity type] etc.


Open a pop-up/modal window after add/edit node to share I'm using Social Share to generate share links on my nodes but I want the user to be prompted to share after adding and/or editing a node. Is there any possibility of creating a pop-up/modal window that contains those links after the add/edit window has been submitted?

without coding, you could setup a message in rules and show it with Better Messages or similar (there is a link to a wiki on the project page) or you could acheive the popup with some coding and the hidden gems of ctools (see the examples in ctools)


Delete old files from server when content is updated When a node is updated by replacing a new file upload, old files exist on the server maintaining versions.
I want to delete old files from the server when content is updated.

This is already discussed topic.
I found some source.

Drupal Forum and Original Source

After that I would create a cron job (Implementing hook_cron). And insert this snippet.

I hope it works out for you.

Alternatively, if you dont want this action to happen once per day, you can insert it in hook_submit, or hook_update. But I would go for the first method.

Do it once per day/week/whatever time period you like.


Theming login form just for specific user registration / Auto Assign Role Page On this page users gets automatically a role assigned by the Auto Assign Role module.

For a better user experience i added the login form also to this page. This works great:

In user--register.tpl.php I added the following code to print the login-form <?php print(drupal_render(drupal_get_form('user_login_block'))); ?>

But how do i THEME this login form on this specific page? So it doesn't affect the original form on /user/login?

You are rendering the user_login_block within your template, which is not rendered on the /user/login page.

As long as you have not placed a login-block, that you don't want to be affected, you should not have any problems.

You can use the template file block--user--login.tpl.php to theme this block or even use a form_alter hook to alter the form.


After upgrading from drush 7 to 8 with multisites, using drush from site directory cannot find drupal 7 (Windows) Previously with drush 7, I could cd to the site directory (e.g. sites/example1.com) and perform drush commands (e.g. drush st). Now with drush 8, unless I specify the root in the drush command, it cannot bootstrap past level 0:

$ drush st
 PHP configuration      :  C:\wamp64\bin\php\php7.1.9\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:/Users/Dan/AppData/Roaming/Composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.18
 Drush temp directory   :  C:\Users\Dan\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :

$ drush st -r c:/wamp64/www/drupal7
           Drupal version                  :  7.64
 Site URI                        :  http://example.com
 Database driver                 :  mysql
 Database hostname               :  localhost
 ....

I do have a sites/sites.php file:

 <?php
 $sites = [
    'dev.example1.com' => 'example1.com',
    'dev.example2.com' => 'example2.com',
    'dev.example3.us' => 'example3.us',
 ];

Local site sites\example1\drushrc.php file:

<?php
$options['l'] = "http://dev.example1.com";
$options['r'] = 'c:/wamp64/www/drupal7';

Without the -r root option, drush doesn't load the sites.php or the drushrc.php.

Drush is installed globally using composer. It was not installed as part of drupal 8.

MORE INFO: Oddly, drush 8 is working with drupal 8 in a multisite directory.

It appears that drush 8 does not support drupal projects that were not built with composer. Drush 7 does not have this requirement. I added this composer.json to the drupal 7 root directory:

{
  "require": {
    "drush/drush": "~8.0"
  },
  "extra": {
    "installer-paths": {
       ".": [ "type:drupal-core" ]
    }
  }
}

I found this in an issue for project drupal-finder, which seems to be used by the Drupal 9 Drupal Launcher. I'm guessing that drush 8 has similar code.


How to change module default path I recently organized my modules in /sites/all/modules in 4 differents subfolders: contrib, custom, patches, migration.
It works very well, but after using the update manager, the new updated modules appears in /sites/all/modules instead of /sites/all/modules/contrib, so I have to move it manually to contrib.
How can I set the default module location to /sites/all/modules/contrib ?

Thanks.

Sorry, I didn't find this issue before, it has been already reported here Set Update Manager to install to sites/all/modules/contrib?

I knew about drush, but I was wondering if it could be done with the update-manager.


Allowing one page to be accessed by Anonymous user in restricted site My site is for logged in users only as "View published content" is unchecked for Anonymous users.

Now the problem is that there is one page that I created which shows a form for a user to fill for applying for a membership. It's been created in Webform and I want to show it to Anonymous user.

Naturally, this page is currently restricted and I am confused as to how to show this page to an Anonymous user.

Any help would be appreciated.

Thanks.

The content access module provides per node access.


How output JSON for multiple "Rest export" views? In Drupal 8, I'd like to retrieve JSON for multiple Rest export views, not just a single one.
Example of data I want to see (cars and tires being two seperate content types):

{
    "cars": [
      { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102] },
      { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102] },
      { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103] }
    ],
    "tires": [
      { "nid": 100, "brand": "Michelin" },
      { "nid": 101, "brand": "Good Year" },
      { "nid": 102, "brand": "Dunlop" }
    ]
}

I can output the JSON fine seperately, so you visit one url to get cars, and another URL to get tires. But I can't figure out how to merge the two.

Can anyone help me figure this out, or anyone who can point me in the right direction to achieve this?

One option would be to create a parent view and use Views Field View to reference the other 2 views displays.

For example, /car-stuff would contain 2 fields, "Cars" and "Tires", each one is a views field view field referencing the relevant json view display. For the parent view, you'd need to add REST Export Nested so the JSON of the child views would be proper JSON instead of a string.

Alternative Solutions

There may be a cleaner way to achieve what you're after.The easiest would be to make 2 calls to retrieve the JSON feeds and join them on the front end.

Depending on your requirements, you could also retrieve the specific tires for each car type.

{
    "cars": [
        { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102],
            "tires": [
              { "nid": 100, "brand": "Michelin" },
              { "nid": 101, "brand": "Good Year" },
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102],
            "tires": [
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103],
            "tires": [
              { "nid": 103, "brand": "Unknown" }
            ]
        }
    ]
}

The above would also use Views Field View, with the child view Tires having a contextual filter of nid. For an example of this approach, see the answer I provided here.


Nodehierarchy and access control... This webcast has a walkthru of NH; it includes the NH.Access module. I assume that he is using 6.x, as a lot of stuff is still very much beta'ish in 7.x, including NH.

I'm wondering if there is a module that gives me the ability to assing a permission to a node and its children.

My current setup is replacing a "Per-node" permission system, so the current Node Access grant is acceptable. I would like to progress into a "Per-Hierarchy" permission, so that a user can create children and maintain them without my intervention.

I just want to be sure I'm not missing a "related module" that's functional.

You might consider the Workbench Access module: It is a hierarchy based approach to grants; it might be a much better match for your use case, and it can use a number of different hierarchy management tools, such as the Menu system, Taxonomy, etc.


Which type of page to use for a customized front page in Drupal 7? I am watching the following tutorial on panels. The author is creating a content type for 'Home page', and later, a node view variant of node templates. He mentions that he is not 100% about this way of proceeding, but he is used to it.

The more I learn about this subject and the more I try to replicate this approach, the less I am convinced by it. Creating a content type for a home page seems like an heresy.

The panels dashboard offers to create panel pages, but also landing pages. It seems to me like a landing page would be enough (after setting it as the default front page), but would a panel page offer more benefit in this case?

I always tend to use the Context module.  Just set up a front page context that doesn't load all the unnecessary items (blocks, breadcrumbs or whatever) then have any node/panel you fancy as a home page without all the extra items that you don't need rendered onto the page.  It does seem slightly overkill to have an entire content type dedicated to one node though, I agree with that.


Change the theme used for the user reset password page Drupal 8 - I have the following issue:

Administrator user creates an account for a user
User gets a welcome email with password reset link
Upon browsing the link and passing through the hint page, the user reaches http://example.com/en/user/[USER-ID]/edit?pass-reset-token=[TOKEN]

The problem is that the password reset page uses the administrator theme, while I need it uses the default site theme.

You can use a RouteSubscriber to do that but it will also affect your user edit form and render it with the default site theme since it uses the same route name. The RouteSubscriber can't alter a route based on a query string parameter such as pass-reset-token
yourmodule/yourmodule.services.yml
services:
  yourmodule.routesubscriber:
    class: Drupal\yourmodule\Routing\YourmoduleRouteSubscriber
    tags:
      - { name: event_subscriber, priority: 1 }

yourmodule/src/Routing/YourmoduleRouteSubscriber.php
<?php

namespace Drupal\yourmodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Custom route subscriber.
 */
class YourmoduleRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.edit_form')) {
      $options = $route->getOptions();
      $options['_custom_theme'] = 'yourthemename';
      $route->setOptions($options);
    }
  }

}


$user not updating and "Validation error, please try again." on form in block I have a form that I am using in a block that was generating the error:

  Validation error, please try again. If this error persists, please contact the site administrator

Doing some research shows that it is to do with $session mismatches with the form token that cause this error.

Further to this I noticed that a default value I was using from the $user variable wasn't updating when I changed login.

Both of these together led me to the realisation that my block was being cached (confirmed by debugging and seeing that my form builder function was only being called after I cleared caches) so I changed caching of my block to 'BLOCK_NO_CACHE'.

I am still getting the error and my $user isn't updating. Any ideas?

Just to answer my own question. In this answer to another question, Berdir mentions that Drupal 6 will not update your block information. The example given to do it in code is here but I just updated the cache field to -1 (BLOCK_NO_CACHE) in the blocks table.


Views theming: How to grab the contextual filter? My setup is really simple. I have a taxonomy view that takes two contextual filters:

Has taxonomy term ID (with depth)
Has taxonomy term ID depth modifier

Due to a new request I need to be able to change the footer of the view based on the contextual filter. Since the contextual filter isn't inside the [fields] array of the view how can I access its value in my template file?

You can achieve this functionality in views itself

In footer add a global text area
Select PHP code in the text format select box
Enter the following code

$view = views_get_current_view();
/* $view->args will contain all the argument values in the order */

However make sure to include php opening and closing tags and read this one if you have multiple views in same page.


How can i make a new node title into a taxonomy term? I have a Drupal 7 content type that, when a new instance is created, its title becomes a new taxonomy term in a vocabulary. How can I do this?

Additionally, if the Title is changed, or the node deleted, then the corresponding Vocabulary should be updated accordingly.

This article might help you sort it out with the Rules module.

Otherwise you would have to create your own module and look into the hooks mentioned here.


How do I create or modify a custom filter? I'm following the docs here to create a custom filter.

The first sentence says:

  Go to Custom Filters (/admin/settings/customfilter) (6.x & 7.x)

However, that link just redirects me to the overall admin menu page (looks the same as if I go to /admin). What am I doing wrong?

Did you install the Custom Filters module? (https://www.drupal.org/project/customfilter)

Works fine for me after I install the module.


How do I get the image path inside a jsonapi response? I a content type for movies that includes plain text fields, and an image. The field name for the image is field_movie_poster.
Using the JSON API, How do I include the image path in the request?
If I put this Postman I get the correct response:
https://drupal-api.ddev.site/jsonapi/node/movies?include=image_field

But the same does not work with JavaScript
getMovies() {
    fetch('https://drupal-api.ddev.site/jsonapi/node/movies',{
        include: 'image_field'
    })
    .then(res => {
        return res.json()
    })
    .then(res => {

        this.movies.push(...res.data)
        console.log(res.data)

    })
    .catch(err => console.log(err))
}

How do I include the image path in the request?
If you look at the image attached, you will see that field_movie_poster is under the relationships attribute, and it does not include the image path.

For entity reference/images fields you have to include them to have their "full" data:
https://drupal-api.ddev.site/jsonapi/node/movies?include=image_field

The response will contain an object called included where you'll find that data,
Details for a image field:
{
  "type": "file--file",
  "id": "cc6ef625-8549-49c3-bc1c-0ef41551d8f7",
  "links": {
    "describedby": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/resource/schema"
    },
    "self": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7"
    }
  },
  "attributes": {
    "drupal_internal__fid": 29282,
    "langcode": "it",
    "filename": "1920x1080.jpg",
    "uri": {
      "value": "public://images/articles/2021-04/1920x1080.jpg",
      "url": "/sites/default/files/images/articles/2021-04/1920x1080.jpg"
    },
    "filemime": "image/jpeg",
    "filesize": 40767,
    "status": true,
    "created": "2021-04-13T10:22:44+00:00",
    "changed": "2021-04-13T10:22:52+00:00"
  },
  "relationships": {
    "uid": {
      "data": {
        "type": "user--user",
        "id": "c178495f-8a4c-410c-8e83-ebac79bc2162"
      },
      "links": {
        "related": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/uid"
        },
        "self": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/relationships/uid"
        }
      }
    }
  }
}

Please note you'll have to cross-check the id of that file with the id value of the image_field to get the correct file\url for each different image.


_blank attribute doesn't get set I'm trying to target on the Menu (Bootstrap) a _blank attribute.

This is my code. It works on my local machine.

if ($variables['url']->isExternal()) {
  $variables['options']['attributes'] = ['target' => '_blank'];
}

The HTML target.

    MySite

BUT,

In here is not working because of the "class="first".

    Example link 1

    Example link 2

    Example link 3

I'm missing something, any help? I don't want to install a module for this.

When you write $variables['options']['attributes'] = ['target' => '_blank'] you are replacing all attributes, never ever do that!

Only set specific keys:
$variables['options']['attributes']['target'] = '_blank'.

If that key is an array, append your value:
$variables['options']['attributes']['class'][] = 'appended_class'


For multilingual sites, where are translated variables for the non-default language stored? I'm managing deployment using the Features module.

Using Strongarm, I have added the site_403 (access denied page) variable to my feature.  However, this only contains the value for the default language (in my case, English).  I also have "translated" this URL into Japanese using the i18n Variable translation submodule, but I cannot find where this translated site_403 variable is stored in order to add it to my feature.

How can I add translated variables (via the i18n module) to a feature?

Please refer to this I18n translation of site_name not working

You need to enable 'Variable translation', 'Variable store' modules. Then you need to specify which variables you want to translate from Configuration -> Multilingual settings -> Variables. With this you would be able to translate your Site Information variables in different languages.

Now in Features, you can export translated variables from the section 'REALM VARIABLES'.


Why isn't my Sub Theme's CSS file showing up? I created a sub theme which is intended to just have a few color changes and background image changes.

The Base theme is called limon. The sub theme is limon_orange. In the sub theme, i have a unique style sheet that I want to use to override the base theme styles via cascade. In the limon_orange.info file I have this  line:

stylesheets[all][] = orange.css

The sub theme works, but orange.css is never used. What am I missing? Why is orange.css not loading?

Any change in .info does not take effect only by clearing cache. Remember to clear the theme registry. You can do this by just going to the admin/appearance and saving it.


How can I get a relation by the endpoints using the "Fetch entity by property" action in rules? Short version: I want to fetch a relation by the endpoints.  The relation already exists in the database.  How can I use the Fetch entity by property action to return the relation?

Long version:

I'm using the Rules and Relation modules on Drupal 7.  I have a relation type that is created between two users (the endpoints are user entities).  The relations I am trying to fetch have already been created.

When one user sends a message to another with the Private Message module, I want to fetch the relation between the sender and the recipient.

Here is the rule:

Event: A message is sent (from Privatemsg module)

Action: Add a variable (List of any entity items, endpoint_list)

Action: Add an item to a list (Add privatemsg-message:author to endpoint_list)

Action: Add an item to a list (Add recipient to endpoint_list)

Action: Fetch entity by property (Entity type: Relation, Property: Endpoints, Value: endpoint_list, Limit results: 10, provides fetched_relation)

However, when I try to perform another action (loop, data comparison, data set, etc.) on fetched_relation, I get the following error in the rules debug log:

  4.468 ms Unable to get the data value for the variable or parameter value. Error: Missing data values.

It appears that the relation is not fetched.  However,

I am sure the relation exists in the database with the correct endpoints (the relation appears in the UI correctly and I even checked the MYSQL table).
When I add an action Print message and print privatemsg-message:author:name and recipient:name, it shows me the names of the correct users, so those variables appear to be correct.
I have looked at the documentation for fetching relations with rules but I can't see what I am doing wrong.

I have managed to fetch relation by endpoint with the help of @marcusx and the patch of @MahmoudMostafa (drupal user names). You can find all in the issue Fetch Relation by Endpoints in rules.
I had also linked your issue to that one.
Resuming the steps here, you need to:

apply the patch

Create a list of any entiy
Put your endpoints in the list
Use the endpoint list to fetch the relation

cited from marcusx comment

(I see you already know this).
Bear in mind that

"fetch relation by endpoints" action in rules, [...] fetches all the relations for the endpoints in the chosen list, even if the list contains only one endpoint.
In this (sub)case, the action fetches all relations pointing to the selected endpoint, whatever the other endpoint.
cited from my comment

And that the resulting fetched_relation is a list (I see you already know this as well).
I believe you only need to apply the patch, which you didn't mention in your question. Is it true?


Custom entity api create options list for checkboxes without field api I want to create a checkbox widget in my custom entity to select multiple options.

I don't want to use the field api, instead I want to use my custom table with multiple columns, one of them shall have the values which were chosen.

For select I use the following:

$info['pricedefault']['properties']['preis_zeiteinheit'] = array(
'label' => t('Time unit'),
'description' => t('Preis Zeiteinheit'),
'type' => 'integer',
'schema field' => 'preis_zeiteinheit',
'options list' => 'zeiteinheit_options_list',
'translatable' => TRUE,
);

and

function zeiteinheit_options_list(){
return array(0=>t('0'),1 => t('YEAR'),2 =>t('MONTH'),3=>t('WEEK'),4=>t('DAY'));
}

But how to write a checkbox function with the correct table column?

Thx in advance,

maen

To store multiple value property values, without the field API, you may find it easier to create a generic extended properties table for one-to-many relationship with the base table.

e.g a table

Table: my_entity_properties

Columns: entity_id | revision_id | name | value

You can then store the extended properties in that table in the save function for your entity - each field value will be a row with the property name and value pair.
You then load them in the attachLoad function, grouping by the revision_id and property name to load the values for that entity revision.


How do I edit the CSS based on node, page, or placement on page? I've been learning how to navigate around and edit my global.css file, but am confused as to how to edit specific elements. I've come across answers to this question that don't specifically describe how to do this

To clarify, say that I have 3 pages on my site titled Red, Blue, and Black. If I want to edit just the h1 headers on page Red, how do I go about doing that? Is there a way to do this without PHP or installing extra modules?

Currently, whenever I try to edit the h1 header on supposed Red page, every single h1 header on my site is updated and edited.

Sorry if this is a duplicate, I honestly couldn't find any answer to my question while I was searching

This isnt a Drupal API question. It's more of a CSS and how does that work in the browser question. That being said there are docs on how to theme drupal 6 and 7. Since drupal is a web application they cover topics such as:

Working with CSS
Standard Drupal Core Styles and Classes

Within (2) it describes the .node and .node-title CSS classes:

  .node

  A wrapper div around all of a node, including its title.

  .node-title

  The title of the node.

Depending on the theme your using you may or may not have those exact classes, every theme is slightly different. Basically in your theme you want to use Firebug or Chrome Developer Tools to look at the HTML markup and CSS classes and IDs attached to things. You can then target a page or node title, and create a rule to target specific page urls if need be. As an example Drupal page (using AdaptiveTheme subtheme):

The <body> tag has a million css classes on it including page-node-2 that specific CSS class would target only this node (by its NID). You can inject other more useful body classes into any theme using hook functions and template files -- but thats beyond this writings scope.

In this case you can also see the node title has an ID of h1#page-title

A general CSS rule to target this 1 page's title you could put in global.css is body.page-node-2 h1#page-title { color: red; }

For your theme it would be the same process:

examine the body tag in your Theme and find a useful CSS class to specifically target the page(s) with a CSS rule.
examine the Section Header tags within the page to find the exact CSS classes/ids to target just that element as well.

Lastly, I dont think every theme has a global.css file ... though most probably do. My exact CSS rules herein will likely not work for your usecase, they're just examples of what you could do. See the documentation pages listed above to better understand Drupal Themeing.


Using searchapi module on a drupal multisite installation We are setting up a Drupal multisite installation, which is going to look like

themastersite.edu
themastersite.edu/somethinglikethesubsite1
themastersite.edu/somethinglikethesubsite2 and so long

I've read some documentaition around Searchapi module, but I can't find out if there is a possibility to have, in themastersite.edu, a searchapi page that should search in all subsites ?

Any help or link, welcome.

You declared that searchapi is the solution but actually Solr Multisite can do this.


Change a comment's body programatically I am building a small custom module that will change the value of a comment's body when the comment in posted. So far I have:

function comment_loader_comment_insert($comment) {
}

So pretty much nothing, just that I want to use hook_comment_insert to change after the comment has been posted.

So what do I need to affect the comment body?

[I am a student who is just learning php and drupal, so clarity is appreciated]

edit:

code so far:

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

/**
 * Implements hook_form_validate().
 */
function comment_loader_comment_form_validate($form, &$form_state) {
  $new_body = 'some text';
  $form_state['values']['comment_body']['#object']->comment_body['und'[0]['value'] = $new_body;
}

Still doesn't have any affect. I am no working in a development environment so I don't know if there are errors.

hook_comment_insert() is fired after the comment body has already been saved to the database, so it's probably not the hook you're looking for.

Instead you could hook up your own validation function to the comment form and alter the body there. That way you're not having to make any extra db calls.

In it's simplest terms you would implement hook_form_FORM_ID_alter() and add the validation function like so:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MYMODULE_comment_form_validate';
}

function MYMODULE_comment_form_validate($form, &$form_state) {
  $current_body = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'];

  $new_body = $current_body . ' some extra text';

  $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'] = $new_body;
}


Huge variations on page load times I've build a website using Drupal 7 (7.34 now) and used quite a lot of modules (CiviCrm, Views, Panels, Webform, etc). I recently put this site live at my hosting provider and now I'm experiencing huge variations in page load times (Time to first byte).

When I enable caching for anonymous users, the page load times are pretty stable (200ms). But when I turn of caching the load times are varying from 1.5 sec to 30 seconds. These huge variations seems to come in periods over time,with a couple of minutes interval.

I've already tried several things to find the problem:

My first suspicion was the performance of my hosting provider, but I'm pretty sure this is not the problem. I've created a PHP benchmark script and executed this while the responses for my website were slow. But the benchmark did still return the same results.
I've used the Profiling module to see if I could find a bottle neck, but it looks like all things are taking more time and not only 1 part.
I've used the Devel module to check the SQL queries, but there wasn't any taking a longer time then normal, when I experienced the slow response.
I've disabled the Update manager, as this could stall page loads, but without success.
I've checked for not properly (un)installed modules, but they are all OK.

It is also not related to any specific page, but all page requests are slowed down when it happens. I never saw any (PHP )error and finally the page will always load properly, but only with a huge delay.

When the slow down period occures, it looks like there is something holding up every page request. Maybe some locks on something??

As the site also has to perform for users logged in, caching for anonymous users is not a good solution. Of course there are several other caching solutions possible for logged in users, but I want to solve the cause of this problem. And not using work-arounds....

Can anyone advise me or has suggestions to find and solve this problem?

Thanx!

Seems to be too broad to answer, few pointers that may help you.

Root Cause of problem might be at

Custom module level which can be drill down with profiling tools as devel profiling which you have already used, another tool can be XHPROF.
Ensure all your custom queries are optmised.
Uninstall all modules which you are not using.
Try to have a comparison of site performance on your local and server, your server might not be allocating required resources.

As per my experience when you have long list of modules installed it causes performance issue especially panels, to overcome you can use caching provided by views module and for panels check if this module does the trick for you.

Having said that Authenticated User Page Caching mdoule will be worth looking at.

Views and panels provide caching


Assigning Template for Parts of Pages I'm new to drupal and coding so I'll try and explain best I can the issue I'm having.

I'm on Drupal 7, using Zen Sub Theme

I have a site which is essentially a database of gadgets.  'gadget' is a custom content type with custom fields such as 'year of manufacture', 'manufacturer', 'image' and 'description'.

I work out of 'page.tpl.php' to control the look of my homepage. I find this to be very easy to use, as far as creating/formatting regions.  Essentially formatting the building blocks of my template.  On the homepage I have list of links (created via views) to the most recent gadgets.  When I click on a gadget it takes me to the 'Gadget' page displaying all the fields I mentioned above.

Now to the issue I'm having:

I can't figure out for the sake of me how I can have a tpl file for the custom content type (ie. the gadget).  I have so far formatted the page with CSS but it would be nice if I can have (I prefer to work through editing the tpl files) a TPL file for the page elements (ie. header, footer) and a TPL file for the region its showing my gadget node.

I've attached a picture of what I'm trying to do:

The home page templating

http://imageshack.us/photo/my-images/402/homepagem.png/

The gadget page templating

http://imageshack.us/photo/my-images/560/pageinside.png/

What I've tried:

1) Formatting the gadget page with CSS : This works fine, but I would prefer to have control over tpl file.

2) In the templates folder I added node--gadget.tpl.php and cleared cache (doesnt work).  node.tpl.php on the other hand does get pulled up by static pages in the site (like the 'about us' page) but not on custom content type (gadget).

3) I added the code below to confirm that content '[type] => gadget':

    <?php
function gadgettheme_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $vid = db_query("SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $vid;
  }
}
?>

4) Finally I put in the code below and create a page--gadget.tpl.php.  This worked but the problem is its page--gadget controls the whole content which means I would need to copy over the template from the page.tpl.php to control the header and footer.  I want these elements to be controlled solely from page.tpl.php and have another node--gadget.tpl.php.

function gadgettheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

?>

Your help is appreciated in advance,

Cheers,

I've managed to solve this issue.

I was using display suite to format my node and without realising I was using the Display Suite's theming file.  Once I renamed my node--gadget.tpl.php to the Display Suites theme name ds-1col--node--gadget.tpl.php it worked!

Cheers,


Why is BaseFieldDefinition::getDisplayOptions($display_context) returning NULL I'm trying to get the weight of each field (of a form) in its display.

$fields = $entityManager->getFieldDefinitions($entity_type, $bundle);

foreach ($fields as $field_name => $field_definition) {
  $field_definition->getDisplayOptions('form'); //returns NULL
}

This returns NULL. $field_definition definitely has stuff inside of it. any ideas?

The getFieldDefinitions() method returns NULL if the field is not displayed. From the docs:

  Return value

  array|null The array of display options for the field, or NULL if the
  field is not displayed.

The code below is responsible for returning the correct value:

  /**
   * {@inheritdoc}
   */
  public function getDisplayOptions($display_context) {
    return isset($this->definition['display'][$display_context]['options']) ? $this->definition['display'][$display_context]['options'] : NULL;
  }

As you can see the $this->definition['display'][$display_context]['options'] array has to be set. If it isn't set the method returns NULL.


Limit one user per IP in Drupal 6.22 Recently I found that multiple accounts are being created in my Drupal 6.22 website by someone from a particular IP. Is someone aware of any modules to limit the user to create only one account per ip?
Thanks.

If it seems spammy, then maybe use Drupal to block the IP address (settings.php or admin) but if it's only a few and they look okay and genuine it could be users from the same college or company behind a proxy server.

If it you still want to block someone you could add an additional validate function to the user registration form and include an IP check in there.


Custom theme block position is not importing Problem:

Making a custom theme with blocks placed in different regions.

Place custom blocks in theme using the UI.
Export config. drush cex vcs
When it came time to import my config in a new environment custom blocks not appearing in proper region despite .yml files for individual blocks being present in my default config directory...

How to import configuration so that blocks from my custom theme appear in the correct region?

The solution was to disable and un-install my custom theme and then re-enable.

Here are the steps (Where vcs is our directory for default config defined in settings.php and my_custom_theme is our theme name).

After running drush si, lets import our config.

drush cim vcs --partial -y

At this point although our config has been imported our custom blocks are not appearing in the regions as set in the config .yml files.

Enable a core theme so we are free to uninstall our custom theme.

drush cset system.theme default seven

Rebuild the cache now.

drush cr

Uninstall our custom theme.

drush pm-uninstall my_custom_theme -y

Enable our custom theme.

drush en my_custom_theme -y

Set our Custom theme as default theme.

drush cset system.theme default rrre_theme -y

Import our default config.

drush cim vcs

Run Server.

drush rs

:)


Make variables outside of node available to pathauto I'm trying to port a website over to Drupal 7. The structure consists of locations which have an entity reference to a region which has an entity reference to a country:

  location<-region<-country<-continent

This all seems to work OK. A location node doesn't directly know what country it is in, but it does know what region it's in.

The problem is I want to use the old URL structure:

  /continent/country/region/location

So far I can get it to work for /region/location (as region is referenced from location) but then I get stuck.

What I'm wondering is there any way to pull these other fields (country / continent) into the node and make them available to pathauto?

If it helps it doesn't really matter what the continent and country are as region & location provide enough info. So a wildcard would be fine.

So, firstly, is this possible with this structure. And if so, how?

Any help greatly appreciated.

I was in a similar boat with a site I was working on recently.  Unfortunately, Drupal 7 does not fully support tokens on field entities; see http://drupal.org/node/691078.  This is why the "location node" type exists in the location module -- it is easier to define tokens for your locations.  However, I did not like the UX for location nodes; I greatly preferred the result that can easily be obtained with cck locations.

Since it was not possible to easily support tokens on cck locations, I instead wrote my own custom token code in my custom module for my site. I did spend quite a few hours trying to do the former first, before giving it up as much too large of an effort.

I'm not sure if you are using the location module, or if you are just defining your own entities that happen to contain locations.  The fact that you have your location entities chained together implies that you're using your own entity types.  Here's the result I came up with for the location module; you should be able to adapt it for standard entities without much trouble.  The code below could probably use some minor improvements; 'und' should be LANGUAGE_NONE, the special-checking for a specific content type is probably unnecessary, etc.; it shouldn't be too hard for you to adapt in some code that resolves your chained entity references to build the tokens you need.

Once you've written your code, it's easy to select your new tokens in pathauto to define your URL structure.

function MYMODULE_token_info() {
  // Because of http://drupal.org/node/691078, we just hack in our own
  // field-based tokens here for now (cough).
  // These tokens are only available for nodes of type MY_CONTENT_TYPE_WITH_LOCATION_FIELD
  $node['field_location_street'] = array(
    'name' => t("Location Street"),
    'description' => t('The street address that a location is located at.'),
  );
  $node['field_location_city'] = array(
    'name' => t("Location City"),
    'description' => t('The city that a location is in.'),
  );
  $node['field_location_province'] = array(
    'name' => t("Location Province"),
    'description' => t('The abbreviation for the province (State) that a location is in.'),
  );
  $node['field_location_province_name'] = array(
    'name' => t("Location Province Name"),
    'description' => t('The full name of the province (State) that a location is in.'),
  );
  $node['field_location_country'] = array(
    'name' => t("Location Country"),
    'description' => t('The country that a location is in.'),
  );
  $node['field_location_country_name'] = array(
    'name' => t("Location Country Name"),
    'description' => t('The full name of the country that a location is in.'),
  );
  $node['field_location_summary'] = array(
    'name' => t("Location Summary"),
    'description' => t('A parenthesized summary of the location (City, State).'),
  );
  return array(
    'tokens' => array('node' => $node),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $location_field = array();
    if (($node->type == 'MY_CONTENT_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_location['und'][0]))) {
      $location_field = $node->field_location['und'][0];
    }
    if (($node->type == 'MY_CONTENT_TYPE_WITH_NODE_REF_TO_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_event_site['und'][0]))) {
      $location_nid = $node->field_event_site['und'][0]['nid'];
      $location_node = node_load($location_nid);
      if (isset($location_node->field_location['und'][0])) {
        $location_field = $location_node->field_location['und'][0];
      }
    }
    if (!empty($location_field)) {
      $location_field['summary'] = "(" . $location_field['city'] . ", " . $location_field['province'] . ")";
      foreach ($tokens as $name => $original) {
        if (substr($name,0,15) == 'field_location_') {
          // $name is always 'field_location_xxx', so key is 'xxx'.
          $key = substr($name, 15);
          if (isset($location_field[$key])) {
            $replacements[$original] = $location_field[$key];
          }
          else {
            $replacements[$original] = '';
          }
        }
      }
    }
  }
  return $replacements;
}


Different CSS files for different browsers Ideally, if all of the CSS files used should be defined in the theme's .info file, how would I go about using different CSS files for different browsers?

The Conditional Stylesheets module allows themes to easily add conditional stylesheets to a theme's .info file.

This module is already used by the Zen, Layout Studio, and Tendu themes.


how to use user_save with custom column? I added custom column in users table, i would like to use user_save to create new user programmatically. How can i do that? This code doesn't work for custom columns:

$new_user = array(
                        'name' => 'Foo',
                        'pass' => $pwd,
                        'mail' => $email,
                        'signature_format' => 'filtered_html',
                        'status' => 1,
                        'language' => 'en',
                        'timezone' => 'Europe/Berlin',
                        'init' => $email,
                        'custom' => $custom_string,
                        'roles' => array(
                            DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                            $role->rid => $role->name,
                        ),
                    );

                    $new_account = user_save(NULL, $new_user);

Everything except custom gets inserted, if i am not wrong it's default drupal columns for each user's table. Thanks

Manually adding extra columns in tables will rarely work for Drupal as there are dependencies and references that have to be honoured.

The correct way would be something along the lines of this case.


How to subtract the node getChangedTime from 1 year I created a field that display a nodes last changed date using hook_form alter like this.

function demo3_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'node_page_edit_form') {
   $node = $form_state->getFormObject()->getEntity();
   $form['field_message'] = array(
     '#type' => 'item',
     '#title' => t('Changed date'),
     '#markup' => format_date($node->getChangedTime(), 'medium'),
   );
}

I need to create a new field underneath it for the Review date. This field needs to subtract the getChangedTime from a period of 1 year or 365 days. So if the changed date was 30 days ago. The Review date will be 335 days and display in a medium format.

Going under the assumption that this is Drupal 8 (based on the $node = $form_state->getFormObject()->getEntity(); line, you can do something like this:

function demo3_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form') {
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = \Drupal::service('date.formatter');

    $node = $form_state->getFormObject()->getEntity();
    $changed = $node->getChangedTime();
    $review = new \DateTime();
    $review->setTimestamp($changed);
    $review->modify('+1 year');

    $form['field_message'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#plain_text' => $date_formatter->format($changed, 'medium'),
    );

    $form['field_review'] = array(
      '#type' => 'item',
      '#title' => t('Review date'),
      '#plain_text' => $date_formatter->format($review->getTimestamp(), 'medium'),
    );
  }
}

Your other option is to use the timeago methods on DateFormatterInterface.


Why does Drupal use the database for the cached data? Why Does Drupal put the cached data in the database? It's hard too understand it, because the database can easily cause performance bottleneck.

The question that asked here is not whether the database cache can be replaced by something else, but why Drupal caches database information in the database. A reason that is not mentioned here is that although database information is again cached in the same database, it is not cached in the same format. The original data, such as node information or theme information, is stored in a kind of normalized form, which makes it easy to edit and query data. The cached values are stored in a way that reduces the amount of processing needed to display a page.

Let's say a page view consists of the following simplified steps:

Fetch information from database
Manipulate information to make it suitable for display
Display the result

Now Drupal stores the result of step 2 into the database, so on subsequent page views, steps 1 and 2 do not have to be executed. This saves time and processing power. When the original data changes, the cache needs to be cleared.


In Drupal 8 can a developer inject Full HTML Pages? I have done a lot of work in WordPress but want to develop a new site in Drupal 8. I have two specific questions before I start on my site.

Is it possible to inject full HTML pages via PHP into a Drupal 8 environment? I have full HTML content being served from an API for SEO purposes.

If the answer to #1 is NO:

Is it possible to change header and footer based on specific paths? So everything at /articles will get a certain header or footer? In this case I would want to pass an incomplete  tag and have the API call close the head tag and provide the body.

Usually you will not inject full HTML pages to Drupal, more likely you will inject your content as node-content. Then use a convenient theme for your needs.

Drupal has - like wordpress - themes. These are nested pieces of HTML code with TWIG syntax for dynamic content.

Unlike, wordpress, you can specify different themes for different URI paths (look for keyword theme_negotiator). I.e., you may configure to use an "article-theme" on path /articles.

But this is only the beginning of a very long story...


How exactly does module_load_include() load a file into the calling script? Here is the code:

function module_load_include($type, $module, $name = NULL) {
  static $files = array();

  if (!isset($name)) {
    $name = $module;
  }

  $key = $type . ':' . $module . ':' . $name;
  if (isset($files[$key])) {
    return $files[$key];
  }

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      $files[$key] = $file;
      return $file;
    }
    else {
      $files[$key] = FALSE;
    }
  }
  return FALSE;
}

module_load_include() is just a function that calls require_once from within itself to load an external file. But it seems to me that require_once should load external file into module_load_include() and subsequently, this loaded file should disappear when module_load_include() goes out of scope. Somehow "magically" the external file is successfully loaded into the calling script(eg: a page callback function) that calls module_load_include(). I don't understand how this is achieved.

It sounds like you're getting confused on scope. There's no "file scope" in PHP. The include/require statements are pretty much the equivalent of dropping the code within the scope that it's called.

Per PHP's docs on the include statement:

  When a file is included, the code it contains inherits the variable
  scope of the line on which the include occurs. Any variables available
  at that line in the calling file will be available within the called
  file, from that point forward. However, all functions and classes
  defined in the included file have the global scope.

If definitions in the included file are global. For example:

global $base_url;
define('MYMODULE_CONST', 123);
function mymodule_function() { }

Then they are global until the script execution ends.

If definition is not global (e.g. $var1 = 'var1 value';) then it only remains within the scope of the include statement.


How can I add a custom part to emails How can I add create a multi-part email in D7?  I need to add custom part to an email.

I am trying to use hook_mail_alter to append a new content type.  The content type is Content-Type: text/calendar.  I can't figure out where to add it in the $message array.

I have tried mimemail but it seems to disregard my SMTP settings.

You could use hook_mail_alter to alter the email message before sending it out. you could change or alter the email body, sender, attachments....etc as you wish


Multi Country and Language Site I'm trying to build a single global website that houses multiple countries, each with their own set of language translations. There is also a global overview site that also has its own language options. The global site will live on global.domain.com and function the same as a country site, and the countries will be at domain.com/langcode-countrycode/ (domain.com/en-us/). From anywhere on any site, the user will have a menu to navigate to another country/language. There will only be a dozen countries or so. There will also be company sites, but they are identical to the country sites. Each country/company will have its own management team that should only be able to edit their section. Each also needs the option to swap the logo and maybe some colors, but that's it.

From what I've found, Domain Access and Organic Groups, coupled with i18n, seems like the best option, but I just can't seem to get it set up in the right way. Is there a better approach to that?

Some countries want to be able to use another domain to access their country site, which I'm guessing would just be an alias to the main domain in Domain Access.

I can mostly picture how I would build this in WordPress, or even from scratch, but I'm new to Drupal, so I might be missing something obvious...

It sounds to me like you need a multi-site Drupal installation and each of those sites needs something like organic groups and also i18n.

Unless I am misunderstanding... what you're describing only makes sense if all the content across all sites is the exact same,  just translated versions.


How do I chose recipient email address depending on textfield value? I have created a webform which has a "Reference number" textfield.

When someone types 101 in that textedfield, the submitted form should be send to example@gmail.com; if someone types 777, the submitted form should be send to example222@gmail.com.

Is there a way to achieve this?

The first solution that comes to my mind will be using hook_form_alter.
and take the value of the field.
Based on the value, send the mail to appropriate address.

But most likely there will be a module for that.
Meanwhile..

http://agileadam.com/webform-mail-alter
can be of service

Regards

Oleg


How do I enable developer/debug mode? Installing drupal 8 core (using standard profile). whenever I get exception/error, I get blank page with "The website has encountered an error. Please try again later." (as below image) text and no details/trace about error.

On a development site I would suggest uncommenting the following lines in the settings.php file.     emacs sites/default/settings.php

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

and then copying the file example.settings.local.php from /sites folder to /sites/default folder and rename it to settings.local.php

cp sites/example.settings.local.php sites/default/settings.local.php

In addition to adding the following setting

$config['system.logging']['error_level'] = 'verbose';

it also adds a few other settings which will help you in debugging and making development easier. If you don't want any of them in particular, you can always comment them out.

Note : If you think adding a file_exists call to each page will slow down the site, you can always remove it in the production code.


Programmatically deleting a filefield content and the associated file? If I do the usual

unset($node->myfilefield["und"][0]);

Would that take care of the actual deletion of the file as well on node_save?

No, it doesn't. You should use file_delete(). The function will remove the attached file from the database and from the disk.

// Load the node.
$node = node_load('1');
// Get the language for the file field.
$lang = field_language('node', $node, 'myfilefield');
// load the file
$file = file_load($node->myfilefield[$lang][0]['fid']);
// unset the field for the node
unset($node->myfilefield[$lang][0]);
// delete file from disk and from database
file_delete($file);
// Save the node.
node_save($node);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.