Eliminate render-blocking JavaScript and CSS in above-the-fold content I am building a Drupal 7 site. These are some of the modules I use: Adaptivetheme (theme), Views and Content Panes, Panels, Mini panels, Panels everywhere, Page manager, Superfish for menus, Addthis, Chosen (drop down).

For improving my site performance and the dealing with the CSS and JS files I am using the Advagg module.

When running the Pagespeed test of Google I am getting the following error as "Should Fix":

  Eliminate render-blocking JavaScript and CSS in above-the-fold
  content Your page has 6 blocking script resources and 8 blocking CSS resources. This causes a delay in rendering your page.  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

This is the info Google supplies:

Remove render-blocking JavaScript
Optimize CSS Delivery

Is there a way I can change the settings of the Advagg module or Drupal core, and solve this issue?

Is there another way to achieve this goal?

Update - after implementing changes according to mikeytown2 answer I got the following message on the Pagespeed test of Google:

  Eliminate render-blocking JavaScript and CSS in above-the-fold content
  Your page has 6 blocking script resources and 4 blocking CSS resources. This causes a delay in rendering your page.
  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

The README has a guide on how to do this using current 7.x-2.31+ version of AdvAgg. Also see this wiki page on the High performance group. Most sites can achieve a perfect 100/100 score on https://developers.google.com/speed/pagespeed/insights/. Directions on how to achieve it for a fresh of install of AdvAgg below.

Be sure to check the site after every section to make sure the change didn't mess up your site. The changes under AdvAgg Modifier are usually the most problematic but they offer the biggest improvements.

Advanced CSS/JS Aggregation

Go to admin/config/development/performance/advagg

Select "Use recommended (optimized) settings"

AdvAgg Compress Javascript

Install AdvAgg Compress Javascript if not enabled and go to
admin/config/development/performance/advagg/js-compress

Select JSMin if available; otherwise select JSMin+
Select Strip everything (smallest files)
Click the batch compress link to process these files

AdvAgg Async Font Loader

Install AdvAgg Async Font Loader if not enabled and go to
admin/config/development/performance/advagg/font

Select Local file included in aggregate (version: X.X.X). If this option is not available follow the directions right below the options on how to install it.
Check "Use localStorage so the flash of unstyled text (FOUT) only happens once."
Check "Set a cookie so the flash of unstyled text (FOUT) only happens once."

AdvAgg Bundler

Install AdvAgg Bundler if not enabled and go to
admin/config/development/performance/advagg/bundler

HTTP/2.0 Settings

Under "Target Number Of CSS Bundles Per Page" select 25
Under "Target Number Of JS Bundles Per Page" select 25
Under "Grouping logic" select "File size"

HTTP/1.1 Settings (default)

Under "Target Number Of CSS Bundles Per Page" select 2
Under "Target Number Of JS Bundles Per Page" select 5
Under "Grouping logic" select "File size"

25 bundles vs 2 and 5 has to do with browser caching. More files equals a better chance of the browser having that combo in its cache, but more files means more connections being established and opened in HTTP 1.1. Use 2 for CSS as this number doesn't wait for any new connections; JS is 5 as most browsers have a concurrent connections limit of 6. This number for bundles was picked after many tests. In HTTP 2.0 there is one streaming connection and the penalty for multiple CSS and JS files is almost non existent; thus optimizing for the browser cache is the best choice; thus 25 should be used for CSS and JS when serving HTTP/2.0.

AdvAgg Relocate

Install AdvAgg Relocate if not enabled and go to
admin/config/development/performance/advagg/relocate

Select "Use recommended (optimized) settings"

AdvAgg Modifier

Install AdvAgg Modifier if not enabled and go to
admin/config/development/performance/advagg/mod

Select "Use recommended (optimized) settings"

Generating Critical CSS Files

Go to https://www.sitelocity.com/critical-path-css-generator and input as many landing pages as needed for critical css; the top 10 is usually a good start. If you have Google Analytics this will show you how to find your top landing pages https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries#top-landing-pages
or for Piwik https://piwik.org/faq/how-to/faq_160/. If you don't know what page to start with do your site's homepage. You can also us this to generate css https://chrome.google.com/webstore/detail/critical-style-snapshot/gkoeffcejdhhojognlonafnijfkcepob?hl=en

Example filenames and paths below are for the "bootstrap" theme; they all start with sites/all/themes/bootstrap/critical-css/; in your theme create the critical-css/ directory. The next directory is based on the user; anonymous/,  all/, or authenticated/ can be used.

The next directory can be urls/ or type/. Looking at urls/; front is a special case for the front page, all other paths use current_path() as the directory and filename with .css added to the end; See https://api.drupal.org/api/drupal/includes%21path.inc/function/current_path/7.x

Looking at type/ this is a special case for node types. Use the machine name and add .css to the end. Any node of this type will then have this critical css file applied and inlined. Below are some examples showing how this works.

valid example file locations for the "front" page:
sites/all/themes/bootstrap/critical-css/anonymous/urls/front.css

valid example file locations for "node/1" current_path() page:
sites/all/themes/bootstrap/critical-css/anonymous/urls/node/1.css

valid example file locations for the node type of "page":
sites/all/themes/bootstrap/critical-css/anonymous/type/page.css

If you want some sort of automated way to generate these css files fourkitchens
has an excellent article on how to set that up:
https://fourword.fourkitchens.com/article/use-grunt-and-advagg-inline-critical-css-drupal-7-theme


How to display multiple products under each category in a views grid? Currently I have a views with grid display that has the fields Content: Category and Content: Title, and a filter criteria of Content: type (is a product). This displays all my ubercart products with their associated category above them. So I have a result like:

Category 1: product x
Category 1: product y
Category 2: product z
Category 2: product t

What I want is to have each category only appear once with a few products listed below each category. Such as:

category 1:

product x
product y

category 2:

product z
product t

I tried giving the field Content: Category and multiple field setting where all values of the field will be shown in the same row but that did not work.

In you view page, click Settings under Format section next to Grid or whatever display type you use.
For Grouping field Nr.1 select Content: Category
Under Fields section, click on the field Content: Category
Check Exclude from display
Save. That's it.


Imagepicker doesn't appear as block I would like the Image Picker to be available on a node (page) as a block so that users can upload images without clicking on 'edit' where they can edit the actual page itself.

I have definitely enabled the setting in the configuration:

Do I need to do it via the Views module (which I do have installed also)?

U want a block for image picker, I have checked it and found that it creates iframe for the same. so what we can do, is create a block either programmatically or manually and alter its content, by using hook_block_view_alter, and load image picker in it, and hide rest of element in drupal 7.


How do I migrate an image attributes? I am migrating a Drupal 7 site to Drupal 8 using the Migrate API. So far, I have been able to do this without writing my own plugins.

How do I migrate additional information in an image field (e.g. the alt and title attributes)?

So far I have been using this, but it does not seem to work.

field_bild:
  plugin: iterator
  source: field_bild
  process:
    target_id:
      plugin: migration
      migration: d7_file
      source: fid
      alt: alt
      title: title

Here is the format I found working:

field_teaser_image/target_id:
  plugin: migration
  migration: attachment_image
  source: file_id
field_teaser_image/alt: file_alt


Allow .oft file extension How to allow media module to support .oft file extension?

Checked supported file extensions in includes/file.mimetypes.inc. It does not have oft extension listed. How can I add it without hacking core files?

To add mime types without hacking core files, you will want to create a new module and use the hook_file_mimetype_mappings_alter.
For example assuming you name your module oftmimetype then like this:

<?php
/**
 * Implements hook_file_mimetype_mapping_alter().
 */
function oftmimetype_file_mimetype_mapping_alter(&$mapping) {
  // Add support for oft.
  $mime_type = 'application/x-font-otf';
  // If the mime type does not already exist, add it.
  if (!in_array($mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $mime_type;
  }
  // Get the array index for that mime type and assign the extension to it.
  $mapping['extensions']['oft'] = array_search($mime_type, $mapping['mimetypes']);
  }
}
?>


Ckeditor: Add Cite tag I am using Drupal Ckeditor (The main one, not the WYSIWYG module).

I would like to add buttons to the interface for inserting <quote> and <cite> tags.

How can I do this?

It already has a blockquote, but I would like <quote> and <cite> as well.

Here is a good tutorial in Custom buttons on CKEditor or Adding CKEditor Plugins Manually in Drupal .
Before asking the question you should have let us know what you have done so far.

If you were checked the links, you would see that in the Adding CKEditor Plugins Manually in Drupal and Add Plugin Part of CKEditor Module section it explained where to put the plugin.


Is there an automated way to create another multisite inside of an existing multisite Drupal install? I have an existing instance of D7 in a multisite configuration on RedHat.

Can I use drush si to create a new database and /sites/ instance -- without altering any existing subsite? Is there a way to automate this?

I'm envious of Wordpress Networks' ability to spawn up a new site inside the admin console.

In my current process, I create a database on local systems.

mysql> create database nominations;
Query OK, 1 row affected (0.01 sec)

mysql> grant usage on nominations.* to nomnom@localhost identified by 'Sup3rS3cr3tP455w04d';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on nominations.* to nomnom@localhost;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

Sudo and edit the alias.conf file

$ sudo su
# vim /etc/httpd/conf.d/alias.conf

In that file add the alias. The current file reads as such. The idea is to point all aliases to the drupal root. Let drupal handle routing based on folder entries inside its /sites/ folder.

 Alias /nomination /var/www/html

Once this file is saved. Restart the server.

# service httpd restart

# exit

Now the database is created and apache has a new alias. Create a new folder inside of /sites/ in the fashion drupal routing will recognize (server.name.path). Create a symlink to make drush maintenance easier.

$ mkdir nomination
$ cp default/default.settings.php nomination/
$ cd nomination
$ mv default.settings.php settings.php

At this point I go to server.com/nomnination and run the typical install process. After and back on the command line, coordinate a bit of module goodness:

$ drush en -y coffee module_filter jquery_update bootstrap

$ drush dis -y overlay

If you configure multisite instances to use https://www.drupal.org/project/dslm, you can use a command like 'drush dslm-new mynewsite drupal-7.34' to provision a new site.  @btopro has taken DSLM a step further calling DSLM and Drush commands from the CIS install profile to completely automate the process from within Drupal for Penn State and the growing number of schools using ELMS.  This configuration allows schools to generate several new Drupal sites from different ELMS install profiles from a centralized Drupal site.  [This screencast][1] explains how the ELMS CIS implementation works.  There is also a vagrant version of this configuration you can spin up from https://github.com/btopro/elmsln-vagrant

CU Boulder also uses a Drupal front end to DSLM to spin up new sites, but we don't use a true multisite configuration and our backend for this service is more complicated
and CU specific leveraging Eve (http://python-eve.org) and F5 server
(https://f5.com/products/modules/global-traffic-manager).

I doubt either of these solutions is a good fit for you out of the box, but if the "automated way" you are only looking for only needs to automated this process at a commandline level, DSLM will get you most of what you need. You can also use code from the ELMS CIS project to create your own front end.

If you looking for a graphical front end that works "out of the box", you might want to consider using the Aegir Project (http://www.aegirproject.org/) with an install profiles like Hostmaster (https://www.drupal.org/project/hostmaster).  Installing Aegir on your own server can be complicated (http://community.aegirproject.org/installing/manual), but there are several hosted Aegir options.  Converting an existing site to Aegir is also more complicated than DSLM.  Aegir is really an
"all in decision" while DSLM can be used along side existing, non-DSLM sites and includes a command to convert an existing site to use the DSLM symlink structure.


The wrong site title is coming up for home page For some reason, the title of our website in browser windows and tabs is coming up as something else. We aren't even sure where this title came from, as it has nothing to do with our site.

I checked the page source to see what was showing up in the <title> tags, and sure enough, it's the same, incorrect title.

I tried changing the name of the site and the site's slogan, hoping that would help. I've cleared the caches. It's been going on for about 8 months, before we made some upgrades to core and modules.

Other page titles seem to be working correctly. There are no nodes with this title. We are using Drupal Commons. Drupal version 7.50.

Normally the <title> element is set in template_preprocess_html

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

That is then output in your theme html.tpl.php

You may have some code or configuration overriding the default title there in a module or theme.

I'd suggest searching through the codebase for the title text, or perhaps in a db dump file.

After that, you can either update it, or add some code for your own HTML <title> logic.


Print mailing address labels from a view We have a site built with Drupal Commerce and are looking for a way to print address labels from a view

So far I have been able to make a grid view of addresses and use the printer friendly version module to create a print view, but i can't seem to get the CSS right to line up the labels correctly.

I have seen this module for Drupal 6 - http://drupal.org/project/mailing_label, but nothing for Drupal 7. I was wondering if someone had any insight.

Thanks.

Our warehouse team needed the ability to print address labels on the Avery 5163 template for every Commerce Order that is set to the status as Pending

I consider this to be a jury rig more than a Drupalish answer, but it got us through just the same.

Here is how we did it.

We created a page with a table view that shows all orders that are pending.

We created a view of Commerce Profiles that showed only the customer addresses in a grid format.

We used the Printer, e-mail and PDF versions module to create printer friendly versions of the views Here is the module - http://drupal.org/project/print

We altered the print.css file in the modules folder so that the address labels lined up with the template. (Later we ended up adding print.css file in our theme to override the one in the module folder and protect it from updates – Here are the instructions on how to add a style sheet - http://drupal.org/node/171209)

We created an html button in the header of view of pending Commerce Orders. It linked to the print version of the address label view.  (you can add the word print before any relative url to get it’s print view)

We altered the browser settings of the guys at our warehouse to exclude all the extra information that comes when the browser prints – Here are some instructions – http://lifehacker.com/5603815/how-can-i-get-rid-of-the-url-and-other-text-when-i-print-from-web-pages

We also altered the margins in the browser.

We will be looking for a better solution as time and money for work permits , but I thought that someone else might find our experience helpful


Order confirmation email with html content? I'm using drupal commerce with its submodules and need to change order's confirmation message to html format and add line items and customer profile. How can I organize this?

Use Commerce Message. It's the best supported way to handle sending emails. It includes several message types out of the box.


Retrieving the product published field Within a node template I can retrieve the status of the published flag by calling the code: node.isPublished()

How do I retrieve the status of the published flag within a commerce product...

I've tried:

product.isPublished()
product.status
product.published

But I can't seem to get it to print. I've tried to look through the core code where status seems to be the key, but no luck, plus api.drupalcommerce.org is down.

Any advice?

Thanks in advance

{% if product_entity.status.value == 0 %}
  {%
    set classes = [
    'is-unpublished'
    ]
  %}
{% endif %}
<article{{ attributes.addClass(classes) }}>
..
</article>


Get node ID in a form submit I am struggling with how to get node id in my user_register_form_submit.
I need to get the node id of the node where my form is, let me explain :

I have created a tpl for my user register form in order to print it in nodes of a special content type, those nodes prepopulate my form and helps to create users, I need this node id to delete the node after submiting the form wich means delete the node after a user is created.

here is my hook :

    function hook_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'user_register_form'){
            $form['#submit'][] = 'user_register_form_submit';
        }
    }

    function user_register_form_submit($form, &$form_state) {
    // print the node id
    }

Last thing, I'm working with Drupal 7.
Thanks !

For Drupal 8 Add your custom submit handler in form alter:

$form['actions']['submit']['#submit'][] = '_custom_node_form_submit';

And add custom submit handler:

function _custom_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  echo $form_state->getValue('nid');
}


How can I override images on migration? I'm migrating images from URLs and I'm mapping the image field with this code:

$this->addFieldMapping('field_image', 'titlePhotos')
     ->xpath('/photo/@URL');
$this->addFieldMapping('field_image:source_dir')
     ->defaultValue(DRUPAL_ROOT . '/sites/default/files/images');
$this->addFieldMapping('field_image:file_class')
     ->defaultValue('MigrateFileUri');

I want to overwrite files if they already exit when running the migration for the first time and on update.

I'm using Drupal 7.

The MigrateFileUri destination has a class property which indicates what to do when collisions are encountered.

  /**
   * How to handle destination filename collisions.
   *
   * @var int
   */
  protected $fileReplace = FILE_EXISTS_RENAME;

What you want to do is, extend MigrateFileUri override $fileReplace to be FILE_EXISTS_REPLACE and then use that as your destination.

example:

class MigrateFileUriReplace extends MigrateFileUri {
  protected $fileReplace = FILE_EXISTS_REPLACE;
}

Don't forget to update your migration code.

$this->addFieldMapping('field_image:file_class')
     ->defaultValue('MigrateFileUriReplace');


Need to flush cache after node translation I have a Drupal 6 site running with multi language support. When I translate a node and get redirected to the newly translated node only the headline is visible. If I flush the cache using the administration tools I can see the rest of the node.

Why is this happening and I how do I prevent it? I feel like I have tried everything!
For example trying:

  drupal_flush_all_caches();
  cache_clear_all();
  cache_clear_all('*', 'cache', TRUE);
  cache_clear_all('*', 'cache_content', TRUE);
  cache_clear_all('*', 'cache_page', TRUE);
  cache_clear_all('*', 'cache_menu', TRUE);
  cache_clear_all('*', 'cache_filter', TRUE);
  cache_clear_all('*', 'cache_views', TRUE);
  cache_clear_all('*', 'cache_views_data', TRUE);
  cache_clear_all('*', 'cache_update', TRUE);
  cache_clear_all('*', 'cache_block', TRUE);
  cache_clear_all('*', 'cache_form', TRUE);

Using function mymodule_node_form_submit($form, &$form_state) and function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL). I have verified that both hooks works using Devel.

I have also tried looking into the cache tables to try and figure out which rows change when flushing the caching using the administration tools, but without luck.

UPDATE JULY 18:
Even if I turn off the cache I cannot see the translated node before I flush the cache. How is this even possible?

UPDATE JULY 18 PT2: I think I have found the problem. In the table cache_content a row called e.g. content:1269:1270 got the value(data) a:0:{}. If I delete this row the text appears. To me it seems that it does not cache the new translation correctly, and thus saving an empty cache which makes the translated node empty. But how do I solve this? Even with db_query('DELETE FROM cache_content'); in the submit hook the row gets created.

Thanks in advance.

Run the cache clear in a shutdown function. A little bit of a hack but it should work.

<?php
register_shutdown_function('cache_clear_all', 'content:' . $node->nid . ':', content_cache_tablename(), TRUE);
?>

Taken from content_delete()


When a link is clicked, a value is retrieved from the table and displayed on a Webform field I have created a basic page with two buttons, "Yes" and "No". When the "Yes" button is clicked, it is directed to the webform.

Aim: When the webform appears, it displays a value from the table into a field.

Database

Table name: Room
Field: Room
Data: Training Room

The Basic Page

The Webform

I created a module for this functionality:

test_presave.info

name = "Test presave"

description = "Retrieving data from table"

core = 7.x

package = Test

test_presave.module

/*

*Implements hook_node_presave()

*/

function test_presave_node_presave($node)

{

    $accessnode=$node->nid;

    if($accessnode==20)//Lettable Room Booking webform

    {

        $result=$db_query("SELECT Room FROM {Room} WHERE Room =:ln",array(':ln'=>'Training Room'))->fetchCol();

        $node->webform['components'][1]['value']=$result;

    }

}

Am I using the correct hook?

Do I have to use the node api or the webform api?

Can you help me with this?

Rather do this:

Alter the button link to include a parameter:

Yes

In hook_form_alter, check for the parameter and set the default value(s):

function test_presave_form_alter(&$form, &$form_state, $form_id) {
    // dpm($form_id); // uncomment to get $form_id
    // dpm($form); // uncomment to get $form
    if ($form_id == 'webform_client_form_2') { // use dpm($form_id) to get your form id
        $param = drupal_get_query_parameters();
        if (isset($param['captured']) && $param['captured'] == "true")
        {
            $result = ...
            if ($result) {
                $form['submitted']['room']['#default_value'] = $result; // use dpm($form) to get your room field
            }
        }
    }
}


Command pm-enable needs a higher bootstrap level to run I've been scouting the forums for the past two days trying to get an answer to my problem, i'm new to Drush but pretty good with Drupal. my environment is as follows:

centos 6
php 5.3.3
drupal 7.x single site basic installation

I've installed drush, then cd to my site root directory and i used drush dl seo_checklist which worked fine.

when I run drush en seo_checklist I get the following output:

Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. [error]

The drush command 'en seo_checklist' could not be executed. [error]
Drush was not able to start (bootstrap) the Drupal database. [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.34
 Site URI               :  http://default
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html/mytestsite
 Site path              :  sites/default

i did modify my settings file to include:

'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost'

UPDATE - 1

drush st returns the following:

 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

everything inside the root folder has 755 permissions and belongs to apache:apache

I am running the drush command as root. i have no idea what could be causing the problem.

Is your settings.php file in sites/all/default?  If not, you'll need to add the --uri option.  If your settings.php file is in sites/all/foo.com, then add --uri=foo.com.

drush --uri=foo.com en seo_checklist

Or, change your working directory to the same folder that contains settings.php.

Or, define a site alias @foo that defines 'root' and 'uri', and then use:

drush @foo en seo_checklist


PDF Preview module not working in ubuntu for Drupal 8.5 version PDF Preview module not creating the image(first page of PDF) in docker (Ubuntu) for Drupal 8.5 version.

I have installed imagick(configured the exce path in imagetoolkit module) and Ghostscript and also configured the PDF Preview to the file filed of my content type.

But when I upload the Pdf file I get below error,

ImageMagick error 1:
convert: no images defined '/var/www/html/web/sites/default/files/pdfpreview/58-samplepdf_9.jpg' @ error/convert.c/ConvertImageCommand/3210.

Could any one please help me to resolve this issue?
Please find more details below,
PHP version - 7.0;
Imagick version- 7.x;
Ghostscript version - 9.18;
OS -  Ubuntu 16.04

I guess ghostscript is creating the issue here. Is there any post installation configuration required in docker that we need do  for imagic or ghostscript.

I found the solution by running the below command in Docker file and run the docker build.

Install ImageMagick

RUN apt-get update && apt-get install -y \
    libmagickwand-dev --no-install-recommends \
    && pecl install ImageMagick* \
    && docker-php-ext-enable ImageMagick

Install GhostScript

RUN apt-get update && apt-get -y install ghostscript && apt-get clean


Drupal - Just want to add HTML to a node's form element how? I have a node/content that outputs like a form that is available to guests to add jobs to.  I would like to implement this HTML inside of the form to reduce spam:

    If you see this, Leave Empty:
        <input id="address" name="address" />

    If you see this, Leave Blank:
        <input id="username" name="username" />

I kind of need this within the <form> tag.

Now when the form gets submitted, I'd like to be able to check for this and be sure both inputs are empty, and if they are empty, the form should be submitted, otherwise, if either is filled in with anything, it should not be allowed to be submitted.  I did this on another, Non-Drupal, site and it eliminated the SPAM on that form completely.  But now I'm on a Drupal site, and would like to understand how to do this via a node.

I don't currently have FTP Access, however, I do have complete Admin Access on the Drupal site, so if there is a way to do this via Drupal that would be preferable.  Is there a module that will do something similar to this that I can add as a field on that node?

Any help to point me in the right direction on getting started for this is greatly appreciated.  Also, I have the Devel Module installed if that helps...

Create own helper module. Use hook_form_alter(), specifically hook_form_node_form_alter() variant. In it, just add #markup element.

$form['my_markup'] = array(
  '#markup' => "Your HTML here",
);

But in content of your question, it seems you want more than own html. It looks like you want to add some active elements. So see Form API Reference for elements you need. To process values, you will need to define submit handlers.


Restrict language based content editing for nodes and blocks I am running a D7 multi-language site. I am looking for a solution to restrict node AND block editing for english language, only. The editor should not be allowed to edit french content. How can accomplish what I'm looking for?

So far, I have created a new user (e.g. english editor) and added them to a new role. I am also using contrib module 'Content Access' and 'block access'. However I have to restrict access per node which is not my perfect choice. With block_access module, english editors are still able to see/modify translations

For your solution you can implement hook_node_access, as you see this function takes 3 arguments $node which is the content the user wants to make an operation on it, there you can check content's language, $op is the operation which user wants to make on the content which in your case you can check if it is edition, and finally $account takes the information about the user so you can decide if user is allowed to do the operation or not.

One big consideration is that this hook is not fired for the super user (user with uid = 1) as he bypasses almost all permissions, so in this case you can use hook_init and make a redirect based on node arguments.


How to load JS as the first item in head tag? We have a custom module that has a JS library that we want to load in the <head> tag as the very first item even before all the normal Drupal JS files. All other libraries are loaded through mytheme.libraries.yml.

How can I load the library (mymodule/myscript) so that it loads as the first <script> tag in the <head>?

What we tried:

mymodule.module

function  mymodule_page_attachments(array &$page) {
  $attachments['#attached']['library'][] = 'mymodule/myscript';
}

mymodule.libraries.yml

myscript:
  version: 1.x
  header: true
  js:
    /path/to/file: { external: true, weight: -200 }

Current problem:

<head>
  <script>script1</script>
  <script>script2</script>
  <script>myscript is loaded here</script>
</head>

Goal:

<head>
  <script>myscript is loaded here</script>
  <script>script1</script>
  <script>script2</script>
</head>

Using @Manav's link, i was able to get to this solution that worked.

function mymodule_page_attachments(&$attachments) {
  $custom_script = [
    '#type' => 'html_tag',
    '#tag' => 'script',
    '#attributes' => [
      'src' => 'path/to/file.js',
    ],
    '#weight' => -200, // this allowed me to do what i needed
  ];

  $attachments['#attached']['html_head'][] = [$custom_script, 'custom_script_key'];
}


How to order by a column with NULL values in it due to leftJoin? If you have two fields on a content type, such as "publications" and "featured publications" and you want to display a single list merging the two fields with the featured content on top.

I'm using two left joins from the base entity table, which leaves the delta non-featured items as NULL in the results set.

The problem I ran into is that orderBy on a delta column doesn't work with NULL values as NULL values will appear before any value with an integer in it.

So given a query like this:

$query = $this->database->select('publication_field_data', 'pfd')
      ->fields('pfd', ['id']);

    $query->leftJoin('node__field_publications', 'fp', 'fp.field_publications_target_id = pfd.id');
    $query->leftJoin('node__field_featured_publications', 'ffp', 'ffp.field_featured_publications_target_id = pfd.id');

    $query->orConditionGroup()
      ->condition('ffp.entity_id', $current_nid)
      ->condition('fp.entity_id ', $current_nid);
    // Sorting by deltas on the featured field, then the non-feature field
    // and then the non-featured field will fail, as the NULL values
    // on the featured field will appear first.
    $query->orderBy('ffp.delta');
    $query->orderBy('fp.delta');

You won't get the proper order.

So the question is, how can we fix the query so that it will order properly, first showing the featured items, then the non-featured items (and not showing duplicates).

As I'm using paging, you can just use two queries.

One solution I found is based on this response:
https://stackoverflow.com/a/4326579/1214689

$query->addExpression('ffp.delta IS NULL', 'featured_delta_is_null');
$query->orderBy('featured_delta_is_null');
$query->orderBy('ffp.delta');
$query->orderBy('fp.delta');

Since sorting on the featured delta will place items with Null values at the top of the list, we need to sort featured delta in two pieces, first by those that aren't NULL (by converting to a boolean, those are lower than the ones that are NULL), then sort on the actual delta for those values that aren't null, this will leave all the other values out to be sorted by the delta on the non featured ('field_publications') field.


Search a content type and return JSON I'm trying to create a JSON API that will return an array of JSON results matching specific search criteria.  It will always be searching one specific content type, but will need to match custom fields for specific search terms.  I will be passing a term to match a given field, for example:

/api/my-content-type?first_name=bob&term_a=my+term&another_field=search+term+here

The response from this needs to be an array of JSON objects containing the fields for that given content type.

I've seen many modules for this, but don't seem to see any that allow searching by field.  Is this something I would need to implement custom?  If so, what is the best module and/or method to start from?

Im not sure if I should be using a Search API, Services, one of the many REST JSON API Modules, etc.

I've seen many modules for this, but don't seem to see any that allow searching by field.

There are many modules which provide this feature, not necessarily out of the box, but with some customization.

I would say, the best module to start with this would be Restful.
I have personally used it for a similar use case for building the service endpoints which could be filtered using specific field values, and it work charms!
The documentation seems to have improved a lot since the last time I've seen it!

There are other modules present which help you create custom endpoint too. However, the ease of building such filterable endpoint is good with Restful as per my experience.


Creating slightly different sites using same code base We are looking to create templated sites that have the same basic structure with the following differences. We would want to look up which site is being created based on domain/subdomain.

Same navigation, but links to different node. ex: About Page has different content
Different logo/header throughout the site.

Is there a module or suggested approach to do this?

NOTE: We want to use the same codebase and database.

The standard way of doing this is called a "multi-site".  It allows you to use the same codebase for multiple sites.  Each site in a multi-site has its own settings.php, so you may use different databases or the same database (this is controlled by the database settings in settings.php.
To use a different logo, just  go to appearance > settings and upload a different image for the logo.
Here is a link to my tutorial about setting up a multi-site:
http://wikihandbooks.com/drupal7/intro_multisite.html
There is also instructions at Drupal.org: https://www.drupal.org/docs/7/multisite/multi-site-sharing-the-same-code-base


Is there a way to have a views filter value be determined by PHP? I need to search for fields that are equal to the value of a visitor cookie. How do I get $_COOKIE[somecookie] as the criterion value in the views filter? (I know that I could use views_php to grab all the records and filter out after the fact but that's a lot of records and would be far too slow.)

It would be preferable to be able to do this without writing a custom module. It seems like this would be a common request by admins so I feel I'm missing something obvious.

Setup the page to use a contextual filter per field you want to be searchable. Then for the contextual filter set it to look for the value provided by the URL. Then select PHP Code for WHEN THE FILTER VALUE IS NOT IN THE URL.

In that PHP blob supply code that pulls the field argument from $_COOKIE, if any or return NULL.


How to integrate Views with apache solr search? In my site I am implementing zip code based search, for that I created one view of user profile and add one expose filter to it which is exposing result on postal zip code entered by user. Now I am thinking that exposed filter integrate with Apache solr.

Help me out for which module I have to use for it and how I configure it?

List of modules I have used in my project:

addressfield
geofield
geocoder
geophp
apachesolr
facetapi
profile2

The module you want is the aptly named Apache Solr Views which will allow you to construct views from the SOLR index. Configuration is pretty simple. It's kind of a drop-in module. You'll choose to create an "Apache SOLR view". From the project page:

  Create a view from admin/structure/views/add and choose Apachesolr search. All of the fields indexed in solr should be available as views fields/filters/sort. Configure the view as needed and save it

Hope that helps you. Good luck!


node has term - show all parents of this term A node has a taxonomy term. My aim is to show  a view on node page, that displays all parents of this taxonomy term and the term as well. Is it possible to acomplish in views? I use views 3 and drupal 7. Thank you.

Although you're looking for a Views solution, if you were to do it custom, e.g with hook_block_info you could use taxonomy_get_parents

Just mentioning in case others looking for that.


Dealing with nodes that do not have the field when sorting views using date field I have an 'Expired' date field that holds the date when a node expires. However, not every node has this field so nodes missing this field come after nodes containing the field. I want nodes that do not have this field to be sorted above nodes that have the field. How can I do this?

You would need to sort your posts by two criteria

Has a expired date
The value of the expired date

Or alternatively you could use ASC/DESC to display those without an expire date first. Doing that would effect the sorting of the rest of the nodes.

If you want to use two criteria, you could create a computed CCK field that has a value of 0/1 indicating if it has an expire date. You can use that to display all nodes without expire date first, and then sort those with an expired date by the expired date.


Get URL of Views 'file' field How can I get just the url of the uploaded file from the Views module 'file' field.  If I do the following:

print $view->render_field('field_url', $id);

I get the entire 'file' object in html format. How can I retrieve just the url of the uploaded file?

If you use the Image URL Module module you can set the field to 'Image URL' format and call it with

$fields["field_name"]->content

and it should only output the url to the image without any surrounding html


How do I control the "more" link from a views content pane to point to a biblio filtered page I'm using Drupal 6. I'm trying to create a view pane that lists three biblio items matching a particular term, and then offers a link to more items filtered using the same term. Biblio allows me to access these items nicely using biblio/term/term_name. Is there a way to control the more link provided by views so that it points to this location?

A simpler solution for this is to edit the display footer, set its input format to PHP and print the link yourself like:

<?php

  $term_name = 'TERM_NAME'; // set term name depending on how you filter for it
  print l('Read more', 'biblio/term/'. $term_name);

?>

if you are using arguments to filter the terms, then you can access the argument(s) like so:

<?php
  $view = views_get_current_view();
  $arg0 = $view->args[0]; // or whatever index the term name has
?>

Otherwise you need to use a custom module and figure out one of the hooks Views implements (e.g. hook_views_pre_view())


modules_install hook causes constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role_permission} (rid, permission, module) I am trying to set several permissions when a feature is being enabled (a new content type).
By default this content type is disabled, and an admin can go to structure/features and enable it

under docroot/profile/my_profile/features/foo I created the following foo.install file

function foo_modules_installed($modules) {
 if (in_array('foo', $modules)) {
  $perms = array(
    'create foo content',
    'edit own foo content',
    );
      user_role_grant_permissions(user_role_load_by_name('publisher')->rid, $perms);
      user_role_grant_permissions(user_role_load_by_name('administrator')->rid, $perms);
}
}

but when I go to structure/features and enable it, I get the following error

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role_permission} (rid, permission, module

I tried different hooks, like enabled and so forth and all have the same issue.

How can I have a feature disabled by default, but still grant permissions to some users? What am I doing wrong

Seems like a hook_install() in the .install file for the feature will work if called with

drupal_flush_all_caches();

I am not sure if this is the best solution, but it seems to work for me


How to limit the products from the compare in drupal? I am working with the Drupal Commerce and the Commerce product comparison module. Here I need to limit the products.

How do I limit the products from the comparison?

You may solve this through Rules module.

Event: After udpdating an already existing line item

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

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


Strategy for unit testing classes that interact with the Entity API Sometimes I find that I end up having to do lots of mocking just to make the class testable, especially if it is interacting with the Entity API. For example, if I have code like this:

$taxonomy_term_storage = $this->entityTypeManager->getStorage('taxonomy_term');
$category = $taxonomy_term_storage->load($product_category_tid);
$category_atlas_key = $category->get('field_name_key')->getValue();

So now, to mock the return value of one field I need to do all of this:

$fieldItemListMock = $this->getMockBuilder('\Drupal\Core\Field\FieldItemListInterface')
  ->disableOriginalConstructor()
  ->getMock();

$fieldItemListMock->expects($this->any())
  ->method('getValue')
  ->willReturn('foo');

$fieldableEntityMock = $this->getMockBuilder('\Drupal\Core\Entity\FieldableEntityInterface')
  ->disableOriginalConstructor()
  ->getMock()

$fieldableEntityMock->expects($this->any())
  ->method('get')
  ->willReturn($fieldItemListMock);

$entityStorageMock = $this->getMockBuilder('\Drupal\Core\Entity\EntityStorageInterface')
  ->disableOriginalConstructor()
  ->getMock();

$entityStorageMock->expects($this->any())
  ->method('load')
  ->willReturn($fieldableEntityMock);

$this->entityTypeManagerMock->expects($this->any())
  ->method('getStorage')
  ->willReturn($entityStorageMock);

As far as I'm aware I've done everything as I'm supposed to, injecting external dependencies via the constructor but it still seems like way too much effort. The problem gets exponentially worse when I'm working with multiple fields or other people's code who haven't injected dependencies properly. So I end up having to create a partial mock of the class I'm testing.

Browsing through core and contrib modules I notice that there seem to be more Kernel tests than Unit tests, which seems contrary to the testing pyramid

Which makes it seem like they have also found unit tests too hard to set up.

So I'm wondering, is it better to just write Kernel tests / Browser tests for classes that interact with the Entity API or am I simply writing my code wrong, which is making it hard to unit test?

So I'm wondering, is it better to just write Kernel tests / Browser tests for classes that interact with the Entity API or am I simply writing my code wrong, which is making it hard to unit test?

In my opinion yes. The Entity API is not designed to work well for mocking/unit tests. Drupal 8 was a very different thing when we started designing and implementing it. Maybe we'd do things differently today, but the kind of extensibility it offers is hard to manage. And we also needed something that we could gradually convert the large Drupal core code base or it would never have been possible.

In regards to the testing pyramid, that is the ideal scenario, but it's not always feasible. I also think that it is makes more sense in a scenario where you built and control the whole system. By building on top of Drupal (which in turn builds on top of Symfony), a huge amount of the complexity and heavily lifting is already taken away from you and covered with the test coverage of those projects. Given that, it makes sense to me that there is a bigger focus on integration/E2E tests as you are mostly integrating existing components.

And if you do have your own components that actually do things worthy of unit tests (and not just shuffle data between forms, entities and templates) then one thing you could do is work with Adapter/Value objects that hide away the complexity of Entity Field API with an interface that you can mock.


Multiple forms on one page I try to input several forms into one page via Controller. With code which is
under, I see those forms but after submit one of them, nothing happens. Any of data is send to database. Has anyone idea how to fix this?
<?php

namespace Drupal\Core\Entity\ContentEntityForm;
namespace Drupal\student\Controller;
use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Drupal\node\Entity;
use Drupal\node\NodeForm;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Routing;
use Drupal\Core\Entity\ContentEntityForm;

class SFormController extends ControllerBase {

  function new_form() {

    $build = [];

    foreach ($stud as $id => $name) {

      $node = \Drupal\node\Entity\Node::create(['type' => 'student']);
      $form = \Drupal::service('entity.form_builder')->getForm($node, 'student_form');

      $build[] = $form;
    }
    return $build;
  }
}

?>

You need to make the form ID dynamic, so that it is different for each instance on the page. As you're extending EntityForm, you'll have to extend it, then register your form on the node class, and finally call your form class.

Extend the entity form:
class MyEntityForm extends EntityForm {
  public function getFormId() {
    // The dynamic form ID allows for the form to be
    // reused on a page.
    return parent::getFormId() . '-' . $this->getEntity()->id();
  }
}

Register your form class on the node entity type:
/**
 * Implements hook_entity_type_alter().
 */
function HOOK_entity_type_alter(array &$entity_types) {
  $node = &$entity_types['node'];
  $node->setFormClass('my_form_type', 'Drupal\[MODULE]\Form\MyEntityForm');
}

Call your form from your controller:
  $form = \Drupal::service('entity.form_builder')->getForm($node, 'my_form_type');


Workflow with per page permissions I am creating a site for a complex organization of authors, editors, and publishers. Basically, each author is responsible for 1-5 pages and can only create drafts of these pages. Similarly, editors can only edit and approve pages to which they are assigned. There are max 5 publishers who are tasked with editing, publishing, creating new pages and navigation items, and assigning authors and editors.

If we have about 50 authors and 50 editors, how do we set up permissions and workflow for this site on Drupal 8?

One solution is to have Workbench Access set up to work on Taxonomy where each page is tagged with an author term and an editor term. We would then have to set up one term for every user and two fields on each page. Is there a more direct approach?

You can use Business Rules module to check if the page has the is on the specific workflow state and if the user has the correct rule to view or edit it.


Add fee to total order balance once Is there a way to add fee to total order balance once, based on some conditions? The product pricing rules are added for each product. I need this to be a price component, so it needs to be displayed as fee on the total order display (not as an added product!).

This is a bit tricky, since the order total is calculated from the line items. Either you would need to add/remove a line item that has the fee, or you would need to add the price to the order after it has been loaded, using hook_commerce_order_load.

I would prefer the line item solution, as it is more robust, but it also requires more work, as you will need to define the line item and either create custom code for adding/removing it.


Hide fields on content creation I have added my own content type with many fields to enter, I want to hide some fields when adding a content according to radio button selection.
I explain, in the add content page, i have two radio buttons (inside/outside) and inside is selected by default and some fields are hidden, when user select outside, some fields will be hidden and the fields accorded to outside will be shown to user to fill them.
How to do this ?

You are looking for Conditional Field Module...

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.


Drupal: showing different page layouts based on form data I'm trying to build a multi step form. Before the second step I have to process the data inserted in step one and display different layout and form fields based on the results.

I use "drupal_get_form" callback in _menu hooks to display the form, but I think I have to use a different approach, because I can't find a way to specify a template and\or HTML code this way.

What can I do? Thanks!

I think you should try ctools multistep wizard to generate the multi step form in Drupal. To start with Ctools wizard form a great example is given at the following link http://internetdevels.com/blog/ctools-multistep-wizard-example


Sending email notification based on flagged node being linked via entity reference I need to send an email notification to followers of a node, when another node that is linked, has been created.

Example:

Users follow "location" type (e.g London) by flagging that node using
the flag module and 'follow' type.
Author creates a "blog" type (e.g. Things to do 2014!) and links it to their location via field_location [entity reference].
When published, send email to all followers of
the "location" type.

Can anyone recommend the way to do this with rules or point me in the right direction?

Thanks,
Paul.

I found the answer to this, or at least, a way to do this. In a custom.module:

Firstly, this checks if something is required to happen (creating a 'blogpost'), and if so, then gets the NID of the item the user is following (e.g. field_linked_item).

function custom_node_presave($node) {
if ($node->type == 'blogpost' && $node->is_new) {
    $linked_node_nid = $node->field_linked_item['und'][0]['target_id'];
    if ($linked_node_nid) {
      $emails = custom_get_blog_follower_emails($linked_node_nid);
      if ($emails) {
        custom_schedule_mass_email($linked_node_nid, implode(',', $emails), 'email_blog_post_linked');
      }
    }
  }
}

This function gets the email address for all users who flagged the blog that is linked to this blogpost (via linked_item) and returns the list to the function above:

function custom_get_blog_follower_emails($nid) {
  $query = db_select('flagging', 'fc');
  $query->join('users', 'u', 'fc.uid = u.uid');
  $query->join('flagging', 'fc2', 'fc2.entity_id=fc.entity_id AND o.entity_type=\'node\' AND fc2.fid=5');
  $query->leftJoin('field_data_field_opt_out', 'o', 'o.entity_id=u.uid AND o.entity_type=\'user\' AND o.deleted=0');
  $or = db_or();
  $or->condition('o.field_opt_out_value', 0);
  $or->condition('o.field_opt_out_value', NULL);
  $result = $query
    ->fields('u', array('mail'))
    ->condition('fc.entity_type', 'node')
    ->condition('fc.entity_id', $nid)
    ->condition('fc.fid', 4)
    ->condition('u.status', 1)
    ->condition($or)
    ->orderBy('fc.timestamp', 'DESC')
    ->execute()
    ->fetchCol();
  return $result;
}

If email addresses are found by the function above, the original function then uses this to send emails via a pre-created rules message:

function custom_schedule_mass_email($nid, $to, $action) {
  $state = new RulesState();
  $state->addVariable('nid', $nid, array('type' => 'integer'));
  $state->addVariable('to', $to, array('type' => 'text'));
  $task = array(
    'identifier' => 'custom_' . $action . '_' . $nid,
    'date' => time(),
    'config' => 'rules_' . $action,
    'state' => $state,
  );
  rules_scheduler_schedule_task($task);
}

You need to create a rule to accept the 'to' and 'nid' (nid in my use is to allow rules to get some information about that post). In my case, the rule is called 'email_blog_post_linked'.

This is pretty specific to my requirements, but hopefully it will point people in the right direction.


How to relate a complex field to another node I'm building a hobby site that is going to be used to record results (golf). A round of golf will have any number of players, selectable from a known list of players.

I would like to be able to create a new round and add players to it, entering a score for each one. My first thought is to create content types for player and round, and a complex field that does something similar to node reference.

Before I went down that path I wanted to see if there was a smarter more Drupal way of doing this. One idea I had was to have a third content type, result, which would be a node reference to a player and an integer field, but this would require having to create the results before hand. Or perhaps the result has a relationship to a round and a player, so the workflow is create a round, then create as many results as required.

The basic question, is there a smarter way to do this?

My solution to this is as follows:

I have basic content types of Player and Golf Course.
When I want to enter new scores, I first create a Round (which is another content
type with a node reference to a Golf Course and a date field).
Once the round is created I create Results (another content type which has
a relationship to a round and a player and an integer for the score).

This handles my data entry requirements even though the workflow is a bit of a kludge, but I can streamline that later I think. Now the next step will be using views to display my results but that will probably be another question :)


Good practices working with databases I'm learning Drupal, and I want to develop a website where the main thing is its database.

I already have the Extended Entity-Relationship Model of the database (kind of complex).

What's the right direction to take when creating a database to be used by Drupal, create it manually and do the queries in Drupal using PHP, as it were a PHP+MySQL site from scratch?
Does Drupal provide an easier way to do this?

Edit:
I'm not a Drupal experienced developer. What I want to know is:

When working with databases, is any better way of doing this that querying the database using SQL syntax, like if I were developing a PHP+MySQL single page?

I just want to know what Drupal developers usually doe when they want to create a database, insert data, modify data, or do some queries and show the data to the users.

Your entity-relationship model is likely going to map to what we call 'Content types' in Drupal.

Content types are defined using the Content Construction Kit module, commonly referred to as CCK.

With CCK, you point-and-click to define what fields you want the content type to have - text fields, numbers, links, references to other content types, references to users in your Drupal site.

With the content types defined, you can figure out what kind of lists for that content you want - tabular, blog-style, etc, and use the Views module to create that listing.  Views is a point-and-click query builder, complete with sorting, filtering, access control, dynamic URL arguments, and relationships (think joins) to other content types.

That's typically how 'databases' are done in Drupal - but you don't have to do anything with the database at all, really.

If you've got a really specific use case that can't be solved with some combination of the 7000 or so contributed Drupal modules, then it might be time to grab a copy of 'Pro Drupal Development' and learn module development to integrate your custom module into the rest of Drupal to meet your exact need.


Method to partially duplicate a node What I need to do is save a node and then add another node that uses some of the data in the saved node. I have figured out how to add another button onto the form that will save the node first and then do something else.

In my form alter I have added a second submit button to the original form:

   // Check for a particular content type's node form.
   if (($form_id == 'content_node_form')) {

   $form['actions']['submit_another'] = array(
   '#type' => 'submit',
   '#name' => 'save_another',
   '#value' => t('Save, and Add Another Submission.'),
   '#submit' => array('node_form_submit','create_partial_duplicate_handler'),
   '#weight' => 20,
   );

   }  //endif

It saves the node then, runs another function that will load some information from the just saved node into a new node.

Should the create_partial_duplicate_handler() function go to a menu item that calls another function or could I load the node form and the values directly in the function?

I have been reading lots of examples that create a menu item with a different url, but have not seen it done any other way. I don't want to waste time trying another method if the menu item method is the only way to do it.

Please let me know. Thanks.

ETA: I am using a second button because the user will have the choice of saving the node with the information entered into the form or saving the node and having another form appear with partial data from the saved node. The user enters the rest of the information into the partially filled form and again has the option of saving or saving and adding another.

I think there are no need of any menu or other submit button.

You can use hook_node_insert for create a different node form partial data of a node  upon creation on node.

The statement is like:

function MODULENAME_node_insert($old_node) {

 if($old_node->type === 'article'){ // check node type

    $new_node_title =  $old_node->title; // get partial data from old node

    $node = new stdClass(); // We create a new node object
    $node->type = "page"; // Or any other content type you want

    $node->title = $new_node_title; // Assign partial data of old node to new node

    $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
    $node->path = array('alias' => 'your node path'); // Setting a node path
    node_object_prepare($node); // Set some default values.
    $node->uid = 1; // Or any id you wish
    // Let's add standard body field
    $node->body[$node->language][0]['value'] = 'This is a body text';
    $node->body[$node->language][0]['summary'] = 'Here goes a summary';
    $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

    $node = node_submit($node); // Prepare node for a submit
    node_save($node); // After this call we'll get a nid
 }

}

If this not fullfil your requirement then use some other HOOKS provided by Node API


how to fix this Drupal\commerce\CommerceEntityViewsData' not found installed Commerce reports using composer. On enabling the module got an error:
"Fatal error: Class 'Drupal\commerce\CommerceEntityViewsData' not found".
what is the solution for this i searched for CommerceEntityViewsData but i couldnot find what exactly it is please help me.
i'm a newbie
Thanks

Make sure you're using Drupal Commerce 8.x-2.6+
CommerceEntityViewsData was added in https://www.drupal.org/node/2882374


How to get a themed form via Ajax in D7? I'm trying to get a D7 form into a Bootstrap modal dialog.  I had this working on D6, through a semi-straightforward process:

The jQuery code that's building and showing the modal does an $.ajax call to a url on my site to get the form contents -- something like /get_my_form/123.  This request is picked up by a Drupal menu entry that makes a call to drupal_get_form() with the appropriate form function and various parameters.  The usual Drupal form-creation thing.
There's a theme function for the form that does a couple of things and then sends the results back to jQuery by doing:

print json_encode($the_form_contents);
exit;
The ajax handler, which is expecting a json object, gets the results and sticks them into the body of the modal, and puts it up.

In moving this code to D7, I've been following the same route.  It almost works, but the ajax call continually fails because the response string from the server includes the HTML from a page template, up to the point where the "exit" in the theming function kills the PHP request.  That HTML is obviously not a expected part of the JSON object, but I can't figure out how to get rid of it.  I've tried using drupal_json_encode in place of json_encode, and replacing the "print" statement with a call to drupal_json_output, but the page template stuff keeps coming.  I'm definitely not adding it to what's produced in the theme function, so there must be some other part of Drupal that's squirting it out in ajax's direction.

Any ideas?  This has REALLY been driving me crazy this afternoon.  Thanks!

I don't know that this counts as a duplicate, but the answer by "jeroen" on https://stackoverflow.com/questions/247991/displaying-a-drupal-view-without-a-page-template-around-it got me past this.  It's a greasy little hack (no offense, jeroen!), but it seems to work.


I need help with an existing variable of drupal How I can use in my code the value where exists on configuration->Logging and errors->Database log messages to keep?? Could anyone help me to find out how I can use this number that the user will select? What is the name of these variable??

The "Database log messages to keep" tells the site how many entries to store in "Recent Log Messages" (/admin/reports/dblog). It stores a record of watchdog events and php warning/errors, etc.

The limit is stored in the variable table, under the variable name of dblog_row_limit.


Strange problem with autocomplete field in forms in Drupal 7 I have an autocomplete field, which has been working perfectly for 1-2 days. Suddenly, it stoped working. I re-wrote the code, cleared the cache, and it works again. After comparing code, it is exactly the same code. I cannot trace the error. The problem is that it does not give back any results and the Firebug error is:

  TypeError: matches is null if (typeof matches.status == 'undefined' || matches.status != 0) ...

I cannot understand why it suddenly stopped working.

I have traced back the problem to a warning by Drupal:

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_search_idiomas_autocomplete/list/confirm/' not found or invalid function name in menu_execute_active_handler()

Still not sure where the problem is. The code is standard autocomplete field from official documentation examples.

I have finally completely solved the issue. I copy the code which is working and below the code which was giving the error. Please some expert on Drupal to verify if I am right:

Working code:
 $items['especialURL/autocomplete/%'] = array(

'page callback' => '_mymodule_autocomplete' ,
 'page arguments' => array(2,3,4),

Wrong code:

$items['especialURL/autocomplete'] = array(
   'page callback' => '_mymodule_autocomplete' . '/' . arg(2) .'/'.arg(3) . '/' . arg(4),

Explanation: the wrong code worked perfectly but once I cleared cache, it stopt working. Somehow the page callback was registered until the cache was emptied, and from that moment it would stop working. Maybe starting with page callback in the form of _mymodule_autocomplete and later adding the args() would work for a while. Interesting. These have been the worst 5 hours of my life working with Drupal due to using the wrong code while I had got it to work just by chance!!!


Preprocess a specific table I'm building a module to extend the functionality of Nodequeue.
So in the nodequeue list I wanna add one more operation link (to the current View | Edit | Delete operations).

The list is build up in a table using theme('table') by Nodequeue.

So for me the be able to extend the content of this table and add one more link, I'm thinking I'll have to preprocess the table theme?
So I'll make a MYMODULE_preprocess_table(&$variables)?

But I just feels like its totally overkill? It must be more simple than that?
Like in the Form API hooks, I have hook_form_FORM_ID_alter().

Is there any alternative to hook_preprocess_hook?

Unlike forms, specific invocations of theme functions don't have identifiers associated with them, so there's no mechanism like hook_form_FORM_ID_alter() that you can use unfortunately.

I can only find one call to theme('table') in the nodequeue module so I think you're talking about the theme_nodequeue_arrange_subqueue_form_table() function.

Luckily enough, this function assigns a unique id to each table (which believe me isn't always the case), so at least you can target it in a preprocess function:

function MYMODULE_preprocess_table(&$variables) {
  if (isset($variables['attributes']['id']) && $variables['attributes']['id'] == 'the_id') {
    // Alter the table
  }
}

As the theme_nodequeue_arrange_subqueue_form_table() function actually renders the table to a string (it has to, being that it's a theme function itself), I don't think there's any other way to do this.

The other (more long-winded way) would be to implement your own version of the entire theme_nodequeue_arrange_subqueue_form_table() function, copying the code from the original and just changing what you need to.


Best way to break up node edit forms smaller, more manageable forms? It's pretty common to end up with massive node edit forms once content types start accumulating fields. Collapsable fieldsets and vertical tabs help the UI, but it can still be overwhelming.

Example: Say I have a local business site, and it involves a content type called 'business' which has lots of fields. One very significant field is the business's location. Rather than having location as just another fieldset in the large node edit screen, I'd like to break out the location-related items (address fields, google map, etc.) into a separate editing screen.

Multi-step forms are not ideal in this case. Is there a straightforward way to break a single node edit form into distinct forms?

I use the field group module to simplify things.  This allows you to easily make collapsible groups of collapsible field sets, use horizontal and other types of tabs, and split a single form into multiple pages.

With the field group module, you can also easily add a css class to any group of fields, which makes it straightforward to theme that specific field (change the background color, increase text size, etc.) for emphasis.


domain-name.com/user and other URLS not loading When I go to my domain.com/user I get a blank page, where as usually that was the URL  I go to to log in and change content. I came across this thing: https://www.drupal.org/node/256410, but I do not know if it is the same issue. I tried uploading a new .htaccess file to no avail. Any thoughts/ suggestions?

You should enable apache's rewrite mod. and then restart your apache server.
Then, goto configuration and check clean URL. After that your site will be using clean URL.


ajax http 500 error while editing panel in drupal 7 I am getting this error when I tried to edit my panel in drupal 7.

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /panels/ajax/editor/edit-pane/panel_context%3Apage-contacts%3A%3Apage_contacts_panel_context%3A%3A%3A%3A/8
StatusText: Internal Server Error
ResponseText: 500 - Internal server error.
Server Error 500 - Internal server error.

Anyone with solution highly appreciated.
Thanks

Please check below configuration & update :

php.ini

  max_execution_time = 30 --> 60 ;

  memory_limit = 32 --> 128, or even 256M ;

.htaccess

Add the below lines :

  php_value auto_append_file none

  php_value memory_limit 128M

my.ini

  max_allowed_packet = 4M --> 64M


after_update doesn't fire I don't know what the problem is, but why don't after_update fire? I can replace it with insert and it works but this doesn't for some reason.

function maillist_user($op, &$edit, &$account, $category = NULL){
    if($op == 'after_update'){
        maillist_register_submit();
    }
}

What I am trying to do is as soon as a new user is registered to my site I want to use that uid but I can't figure out how to get that uid.

The after_update case called is called after the user modifies his account from my understanding of hook_user.

So that would mean that the user account has been created and the user updates his profile such as changing user image or password etc., which would trigger update and after_update.

I guess when the user is created it is only normal that the insert is triggered. If you have customized the registration so that in course of the registration the user account has been created and while completion the account information is being modified by him the update and after_update would be triggered.

If you wish to get the uid of the user who's registered most recently I suggest you could implement hook_user with insert case and query the database to get the max(uid) which would be the recently added user's id, only making sure your module has a greater weight so that user module's insert of the user happens first and your retrieval of the uid follows it. Though my suggestion feels less than optimal I believe it would work.


Db_Query Fatal error: Unsupported operand types I am simply trying to return the rows from a table in my db but i keep getting this error thrown back at me no matter what I do "Fatal error: Unsupported operand types in C:\xampp\htdocs\d7\includes\form.inc on line 1009". Am I missing a argument or something?

This is my function

Hook menu

function auto_form_menu() {
$items = array();
$items['admin/config/auto_form'] = array(
    'title' => 'My Module',
    'description' => 'description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('auto_form_records'),
    'access arguments' => array('administer site configuration'),
    'file' => 'auto_form.admin.inc'
);

$items['admin/config/auto_form/manage'] = array(
    'title' => 'My Module',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'description' => 'description',
    'weight' => -10,
);
return $items;
}

'auto_form.admin.inc'

function auto_form_records() {
  $header = array('First Name', 'Last Name');

  $dbresult = db_query("SELECT first, last FROM {auto}");

    $rows = array();
    foreach ($dbresult as $dbrow) {
        $rows[] = array(
        $dbrow->first,
        $dbrow->last
      );
    }
    return $output = theme('table', array('header' => $header, 'rows' => $rows));
}

Updated Code:

Any help is appreciated seeing how I am completely lost on figuring this out.

I'm not sure exactly which one is causing the error but there are a couple of things:

You're trying to loop over a variable called $dbresult which you haven't declared; you probably meant

$dbresult = db_query("SELECT first, last FROM {autoform}");

$results = '';
foreach ($dbresult as $dbrow) {

It looks like you're using Drupal 7, and the call you're making to theme_table contains arguments in the style of the Drupal 6 call. Variables are all named in Drupal 7 so you need to invoke the function like this:

$output = theme('table', array('header' => $header, 'rows' => $data));

theme_table() takes an array of rows, and each of those arrays will have the data for a number of columns, one for each that you've defined in your header. At the moment you're concatenating a single string and creating a single row containing one cell, with that single string in it.

I think something like this is more what you're after:

$rows = array();
foreach ($dbresult as $dbrow) {
  $rows[] = array(
    $dbrow->first,
    $dbrow->last
  );
}

$output = theme('table', array('header' => $header, 'rows' => $rows));

Also if you want a nice little shortcut leveraging some of the db API you could use this reduced code:

$header = array('first' => 'First Name', 'last' => 'Last Name');
$rows = db_query("SELECT first, last FROM {autoform}")->fetchAllAssoc();
$output = theme('table', array('header' => $header, 'rows' => $rows));

That last snippet will become less useful the more you need to customise the individual rows/cells of the table.


Link to node for each of the items in a view I have a D8.2.0 website with a view showing unformatted list of content of certain content type. For each item in the content two field values are shown.

I want one of the fields to be a link to the content item node. I used Rewrite Results > Output this field as a custom link and put the following value:

/node/{{ node.id }}

But no luck. I also tried nid. I cannot seem to find a documentation or a blog post that discusses different values that can be used in twig-enabled fields in D8 views.

If possible please add references to documentation or posts that explain what variable names are available in addition to what is the correct way to use the node id by twig.

If you have option link to content you can check it:

Else you can:

Add new field "Content:Path"
Hide this new field from display
Place it before your desired linked field
Rewrite output of field with: {{ field_name }}

Step 3 is very important : field rewriting tokens needs to be placed before your field.


Thumbnail preview not showing in Video Embed Field Module I am using Video Embed Field Module for embeding videos in dupal 7 site. The thumbnail preview is not showing. I created a view block in the preview section of the view its shows the thumbnail but when the block in in some region of page it only displays the title.

Did you check the access permissions for your thumbnail images


Why the action buttons are not working? I am rendering the user profile edit form ($form_id = 'user_profile_form') on a custom tpl.php page. All the custom fields are user-defined under configuration > Account Settings > Manage Fields:

Following is the code:

<?php $form = drupal_get_form('user_profile_form');?>

<div class="some_class">
    <?php print(drupal_render($form['field_2'])); ?>
    <?php print(drupal_render($form['field_3'])); ?>
    <?php print(drupal_render($form['field_4'])); ?>
    <?php print(drupal_render($form['actions'])); ?>
</div>

All the fields are being rendered well. Even the submit and cancel buttons under the actions field are rendered BUT they are not working. Nothing happens when I click on them.

Please point out any error.

UPDATE:

I should point out that I don't want all the form elements to be rendered, which is why I am trying to render the elements separately.

Can you try to use:

drupal_render_children($form),

remove "actions". and hide all redundant elements :)

As second approach, you can

  echo render( $form['form_id']);
  echo render( $form['form_build_id']);
  echo render( $form['form_token']);
  echo render( $form['options']['status']);

in the beginning of the template file
Regards


views3 error with contextual filter I'm trying to show user posts in their profile with views 3 by following this post  http://drupal.org/node/228959#comment-4591334

after i add the following code to the contextual filter

if (arg(0) == 'user' && is_numeric(arg(1))) {
  return array(arg(1));
}

and it works, but also giving this error

Notice: Array to string conversion in views_handler_argument_numeric->title()
(line 77 of /test_drupal/sites/all/modules/views/handlers/views_handler_argument_numeric.inc).

Warning: html_entity_decode() expects parameter 1 to be string,
array given in decode_entities() (line 429 of test_drupal/includes/unicode.inc).

It looks like it's expecting a string, but your code is returning an array.

Try changing your code to the following:

if (arg(0) == 'user' && is_numeric(arg(1))) {
  return arg(1);
}

That should return the string value rather than returning [0] => uid.


Using Drush without local copy of Drupal, only calling site aliases - No site aliases found We have a project which does not contain a Drupal codebase. It's Cypress.io test with Drush 9 added using Composer. I would like to execute Drush with site alias to work with the remote site while running tests.

I'm able to call Drush from Cypress test just fine. The Cypress part actually does not matter at all as the behaviour is the same when I run Drush command directly.

The setup:

composer init fresh project
composer require drush/drush

✔ rk:/tmp/drushtest> vendor/bin/drush version
 Drush version : 9.7.1
✔ rk:/tmp/drushtest> vendor/bin/drush sa --debug
 [preflight] Config paths: /tmp/drushtest/vendor/drush/drush/drush.yml
 [preflight] Alias paths:
 [preflight] Commandfile search paths: /tmp/drushtest/vendor/drush/drush/src
 [bootstrap] Starting bootstrap to none [0.09 sec, 7.33 MB]
 [bootstrap] Drush bootstrap phase 0 [0.09 sec, 7.34 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.09 sec, 7.34 MB]
 [success] No site aliases found. [0.09 sec, 7.36 MB]

Already there is nothing in Alias paths.
Added some drush aliases to drush/sites/remoteproject.site.yml (valid yml file that is working in the Drupal project)
While debugging this I tried to add a drush.yml config file to point drush to the alias.

✔ rk:/tmp/drushtest> tree
.
├── composer.json
├── composer.lock
├── drush
│   └── sites
│       └── remoteproject.site.yml
├── drush.yml
└── vendor
    ├── ...

✔ rk:/tmp/drushtest> cat drush.yml
drush:
  paths:
    alias-path:
      - drush/sites/remoteproject.site.yml

✔ rk:/tmp/drushtest> vendor/bin/drush sa --debug --config=drush.yml
 [preflight] Config paths: /tmp/drushtest/drush.yml,/tmp/drushtest/vendor/drush/drush/drush.yml
 [preflight] Alias paths: drush/sites/remoteproject.site.yml
 [preflight] Commandfile search paths: /tmp/drushtest/vendor/drush/drush/src
 [bootstrap] Starting bootstrap to none [0.08 sec, 7.34 MB]
 [bootstrap] Drush bootstrap phase 0 [0.08 sec, 7.34 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.08 sec, 7.34 MB]
 [success] No site aliases found. [0.08 sec, 7.37 MB]

So I convinced Drush to see the site alias file, but the alias itself is not loading.

When I try to use the alias:

✔ rk:/tmp/drushtest> vendor/bin/drush @remoteproject.remotesite.dev status -debug --config=drush.yml
 [preflight] The alias @remoteproject.remotesite.dev could not be found.

Is this conceptually wrong? (Having only Drush and calling remote site using site alias.) Am I just missing some option? Or is this ready to be "promoted" to Github bug report / feature request?

Thanks!

If your Drush 9 alias file is remoteproject.site.yml, and it has keys like live:, then your alias should be @remoteproject.live.

If you have multiple remote sites, do not put them in the same .yml file in Drush 9. Make one file per site, e.g. remotesite1.site.yml, remotesite2.site.yml and so on.

Use ./vendor/bin/drush sa to see the list of aliases found by Drush.


Using jQuery to copy some content from div to input value - value displays nicely but there`s no value in html I've got a webform in a block (using webform pay and webform block) which printing in a overridden template via module_invoke.

There is a simple price field (input). In the content type i`ve got a price field also.
I am using this kind of script to copy value from node's price div to another input field in a block:

$(document).ready(function(){
  var txt = $('.field-field-price .field-item').html();
  var txt = jQuery.trim(txt);
  $('#edit-submitted-price').val(txt);
});

The needed value displays just fine but in html value="" and i just can`t submit the form with needed value in price field. The screen-shot is attached. Thanks in advance for your time and understanding!

The value attribute for text inputs determine the initial value, it does not change when the user inputs something in the field or when it's changed by JavaScript.

If you are experience some error, it's most likely something else that's the problem.


Global Variable with a dynamic value set by variable_get() in multisite My question is, if I have a multisite environment what is the expected behaviour of global variables set like:

define('GLOBAL_VARIABLE' , variable_get('myvar'));

'myvar' is set in a module configuration page, all the sites share the same module.
Will each site use an independent value for 'GLOBAL_VARIABLE'? Which is what I want, each site to have different values for these global variables.

I can't seem to find any documentation on how this would work, or any previous questions either. It's something that would significantly affect how my module is structured, as there's a rather large amount of customization settings.

Any input is greatly appreciated.

If you are running true multisite, then your sites are sharing the same code, but not the same database catalogs.

If you are in a situation where you only have access to a single database catalog, then you can use prefixes to keep all of your instances separate.

It is also possible to share tables in the same database catalog between multiple sites.  This is primarily meant for the {users} table, and cousins.  Sharing anything else, is likely a recipe for disaster.

So, to answer your question, the {variables} tables in a true multisite instance will be distinct unless you went out of your way to share them.

If you are using the Domain Access module to share some content between sites, then everything is really in the same database, and you will have a single {variables} table.

Now, you have the sample code

define('GLOBAL_VARIABLE', variable_get('myvar'));

This is not really a good idea; just use variable_get('myvar') wherever you need it.  If you have a lot of settings, then I would consider wrapping everything up in a singleton with a getter function that uses drupal_static().


Use hook twice in a single module I have created a custom module with some inc files for different functionalities, these inc files adds config pages for admin but i had to define all urls in .module file.

is it possible to use hook_menu in inc files as well, i already used it once in .module file. what i need is menu should be added from inc file itself.

You couldn't implement a single hook in the module twice.

Instead you can define a custom helper function like _MODULE_include_menu() in the .inc file and then use it in the main .module like:

function MODULE_menu() {
  $items = array();
  $items += _MODULE_include_menu();
  return $items;
}


How to add multiple terms to a taxonomy reference field via feeds? I would like to import a node with multiple taxonomy terms referenced in one of node fields.
How can I do this with Feeds and Drupal 7 ?

Use the Feeds Tamper module to "explode" the comma-delimited list of taxonomy terms into individual references.

  Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below.
  Additional plugins can be added in separate modules or through the issue queue.


I want to define a hover color in the style sheet I designed a page with the corporateclean theme on http://www.athleticedgefitness.com/. I used nice menus for the drop down. Now I would like to color all my links #E3007B on hover, but I'm not exactly sure how I can get this accomplished. Any help would be appreciated!

Just put this in the css of your subtheme ("styles.css" i think):

a:hover, li:hover {color:#E3007B !important;}


Drupal commerce "family group" Is there a way to create "familly group" in drupal commerce, like with an image and a description ( looks like a product ) and when you select it in shop you've got a list with all the product with this image in different shape ( with price, ... )

I guess there must be a module for that,  i don't think this is very special.

If someone know what I can do, please tell me.

Thank you

I think what you are talking about is the concept of product variations introduced by Commerce Kickstart 2.0.  Product variations allow you to group together commerce products based on choices like size and color and price.  So for example say you create a Product Variation Type called T-Shirt.   You can group together the different sizes.

There are a few ways to get this done.  You can install Commerce Kickstart 2 and follow their tutorials.

You can install their stand alone module called commerce_backoffice and its dependencies.  I recommend the book Getting Started With Drupal Commerce by Richard Jones for an explanation of how to use back office.

As a note, I started out trying to get all of the functionality I wanted from the stand alone, but found that it was better to use Commerce Kickstart 2.0


Cant remove description field for new taxonomy terms Ive created a new taxonomy vocabulary. For some reason I cant remove the description field for the terms, but I only need the title field.

Is this a bug or impossible to do or are the settings hidden somewhere strange? Thanks

The description field is a main field. The equivalent to the body field in a node. If you dont need it you have 2 options.

1) You can just ignore it
2) You can use hook_form_alter to hide it for this (or all vocabularies)

There is no setting 'hide description field). If you want to hide the field from the form altogether let me know and I can explain hook_form_alter if you need me to. Otherwise when I don't need a description field in my taxonomy terms, i just leave it blank.

Edit to include the hook form alter

Information on hook_form_alter can be found here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7

This can go either in your theme's template.php or a custom module, I'm going to assume your theme, and rather than the standard hook_form_alter we'll use hook_form_FORM_ID_alter

/*
* Implementation of hook_form_FORM_ID_alter
*
* Hiding taxonomy term description field
*/

function YOUR_THEME_NAME_form_taxonomy_form_term_alter(&$form, &$form_state) {
  $form['description']['#access'] = FALSE;
}

Just change theme name for module name if your using a module


Problem blocking users in Drupal 6 I have encountered a weird problem in a Drupal site. Whenever I try to ban an abusive user, by going to the user's profile, change his status from active to blocked, and click save, the change does not take effect. Instead I just get a server time out message. There are a couple of thousands of users so disability to ban abusive ones is quite a hassle. Any suggestion to solve this?

Do it in the actual database, not via Drupal but via CLI, PHPMyAdmin, or whatever you have.

Find out the user's ID.
Go in to the raw database, i.e. not via Drupal but via CLI, PHPMyAdmin.
Go the user table.
Find their ID.
Set the status field for that user to 0 (which means blocked).

The raw SQL would be something like (I haven't tested this):

UPDATE users SET status = 0  WHERE id = [user's id]


Session API Security Advisory I'm working on a website that is interested in adding chat features. I did some research, and ended up installing the DrupalChat module, and its dependencies. After configuring the module, I realized it would not work for anonymous users unless I also installed the Session API module.

My concern is that on the Session API module information page, it displays a banner stating that

  This project is not covered by Drupal’s security advisory policy.

I have not run into this issue before, so I'm not sure how leery I should be to use the Session API module?

Does this mean it's likely to receive a future update to address pending security issues? Should I use some other method of adding chat to the web site? If so, any recommendations?

Basically all this means is that the module maintainers haven't opted into Security Advisory Coverage yet. Seems they haven't even opened an application in the review queue.

I asked them to do so in a new issue. As also Acquia does not recommend implementing modules not covered under the Security Advisory Policy (article). Pantheon takes that as a red flag (article), too.

But I wouldn't be worried too much. Just remember to always update this module first. But yeah, I'm not a security expert :)


Create a Modal popup with buttons I am having issues opening a modal with buttons using OpenModalDialogCommand.
It says in the docs of that command, that it can take as it's 3rd param any Jquery UI option (from http://api.jqueryui.com/dialog/) and it works well, for width/height/class, but anything more advanced i hit a wall. I am trying to make a button but can't figure it out.

$response = new AjaxResponse();
$options = [
    'width' => '800',
    'height' => '300',
    'dialogClass' => 'no-close',
    'buttons' => [
      'text' => 'Proceed',
      'click' => 'function() {alert();}'
    ]
];

$response->addCommand(new OpenModalDialogCommand('Title', 'Body', $options));
return $response;

This returns a modal successfully, width is ok, height is ok, class is ok, but there is not button, i tried 3/4 variations of it with no luck.

~p.s. i know i can make a simple form with one button, and return that in the modal, but there has got to be a way to make this work.

Ok figured it out.

$options = [
    'dialogClass' => 'my-form',
    'buttons' => [
        'button1' => [
            'text' => 'Proceed',
            'id' => 'onClickDoSomething',
        ]
    ]
];

And then in the .js file just write a function which fires when clickcing on a selector with the id onClickDoSomething voila, it's working.


altering a hook_form_alter function Is it possible to use hook_form_alter() on a hook_form_alter() function already defined in another module?

For example, if I want to alter the output of the following hook from the menu module, can I define a function which allows me to alter the renderable array?

function menu_form_node_type_form_alter(&$form, $form_state) { ... }

I have looked at the documentation but can't seem to find anything that suggests this is allowed/possible.

Not as such, but you can just implement your own version of that alter hook to make the changes you need to, and make sure your implementation runs later on.

To do that you'll need to implement hook_module_implements_alter():

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Push your module's implementations of hook_form_alter(), and derivatives,
    // to last in the list. This will make it run after menu_form_node_type_form_alter()
    // so you can alter whatever you need to.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  // Make changes as usual
}


Invoking the rate module in views template file doesn't work I have installed both the Views and Rate modules. In the views-view-fields.tpl.php file, I put the following code.

$node = node_load($row->nid);
echo $node->content['rate_poll']['#value'];
echo $node->title;

There is no output for $node->content['rate_poll']['#value'], while the code outputs the node title. Why?

How can I output $node->content['rate_poll']['#value'] in views-view-fields.tpl.php, or other Views files?

The code you wrote doesn't work because $node->content['rate_poll']['#value'] is only present when the node is being viewed. The code that adds $node->content['rate_poll']['#value'] is in the implementation of hook_nodeapi(), and the code is executed when the operation is "view."

/**
 * Implements hook_nodeapi().
 */
function rate_nodeapi(&$node, $op, $a3, $a4) {
  // Adding the form to the node view
  if ($op == 'view') {
    $widgets = rate_get_active_widgets('node', $node->type, $a3);

    foreach ($widgets as $widget_id => $widget) {
      $widget_name = 'rate_' . $widget->name;
      _rate_check_widget($widget);

      $display_mode = $a3 ? $widget->teaser_display_mode : $widget->node_display_mode;

      $widget_code = array(
        '#value' => rate_generate_widget($widget_id, 'node', $node->nid, $display_mode),
        '#weight' => $widget->node_display == RATE_DISPLAY_ABOVE_CONTENT ? 0 : 50,
      );

      if ($widget->node_display != RATE_DISPLAY_ABOVE_CONTENT && $widget->node_display != RATE_DISPLAY_BELOW_CONTENT) {
        $node->$widget_name = $widget_code;
      }
      else {
        $node->content[$widget_name] = $widget_code;
      }
    }
  }
}

For the code to work, you should change it to the following one.

$node = node_load($row->nid);
node_invoke_nodeapi($node, 'view', FALSE, TRUE);
echo $node->content['rate_poll']['#value'];
echo $node->title;

node_invoke_nodeapi() invokes any implementation of hook_nodeapi(), using its first parameter as operation value. Once the function returns, $node will contain any $node->content value added by the modules, including $node->content['rate_poll']['#value'].


Get term plain text aliased url from tid I realise that this is similar to other questions posted, but they all seem to involve using print l() to output a fully formed anchor.

What I need is just the uri, output in plain text to use directly in the node template. I nearly got there with the following, but end up with the unaliased version:

<?php
  if (isset($node->field_source_of_tid['und'][0]['tid']) && $node->field_source_of_tid['und'][0]['tid']) :
    $term=taxonomy_term_load($node->field_source_of_tid['und'][0]['tid']);
    $term_uri = taxonomy_term_uri($term);
    $output = $term_uri['path'];
endif; ?>

And I use the output as so:

<a href="<?php print render($output); ?>">A BUTTON </a>

Any ideas?

Thanks!

You're probably looking for url()

  Generates an internal or external URL.

e.g.

$output = url($term_uri['path']);


How to print add to cart form for drupal 8 commerce on my custom page programatically I have a site where I created a custom page to list products (can't use views module due to custom requirements for printing that list). On the list page for each product I have variation sku available. I want to show add to cart form with qty field on this custom list page. I have searched for a solution but couldn't find one for drupal 8. I know how to do it in drupal 7 but can someone help me with how we can have this in D8?

I got solution to the above problem. I used a drupal commerce service to load the form. Below is the code which I used, please let me know if it is an acceptable solution.

$commerceProduct = \Drupal::service('commerce_product.lazy_builders');
$cart_array = $commerceProduct->addToCartForm($product_id, 'teaser', true, $language);

This gave me a renderable array which I rendered using render service. Add to cart form is working fine.