How to update the node status? I'm using data from JSON to create new nodes or update fields on existing if node exist on my Drupal 8 website. So, when I use method to update nodes, I need to save in array node id of updated nodes and keys of fields with changed values in this node.

After update is finished I need to print table with all nodes of this content type where fields of updated nodes need to have different style (color, background, etc).

So if my old node have
body = "body1" and description  = "description 1" and new node have body = "body2"and description  = "description 1" after update is finished i need to get output like this:

Here is an example:

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("description", 'New value');
$node->save();

Any suggestion?

Note: when I use $node->save(); if all updated values is same nothing is changed (date of node in content from admin panel is same as before update), but if values is different I need to store node id, keys and values only of changed fields in array.

To set the status you can use the setPublished() method:

  public function Node::setPublished

  Sets the published status of a node..

  Parameters

  bool $published: TRUE to set this node to published, FALSE to set it
  to unpublished.

In your case:

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->setPublished(TRUE);


How do I correctly use states? I have a form that has a field with conditional validation. I mean if a certain radio button is checked, then the field need to be required.
Please find below a code snippet of how I tried to solve it. Unfortunately, when I run this code, the field disappears, and when I comment out this logic, the field appears again.

I implemented the code from https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_process_states/8.2.x.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['the_field'] = [
    '#states' => [
      // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
      'required' => [
        ':input[name="field_of_type_radio"]' => ['value' => '1'],
      ],
    ],
  ];

}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  // If your field is link field
  $form['the_field']['widget'][0]['uri']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
  // If your field is text field
  $form['the_field']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
}


How do I disable a single option from select I have used a taxonomy entity reference to fill the values of a select form field. Based on the user roles, I want to limit the options between Submitted, Reviewed, Accepted, and Rejected.

I have used a content type to submit ideas. The field idea status is disabled for a subscriber role and available for moderator role and approver role. I want the Moderator to get the status Reviewed and Rejected. Approver should see Accepted and Rejected status.

How can I achieve this?

The options can be hidden by a one liner code,

unset($form['field_name']['und']['#options'][1]);

where

['field_name'] is the name of the your field

[1] is the index of the option in the list

In my case [1] is Submitted, [2] is Reviewed, [3] is Accepted and [4] is Rejected


Best CSS and JS aggregation/minification strategy for D7 Drupal 6 has the awesome advagg module, which does an awesome job of intelligently bundling CSS and JS, but currently no D7 release.

What I am looking to achieve is:

less CSS and JS files (5 CSS and 5 JS files is far too many)
JS files have minification (currently core only does this for CSS)

Is there a drupal 7 solution that will help here? What are other people's experience with optimising this?

Edit: The question was originally posted in 2011. There is now a very stable D7 release of advagg.

For D7, there's Core Library which has a learning mode that aggregates based on real-world statistics about your site.

If you want to brute-force everything into one giant aggregate, I've written an article with some sample code:

/**
 * Implements hook_js_alter().
 */
function mymodule_js_alter(&$javascript) {
  uasort($javascript, 'drupal_sort_css_js');
  $i = 0;
  foreach ($javascript as $name => $script) {
    $javascript[$name]['weight'] = $i++;
    $javascript[$name]['group'] = JS_DEFAULT;
    $javascript[$name]['every_page'] = FALSE;
  }
}

/**
 * Implements hook_css_alter().
 */
function mymodule_css_alter(&$css) {
  uasort($css, 'drupal_sort_css_js');
  $i = 0;
  foreach ($css as $name => $style) {
    $css[$name]['weight'] = $i++;
    $css[$name]['group'] = CSS_DEFAULT;
    $css[$name]['every_page'] = FALSE;
  }
}

Drupal.org issue #1034208 also proposes relaxing the strict ordering requirements slightly.


load one-off page fast I want to create a landing page for my Google Ads on my site so that potential customers will be able to download and see the page very quickly. My site can be a bit heavy with CCS and javascript and other stuff sometimes.

All I want is to avoid losing potential clients due to a slow website. So I wonder if there's a simple way of the landing page being a light version of my site (with links to the "real" drupal site).

Many thanks

Oli

If you want your website to load fast, you need to cache.

Go to Performance (/admin/config/development/performance)

and enable caching and aggregate css and javascript


I'm looking for a Drupal Commerce Shipping in-cart estimate I am working on a Drupal Commerce site, we are trying to add a feature in the cart that would allow the user to input their zip/postal code or country and receive an estimate on shipping, before proceeding through the checkout. I'm new to Drupal Commerce, so maybe this functionality already exists?

a shove in the right direction would be greatly appreciated. Thanks.

link- https://drupal.org/project/commerce_shipping
Commerce Shipping provides a shipping rate calculation
system for Drupal Commerce , integrating shipping
service selection into both the checkout form and order
edit form. This module is a framework that is meant to
be used in conjunction with shipping method modules
like Commerce Flat Rate , Commerce UPS , and others.
Shipping service availability and rate calculation is
handled in the user interface through Rules and is
backed up by an API that gives you a high level of
flexibility to implement simple or complex shipping
scenarios.


How to get the field and value of a content type in drupal 8? I wanted to create a module that fetch the entire data from my custom content type to  generate a json file. So I used the function

$values = \Drupal\Core\Entity\ContentEntityBase::get('field_name');

to read the field and its values of a content type. Any way to dynamically fetch all the fields and its values. Any solution?
Thanks in advance..:D

You can get all the field definitions for a content type using getFieldDefinitions from the Entity Field Manager service. The definitions are indexed by field name, so you can iterate on the keys of the returned array for any of the nodes in your site.

An example would be the following:

<?php
  // Get the definitions
  $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

  // Load a node for which you want to get the field values
  $my_node = \Drupal\node\Entity\Node::load($my_nid);

  // Iterate through the definitions
  foreach (array_keys($definitions) as $field_name) {
    // Get the values for your node
    // Use getValue() if you want to get an array instead of text.
    $values[$field_name] = $my_node->get($field_name)->value;
  }


Proper directory permisions for module installation? So I'm trying to understand the correct permissions for file directories in order to install a module. I've installed drupal, and I try to install a module, which looks like so:

But When I click install it takes me here:

I then wanted to test if it was permissions preventing it from installing, so I chmod'd everything to 777 in the sites folder just to see, and yes, the module then installed easily and correctly. But of course, 777 on everything is insecure, so I quickly installed drupal again from scratch. So now when I check the permissions they look like this

html/sites$ ls -l
total 16
drwxr-xr-x 5 6226 6226 4096 Jun 17 18:38 all
dr-xr-xr-x 3 6226 6226 4096 Jul 19 20:08 default
-rw-r--r-- 1 6226 6226 2365 Jun 17 18:38 example.sites.php
-rw-r--r-- 1 6226 6226  904 Jun 17 18:38 README.txt

So after an installation the all folder has r-x permissions and the default has r-x as well for group and other. (A side question being, what do I make of the user and group, "6226", "4096","2365", and "904"?)

The "modules" folder, inside "all" folder where they get downloaded is also set to r-x.

html/sites/all$ ls -l
total 12
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 libraries
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 modules
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 themes

I don't know if this seems right to me. Shouldn't it be able to write to the folder to download the module from an external source?

Thanks for all the feedback in advance, I look forward to hearing what people have to say.

Edit, more details:

Linux myhostname 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

ubuntu@myhostname:/var/www/html/sites/all/modules$ ls -la
total 12
drwxr-xr-x 2 www-data 6226 4096 Jun 17 18:38 .
drwxr-xr-x 5     6226 6226 4096 Jun 17 18:38 ..
-rw-r--r-- 1 www-data 6226  952 Jun 17 18:38 README.txt

Okay! So. after reinstalling and repeatedly chowning folders until I made it past that request for FTP details, I finally got it to ATTEMPT to download the file. All I had to do after a fresh install was sudo chown www-data /var/www/html/sites/default. What confuses me is why that would work. Beause before and after chowning, the permissions were dr-xr-xr-x 3 www-data 6226 4096 Jul 20 09:03 default for the default folder. So my understanding is that the owner, group, and others could all all read and execute, so why would changing the owner even matter?
Now when attempting to "Install from a URL" after chowning default, a loading bar appears and says "Completed 100%", and then this screen appears instead of the FTP login request:

The module directory has contested ownership. In your case, using the FTP set up from the browser, the modules directory (and subdirectories and files) need to be owned by the FTP user you are logging in with.

For example: if you are ftp-ing in with myusername then the ownership on the directories and files are most likely be myusername. That is the default configuration for most FTP servers (ProFTPd for example).

$ chown -R [myusername] [pathtomodules]

If you are updating Features (or configuration in Drupal 8) from the Drupal backend you'll want the modules directory owned by the same user as your web service runs as. Then you can have your permissions set to something more reasonable.
If you grep ps for Apache, nginx or httpd you should discover the user that's running the process.

$ ps aux | grep -i 'www\|apache\|nginx'
$ chown -R [username] [pathtomodules]

And finally if you are using drush dl you'll need the owner to be your SSH user.

In all cases you can set the strongest permissions with the following. Remember the webserver needs read on all files and execute on all directories. This command will give you 755 on directories and 644 on files.

$ chmod -R u+rwX,go+rX,go-w [pathtomodules]

The first two numbers in your ls command are user and group. That may be a numeric match for your web service user above. The third column is size.


How can I check to see differences across my multisites? Currently, we're using Acquia Content Hub to syndicate content across our sites with a spoke and wheel syndication architecture. We essentially use a single site (that content editors use to create/maintain our content) and push out content to all of our subscribing sites.

However, it seems that some of our developers implemented changes on certain sites but not all sites and this is causing differences for each of our site environments (example: All sites would have an article content type but with different fields/naming conventions for fields). These differences then end up preventing our synchronization (especially if there is a field on the main content site and not on a subscribing site) from moving past the item and then requires a clear (and re-queue) of all items to syndicate.

Is there any easy way to set up a PHP script or something to check each site for differences against the main content site for entities?

For example:

If on the main (content) site the article had 3 fields:
- Article Title
- Article Body
- Article Image

And on a subscribing site, the article had only 2 fields:
- Article Title
- Article Body

I would expect said magical script to print out some indication that on the main (content) site, there is an "Article Image" field present that's not available on the subscribing site.

Is there any way that I could accomplish this? Any and all assistance would be greatly appreciated, thanks!

That's a task for the Features module. Before Drupal 8 and its superb configuration management the Features module was used to track and deploy changes to entities or settings from local to prod or to your coworkers. Nowadays you can use it to track changes and sync features across multiple instances of Drupal.

Let's say you have two Drupal 8 sites or two Drupal 8 multisite instances and both of them have a content type "Foobar". Then there's Features that lets you export the whole content type into a so called Features module. Which is just another module but also holds the whole config for this "Foobar" content type in it. Now you activate this Features module on both sites or instances and both will have the same content type with the same fields in it.

From now on when you change something in this content type on either instance Features will recognize the changes and offers you to recreate the Features module. Do that and the other instance will recognize the Features module had been recreated and offers you to import these changes.

And that's what you can do now. Go to the instance you consider being the master. Use Features to export the content type in a Features module. Enable this module in this instance and also in the other instance which you think got overridden or which you think is missing the changes and use Features to explore the differences and to maybe sync the changes.

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.


how do I make JavaScript run after the page is loaded With Drupal 8, I am adding JavaScript to my theme in the libraries.yml so that I can put lift segments into the data layer.  But it is running before the body is loaded, and the data layer is being overwritten.

How can I make this script run after the body load?

Did you use $(document).ready or better Drupal.behaviors?

This is from drupal docs:

  When using jQuery it is standard for a large majority of situations to
  wrap almost all code inside the $(document).ready() function, like
  this:

$(document).ready(function () {
  // Do some fancy stuff.
});

  This ensures that our code will only run after the DOM has loaded and
  all elements are available. However with Drupal there is an alternate
  better method; using the functionality of Drupal.behaviors and once().
  If used properly this will ensure that your code runs both on normal
  page loads and when data is loaded by AJAX. The Drupal.behaviors
  object is itself a property of the Drupal object, and when we want our
  module/theme to add new jQuery behaviors, the best method is to simply
  extend this object.

  A really basic example:

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Using once() to apply the myCustomBehaviour effect when you want to do just run one function.
    $(context).find('input.myCustomBehavior').once('myCustomBehavior').addClass('processed');
    // ... left out the more complex examples
  }
};

Quote from JavaScript API in Drupal 8


How to update the database schema without losing existing data I have a custom module with my_module.install file defining my two data tables in mysql. Module is already installed and I am able to save data from forms into them. Now my requirements changed and I need to create a third table in the same module. How do I approach the reinstall of the module.

1) Prepare MYSQl scripts to backup the existing data into temp tables and after uninstall and reinstalling the module, copy back the data into tables from temp tables.

2) Looked into https://www.drupal.org/project/backup_migrate not compatible to drupal core version I am using 8.6.0

3) Any other modules or ideas?

edited after the suggestion:
I have created the below function in  mymodule.install file and also edited mymodule_schema() method and run drush updatedb. Still no db changes as expected table is not getting created. Not able to look into system table to get the recent version number as mentioned elsewhere because that table is not available in my current local DB.

   function mymodule_update_8601(){
    $spec = array(
    'fields' => array(
     'application_setup_id' => array(
     'type' => 'serial',
     'not null' => TRUE,
     'description' => 'Primary Key: ID',
     ),
    ),
   );
   $schema = Database::getConnection()->schema();
   $schema->createTable('application_setup', $spec);
  }

When you want to apply database schema changes you don't reinstall the module. You apply these changes via hook_update_N() from your MYMODULE.install file.

See Updating Database Schema and/or Data in Drupal 8 on drupal.org.

  If your module is making a data model change related to database
  schema that your module defines with hook_schema(), then you need to
  properly update your data model. The two steps are:

  Update your hook_schema() code so that it reflects your new data model if the database table and field definitions have changed. This
  will make sure that people that install your module after you made the
  change will install the correct database tables. See the Schema API
  documentation for details on that.
  Write a hook_update_N() function. This will update the database for existing users of your module who already had it installed before
  you made the change so that they can continue to function. This is
  described below.

There also is a sample on how to add a new table from hook_update_N():

$spec = [
  'description' => 'My description',
  'fields'      => [
    'myfield1' => [
      'description' => 'Myfield1 description.',
      'type'        => 'varchar',
      'length'      => 255,
      'not null'    => TRUE,
      'default'     => '',
    ],
    'myfield2' => [
      'description' => 'Myfield2 description',
      'type'        => 'text',
      'not null'    => TRUE,
    ],
  ],
  'primary key' => ['myfield1'],
];
$schema = Database::getConnection()->schema();
$schema->createTable('mytable2', $spec);


how to hide the facet api block if it has only one item? I have to hide the Drupal facet API block if it has only one item. Is there any settings available or should I go with any hooks?

Use the module facetapi_bonus and you will get an option to hide a facet if the view has only X item(s)

This setting can be accessed through 'facets > configure filters'


Disable an option for the select form field How do I disable an option in the select form field?

$form['feed'] = array(
  '#type' => 'select',
  '#title' => t('Display of XML feed items'),
  '#options' => array(
    'title' => t('Titles only'),
    'teaser' => t('Titles plus teaser'),
    'fulltext' => t('Full text'),
  ),
  '#description' => t('Global setting for the length of XML feed items that are output by default.'),
);

How can I disable, for example, the "Title only" option?

Disabling an option may be tricky to achieve (Using form_alter to disable ONE option of a select field) so I'll recommend you to look at optgroups as an alternative. The Drupal form API documentation doesn't explain it but the API allows nested array for the options, have a look at form_select_options() and the <optgroup> part.
You can write this code:

$form['feed'] = array(
    '#type' => 'select',
    '#title' => t('Display of XML feed items'),
    '#options' => array(
        'Titles only' => array(,
          'teaser' => t('Titles plus teaser'),
          'fulltext' => t('Full text'),
        ),
        'Titles only 2' => array(,
          'teaser2' => t('Titles plus teaser 2'),
          'fulltext2' => t('Full text 2'),
        ),
    ),
    '#description' => t('Global setting for the length of XML feed items that are output by default.'),
);

Have a look at Drupal 6 forms and optgroup arrays.

Edit: to clarify this is an alternative and not a direct answer.


How to create a distribution list for sending eMail? In my project I want to create distribution list.
eg: while sending mail if I select drupal, then all drupal user should get mail. This means according to user group, mail will get created and if I selected any of the user group, then all mail id of that particular group will get selected and mail will send.

Any suggestions?

You can use the Rules module for this, simply by using Rules Action "Send mail to all users of a role". So all you'd have to do is to create a role that corresponds to your "user group", and grant access to the role you created for it.

However, if your user group consists of many, many users, then you might want to use a more granular approach as details in my answer to "How to delay sending emails using Rules to avoid being considered as a spammer?".


A user-centric multi-site installation How do I go about creating a similar content-structure as wordpress.com?

I want the user experience to only be of the sub-site (sub-site.example.com) and not of the main website (example.com). E.g. the home link goes to the sub-site, like this http://fiveandspice.wordpress.com/
In my case I will not offer blogs, but a web-application.
I'm thinking of utilizing Drupal for the user-system to handle the subscription-based accounts and generating the web pages.
The account-owners will have visits to their "page", and those visitors in turn would as well need account to do certain actions. Similar to how Basecamp work.

You can do this with the Aegir hosting System http://www.aegirproject.org/
It presents an intuitive front end to multisite.


How to set up this view of commerce orders...? Really hope someone can help me with this as am completely stuck, sorry it's a bit long but I don't know what else to do...

I'm working on a commerce site for a client that offers blocks of pilates classes. Users will purchase blocks of 6 classes in order to book onto them.

I have one product in the store called 'standard-6-block' at a price of £45.

I then have a product display called 'Class (Block)'.

The Class (Block) nodes will list 6 dates using just a text field with an unlimited number allowed (although each block will just have 6 classes added)

Blocks of classes run for 6 weeks, hence the 6 dates in each node, and will be added every week.

For example there may be one Class (Block) node with 11/01/2017, 18/01/2017, 25/01/2017, 1/02/2017, 8/02/2017, 15/02/2017 dates.

There will then be another node added a week later with 18/01/2017, 25/01/2017, 1/02/2017, 8/02/2017, 15/02/2017, 22/02/2017 dates.

This is because users may start blocks of classes at different times so we've agreed blocks will be added each week.

I now need my client to be able to run reports using a views page to show who has booked on to each class. (Not each block of classes (node) but individual classes in blocks (dates in the 'Class Dates' field in the node).

I've created one test order in my store which has purchased just one block of classes. There are currently 4 blocks of classes available to purchase on the website.

My view settings are:
View of: Commerce Orders

Relationships:
Commerce Order: Line items, (Line items referenced by commerce_line_items) Commerce Line item: Product, Commerce Order: Owner, (Products referenced by commerce_product) Commerce Product: Referencing Node, Commerce Order: Payment Transaction

Filters:
(Node referencing products from field_product_type) Content: Class Dates (exposed) and is REQUIRED!

Now when I run the report and enter a date for example 18/01/2017, the view doesn't just show the ONE order in the store IE this user has registered and paid for this class, it shows all 4 of the nodes that have been added.

Really hope that makes sense...? Thank you so much for taking the time to help me

Turns out I need to make every block of classes individual products in the store and use 'Auto product display' module to automatically create the node displays.  Then have to create a view that lists the commerce products rather than node displays


How can I convert the code that used drupal_get_http_header() to check if a 403 or 404 error is returned? I have a module that in hook_preprocess() checks with drupal_get_http_header() whether Drupal is returning a 403 or 404 error, but in Drupal 8 that function is deprecated, since header handling is being shifted to a Symfony response object.

The used code is similar to the following one.

$header = drupal_get_http_header('Status');

switch ($header) {
  case '403 Forbidden':
    // Add new headers.
    // …
    break;

  case '404 Not Found':
    // Add new headers.
    // …
    break;
}

What code should I use in Drupal 8? If that means to use a different hook, that is fine.

I would also be interested in the case I need to add HTML output to the page. I guess that in this case I should use hook_page_alter(), but I still don't know how to access the response object for the page being served.

You can subscribe to the Symfony KernelEvents::RESPONSE event:

The RESPONSE event occurs once a response was created for replying to a request
This event allows you to modify or replace the response that will be replied. The event listener method receives a Symfony\Component\HttpKernel\Event\FilterResponseEvent instance.

To do so, create a new module ("response_test" in this example), with the usual .info.yml and .module file.
Then register your event subscriber in the module's services file:
response_test.services.yml
services:
    response_test.response_subscriber:
      class: Drupal\response_test\ResponseSubscriber
      tags:
        - { name: event_subscriber }

Now all you need is the class to handle the event:
lib/Drupal/response_test/ResponseSubscriber.php
<?php

namespace Drupal\response_test;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ResponseSubscriber implements EventSubscriberInterface {

  public function onRespond(FilterResponseEvent $event) {
    if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
      return;
    }

    $response = $event->getResponse();
    if ($response->getStatusCode() == 404) {
      // Prepare a new Symfony\Component\HttpFoundation\Response and use
      $event->setResponse($new_response);

      // or call one of the setter methods on $response, the changes will persist
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }

}

I'm a little unsure about changing the HTML content in this context; you have access to $response->getContent() and $response->setContent() so you can manipulate the raw string directly, but as far as I can tell everything's already rendered at this point.


Is it possible to add or somehow relate a checkfiled to taxonomies? I am trying to make something with the commerce module and I need to create options for my product and I was thinking making this via a taxonomy, but the options must be clickable (checkboxes) so ... is it possible to change taxonomies to checkboxes? if so, then how?

To change the tag selection for a taxonomy field from autocomplete to check boxes go to the content type or product type and change the widget in the tab Manage form display:


How to bulk create an extra node for each user I need to create an additional node for each authenticated active user on a Drupal 7 site.

The nodes will be populated with default content from taxonomies, and also with some field content based on content owned by each user.

Something like :

create node with author=user1
field 1= populated from a taxonomy
field 2= Count of number of nodes of content type A authored by user1 that are
published
field 3= current date

And then loop through all active users creating a similar node for each one.

What's the best way to handle this?  Ideally I'd like to do it in a way so that the batch node creation job could be triggered by a scheduled Rule in future.

The idea is to provide a report showing a snapshot of the account status at a fixed time.

Shouldn't be too difficult if you're ok with writing a custom module, I can't think of any other way to iterate through your user base.

Create the node type for storing your statistics with:

Title (compulsory, unfortunately.  consider using Automatic Nodetitles)
Entity Reference field that references a user
Date field for storing the date
Other field/fields to store your statistics

Write a custom module that does the following things:

Iterate through all of your users
Check to see if the user is active
Queries the database to see how many nodes the user has.
Creates a new node containing the information you wish to store.

See how you go and of course ask more, detailed questions about each step showing what you have tried if you really can't work it out through the documentation and existing questions/answers available here and elsewhere.


How can I create a panel/page/view that shows a list of nodes, and on the other side of the screen details about that node? Below is the generally layout of what I want to do. A list of nodes/items of a fixed content type with a custom view on the other side.

On the left hand side we see a list of nodes, shown as squiggles. One is selected (highlighted with a red border).
On the right hand side we see the details of this node: The Title, The Description and so on.

I've looked into Views and Panels. I think what I want is a View that is specific to the listed content type. And then to include that in a panel that has the list?

I've tried several times but gotten mixed up in what I need to do.

Is there a simple non-video (blocked at work) guide to doing this sort of thing?

All the examples I've seen either use pure php or make too many assumptions about knowledge of drupal.

I don't know of any Drupal Contrib Master-Detail views modules. Views Megarow comes close, so check it out.

You can use Panels and Page Manager (part of CTools) if you don't mind a page reload to update the detail view.

To start, install Panels, Page Manager (part of CTools), and Views content panes (part of CTools).
Select a path that you want your master-detail view on: I choose detail-view for this example.
Create a view that lists your content titles (master display only). Add field nid to this view, set its display to none, and move it to above title field. Alter title field settings by removing 'link this field to the original piece of content', and rewrite results on this title field by selecting 'Output this field as a link', and enter detail-display/[nid]

Create a second view similar to first (view of nodes, master display). Add a 'Content Pane' display to this view. As this view will display fields for a single node only, add the fields you want to display. Then add a contextual filter of nid, and hide the content when the filter is not available. Now comes the important part. Click on 'Edit' next to 'Argument input' in the middle pane of the views UI.  Select 'From Panel Argument' for the list box 'Content: Nid Source', then select 'First' from Panel argument.

Add a custom page (admin/structure/pages/add). Add your desired path (ie detail-display). Select Panel as the variant. Next screen of wizard choose a two-column layout.
When you get to the UI page where you select the content for the left and right side, do this.

a. For left panel, select 'Add content'. Select 'View Panes', and select the view pane that you created first (ie the one that lists all the titles).

b. For the right panel, select 'Add content', then select 'View Panes', and select the view pane that you created second (ie the one that lists detail for one node only).

Update and save the panel, and you are good to go.


How to pull node reference into view on a search index? I'm wondering how to pull the node reference into a view based on a search index. I did this with my earlier product catalog by adding a relationship to the product referenced node, adding the node reference, and then rewriting my image's output as a link.

With the view set on my search index, I don't have the option to add a relationship to the referenced node, so I'm not sure where to pull the node reference from to link  the images back to their product displays.

Any advice would be appreciated.
Thanks in advance.

A search API based view can just take fields and information which are put into the index. Go to the index settings page and add the reference field. Then you can add addtional fields and relations connected to the reference.


Drupal duplicate alias for same node Any of you guys know why drupal it's duplicating my url alias when save a new node?

$node->path = 'st.louis';
node_save($node);

But in my alias table I have  st.luis and stlouis

That might be because of Locale core module. I had the same problem, but when i disabled the Locale module the problem was gone.

You can observe the main cause of the problem. When you look into the duplicate url aliases you will find the difference between the original url alias and duplicate url alias. In the original url alias you will have language = " and whereas with new/duplicate url alias you will find language = 'en'.

Hope this answers your question.


Capture generated Drupal 7 html output into a variable Trying to hook into Drupal 7 from an external php file by using various variants of ...

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
ob_start();
menu_execute_active_handler();
$contents = ob_get_clean();
return $contents;

However, it seems D7 just spits out the HTML to the browser on the menu_execute_active_handler() call.

Any ideas how to get the html output into my variable?

Tracking the Drupal flow line by line and function by function reveals the culprit to be ob_flush in the drupal_page_footer function

Using the following instead of ob_flush would make the application a bit more friendly

$data = ob_get_contents();
ob_clean();
print $data;

Expanding on this,

Finally solved by adding a delivery callback to my module_menu function and handling things there to bypass the problem function.

/**
 * Implements hook_menu().
 */
function MODULE-NAME_menu()
{
    $items = array();
    $items['MODULE-NAME'] = array(
        'page callback'     =>  'MODULE-NAME_output',
        'access arguments'  =>  array('access content'),
        'delivery callback' =>  'MODULE-NAME_deliver_html_page',
        'type'              =>  MENU_CALLBACK
    );

    return $items;
}

/**
 * Page callback: Display MODULE-NAME HTML Output
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_output()
{
    return 'Some Output HTML';
}

/**
 * Delivery callback: Render MODULE-NAME Page
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_deliver_html_page($page_callback_result) {
    /* Adapted from "drupal_deliver_html_page" */
    // Menu status constants are integers; page content is a string or array.
    if (is_int($page_callback_result))
    {
        // Integers mean an error page is required!
        // Send to the default Drupal function and exit.
        // Note use of exit instead of drupal_exit (not needed here).
        drupal_deliver_html_page($page_callback_result);
        exit;
    }
    elseif (isset($page_callback_result))
    {
        /* Print anything besides a menu constant if not NULL or undefined. */
        // Send the correct charset HTTP header if code running
        // for this page request has not already set the content type header.
        if (is_null(drupal_get_http_header('Content-Type')))
        {
            drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
        }
        // Send appropriate HTTP-Header for browsers and search engines.
        global $language;
        drupal_add_http_header('Content-Language', $language->language);
        // Render page
        print drupal_render_page($page_callback_result);
    }
    /* Adapted from "drupal_page_footer" */
    // Perform end-of-request tasks.
    global $user;
    module_invoke_all('exit');
    // Commit the user session, if needed.
    drupal_session_commit();
    if (variable_get('cache', 0) && ($cache = drupal_page_set_cache()))
    {
        drupal_serve_page_from_cache($cache);
    }
    else
    {
        $data = ob_get_contents();
        ob_clean();
        print $data;
    }
    _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
    drupal_cache_system_paths();
    module_implements_write_cache();
    system_run_automated_cron();
}


Check Content Type in Page PreProcess Hook I'm attempting to get the content type in my page preprocess function...but apparently I'm missing something.  What am I doing wrong here?  I'm attempting to get the $node variables first - then test from there.

function mytheme_preprocess_page(&$variables) {
   $node = \Drupal::routeMatch()->getParameter('node');
   switch ($node->getType()) {
       case "client":
           $variables['attributes']['class'][] = 'clientpage';
       break;
        case "something_else":
           // ...
       break;
   }
 }

Instead of looking at the route parameter, you can also do:

$node = $variables['node'];

Here is some example code that I have that is working from preprocess_page:

    $node = $variables['node'];

    if ($node instanceof NodeInterface) {
      $type = $node->getType();

      if ($type == 'listing_page' && trim($node->getTitle()) == 'News') {
        $variables['is_news_page'] = TRUE;
      }
    }

Don't forget your use ... statement if you check node is NodeInterface.

So this is definitely doable - if you are getting any error messages please post them and double check your content type machine names.


How to debug EntityMalformedException? I've got fatal error EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7700 of .\includes\common.inc) when trying to access user/xyz.

I tried to retrieve info about the malformed node at line 7700, where the error message is built, thinks like :

if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
 dpm($info);// or dpm($entity);
 throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

dpm($entity) returns an unexpected user object, and $info a huge qty of things.

Could somebody put me on the right way ?

I already read whatever I could find about Missing bundle property errors, but none helped solving.

dpm($entity) returns

uid (String, 2 characters ) 70
name (String, 9 characters ) John
pass (String, 55 characters ) $S$DUwPuOuDPiDL4nRTYXqc7a5uOfMKey7pyhOFUEKka1XM...
mail (String, 30 characters ) john@example.com
theme (String, 0 characters )
signature (String, 0 characters )
signature_format (String, 13 characters ) filtered_html
created (String, 10 characters ) 1396286331
access (String, 10 characters ) 1397146661
login (String, 10 characters ) 1396513460
status (String, 1 characters ) 1
timezone (NULL)
language (String, 2 characters ) fr
picture (NULL)
init (String, 30 characters ) john@example.com
data (Array, 5 elements)
roles (Array, 1 element)
og_user_node (Array, 0 elements)
message_subscribe_email (Array, 1 element)
field_bio (Array, 0 elements)
field_name_first (Array, 1 element)
field_name_last (Array, 1 element)
field_facebook_url (Array, 0 elements)
field_linkedin_url (Array, 0 elements)
field_twitter_url (Array, 0 elements)
user_trusted_contacts (Array, 1 element)
group_group (Array, 1 element)
group_access (Array, 1 element)
metatags (Array, 0 elements)
rdf_mapping (Array, 3 elements)
realname (String, 13 characters ) John Doe
content (Array, 13 elements)
entity_view_prepared (Boolean) TRUE
privatemsg_disabled (Boolean) FALSE

The error:

  EntityMalformedException: Missing bundle property on entity of type node.

happens, because your bundle property is malformed either on load or save, so Drupal can't find what type of bundle is it.

The logic of that Exception is:

// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  // var_dump(debug_backtrace()); exit; // You may want this line to debug.
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

So basically value of $info['entity keys']['bundle'] (for node it's: type) can't be found in $entity object ($node->type for the node), therefore Drupal doesn't know with what kind of entity it's dealing with. So most likely your entity is invalid (e.g. you're loading something else instead) or it is just empty ($entity is NULL).

If you haven't modified any Drupal code, this potentially can be caused by variety of things (most likely by specific Drupal module bug), such as:

saving invalid entity such as:

missing type from the node object (e.g. wrongly generated by Devel Generate?);

orphaned nodes in node table;
invalid rows in field_data_field_xxx table;
having orphaned nodes, caused by:

search view having indexed nodes which aren't in the system;
other modules (like Feeds) removing nodes from Drupal improperly;

nodes having invalid/non-existing references; for term data this can be checked by:

drush sqlq "SELECT nid, title from node WHERE nid IN (select entity_id from  field_data_field_some_ref WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data));"

Where field_data_field_some_ref is data field of field_some_ref which is type of 'Term reference'.

See: DB records not deleted for Term Reference Fields after Term is Deleted
having orphaned taxonomy terms (so you may use Taxonomy Orphanage);
entity caching issue;
when using Rules Link module;
invalid custom code (human error) such as:

badly implemented Entity API,
badly implemented CTools/Form API,
!empty() test on the entity variable before calling field_get_items(),
rendering field by invalid calls,
triggering functions which shouldn't be triggered on certain pages (e.g. field_view_field()),

Here is the responsible code which is thrown by Drupal core (file: common.inc):

 if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }

Debugging

If you don't recognise anything above, the easiest thing to debug that kind of error is by placing var_dump(debug_backtrace()); or dd(debug_backtrace()); (when Devel is on) before the actual throw new EntityMalformedException on the affected line in common.inc.

Note: Using dd() function from Devel will generate the debugging info to the file in your Drupal temp folder (temporary://drupal_debug.txt) with backtrace dump, otherwise could be too big and difficult to read when dumping on the screen. When using var_dump(), it's easier to call die(); after the call and check the dump in the view-source mode of the page.

If this is happening on node save, check this EntityMalformedException post at SO for more detailed instructions.

See also the following Drupal issue: #1778572 for more ideas.


Setting up a Drupal environment on Ubuntu After a few years of setting basic Drupal environments on Windows only, with WAMP (both the installment and the WAMP program) and Drush 7.0.0, I came to the conclusion I also need to work with LAMP and especially Ubuntu-based as it would give me access to more development tools, and more easily, for example in relation to tar, tar.gz, curl (non-core UNIX command), Composer, Drush master (which as of 2015 is not recommended for Windows usage) Xdebug, and more.

I have installed Ubuntu on a virtual machine, but what do I do now? Of course there is no WAMP (Windows, AMP) on Linux, and my options seem to be manual installation of the server \ Linux-XAMPP... But besides that, my question is what are the main differences between a Windows Drupal environment to a Linux one, in these points:

Is there something else needed for a Drupal (8) environment besides the things I mentioned?
In Windows, my WAMP folder was in c:\WAMP\ --- What is the drupal folder hierarchy in Linux?

Please answer on these points and detail as much as you can on the process, for newcomers like me could have a nicer acquaintance.

So, Ubuntu doesn't come with LAMP out of the box but it's super easy to set up with sudo apt-get ubuntu command. The basics of setting up a lamp environment are beyond the scope on an answer here, but there are plenty of tutorials on how to do it and robust community of Ubuntu users for questions.

Based on what you're describing, I would recommend using ubuntu desktop rather than server on your VM. This will give you a GUI interface which will be a little more familiar than trying to run Unix commands through your terminal on the VM, which will require further setup of your windows box.

Once you've set your VM up the basics you will need are: Mysql (or your db of choice), php, and Apache (or your web server of choice). You can download and install all of these free, but you'll do most of this from the command I mentioned above, so I would school up if you're not comfortable Ubuntu LAMP set up. There are many tutorials on how to turn Ubuntu into a wed dev machine, pick and choose what you find useful.

You'll have to set up the Mysql server and most of the programs manually before you have a set up you can install drupal on.

To answer your two questions:

No, you don't need any tools that you didn't mention, although depending on your set up and being new to Unix environments I would look into GUI tools like Mysql workbench.
Ubuntu Desktop and Server have a designated html folder it will be in
 /var/www/html

Where it gets tricky for someone who isn't familiar with the environment is that you need to configure your folder and file permissions  for the /var/www/html folder. It has to be owned and readable to the apache or your webserver user.

This here is a good tutorial, it will get you where you need to go once you have a working LAMP server on your dev machine.Ubuntu Drupal

So, from here you have to ssh into your virtual machine or use the GUI interface to set your drupal install. This is the same as on windows:

Get a copy of Drupal Core in your web root folder.
create a drupal database, database user
point your site to the db with settings.php in your sites folder.
Run the install.php script in your web browser.
drupal and profit.

You mentioned using a lot of Drupal dev tools. You'll have to configure those yourself, but you'll have to either do it on the VM (and work natively on VM) or configure your windows drush to connect to your VM like you would a remote server. This is all good practice but, beyond the scope of a single post.


Session breaks Entity API Whenever I try to use $_SESSION or variable_set it breaks the Entity API. It says

  "Fatal error: Call to undefined function entity_get_info() in
  mydrupal\sites\all\modules\entity\includes\entity.inc on line 55"

And then I have to reinstall the entire website because this fatal error shows up on every page. So I can't even access any of the adminscreens or anything to uninstall the modules or anything.

Does anybody here know if this is just a bug or am I doing something wrong? I was just filling the session with an entity.

Variables are serialised (as are session writes as I understand it), and complex objects like entity API entities don't serialise well.

The better solution would be to store the entity type and ID in the session, then load it when reading:

$_SESSION['saved_entity'] = array('type' => 'node', 'id' => 1);

...

$saved_entity = entity_load($_SESSION['saved_entity']['type'], array($_SESSION['saved_entity']['id']));

And do the same thing for the variables.


View file when node is viewed Lets say I have a node type that has a file field(docx,pdf etc). Is there a way to get drupal to show the file directly on node view instead of having the user to navigate to the node and then click on the file to view it?

The PDF Reader module sounds like what you're looking for.


Caching results from an API via drupal_http_request I need to frequently access a restful API via drupal_http_request. I am doing this in a custom View. Is there anyway to cache this data so that I don't need to as frequently query the servers?

You could use the Drupal's cache API to store the response doing something like:

if (!cache_get('my_module_cache')) {
  $data = drupal_http_request($url, $options); // Add the param for the request to web service
  cache_set('my_module_cache', $data, 'cache',  REQUEST_TIME  + (3600 * 24 * 30 * 6)); // Stores in cache table and expires after 6 months
  return($data);
} else {
  $return = cache_get('my_module_cache');
  return($return->data);
}

Depending on how many times you need to get that cached value on same execution, you could also use drupal_static().

On the example that I provided above, the expire policy is only based on time (6 months), in your case, you will need to analyse carefully the expire policy you are going to implement to expire/renew the cached value.

Lullabot has a great article about Drupal cache: A beginner's guide to caching data


"This is a debugging block" on Permissions page On my dev site, everything is working fine EXCEPT the permissions pages.  This includes /admin/people/permissions and the permissions pages for individual modules (example: /admin/people/permissions#module-advanced_forum).

I have the Faster Permissions module installed, and this module gives a list of all the modules installed with links directly to their individual permissions. This page is working fine.

All of these pages are working fine in my production site, so there is something about my dev site that is causing this error. Has this happened to anyone before? What could be the problem?

FYI, debugging blocks have been turned off in settings.

If you are using the Omega theme debugging blocks are always visible to uid=1. Check out this issue.


Easy PHP, Radioactivity module: Read out a node's current energy? Sorry, this is a super stupid problem but I'm new to PHP and failed at solving it myself.

On my node I have an energy field (Radioactivity module) and a computed field. The computed field is supposed to read out the node's current energy, plug it into a function and return another value.

I have tried all of

float( $entity->field_energy ),

float( $entity->field_energy[0]['value'] ), and

float( array_pop(array_pop(field_get_items($entity_type, $entity, 'field_energy'))) )

to read out the node's current energy, but everythings gives me an error. When I replace the above with a static number everything works fine.

Can anyone tell me how to read out the energy? I don't even know what data type is used to store the energy.

(I couldn't add a radioactivity tag. Unfortunately I don't have enough reputation points for doing so.)

My guess is that it is something like

float($entity->field_energy['und'][0]['value']);

Also, you can do

print_r ($entity->field_energy);

to see what is contained in object.

also, it may be contained in node object so maybe it is

float($node->field_energy['und'][0]['value']);

My blind guess but it may help you :)


Why creating the front page doesn't work? I created the file named page--front.tpl.php, which is empty, in the Garland theme and set the front end to it. I still can access the front page: why?

Have you cleared the cache after you added the new template file in the theme directory? You should always clear the cache, once you change a template file for a theme already installed, or you add a new file that was not used before.


Multiple fields that are generated dynamically in forms In a particular section of my form, some of fields are iterated over n number of times whenever we click add button n times.

I want to add below details of each student by click add button and remove the details by remove button.

Help would be greatly appreciated :)
Drupal version  is 8.

  $form['reg']= array(
          '#type' => 'textfield',
          '#title' => 'Registration Number',
          '#validated' => TRUE,
      );
 $form['fname']= array(
          '#type' => 'textfield',
          '#title' => 'First Name',
          '#validated' => TRUE,
 );
  $form['lname']= array(
          '#type' => 'textfield',
          '#title' => 'last Name',
          '#validated' => TRUE,
  );
 $form['email'] = array(
       '#type' => 'textfield',
       '#title' => 'Email',
       '#validated' => TRUE
 );

You can use session to store your data like:

$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->set('counter', $session->get('counter',0) + 1);
$counter =$session->get('counter');

$form['counter'] = array(
   '#type' => 'hidden',
   '#value' => $counter
);

Tuto : http://www.drupal8.ovh/en/tutoriels/25/save-user-temporary-data-on-session


problem with $conf['i18n_variables'] i have installed i18n module and added this lines to setting.php and empty cache to translate slogan and contact form information and  ...
but it doesnt affect site and values dont add to i18n_variable table.

$conf['i18n_variables'] = array(
        'site_name',
        'site_slogan',
        'site_mission',
        'site_footer',
        'anonymous',
        'user_registration_help',
        'user_mail_welcome_subject',
        'user_mail_welcome_body',
        'user_mail_approval_subject',
        'user_mail_approval_body',
        'user_mail_pass_subject',
        'user_mail_pass_body',
        'contact_form_information'
    );

do you have any suggestion to solve this problem?

You need to actually go to the page in the admin that updates the variable and edit it from the non-default language url.

For example, with site name, if you have one other language with 'es' as a path prefix you would go to 'http://example.com/es/admin/settings/site-information' and change the site name. Once you do that in another language it will create the variable in the i18n_variable table.

You will know you are on the right track when the element you want to update in the admin says "This is a multilingual variable"


How to Disable Whole Form from hook_form_alter? I've got a form I want to be disabled when certain criteria are met. According to the Form API I thought $form['#access'] = FALSE; would be sufficient. But no dice.

Instead, I'm doing this, which feels wrong, plus I get an error, "Warning: implode(): Invalid arguments passed in form_builder()"

foreach($form as $key => $element){
          unset($form[$key]);
}
$form['#prefix'] = 'Bad user. Don\'t access this form!';

Kind of a big stick approach. What's the right way to do this?

Drupal doesn't cope with the form being removed in such a way because it is expecting certain things in the form array after you have altered it.

That's why you are getting that error, because form_builder() does this:

if (!isset($element['#id'])) {
  $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
}

but you have removed $element['#parents'] when you looped through unsetting everything, including #parents.

If you want to loop through all form elements are remove them the correct way would be to use element_children(), which will loop through the keys of child elements but skip properties of the current element.

So to loop though child elements you would do this:

// Remove all elements from this form.
foreach (element_children($form) as $key) {
  unset($form[$key]);
}

Alternatively you could restrict access like this, which could cause you less side effects if other modules are expecting form elements that you have deleted.

// Restrict access to all elements in this form.
foreach (element_children($form) as $key) {
  $form[$key]['#access'] = FALSE;
}

If the form is a page though, not in a block or something, then it might be better to use hook_menu_alter() to block it as Shawn said in his answer.


Do some tasks after a simplenews newsletter has been sent I need to unsubscribe users from a specific simplenews newsletter category after a newsletter of that category has been sent. The best way is to do this action after updating sent status of newsletter. but there are not a hook or event to do this. What is your opinion to implement this task?

The best way would be patch simplenews to offer more events.

Second best would be to override simplenews via a custom module to offer more events.

There are other options but those are the best following the Drupal way.


Replace existing content type with feature Once upon a time a made a terrible mistake on one of the test sites by not enabling feature module but cloning database along with content types data from my local dev machine (drush sql-sync @local @test). This test site went live with feature disabled, but content type exists and has content.

Is it somehow possible to enable this feature at this stage to override existing content type and keep it's content?

Yes, it is possible to enable the feature. Enabling the custom feature module does not change anything on the site. The feature will have a different state depending on if the code in the feature module differs from what is stored in the database. A quick way to check the state of your features is the drush command:

drush fl

If your custom feature's components are simply the content type, and assuming field_base and field_instance components, then enabling the feature will tell you if they are either:

Overridden: the components (content type settings, field settings) are different in the database and the custom feature code.
Default: the components in the custom feature code are the same as the settings in the database.

If your custom feature is "Overridden" you have two options:

Update: drush fu featurename - Updating your feature will update the custom feature code with the settings that are stored in the database.
Revert: drush fr featurename - Reverting your feature will restore the feature's component's settings in the database to what is stored in the custom feature module's code.

So, either way, this shouldn't affect your node content. Unless you revert your feature components thus affecting the content type or field settings.

See the drupal.org documentation for more on using features & drush: https://www.drupal.org/node/960926


How to embed edit user profile page in a panel I am trying to embed the edit user profile page (ie what appears at the url domain.com/user/27/edit) into a panel. I have searched high and low on how to do this but I can't find any info on it. Is it possible to do this? There reason why I am asking is that I want to clean up the user's profile page so that it looks more professional and is easier to use.

Can anyone point me in the right direction on how to accomplish this?

Thanks

You need 1 context and 1 relationship to get the Form pane

Context: User => current user

Relationship:  User category edit form from user (default?)

and THEN you get the "Forms" category with "General form pane" under it


Is there a Drupal API function to get the list of nodes by type? Is there a Drupal API function like node_load() that will return a list of nodes by a given type?

I've tried $nodes = node_load(array("type" => 'student_vote')), but it only returns one node.

I know I could code up something like node_load(), but I wanted to see if there might be anything like that out there already.

Depending on the version of Drupal :

drupal 6:

$nodes = db_query('SELECT nid FROM {node} WHERE type="%s"', $type);

drupal 7:

$nodes = node_load_multiple(array(), array('type' => $type));

drupal 8:

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'NODETYPE')
  ->execute();
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($nids);


Link menu item to an element ID on the same page I want to link my menu items not to a page, but to a specific ID of a div tag on the same page, so if anyone click on it would go to the div section. basically its because I want to make a list of some items in my page.

I appreciate any guidance, thanks.

well I just figured that out, I can simply link it like: node/515#node-2 so it wont refresh the page and goes straight to the div.

node/515 (same page that my menu are in), but the thing is it doesnt work with url alias so better stick to the classic node url's


Commerce : adding optional insurance block to shopping cart form : ajax callback Customers will be purposed an optional insurance in the shopping cart, calculated as a percentage of Cart Total. I added this feature as an editable field in a footer view of the shopping cart, and I'm trying to setup ajax callback to update the cart.

EDIT (@people who already read the question) : I solved the initial bugs, so this is a clean update. You can jump to item 7 if you don't want to read the full implementation...

What I've done so far :

Created an insurance taxonomy, each term is an insurance option with a % decimal fields (in order to allow insurance options changes at any time).
Added this taxonomy to the order fields with a term reference field "Insurance" .
Created a very simple view block called cart_field_assurances with that Insurance field, with editable format.
Installed Cart View Override, cloned shoppping cart form and set that clone as shopping cart
Created a views-view--commerce-cart-form-assurances.tpl.php template with :

print $rows;
print views_embed_view('cart_field_assurances', 'block');

Moved insurance view before #edit-actions div with Jquery

var insurance = $('.view-id-cart_field_assurances').detach();
insurance.prependTo('#edit-actions');

Removed action buttons, added ajax to the field, declared insurance price component

function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  $ajax = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = $ajax;
  //Hide buttons
  $form['field_order_assurances'][0]['actions']['submit']['#attributes']['class'] = array('hidden');
  $form['actions']['#attributes']['class'] = array('hidden');
}

//ajax callback
function vts_insurance_cart_refresh(&$form, &$form_state) {
  //Load the order
  $view = $form_state['build_info']['args'][0];
  $order_id = $view->result[0]->order_id;
  $order =  commerce_order_load($order_id);
  //set new value
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
}

//insurance price component
function vts_insurance_commerce_price_component_type_info() {
  return array(
    'insurance' => array(
      'title' => t('Insurances'),
      'display_title' => t('Insurances'),
      'weight' => -10,
    ),
  );
}

Set up a rule : Before saving a commerce order, calculate the insurance amount and add it to total as an Insurances price component

To illustrate, this is the shopping cart form, with the optional insurance field below

The question

How to refresh the display of "Cart Commerce Order total" shopping form view (and its price components of course) in vts_insurance_cart_refresh ajax callback ?

To implement an optional insurance field in the shopping cart : first, follow question steps 1 to 6.

For a nice ajax replacement, create a very simple Order total view with a Global: Custom text field (which we'll hide with a css class, just to have the minimum :one field) and put Commerce Order: Order total field in footer.

Then alter the form and setup the ajax callback :

function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  //add ajax to our field
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  //unset unused buttons
  unset($form['field_order_assurances'][0]['actions']['submit']);
  unset($form['actions']);
}

function vts_insurance_cart_refresh(&$form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);

  //set the order insurance field value & save it
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
  commerce_cart_order_refresh($order);

  //Display a message to customer
  $term = taxonomy_term_load($order->field_order_assurances['und'][0]['tid']);
  dsm(t('Insurance : you selected ').$term->name);
  $commands[] = ajax_command_replace('.messages.status', theme('status_messages'));

  //Refresh the cart total display
  $cart_total = commerce_embed_view('shopping_cart_total', 'block', array($order->order_id));
  $commands[] = ajax_command_replace('.view-shopping-cart-total', $cart_total);

  return array('#type' => 'ajax', '#commands' => $commands);
}

In the module js file, play with your DOM elements to display them as wished

(function ($) {

  $(document).ready(function(){
    //A wrapper for the first shopping cart total refresh
    $('.commerce-order-handler-area-order-total').wrap('

');
    //Move the editable field above buttons
    var assurances = $('.view-id-cart_field_assurances').detach();
    $('.view-shopping-cart-total').before(assurances);
    //A wrapper for ajax messages
    var insurance_message = $("

");
    insurance_message.appendTo(assurances).hide();
  });

})(jQuery);

A rule setting up a Fee price component, depending on the insurance field percentage value.

{ "rules_calcul_des_assurances" : {
    "LABEL" : "Calcul des assurances",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "commerce", "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "entity_exists" : {
          "type" : "commerce_order",
          "property" : "order_id",
          "value" : [ "commerce-order:order-id" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_order_assurances" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
            "op" : "*",
            "input_2" : [ "commerce-order:field-order-assurances:field-pourcentage" ]
          },
          "PROVIDE" : { "result" : { "assurance_cout" : "Co\u00fbt de l\u0027assurance" } }
        }
      },
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "assurances",
          "amount" : [ "assurance-cout" ],
          "currency_code" : "EUR"
        }
      }
    ]
  }
}

With such implementation, it is possible to add any kind of field in the shopping cart footer, allowing customers to choose options that will change the order total adding a price component, with Ajax feature. Nice.


The fieldset isn't shown as collapsed I am writing a module that executes some queries, and returns the result in to a collapsed fieldset which is not shown as collapsed; I view its content. The collapse.js files are loaded.

This is the code I am using.

$body = $body . '<fieldset class="collapsible collapsed">' .
  '<legend class="gestioneinterna">Viste aggiuntive</legend>' .
  '<description class="description">fieldset extra.</description>' .
  '

Vista progetti

';
print $body;

You're missing a closing </fieldset> tag which probably won't be helping things, but I wouldn't advise doing it the way you currently are anyway.

A better way would be to make use of the theme_fieldset() function like so:

// Make sure the collapsible library is loaded
drupal_add_library('system', 'drupal.collapse');

// Build up the fieldset
$fieldset = array(
  '#theme' => 'fieldset',
  '#title' => 'Viste aggiuntive',
  '#attributes' => array('class' => array('collapsible', 'collapsed')),
  '#description' => 'fieldset extra.',
  '#children' => '

Vista progetti

</fieldset>'
);

// Add it to the body
$body .= render($fieldset);

That works great for me.

You might want to replace the call to render() above with drupal_render() as it offers a minute performance increase; I tend to use render() for all my calls for this sort of thing for continuity, and so that I don't have to check the type of the data being passed.

In this case, as you know the argument is not a string, you could save yourself the few microseconds and use drupal_render() instead.


How to change menu links items title programitically? I have created a menu name My Menu (machine name: my_menu ) with menu item My Nodes and My messages. Now I want alter My nodes and My messages link title. So the menu items should look like Nodes and Messages instead of My nodes and My Messages.

So I don't understand and also didn't find how can I alter the menu link title programmatically. i am trying to use hook_menu_alter(&$items) and hook_menu_link_alter(&$item), but it doesn't give any result.

So can anyone please tell me how can I alter the menu link items title?

Thanks in advance

Use theme_link function for altering your link markup. I have recently come across a scenario where I needed to change my account name to user name I did with the following code.

function THEMENAME_link($variables) {
  if ($variables['text'] == "My account") {
    $variables['text'] = $GLOBALS['user']->name;
  }

return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}


Creating section with static image and text with dynamic link I want to create a section with a static image and text but with a dynamic link and place it in one content type in Drupal 8. What would be the best way to approach this? Every approach seems to have some problem.

If I try using views to make a block and use the default values to populate the static content, the default value of the text field is not shown while default image and dynamic link are displayed.

Another approach I tried is to create a custom block, override its template with static images and text but getting the dynamic links to this block is a problem as I don't know how to access the current node fields in such block.

Is there any way to make the default value of a text field that we create in our content type to be printed through a view? Or in the alternative how would I access the node fields (specifically a link field) in a custom block?

Also, any other approach will be appreciated. I have no experience of working with the .theme file and don't really know the ins and outs of that.

Found a way around - To use it as a view with some static content, create a label for a field in the view and style in template file.


Confirm module uninstall I have written a module that creates a node type and I want to put in a warning on uninstall that lets the user know that the nodes created under that node type will be deleted if they continue to uninstall the module.

Now someone suggested that I use the confirm_form function. But I don't see how this would work or even apply in this case since it has to integrate with the hook_uninstall function for the module.

Any thoughts on this? Thanks!

EDIT: This module is written in Drupal 6 with a Drupal 7 version coming once this one has been approved by the Drupal community (my first community posted module, so I am not yet sure how to create the separate version branches yet).

In Drupal 6 you can alter the system modules uninstall form.

function MYMODULE_form_system_modules_uninstall_alter(&$form, &$form_state) {
  if (isset($form['modules']['MYMODULE'])) {
    //alter form how you would like
  }
}

The only change for Drupal 7 is there is an additional function argument

6       hook_form_FORM_ID_alter(&$form, &$form_state)
7 – 8   hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

NOTE: This form gets call on the /admin/module/uninstall & /admin/module/uninstall/confirm.   If you just want it on one then add an additional case to the if statment, checking the path.


Cannot format date for date field in a Views_Database_Connector view I am using the Views Database Connector module in drupal 8 to display the data from an external mssql database.  I am running into issues with the date field.  When I am asked to configure this field in the view, I am asked to choose a format for the date.  However, when I go to view the page, I get this error (and stacktrace):

InvalidArgumentException: The timestamp must be numeric. in Drupal\Component\Datetime\DateTimePlus::createFromTimestamp() (line 172 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\Core\Datetime\DateFormatter->format('2009-03-02', 'html_year', '', 'UTC', 'en') (Line: 323)

format_date('2009-03-02', 'html_year', '', NULL) (Line: 177)

Drupal\views\Plugin\views\field\Date->render(Object) (Line: 1144)
Drupal\views\Plugin\views\field\FieldPluginBase->advancedRender(Object) (Line: 224)
template_preprocess_views_view_field(Array, 'views_view_field', Array) (Line: 287)
Drupal\Core\Theme\ThemeManager->render('views_view_field', Array) (Line: 435)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)

I have not been able to figure out how to get the date to be converted to a timestamp so it can be formatted.  I have tried a preprocessor but the template_preprocess_view_view_field always occurs first and the exception occurs before it gets to my preprocess function.  Is there something particular about the date data type in mssql?  Any suggestions how to get the date to not generate the exception?

Took me a while but I figured out what I needed to do - create a custom module with a plugin to override the Date.php plugin (which actually overrides the FieldPluginBase.php).  Using the LastTimestamp.php plugin (which overrides the Date.php) from drupal's core comment module as a reference, I was able to piece together what I needed to do.

First step is when reading in the data from the tables (via the Views_Database_Connector module), I gave the drupal date field a different id rather than the default 'date' (eg "date_to_display").  This is the id used to trigger the call to the custom plugin rather than the Date.php plugin.  While the VDC was the first step, actually giving the date field a different id was the final piece of the puzzle to make this work.

Next step was to create the custom module and then create the plugin to override Date.php and use the id in the annotation (this is important):  @ViewsField("date_to_display").  You can read about this in Drupal's doc Annotations-Based Plugins in Views.  In the custom plugin, override the render function.  In my particular case, I simply just checked to see if the date field value was numeric (which seems to be required for this to not throw an exception), and if not, convert it to timestamp (new value = strtotime(value)).  For me that did the trick. The top part of the created plugin looks like this:

<?php

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\Date;
use Drupal\views\ResultRow;

/**
 * A handler to provide proper displays for dates.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("date_to_display")
 */
    class ViewsDateField extends Date {

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {


Content, terms and user/author import or migration to D8 without custom module How can I only import or simply migrate content (nodes), related terms and users/content-authors from a D7 project into a better structured D8 installation, which is similar to the old project, but meant as a project upgrade replacement, but with changes regarding how things work in D8 and which require to import the data only, apart from the code/modules of the old project?

The D8 installation is already prepared to reflect the old project with the same fields, menus, etc, but it uses different solutions for relationchips than its D7 predecessor. I would love to import content, comments, terms and users seperately (for example as CSV) and with key-ids helping to rebuild their relationchips. But ...

TBH, the migration docs I read over the last days made me even more confused than being helpful since many little in between parts and steps are not further explained so that I can not hook into and alternate the steps for my needs.

All I already know is, that Feeds and Feeds import isn't ready yet and that migrating is rather complex and is made for not only importing content but for whole project structures? But how if so many modules have no D8 version or working upgrade path?

What I read so far is:
https://www.drupal.org/docs/8/modules/migrate-source-csv/using-the-migrate-source-csv-plugin

which maybe comes close to what I maybe need for my issue. But I have a hard time to understand parts of it. So I see a use example with

 migration_groups:
  - ACME import

in it but without explanation if this line is required and what it is about. Googling for migration groups confuse me even more.

Is migrate_plus with migrate-source-csv the right direction for my purpose and is somebody out there who can help about the terminology of the migration docs and what parts are important to understand?

I have successfully migrated D7 content into a D8 site with similar content types using this small drush extension for D8 along with the built-in D8 Upgrade option:
https://www.drupal.org/project/migrate_upgrade

I believe the upgrade process from D7 or D6 is now apart of D8.3+ in the Admin UI and can simply be enabled after drupal 8 installation under the Module listing. Alternatively, you can use Drush via the module above.

Your D8 project just need localhost access to your old site files (such as images,pdfs, etc ... your old Files directory in Drupal 7/6) and database connection access.

It's a rather painless process for simple websites.

Please review the official documentation on performing a drupal 8 upgrade migration


How do I print a menu with links generated by my custom module? If I use

theme('links', array('links' => menu_navigation_links('main-menu'),
'attributes' => array('class'=> array('links', 'main-menu')) ));

It will print the links in my Main Menu. I need to print the links that are created by my custom module, but I do not know what the system menu name is.

For instance:

 //hook_menu
 function custom_menu() {

     //admin page
     $items['admin/custom'] = array(
     'title' => t('Custom Admin Page'),
     'description' => t('Manage Custom Module'),
     'page callback' => 'custom_admin_page',
     'access arguments' => array('access toolbar'),
     'type' => MENU_NORMAL_ITEM,
     );

     //add event
     $items['admin/custom/add'] = array(
     'title' => t('Add Custom'),
     'decription' => t('Add custom'),
     'page callback' => 'custom_add',
     'access arguments' => array('add custom'),
     'type' => MENU_NORMAL_ITEM,
     'file' => 'custom_add.inc',
     'file path' => drupal_get_path('module', 'custom') . '/includes',
     );

The page 'admin/custom' automatically goes into my administration menu, and the page 'admin/custom/add' is seen under the admin/custom link when viewing all of the links in the administration menu, but I want to print that menu (admin/custom) on the 'admin/custom' page so that I can see the link 'admin/custom/add'.

Menus and paths are slightly different things...in hook_menu() you're defining paths that can be consumed; menus create the links to those paths - the two concepts aren't necessarily related (a path can exist without a menu link).

You can assign a particular router path to a menu using the menu_name property in your hook_menu() items, but that menu needs to exist already.

Fortunately Drupal provides a method for adding links to the top of a page through hook_menu(), and you only need to change one line:

$items['admin/custom/add'] = array(
  'title' => t('Add Custom'),
  'decription' => t('Add custom'),
  'page callback' => 'custom_add',
  'access arguments' => array('add custom'),
  'type' => MENU_LOCAL_ACTION, // <-- This one changed
  'file' => 'custom_add.inc',
  'file path' => drupal_get_path('module', 'custom') . '/includes',
);

That will put a link to 'Add Custom' at the top of the 'admin/custom' page; if you're using the Seven theme for administration it'll look like the 'Add Content' link on the content admin page:


What does check_markup() actually do? The following code:

var_dump(check_markup('This is a test', 'plain_text'));

outputs:

string(22) "
This is a test
"

Why does it do this?

check_markup() will:

  Run all the enabled filters on a piece of text.

Since one of those filters will probably be the HTML corrector, you'll get the

 tags wrapping your text string.


Getting error 'Redirects to external URLs are not allowed by default' Getting the error after created this .htacces in root folder.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/web
RewriteRule ^(.*)$ /web/

I want to redirect visitors to /web folder. I can login as Admin and enable modules, install themes and create content without any issues.

When a theme is installed, content created and publish it I get a blankpage with:

"Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it."

I have trusted hostsettings configured like this in settings.php

$settings['trusted_host_patterns'] = array(
  '^my-domain\.com$',
  '^my-domain\.com\.web$',
  '^.+\.my-domain\.com$',
  '^.+\.my-domain\.com\.web$',

according to this issue uncomment RewriteBase / didn't work out either

Hope someone has a solution to this.

If you still haven't figured this out, check this comment on d.o: https://www.drupal.org/project/drupal/issues/2612160#comment-11767977

It suggests a workaround by removing the subdir from the script name, adding to settings.php the following:

if (isset($GLOBALS['request']) and
'/subdirectory/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}


How do I clear settings from the Drupal object? I have a module, which renders an AJAX form, which passes data to a script via drupal_add_js and stores it in the settings property of the Drupal object. My problem is that I cannot seem to remove old data from the object (a user can toggle options on the form and send new datasets to the javascript). Logically, I thought passing an empty array would clear the values, but it doesn't.

// Clear old data from settings.
$js = array(
  'd3' => array(
    'inventory' => array(
      'chart' => array(
        'dataset' => array(),
      ),
    ),
  ),
);
drupal_add_js($js, 'setting');

I need something like drupal_remove_js($js, 'setting')? or a method for removing object properties?

drupal_add_js adds javascript to the page <head>, so as far as I know you can't change that anymore with AJAX. Thus placing it in an AJAX callback doesn't work. You need to solve this at Javascript level in the the browser.

You'll have to make sure all data for all options is sent to the client during rendering and then use simple jQuery selectors to enter the correct part of data into the visualizer.


Where are logs created by drush_log() stored? I have installed Devel module to use xhprof. In devel settings, I have enabled xhprof, but when I load a page, can't see a link to xhprof. I read the source and found this:

drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'notice');

Where is this log stored and how can I see it?

It's not. It's printed.

However, notices are by default not visible unless you increase the verbosity of drush using the -v option.

To display internal messages you'll need to enable debug option -d. This will display even more information.

Alternatively, you can change the message type parameter from 'notice' to 'ok' to print out to the console.

drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'ok');


Making user profiles publicly accessible in Drupal 7 How can I make user profiles publicly available to anonymous users and search engine bots accessing my website?

Details: User profiles are not publicly accessible by default. Without being logged in to Drupal, if you try to access /user/123 for example, you get the You are not authorized to access this page error message. I want to display the user profile details instead.

Simply go to /admin/people/permissions, scroll to the bottom of the page and turn on all check boxes for the View user profiles permission.


Safely enter PHP code in block to prevent site crash? When I enter a php snippet into a block (or story or page), it can crash the site.

Two questions:
1) How can the chances of this be reduced? For example, I just crashed a fresh installation because a function name was not recognized. Would placing the code in a try/catch block been likely to prevent that crash?
2) If/when I do crash the site due to malformed php code, how can I recover the site?

The usual way to avoid problems with your production site is to try out everything first on a dev or staging site, and then push it to production after it is tested.  There are two main problems with php in blocks: one is that block data is stored in the database.  If you push the database from dev to production, you will lose new content on your live site -- no good.  The solution to this problem is to use the features module to export your database configuration to your code files, which allows you to push your config-in-code from dev to live & then re-import on the live site.

The other problem with putting php in blocks, though, is that it opens up a security hole in your site, as anyone who has the right to configure blocks can now run code on your server.  This means that your site is one guessed password away from compromise at all times.  It is therefore better to write your blocks in code using a custom Drupal module rather than put php in the database.

If you do have a site with malformed code in a block, you can disable the block using the drush block-disable command from the drush_extras project.


Defining hook_menu() paths for specific base URLs I have a multi-site; each site has its own database but they all share the same codebase. I would like to know if there is a way to define hook_menu() paths at specific base URLs.

Being it a multisite, I have created a common module used by all the sites. I wanted something like this in hook_menu().

 if (base_url == 'wmc.en') {
   $items['wmc/contact-us'] = array('hook menu stuffs');
 }
 if (base_url == 'gmc.es') {
   $items['gmc/contact-us'] = array('hook menu stuffs');
 }

I tried this type of code, but hook_menu() doesn't seem to recognize base_url or $_SERVER['SERVER_NAME'].

Is it possible to achieve what I am trying to do?

If you want to use base url, you should first declare it as a global variable and then use it as $base_url. You should also note that $base_url will include the url scheme (i.e) http or https.

If you have a development or staging environment setup, your base url will probably differ between dev, stg and prod environments. In most of the cases, the production environment will be SSL enabled. So you may have to consider this as well while writing code.

In my opinion, as you have mentioned, you may use a different module and enable it only for the specific site. Or if you deliberately want it to be in a common module, consider using access arguments and define hook_permissions.


CDN Module and Canonical Domain I have a site where I am using the CDN module in origin pull mode with Amazon CloudFront.  Apache is configured so Drupal will handle www.example.com and static.example.com.

Is there a way to get Drupal to only use the static URL only for my static resources (images, CSS, JS, etc), and redirect other requests to www?  Is the only real way to implement a hook_page_build() and check the Content-Type header to see if it begins with "text/html", and potentially redirect then?

If by static resources you mean resources for which the content is served from the server, using the content of a file, then hook_page_build() is not invoked for such resources.
It's the server that handles those requests, and Drupal doesn't do anything. In that case, you could edit the .htaccess file to redirect the users to the right domain.

That is what I would do also in the case it's Drupal to produce the content. Rather than letting Drupal produce the output, and redirect the user to the correct sub-domain, where the output would be produced again, I would rather redirect the user once it is clear what type of resource is being requested, and which is the URL of the resource.


Programmatically created revision set as the main node instead of revision I am using D8 and creating revision for a node with the following code.

  $nid = "my_node_id";
  $node = \Drupal\node\Entity\Node::load($nid);
// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

When I create a revision, it is set as the main revision, instead of one of the revisions. Is it taking the revision timestamp when creating, and pushing latest to the top? Is there a function that tells me I am using the latest revision?

You're looking for \Drupal\Core\Entity\RevisionableInterface::isDefaultRevision(), set that to false if you want to save a revision that is not the default revision.


How to retrieve a query result in a computed field? I'm trying to run the following select in a computed field, but it doesn't work: any clue on what is going wrong ?

$nid = $node->nid;

$result = db_query('SELECT description FROM {taxonomy_term_data} AS ttd
                    LEFT JOIN {taxonomy_index} AS ti ON ti.tid = ttd.tid
                    WHERE ttd.vid = :vid AND ti.nid = :nid',
                  array(':vid' => 16, ':nid' => $nid));

$entity_field[0]['value'] = $result;

db_query() doesn't return a column, to do this you need to fetch it using fetchField():

$nid = $node->nid;

$result = db_query('SELECT description FROM {taxonomy_term_data} AS ttd
                    LEFT JOIN {taxonomy_index} AS ti ON ti.tid = ttd.tid
                    WHERE ttd.vid = :vid AND ti.nid = :nid',
                  array(':vid' => 16, ':nid' => $nid));

$entity_field[0]['value'] = $result->fetchField();


How can I call form function in html? I have requirement in that I want to show a dropdown values. So to achieve this I created a form function with select type and returning the form. I want to display it in a html page. Here is what I have tried:

function cart_confirmation_form($form, &$formstate){

  $opt = array('Hi','Bye');
  $form['dropdown'] = array(
    '#title' => 'somethinfg',
    '#type' => 'select',
    '#options' => $opt,
  );
  return $form;
}
   function testing(){
     $message .= '
' . cart_confirmation_form($form, $formstate) . '
';
      $message .= '
'.$form_message.'
';
    drupal_set_message('
' . $message . '
' );

}

This is not working, It says array to string conversion, form and formstate is undefined something like this. I know this is not correct way please suggest me the correct way to print values in dropdown.

Assuming testing() is a page callback, you want this:

function testing()
{
  $form = drupal_get_form('cart_confirmation_form')
  $output = '
' . render($form) . '
';

  return $output;
}

Though personally I'd built it as a render array:

function testing()
{
  $page = array
  (
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('cart_confirmation_form')
  );

  return $page;
}


Dynamically link /sites/default/css/css_***.css file for WordPress template header FYI, I don't know Drupal at all. What I've done is stick a WordPress install at /blog/ and pull in the /sites/default/css/css_randomstring.css and static html from the Drupal page - and along with the WordPress loop in the index.php file of Wordpress - somewhat integrate WordPress into Drupal. (I don't want to use the Drupal WP module).

The problem is that the Drupal CSS link changes when there are small edits from time to time on the Drupal end. (The php/html of the Drupal site isn't slated to change.)

Question: are these randomstring CSS files a cache or the active CSS file? How can I dynamically pull in the sites/default/css/css_(randomstring).css file when the string changes? Or is there a different CSS file I should be linking to?

To answer your direct question, drupal's CSS and JS aggregation contains a random MD5 hash to guarantee uniqueness, and also to guarantee that there is no programmatic way to work this out.

In order to include CSS and JS from an aggregated site into another CMS there are a couple of options:

Use un-aggregated CSS and JS and link to the files direct (bad)
Compress the files yourself and host them in a known location - e.g. /css/main-compressed.css
Or another option is what we have used in the past where you basically make a really simple page.tpl.php which includes basically no content, and is for all intensive purposes a blank wrapper for your site. You have your other CMS drag this template down after every deployment, and then used it for it's page wrapper. This way you do not need to worry about the CSS and JS changing as you always have the most up to date versions in the <head> section.

Hope this helps


How to login-redirect users to their profile page on specific days only? By using Rules Once per Day module, logged in user would be redirected to profile page on specific day. My issue is, every time when user logged in to the site, the user is redirected to profile page.

But I want this rule to work on specific days, like Monday and Thursday. How I can handle this without Rules Once per Day module?

I want to this functionality works at only once. How can I do this?
Any suggestions?

You could do it simply by rules module (no extra module required):

Create a new rule.
Select event - user has logged in
Could add in a condition, check for a role for eg. This step is optional, and can be ignored if not required.
Select an action - Page redirect, and add the url /user to the destination.
Make sure you enable the rule.
Test, test, and test ;-)

If you want to schedule this view to run on a particular day you could check on Scheduling rules. There is also a very good video from nodeone about the same.


Extend Theme to Different Content I've installed a theme on my site, and can't figure for the life of me how to extend the theme to different content.

For example, comments are themed on the blog pages; however, when I add new content types with comments, the theme is not applied to these comments.

How do I get the theme to extend to the different content types?

Worked this one out after a bit of fiddling, so for others trying to figure it out too...

First find the template file you need to override - if it's part of a module, it might be in the module templates folder. Otherwise install Theme Developer - it will help you track down the template that's being used for that content https://www.drupal.org/project/devel_themer
Chances are you'll need to override that template with one from your theme - identify the template theme that you want to use (easiest done using Theme Developer on the page that is coming up how you want), then copy that template file from your theme templates folder ([theme].tpl.php) to your sub-theme templates folder
Rename the template file in your sub-theme templates folder the same as the one you want to override (as identified in step 1), and voila.
(optional) you might find a CSS file somewhere is still screwing up the way your content looks (in my case it was in the module css folder) - you can either tweak it with other tools like CSS Injector, or copy the offending CSS file into your sub-theme css folder and tweak it there.
If you are overriding CSS, you'll need to identify the CSS file in the sub-theme .info file (found in your sub-theme folder) - add the following line: stylesheets[all][] = css/filename.css  (where filename.css is the name of the tweaked CSS file) under the line stylesheets[all][] = css/custom.css


How to see the error messages when I get the white screen of death? How can I see the error messages when the site I am working on gets a white screen?

Put this at the bottom of settings.php:

error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);