How to troubleshooting a D7 website that doesn't load (Gateway Timeout) A website of mine, using D7, suddenly doesn't load. I always receive a Gateway Timeout error.

The strange is that with a ftp client I can browse the website as usual

What are the steps I should follow to troubleshooting this situation?

I solved the problem disabling the Database logging module.

I had the same problem also in another website (D7 + Database logging module, solved disabling the Database logging module)

Hope this helps.


Custom contraint validator: show an error message with a link We use a custom constraint on a custom entity type. In this entity type we have a string field "url basis" which is used to create aliases for many kinds of pages and data related to this entity.
Therefore it is important that this url basis is unique with every single entity. Here is the constraint:
class UniqueParliamentBasisUrl extends Constraint {
  public $notUniqueURLBasis = 'The basis URL needs to be unqiue but the set basis URL %basisurl is already in use: @parliament_link';
}

In UniqueParliamentBasisUrlValidator->validate() I try the following:
    $link = $parliament_using_basis_url->toLink($parliament_using_basis_url->label(), 'edit-form', ['attributes' => ['target' => '_blank']])->toString();
    $this->context->addViolation($constraint->notUniqueURLBasis, ['%basisurl' => $item->value, '@parliament_link' => $link]);

Here $link becomes the HTML markup for a link so that the user can easily switch to the entity which already uses this url basis in order to edit it. Unfortunately the markup becomes escaped so that the user does not see a clickable link on the form but the markup:
The basis URL needs to be unqiue but the set basis URL bundestag is already in use: Bundestag

Is there a way to add markup to the violation message without being escaped?

You shouldn't chain up placeholders / use HTML inside placeholders. And for URLs use the :placeholder notation with double dots
 $notUniqueURLBasis = 'The basis URL needs to be unqiue but the set basis URL %basisurl is already in use: @link_text';

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/class/FormattableMarkup/8.2.x
and
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8.2.x


Can a block span more than one region in a theme? Can a block span more than one region in a theme? Sometimes I would like content to do this, depending on the page.

I'm aware (and heavily use) Panels which are great but I thought it would be worth considering other solutions.

Not by default, but the MultiBlock module will solve this for you, out of the box.


How to manually use Drupal 7's admin Overlay? I am thinking of using Drupal's built-in admin overlay jQuery script to overlay my own contents. Is it possible?

You can also use the Overlay Paths module. This is a simple module that enables administrators to use the built-in Overlay for non-admin pages. This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.


*Some* Users Experiencing Login Failures A significant minority of our users repeatedly experience login failures and have to reset their passwords every time. Can anyone suggest possible solutions please? Details as follows.

Apparently, the behaviour is as follows:

User opens login page, enters valid username and password.
Login fails, repeatedly!
User requests password reset. Then, using link from e-mail able to: reset password, login and access their account
Next login, user has to repeat process.

Unfortunately, we can't duplicate the issue ourselves. But we have looked through Drupal logs and Apache access logs and observed the following:

The problem is not confined to a specific browser (seen on IE, Safari, Firefox) nor a specific OS (seen on Windows, Mac, iPad)
The users do generally have cookies turned on. We have inserted some custom code to warn users with cookies turned off and write "cookies disabled" to Drupal logs.
Clearing all caches in Drupal doesn't fix issue.
Clearing cookies in browser doesn't fix issue either, one of our users has tried.

We are running Apache on an Ubuntu server.

In settings.php, $base_url is commented out; $cookie_domain is also commented out. It was set, but we decided it was safer to remove it although, I'm not sure that made any difference.

We are using "Profile2" and "Profile2 Registration Path" modules. However, I doubt those modules are the source of our problems as I cannot find any record of anyone else having login problems with those modules.

Do you have any suggestion?

I should have mentioned, the site is running Drupal 7.13.

When the user clicks on the password reset link they are currently prompted to change their password.

We have also asked one user to try another browser but sadly, that didn't fix their problem. Also we have noticed that the problem on IE, Firefox & Safari so, we don't think it's browser specific

I would ask one of the people who has had this problem to work through it with you. Do a skype screenshare or look over their shoulder while they experience the problem.

In my experience, these people are not clicking "save" after entering a new password so their password isn't actually getting changed.


getting around recursion when dumping a node? I'm working on a template and I'm using kpr() from devel to look at the values defined in $variables. One of them is the node in question, and what gets displayed is a big infinity sign indicating recursion.

Is there any way to get around this to have a look at what data I actually have available in the node object?

What is it in the node that creates the recursion?

You cannot get around this in the sense that kpr($variables) will always display this unless you hack the implementation of krumo (the library that kpr uses).

Use

kpr($variables['node'])

to display the node instead.

Also, the node page has a devel tab that does exactly this.


Conditional Fields module with Google Maps I'm trying to initially hide a geofield created with Geofield module using Conditional Fields that uses the Geolocation Field Google Maps Input Widget.

If I click on one of my conditional fields to show the Google Map Input Widget, it shows the Google Map Input with a grey background.  If you resize the browser, the map tiles show again.

Does anyone know of a way to hook into the javascript somehow to reinitialize the Google Map when it is shown?

I added a possible solution at https://www.drupal.org/node/1277888#comment-11680473.  Hope that helps someone.


Adding JS to a form within Omega 4 theme I need to add some JavaScript to forms within my Omega 4 theme.  My code right now is:

function mytheme_preprocess_form(&$vars) {
    $vars['element']['#attached']['js'][] = 'path/to/myjs';
}

This isn't working, but it seems like it should.  I need to do this from my theme.  I don't want to use drupal_add_js(), since that's being deprecated.

You cannot do what you want to do in the form preprocessor.

Try using hook_form_alter() instead.

Keep reading for more information on why your current code doesn't work.

If you look at drupal_render() you can see that it runs this to theme the element:

if (isset($elements['#theme'])) {
  $elements['#children'] = theme($elements['#theme'], $elements);
}

This call to theme() is pretty much where your preprocess code code is running.

The output of that theme function (theme_form() outputs a string of form markup) is then going into $elements['#children'].

Then further down in drupal_render() it does this:

if (!empty($elements['#attached'])) {
  drupal_process_attached($elements);
}

But the #attached code you added never ended up back in the $elements of the drupal_render() function though so nothing happened.


Is it a bug? blog-View read more button reference to home page I manually created a blog which is a view page with 3 manually-picked fields:

image
title
body

The body field got a read more link, yet instead of pointing to the specific node listed in the blog, it lists to the home pages.

I didn't track anything that would cause it. Maybe I'm missing something:

Further information:

I also tried to insert the token [node:nid] but no change was seen.

The problem here is 2 issues:

You're missing a field on your view to reference. In order to reference the Node ID in your view you'll need to add the field Content: ID so that it can be referenced in replacement patterns. It will also need to be ordered before your body field so that its value can referenced. You can use the Exclude from display option if you do not want it appearing in your view.
The format for token replacement has changed with D8. It's now Twig-like: {{ field_name }}. By default the Content: ID field should use the field name nid so your More link path value should be /node/{{ nid }}.


Add rel="nofollow" to menu displayed by menu_block module I am trying to add rel="nofollow" attribute to menu links output by the menu_block module.

My core menu is called Main Menu, which I do not want to modify as it is used for main navigation. However the product level of this menu is output in the footer by Menu Block module, and it is these links I want to add an attribute to.

Thanks.

If you use different menus then:

There's a module for that(tm) Menu Attributes

If it's the same menu then things get farm more complicated as you'll have to implement some hook. Take a look at hook_menu_block_tree_alter in menu_block.api.php.


What does the votingapi_set_votes function in the votingapi module actually do? I am trying to use the Voting API module to add a vote through a menu item. Meaning that when someone visits a menu item [the/menu/item] a vote is added to the database.

There is already the Voting API functions that does that. I don't understand what the votingapi_set_votes function in the Voting API module does.

I have read the website documentation however I don't understand what it does and how can I use it. And couldn't find an example of usage either.

I have tried the follwing to add a vote:

  $items['the/menu/path/1'] = array
  (
  'title' => 'Some title',
  'page callback' => 'my_page',
  'access callback' => TRUE
);

return $items;
}

function my_page(){

  $votes = array();
  $votes[] = array(
    'content_type' => 'news',
    'content_id' => 1025,
    'value_type' => 'points',
    'value' => '1',
  );

  $criteria = array(
    'content_type' => 'news',
    'content_id' => 1025,
    'function' => 'sum',
    'value_type' => 'points',
  );

  if (TRUE) {
    if (module_exists('votingapi')) {
      // die("test");
      votingapi_set_votes($votes);
      die();
      $result = (votingapi_select_results($criteria));
      print 'result is: '.$result[0][value];
      $result = '';
    }
  }
  return "true";
}

But it gives me an SQL error like so:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'content_type' in 'where clause': SELECT votingapi_vote.* FROM
  {votingapi_vote} votingapi_vote WHERE (content_type =
  :db_condition_placeholder_0) AND (content_id =
  :db_condition_placeholder_1) AND (value_type =
  :db_condition_placeholder_2) AND (uid = :db_condition_placeholder_3) ;
  Array ( [:db_condition_placeholder_0] => news
  [:db_condition_placeholder_1] => 1025 [:db_condition_placeholder_2] =>
  points [:db_condition_placeholder_3] => 130 ) in
  votingapi_votingapi_storage_select_votes() (line 225 of
  C:\Users\tarek.ismail\public\egyptinnovate\sites\all\modules\contrib\votingapi\votingapi.module).

Here is a working example:

function YourModule_menu(){
  $items = array();
  $items['the/menu/path/1'] = array
    (
    'title' => 'Voting button',
    'page callback' => '_YourModule_voting',
    'access callback' => TRUE
    'type' => MENU_CALLBACK,

    );
  return $items;
}

function _YourModule_voting(){
  $nid=arg(3);
  $votes = array(
    'entity_type' => 'node',
    'entity_id' => $nid,
    'value_type' => "points",
    'value' => 1,
    'tag' => "like",
    );

  $criteria = NULL;

  if (module_exists('votingapi')) {
      votingapi_set_votes($votes);
  }

  return "true";
}


Image uploads seem to be timing out I hate asking a vague question like this but I'm really at loss as to my current problem. I'm setting up a new site and image uploads fail on my production site (both in custom and content type forms). The failure occurs when a file is sufficiently large (greater than ~4mb). I believe the failure has more to do with something timing out rather than a limit to file size. At my office where the connection is good I can upload an 8mb image but on my slower home connection I can't upload more than a 4mb image. The upload seems to consistently timeout at about 20 seconds.

When the upload fails the form itself doesn't provide any feedback. The little blue spinner just disappears and the remove button never appears. The only feedback I receive is through the browser's console. I'm getting a HTTP Result Code: 400 error. Paths are good because like I said I'm able to successfully upload when the image or file is sufficiently small.

My relevant php settings are:

max_execution_time 300
max_input_time -1
post_max_size 18M
upload_max_filesize 16M

I'm able to confirm these php settings through a phpinfo.php page so I'm reasonably confident it's not this.

I'm running Drupal 8.7.6 on CentOS7 with PHP 7.2.21.

Does anyone have a good guess as to what my problem could be? I'm sorry this is vague and most likely not an issue with Drupal. Thanks, I appreciate any hints you might provide.

Set your max_execution_time 300 to -1 which is unlimited or can increase according to your need.
And memory_limit to 1024M or more.


Drupal 7 and google maps, distribution or modules Throughout my apprenticeship with Drupal 7 I always wondered if it is able to do this:

http://www.teslamotors.com/findus
http://bigblogmap.com/

I mean inserting Google map and how it interacts with such websites.

For example: in Teslamotors page, at the top there are buttons: "N. AMERICA EUROPE and ASIA / PACIFIC "and that by giving clik in each, the map is changed geographical position.

Another example that I'm interested in this page (teslamotors) is seen as the pinmaps update when I press the buttons (which are at the bottom center of the map inside): "STORES & GALLERIES" or "service centers." Geographical points are updated and change color.

Similarly we can see the same for the second page I share, on the button: "All Blogs" and see how the updated pinmaps position icons and very dynamic.

Can this be done with Drupal 7? Maybe, I do not know, and there is a distribution which contains all this attached, so I can analyze it and go familiarizing myself more with this fascinating Drupal platform.

Both the Open Layers project and the Gmap module support google maps. Both can work with a number of geolocation types. See the modules for more details.

I am using both (in different sites) and either one can support what you are trying to accomplish. I would recommend Open Layers as more versatile, and Gmap as easier to use.


Converting url() to routing based URL I am converting a simple module from Drupal 7 to Drupal 8 and I used the Drupal Module Upgrader to do this. The code has been reformatted and some @FIXME notes have been added, I have no experience developing modules though and I'm not sure what to do.

When I search for more info concerning my problem I found this link https://www.drupal.org/node/2346779 but I'm not sure how to rewrite my code snippet exactly.

This is the .module file.

/**
 * @file
 * The littlurl module does little urls.
 */

/**
 * Implements hook_menu().
 */
function littlurl_menu() {
  $items['n'] = array(
    'title' => 'Forward n to node',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['u'] = array(
    'title' => 'Forward u to user',
    'access arguments' => array('access user profiles'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['t'] = array(
    'title' => 'Forward t to taxonomy/term',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Page callback to forward people along their merry way.
 */
function littlurl_forward() {
  // Get the elements of the URL.
  $args = explode('/', $_GET['q']);

  // Get the elements of the query string.
  $query_string = $_GET;
  unset($query_string['q']);

  if (count($args) > 1) {
    switch ($args[0]) {
      case 'u':
        $args[0] = 'user';
        break;

      case 't':
        $args[0] = 'taxonomy/term';
        break;

      case 'n':
      default:
        $args[0] = 'node';
        break;
    }
    // It's easier to use url than deal with drupal_goto's arguments.
    // @FIXME
// url() expects a route name or an external URI.
// $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

    drupal_goto($destination_url);
  }
  else {
    // This should never happen.
    drupal_goto('<front>');
  }
}

This is the Controller.php file. It has the same code the .module file has. Should I remove the redundant code snipped from the .module file?

/**
 * @file
 * Contains \Drupal\littlurl\Controller\DefaultController.
 */

namespace Drupal\littlurl\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the littlurl module.
 */
class DefaultController extends ControllerBase {

  public function littlurl_forward() {
    // Get the elements of the URL.
    $args = explode('/', $_GET['q']);

    // Get the elements of the query string.
    $query_string = $_GET;
    unset($query_string['q']);

    if (count($args) > 1) {
      switch ($args[0]) {
        case 'u':
          $args[0] = 'user';
          break;

        case 't':
          $args[0] = 'taxonomy/term';
          break;

        case 'n':
        default:
          $args[0] = 'node';
          break;
      }
      // It's easier to use url than deal with drupal_goto's arguments.
      // @FIXME
      // url() expects a route name or an external URI.
      // $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

      drupal_goto($destination_url);
    }
    else {
      // This should never happen.
      drupal_goto('<front>');
    }
  }

}

This is a routing.yml file. It seems to be linking to the controller.

littlurl.forward:
  path: /t
  defaults:
    _title: 'Forward t to taxonomy/term'
    _controller: '\Drupal\littlurl\Controller\DefaultController::littlurl_forward'
  requirements:
    _permission: 'access content'

The hooks/functions you shown for the .module file can be removed, since Drupal 8 doesn't use hook_menu(); therefore, Drupal will not use the littlurl_forward() function defined from the module.
The code in the Controller.php file needs to be rewritten for Drupal 8, since:

It should not access $_GET['q']
Instead of drupal_goto(), it should use the redirect() method of the controller

The first point means you should have three different methods you assign to the three different paths, which makes also more sense. It doesn't sense to assign the same method to three different paths, and the method then still need to understand for which path is being called.
As side notes, keep in mind that:

If you are editing a module that is already installed, or any of its files, you need to uninstall it first, since Drupal keep in a cache the list of hooks the module is implementing

The method of a class should not be named like lower_case(), but camelCase()

From the code you are showing, it seems you are redirecting from n to node; if that is the case, then you can simply use a path alias

If instead you are redirecting from /n/node-id to /node/node-id, then it is probably better to use the Pathauto module which creates path aliases for nodes, taxonomy terms, and users (and lets you decide which pattern to use for those path aliases)

If the routes you are defining get arguments, you should define them in the routes, such as /n/{node}

If all the routes are doing is allowing to use /n/node-id instead of /node/node-id, I don't see much of a reason to write the code just for that


changing unicode characters in a module There are hundreds of records in a database that are in windows-1256 charset, I want to read these data and convert them to utf8 then insert them in a new table, to read these data I need to change the MySQL unicode to latin1 and convert the data to utf8. from this link I successfully did this.
Now I need to insert these data into database and their charset must be utf8, the problem is $database variable in settings.php have this configuration

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB_NAME',
      'username' => 'PASSWORD',
      'password' => 'PASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'collation' => 'latin1_general_ci',
      'pdo' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES latin1",
      )
    ),
  ),
);

and in database/mysql/database.inc line 57 changed to this:

if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES latin1 COLLATE ' . $connection_options['collation']);
}

so because of this new database configuration, insertion the converted records (to utf8) doesn't provide the desire result (because MySQL is latin1 now), I need to reset the database configuration to its origin just before inserting the data. how do I can do this?

UPDATE:

the only solution I have found so far, is to create another database in utf8 and using external connection move the data into there !!!

1) run query
ALTER DATABASE DB_NAME DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
on your data base

2) change line

  'collation' => 'latin1_general_ci'

in settings.php to

  'collation' => 'utf8_general_ci'

and line

  PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES latin1"

to

  PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"


#ajax response handler function Hi I am using #ajax in my custom form. I need a response handler function for my form in jquery. How can i acheive this goal?

For example:

$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
  'one' => 'one',
  'two' => 'two',
  'three' => 'three',
),
'#ajax' => array(
  'callback' => 'ajax_example_simplest_callback',
  'wrapper' => 'replace_textfield_div',
 ),
);

Here i have the ajax_example_simplest_callback in php. I need a response handler in js.

Try this

(function($) {

  Drupal.YOUR_MODULE_NAME = {
    form_id: 'FORM_ID'
  };

  Drupal.behaviors.YOUR_MODULE_NAME = {
   attach: function(context, settings) {

    for (ajax_el in settings.ajax) {
      if (Drupal.ajax[ajax_el].element.form) {
        if (Drupal.ajax[ajax_el].element.form.id === Drupal.YOUR_MODULE_NAME.form_id) {
          Drupal.ajax[ajax_el].success = Drupal.YOUR_MODULE_NAME.success;
       }
      }
     }
    }
   };

 Drupal.YOUR_MODULE_NAME.success = function (response, status) {
    // HERE YOU GET THE response
 }

 });


How to disable modules using config split? I have created different split for each environement (local, dev, test, prod) using the Configuration Split module. How can manage modules (enable/disable) in each environment?

Should I keep core.extensions.yml in each split and remove the module to be uninstalled from the list?

The core.extension.yml should only be put into the default, shared config. As it only holds those modules, that are enabled across all your different environments.

$config_directories['sync'] = '../config/sync/default/shared';

This default Drupal config sync directory also has the config_split.config_split.local.yml in it, which defines which modules apart from the ones in the core.extension.yml should be enabled additionally when the local split is active.

uuid: abc123456-7890-abcd-906d-abc123456
langcode: en
status: false
dependencies: {  }
id: local
label: Local
folder: ../config/sync/default/local
module:
  browsersync: 0
  devel: 0
  features_ui: 0
  field_ui: 0
  kint: 0
  link_css: 0
  masquerade: 0
  views_ui: 0
  webprofiler: 0
theme: {  }
blacklist: {  }
graylist: {  }
graylist_dependents: true
graylist_skip_equal: true
weight: 0

Then, inside each environment's settings.local.php you have to define which split in addition to the default, shared config should be active and which not. Here's how it may be configured on your local machine:

$config['config_split.config_split.local']['status'] = TRUE;
$config['config_split.config_split.dev']['status']   = FALSE;
$config['config_split.config_split.stage']['status'] = FALSE;
$config['config_split.config_split.prod']['status']  = FALSE;

The core.extension.yml only holds those modules that are shared among all your different environments.


How do I render an image from a Twig template? I cannot get this to render out. This is what I get with {{ kint(paragraph.field_image.value) }}.

If this makes any difference, the image is uploaded through a media entity browser widget.

How do I render an image from a Twig template?

you could just use {{ content.field_image }}

Here is an example of a template file from a paragraph

{%
  set classes = [
  'paragraph',
  'paragraph--type--' ~ paragraph.bundle|clean_class,
  view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}
{% block paragraph %}

  {% block content %}

              {{ content.image }}

  {% endblock %}

{% endblock paragraph %}

Notice that I only need to write {{ content.FIELDNAME }}, if I wrap everything in a {% block content %}


How to create "Add to my List"? I have a movie site and I want users to be able to add movies (node) to their list by visiting the movie and it should have a link saying "Add to my list". When they are about to add to their list it should have a selection box with options like watching, completed, on-hold etc...

An example site http://myanimelist.net/anime.php?id=269 you can see when you click their "Add to my List" it gives some more options like status, eps seen, score

So how can I do this?

I would recommend using the Flag module, as it provides this functionality for users upon install. The Nodequeue module is intended for admin-configured lists.


Let Composer place a Git repo into a custom path How to place git repo to a custom path? I am using composer/Installer. and I have develop a module on git repo. I would like to add it to composer.json but after pull it should be placed web/modules/custom directory. How can i do that.

I added this parts in my composer.json

"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/miteshmap/axelerant_custom"
    }
],

"require": {
    "miteshmap/axelerant_custom": "*"
},
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/modules/custom/{$name}": ["type:drupal-module"],
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"]
    }
}

"require": {
    "composer/installers": "dev-master",
    "miteshmap/axelerant_custom": "*"
},
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/modules/custom/{$name}": ["type:drupal-custom-module"]
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
        "drush/contrib/{$name}": ["type:drupal-drush"],
    }
}

We can do that when composer/installers have defined the type and for that a request was merged with master here - https://github.com/composer/installers/pull/269

And to add the new merge of composer/installers into your json. you can update the composer.json as per the The solution proposed here - https://github.com/drupal-composer/drupal-project/pull/118. The same is explained in above code.


Error after updating Webform from 8.x-5.0-beta15 to 8.x-5.0-rc1 A Drupal 8 site hosted on Pantheon gives this error message after updating Webform from 8.x-5.0-beta15 to 8.x-5.0-rc1:

The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to Drupal\webform\WebformTokenManager::__construct() must implement interface Drupal\Core\Config\ConfigFactoryInterface, instance of Drupal\Core\Extension\ModuleHandler given, called in /srv/bindings/261ff5c4a9e04814be06a20de36ae33a/code/core/lib/Drupal/Component/DependencyInjection/Container.php on line 266 in Drupal\webform\WebformTokenManager->__construct() (line 46 of modules/webform/src/WebformTokenManager.php).

The site is completely down at that point and we have to revert to a backup.
Any suggestions?

Yes, flushing the cache via Drush should solve the problem.

If you can't use Drush, you must put your site in maintenance mode, set $update_free_access=TRUE, and run the pending updates via /update.php.

Also see

http://www.zymphonies.com/blog/update-drupal8-core
https://www.drupal.org/project/webform/issues/2907960


Passing a Solr search query to a view When a user enters a search query into an Apache Solr Search box, is it possible to pass that query onto a view - specifically to a Apache Solr Views view?

While you could technically do this by implementing a hook_form_alter, to capture and overwrite the submit handler, if you're already using the Apache Solr Views module, you'd be better off creating an exposed filter, setting the exposed filters to display in a block, and then using that instead of the default search form block. You can do that without custom code.


Views Search is displaying no results behavior by default I've created a Drupal 7 Views Search page. It works overall. However, when there are no returned results I want it to display a message such as 'your search returned 0 results. try something else.' So I put that message in an unfiltered text area using 'advanced > no results behavior' but now it's showing that message by default before someone has even entered their search terms.

I want the search page to only show that message once they've entered a search term in the 'search: search terms' exposed filter criteria and it actually returns no results. I don't want it to display right when they get to the page.

Anyone know how to keep that from happening?

I assume you are using the "On empty input: Show none" option of the search terms filter.
In this case the view is actually still running but returning no results due to the filter, so you get the empty text displaying.

To stop that you can change the "Exposed form style" to "Input required".

Then the view will not run until a search term is entered, which means no unwanted empty text.


edite content type style I clone content type by using bundle copy module, but the view of the content type never the same as the first one, how can I clone the style too

Copy the template also. For example if you have a node--old-content-type.tpl.php file you'll need to copy it to node--new-content-type.tpl.php.


How can I link back to Term's page using Node Auto Term [NAT]? I'm using NAT on a content type called Profile configured as follows in the picture below. I've been able to use this in great ways in some views.

I see that when I do a dpm($var['node']) from theme_preprocess_node($vars) that I see a NAT entry in the debug output.

My question is how do I properly grab this tid and automatically create a link to the taxonomy term's page (/taxnonmy/term/503)?

Cross reference: https://www.drupal.org/node/2291797

This is the closest I've come but it's still sort of hack-ish.

 function MYTHEME_preprocess_field(&$vars) {

        $termid = "none";
    if (
        isset($vars['element']['#object']->nat) &&
        $vars['element']['#field_name'] == 'body' &&
        $vars['element']['#object']->type == 'instructor_profile'
        )
    {

    list($termid, $value) = each($vars['element']['#object']->nat);
    $vars['term_id'] = $termid;

    /* Use EFQ to determine how many nodes may have this taxonomy attached
    to it. I'm only interested in the count()*/
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_related_instructor_mention', 'tid', $termid)
    ->addMetaData('account', user_load(1));
    $count = $query->count()->execute();

    /* If there is information ($count>0), then show. If no links
    don't worry about it */
    if($count > 0) {

        $vars['items'][0]['#markup'] =
        "
" .
        "
More News
" . "
" .
        $vars['items'][0]['#markup'] ;
    }

}

    }


I need to reference a custom field I created in User Profile I used Drupal 7 computed fields to calculate weight loss. This is what I current have. Which works in a sense but only where the user inputs their initial weight and subtracts their current weight to track the total weight loss at the time of the input. But I need it to reference their initial weight from their user profile so that they only have to enter their current weight. One step process versus having to always enter the data that already exists. How can I achieve this?

Current Code which works great but two fields have to be filled in. Needs to reference field in user profile.

$entity_field[0]['value'] = ($entity->field_iweight['und'][0]['value']) - ($entity->field_current_weight_['und'][0]['value']);

Use the $user object to access the logged in user.

 global $user;
 $account = user_load($user->uid);

Now you can use $account->field_iweight['und'][0]['value'] (just an example) to access the weight or any other field from the user profile.

Updated code:

<?php
global $user;
$account = user_load($user->uid);
$entity_field[0]['value'] = $account->field_iweight['und'][0]['value'] - $entity->field_current_weight['und'][0]['value'];
?>


Add a variable to custom views template I have created a view that is grouped by taxonomy term and it displays exactly how I want it. But what I need to do is add the term ID that the view is grouped by as a class, I have the following custom views template created but the term ID is not available as a variable to use.

The template is views-view-unformatted--products.tpl.php where I have printed the title as the class of the wrapper I need to add the term ID instead (the title is actually the term name as this is what the view is grouped by.)

<div class=<?php print '$title)'; ?>>
  <?php if (!empty($title)): ?>

<?php print $title; ?>

  <?php endif; ?>

    <?php foreach ($rows as $id => $row): ?>
      <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
        <?php print $row; ?>

    <?php endforeach; ?>

I haven't time to actually investigate the details of this right now, but if you enable the devel module, put

<?php dpm(get_defined_vars()); ?>

somewhere in your template file somewhere, and then refresh the page twice you will get a list of available variables which you can then click on to expand and drill down into the arrays and objects.

If you still cannot find the tid anywhere to use, try adding the tid as a hidden field to your view, then it will definitely be in there somewhere for you to use.


How to display content where author matches connected user? is it possible to modify admin/content view to display only the content the connected user has created ?

If not , how to achieved that?

thanks to kevin

with contextual filters , selecting fixed value:

author == id of connected user


Print custom module in a block I want to print a custom module in a type of content already created through the interface. Is there any way to print it?

I have seen that one of the ways in drupal 7 to print the module is by using the 'module_invoke' function, is there any equivalent in drupal 8 to print in a twig template?

Thanks!

Copy Print's print.tpl.php file into module folder, and name it print--node--foo.tpl.php.

function foo_theme_registry_alter(&$theme_registry) {
    $theme_registry['print__node__foo']['template'] = 'print--node--foo';
    $theme_registry['print__node__foo']['path'] = drupal_get_path('module', 'foo');
}

Note: My module and content type share the same name of foo.


Content Update Option I'm using Drupal 7. I made a couple of content types and taxonomies. Is there any way to select multiple content in the same content type and modify their fields together?

For instance, I have account type with the fields: account number, test case, ...

I want to set multiple account contents' test case to the same value.

Note: the test case is just a field with a selection of test case names, sry about the confusion

If you're coding up test cases -- not really. You could build the nodes programatically with some test account numbers, etc. But, you'd have to do that by hand. There are alot of tutorials for SimpleTest and creating nodes in drupal.

If you need a GUI to alter many node fields at once, take a look at Views Bulk Operations (VBO).


What are the variables does one search for when trying to render a custom form? In Drupal 8, the following code renders the node creation form (node/add/page) when integrating it into a custom module:

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

We know the module in question is the Node module, which generates the content type page. What should I do to render the user creation form (/admin/people/create)?

I can easily change the code to the following, and replace 'node' with 'user' and 'page' with 'user'.

  ->getStorage('user')
  ->create(['type' => 'user']);

This would now render the user creation form. For me to come to the conclusion that it would render the user form was only a guess and apparently it works. But this problem solving approach will not work if I wanted to render some other form that might not be so obvious.

What does one have to grep for in the code base or other investigative work to come to the conclusion of the following 2 lines in the above code?

To answer your explicit question (and to reiterate what Clive said), there's no one thing that you could grep to conclude the arguments to change for the getStorage() & create() methods.

The above solution assumes:

You're looking for an entity form.
You're aware that EntityFormBuilderInterface::getForm() needs an entity object.
You can build an entity object with Drupal::entityTypeManager().

It's a specific solution to building entity forms. If you're looking for a method to find any arbitrary constructed form, this solution isn't going to help here.

The most generic thing one could search for to find such a form (an invoke it for rendering), is probably a label that is unique to the custom form, but it really depends on how the form is constructed (e.g. EntityFormBuilderInterface::getForm(), FormBuilderInterface::getForm(), or some arbitrary form array builder function).

If you're familiar with the pattern of construction, there might be some specific terms to search for (e.g. searching for classes implementing FormBuilderInterface or EntityFormBuilderInterface), but there's not going to be one search pattern that works for all forms.


The directory sites/default/files exists but is not writable and could not be made writable We've recently had a few problems with our server, which seem to have been all patched up by myself, my host, and the cPanel team. However, since then we have been having problems with sites/default/files. The problems are happening on the active site running D6, and our dev site, running D7 in a subdirectory at the moment. I'm assuming the problems are related, so after I figure out how to fix one site, I'm sure it will be a similar fix for the other.

On the D7 site, when I save a piece of content, I get the message:
The specified file temporary://filetLWqk4 could not be copied, because the destination directory is not properly configured

At admin/config/media/file-system, I'm seeing the error: The directory sites/default/files exists but is not writable and could not be made writable.

When clearing the cache, I get an error including: Warning: unlink(mysite/sites/default/files/js/wysiwyg/wysiwyg_tinymce_VxxRIlcaFmzHlghU8SsOGCZd5TC_PCxyhQAlqydMALE.js): Permission denied in drupal_unlink() (line 2197 of mysite/dev/includes/file.inc)

What I have read seems to indicate that this is the result of a permissions problem that people seem to have with some clean installs and server migrations. Neither of these cases apply to me, but I thought the solutions might. Most pages that I can find essentially recommend

chown -R www-data:www-data sites/default/files

and making sure that permissions are set to 755 or 775. I'm on centos, which uses apache instead of www-data, so I substituted it where appropriate, but I still have no luck.

I also just tried changing the permissions of sites/default/files to 777, and I'm still getting the error that it couldn't be written to.

Any ideas?

RHEL and Fedora (among others) may have SELinux security enable.  This will mask whatever the regular Unix permissions are showing.  If this is enabled and there is not a "rw" in the context for the files/ directory it will not be writable no matter which group, user or unix permissions are granted.  To see these "hidden" settings:

ls -laZ sites/default

drwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 .
drwxr-xr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 ..
-rwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0         default.settings.php
drwxrwsr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 files
-rwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_rw_content_t:s0 settings.php

To change the settings on files/ so it is writable:

sudo chcon -R -t httpd_sys_rw_content_t files

When the install is done reset the context using the same command with the original "http_sys_content_t" context.

fyi - This command will also be necessary to enable writes when installing themes under the "all" directory.


Theme taxonomy term page with template override I know this is far from duplicate but im a bit stupid.
I am trying to theme the terms page for each term for a specific vocabulary i created.
I 've used path auto when i was creating the terms so i have a specific path for each vocabulary term.

My website is using a subtheme that i created by copying and pasting the main theme which is ninesixty. So i have tried creating a new template for taxonomy terms like taxonomy-term--12.tpl.php added my html code and unfortunately the template wasnt overridden.
I have also tried to override the template using the template.php file with no luck.
 I dont want to use any module so any clear answer will be helpful.

You can use the below filename structure to create a taxonomy term template:

taxonomy-term--[vocabulary-machine-name|tid].tpl.php


Commerce Feeds Node Parser Problem: product SKU "missing" from mappings causing empty product displays I'm rebuilding a commerce site and I'm trying to use Commerce Feeds to bulk import my products. The issue that I'm having is that the node parser isn't mapping to the product SKU which is creating incomplete product displays. The title is imported, but most of the product display is empty until you manually set the SKU to the correct product. Doing this manually defeats the purpose of bulk importing them in the first place.

I even tried to import the working importer from my other site, but there the SKU mapping is labeled "Missing."

So, 1) what can I do that I don't have to manually set the SKU's for my products?

2) why is the product sku missing from the mapping options?

Found a similar problem in one of the issues, switched the dev version which solved my problem.


How to make all menu links without www? (shortened menu links) I've seen a few sites, not necissarily Drupal sites, in which the menu links, are without www. (that is the Cname DNS record).

Drupal 7 shortens links from http://www.barackobama.com to be www.barackobama.com

I am asking if it is possible to create links without the Cname even, I.E that the final result would be:

barackobama.com

Can be done from inside the Drupal GUI? If not, please at least example how will you do so from the .htaccess file?

No, this is something that is been handle at the server or DNS level. From the GUI, you do not have control of where you application (Drupal) can will run.

If you are running Apache you can add this code to your .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Source: Force drupal 7 to place "www" in front of urls


When should the "container" form element be used? The System module defines the container form element, but that form element is not documented in the Form API Reference.

When should that form element be used? What is its purpose?

It looks like it can be used when you want to wrap a part of the form in a div, for example to be able to add some classes to it.

Some examples from core are the following:

field_default_form()

// Also aid in theming of field widgets by rendering a classified container.
$addition[$field_name] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
     'field-type-' . drupal_html_class($field['type']),
     'field-name-' . drupal_html_class($field_name),
     'field-widget-' . drupal_html_class($instance['widget']['type']),
    ),
  ),
  '#weight' => $instance['widget']['weight'],
);

node_filter_form()

$form['filters']['status'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('clearfix')),
  '#prefix' => ($i ? '
' . t('and where') . '
' : ''),
);
$form['filters']['status']['filters'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('filters')),
);

search_form()

$form['basic'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('container-inline')),
);

Forms in Drupal 6 often used #prefix and #suffix on the first/last element to do this; this is a lot better because it is easier to add additional items or move them around.

I could use this in a few places in my own contributed modules, actually. ;)


How to enable Views caching for all pages instead of only the first page? Problem

I'm trying to cache my view (search specific). However doing so only caches a single page of results and stops me from changing pages either with the pager, or by manually changing the URL.

Has anyone else run into this problem? And if so how have you fixed it?

Details & Thoughts

The hyperlinks on the pager still look ok. It's just that using them only gives the first page of results so it seems to do nothing.

It seems like Drupal is only capable of caching a single page of results and then returns that for all queries.

For example: If I change the caching (signalling the cache needs to be rebuilt) then enter the URL for page 3 of views results, then it caches that instead of the first page and will only return that for all searches.

My Set-Up is:

View Based On: Search API index.
Caching: Search Specific | 1 Hour

And caching mechanism's I have running are:

Memcached
Authcache
Varnish

I don't think it's related to Authcache. If I turn it off I get the same problem. (I presume view caching is separate and un-related to caching based on users. Also see the next point.)

I'm running Authcache Debug and it's telling me that it can't cache the view because of a client form token. (I have an exposed form on the views page which will block Authcache.)

While I haven't used a search view, I ran into a similar problem with pagers. Views caching has two parts out of the box, query and render. The render cache was interfering with the pager. I think setting the Views caching to Search Specific is setting both query and render in one swoop.

I would try changing it to Time Based and caching the query, but not the render. Varnish will then be able to correctly cache the various pages of the view.


Programmatically create alias using pathauto for node Developing a site that allows users to post images (node type = my_image) to a specific category.  Basically, we create the categories and users submit images to them.

Users do not have menu or url permissions, we want to do this for them.  When a user is in a category, the drupal form is displayed on that page using drupal_render_children().

In HOOK_node_insert (type == my_image) we identify what category they were in and add it to the menu.  Following this we are trying to use pathauto_create_alias to generate the alias (based on title) but have been unsuccessful thus far (HOOK_node_update would, well update the alias).

Obviously, if we grant the user permission for menu and url, the alias is created.  We don't want the user to have direct access to the menu system nor aliasing.

Does anyone know the proper way to use pathauto_create_alias in the above scenario?

Basically to generate URL aliases in code using the pathauto module you would have something like this:

module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module

/*
   pathauto_create_alias($module, $op, $source, $data, $type, $language)
   @param $module: Your module name
   @param $op: The operation (insert, update, return, bulkupdate)
   @param $source: Internal Drupal path (i.e.: node/1)
   @param $data: Addition data used to generate a pathalias, in this case the node object
   @param $type: Type of content that will be used to match a pattern, defined in the backend url alias patterns
   @param $language: If you have a multlingual website, you need to pass the language for which you want to generate the url alias
*/

pathauto_create_alias('your_module_name', 'insert', 'node/1', array('node' => $node), $node->type, $language->language); // Language is optional


How to process a multiple values field (comma separated) in a Rules Action? I am using modules "SMS Framework",Clickatell for sending message and I have configured all the settings which was required. I have also created a rule where node (Article) be saved and send a message.

It is working good when I use single mobile number but unfortunately it is not working when I use multiple mobile number with comma separated.

The rules action calls sms_send, whose first argument is:

  The destination number.

i.e. singular. So the module doesn't have support for sending to multiple, comma-separated numbers in one go through rules. It is in alpha to be fair, so it's not likely to be fully-featured yet.

Two ways you could get around this limitation (there are probably more):

Create a custom rules action which splits the incoming string by comma, then loops over and calls sms_send on each. If you choose this method, contributing the code back to the project would I'm sure be greatly appreciated.
Restructure your workflow so the existing rule is invoked once, in a loop, for each phone number.


Protecting original images (D7, watermark, imagecache) My goal is to have watermarked images and protected originals for a node image field in D7.

How to add a watermark to images has already been explained: add watermark to all images uploaded in the site

What I'm missing is how to protect the original images! These are still available via direct url.

Someone solved the problem for D5: http://drupal.org/node/424068 but the mentioned rights are not present in D7 anymore.

An other approach is presented in the comments of this page: http://drupal.org/documentation/modules/file

Create a private filesystem
Change the field's filesystem to the private one
Use the content access module to protect the node (a), or
create a custom module and use the file_download() hook to prevent access (b).

Possibility (a) doesn't work for me as I don't want to protect the access to nodes, but only to the plain original image files. Possibility (b) hides the imagecached images as well.

You can try using an .htaccess to protect the directory containing the original images as mentioned at http://drupal.org/node/424068#comment-3149994


Alternative for Node Gallery in Drupal 7? Will I be able to have show an image gallery for a multiple value image field on the node display in drupal 7 with some alternative module?

http://drupal.org/project/node_gallery is only available for drupal 6

that´s anoying, every alternative that I´ve found is eighter abandoned or only for D6


How to test a sandbox module I found a sandbox module that I want to test.

What should I do to use it on my site?

The easiest thing to do is to get a version of git for your machine.  On Windows, TortiseGIt works reasonably well.  You can then use that to checkout a version of the sandbox module.  If there are patches, you can apply them to the module.  Then you just need to upload the module to your Drupal site with your normal methods (don't forget to run update.php).

A lot of this is made easier if you are using an IDE, as newer ones are well integrated with git.


How to send email to all members when a post is updated by user? I am creating  a rules to send an email when a (node with content type update) is updated which has field_og_audience as field and it is placed on the groups page using advanced form block.
I want to send an email when node (with content type update) is updated by user then all the members of the group(selected in the field_og_audience) should recieve an email.

EVENT

After saving new content

CONDITIONS

Entity is group content

Parameter: Entity: [node]

ACTIONS

Get group members from group audience
Parameter: Group content: [node]
Provides variables: Fetch a List of group members (group_members)

Loop
Parameter: List: [group-members]
List item: Get list of group members and their email ids (list_grp_members_emails)

Send mail Parameter: To: [list-grp-members-emails:mail], Subject: Notification: Content..., Message: Test


How customize update interval of aggregator module By default   update inteval of RSS aggregator in Core aggregator module start form 15 min, I mean 15 min is minimum value,

But I need update RSS aggregator shorter than 15 min,and update my feed each 2,5,10 minute too,

How can I set Update interval to what I required?

one solution is using alternative module like feeds module but it is not stable yet.

The update interval values for an Aggregator Feed is hardcoded into the Entity definition for the refresh field. You'll need to alter the definition to allow different values.

In a custom module, you can evoke hook_entity_base_field_info_alter() to alter the Feed definition to accept shorter intervals:

function MYMODULE_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->get('id') == 'aggregator_feed') {
    $definition = $fields['refresh']->getItemDefinition();
    $intervals = $definition->getSetting('allowed_values');
    $intervals = array(
      120 => '2 min',
      300 => '5 min',
      600 => '10 min',
    ) + $intervals;
    $intervals = $definition->setSetting('allowed_values', $intervals);
    $fields['refresh']->setItemDefinition($definition);
  }
}


Adding a new variation I'm building a store using the commerce kickstart drupal distribution and I'm a beginner with it, however do possess some alternative Drupal 7 experience. Now, I need to add a different product variation type but when I try to add one, I and I want to add a Images field to it, the default Machine name assigned it field_images and when I try to store my variation with this field, I get the message The machine-readable name is already in use. It must be unique. - Fair enough you would think, but if I go and check in the existing sample variation types, there's multiple existing variation types that use the exact same machine name, *field_images* this is, why is that? It puzzles me why I should not be able to do the same for a new variation type.

To add field_images to your product type, you need to use the "Add existing field" and not "Add a new field" Then the existing machine name is reused. Following that you can configure bundle specific settings under field "instance" settings, as opposed to the shared "global" field settings.


Do not cache custom block I have a custom block created in code. I do not want to cache the block. I know I need to use BLOCK_NO_CACHE but I am not sure where to use it.

function mymod_block($op = 'list', $delta = 0)
{
    // set up an empty array which will contain the block contents
    $block = array();
    if ($op == "list") {
        // Generate listing of blocks from this module, for the admin/block page
        $block[0]["info"] = t('mymod');
    }
    else if ($op == 'view') {
        $block['content'] = "hello world";
    }
    // return the built content
    return $block;
}

In your list $op, add:

$block[0]['cache'] = BLOCK_NO_CACHE;

However, note that Drupal 6 will not automatically update your block information, you will have to do that yourself, see privatemsg_update_6002() for an example.


View conditional logic based on dropdown value I have a view that is outputting fields from a paragraph. I want to be able to output different markup. There are two available values in the dropdown

1|Wrapping Link
2|Internal Link

and they should determine if the markup is wrapped by a link or if the same link is a contained within the markup as a stand-alone link.

In my custom version of views-view-fields.html.twig I want to have some logic in place that will check the value of the dropdown and display the correct markup. I have tried the following but this is invalid.

{%- if {{ fields.field_banner_type.content }} = "1" -%}
    // wrapping link
{%- else -%}
    // no wrapping link
{%- endif %}

No need to {{ fields.field_banner_type.content }} inside if statement use fields.field_banner_type.content like the following:

{% if fields.field_banner_type.content == "1" %}
  {# wrapping link #}
{% else %}
  {# no wrapping link #}
{% endif %}

For more info See Twig if Documentation


jquery slide toggle - affects all on the page I have a view with a list of a content type and using drupal behaviors and jquery toggle, I trying to toggle some content when the user clicks a div. The only problem is that it's affecting all the divs and they're all toggling open, I'd just like the one they clicked to open.

Here is my code:

(function ($) {
 Drupal.behaviors.myToggle = {
  attach: function(context, settings) {
  $('.views-row').find('.views-field-field-mp3').hide();

    $('.mp3-toggle', context).click(function() {
     $('.views-field-field-mp3').slideToggle();
    });
  }
 };
})(jQuery);

I've tried return false and a couple of other things, though none seem to work.

Any help would be much appreciated.

You'll need to make use of the this keyword inside your click function:

 Drupal.behaviors.myToggle = {
   attach: function(context, settings) {
     $('.views-row').find('.views-field-field-mp3').hide();

     $('.mp3-toggle', context).click(function() {
       $(this).parents('.views-row').find('.views-field-field-mp3').slideToggle();
     });
   }
 };


Custom template for 404 error pages A quick noob question here! How to set a theme to use a custom template for 404 error pages instead of using page.tpl ?

Yet another solution from this discussion that works without panels or other custom modules.

In your theme folder locate template.php and write this code. Replace YOURTHEME with the name of your theme:

function YOURTHEME_preprocess_page(&$vars) {
  $header = drupal_get_http_header('status');
  if ($header == '404 Not Found') {
    $vars['theme_hook_suggestions'][] = 'page__404';
  }
}

Whenever 404 occurs your page--404.tpl.php will be used. Remember to put "--" not "__" in your template file name.


Limit taxonomy terms display on hierarchical select I need to limit the taxonomy terms visible in a field type 'taxonomy term' using the module 'hierarchical_select' when creating a post.

There is a way to do this?

I have a vocabulary called 'cities' in this format:

state
-- City 1
-- City 2

I have a content type called 'condominiums' and this type of content I have a field called 'city' of type 'taxonomy term' (vocabulary cities) using the HS module.
I have a user with role 'city' and in this paper there is also a field called 'city' of type 'taxonomy term' (vocabulary cities) using the HS module.
I need the user with role 'city' look in the 'city' (when you create a new content) only city that is attributed to him.

Something like:

superadmin user (city 1) can see:

state
-- City 1
-- City 2

user city (city 2) can see:
state-
-- City 2

Tanks :)

Workbench Access module might be a great solution for your issue.

  Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.

  The module supports Taxonomy and Menu modules for the management of access hierarchies.

Also, take a look at the current issue for Hierarchical Select module integration with Workbench Access module


Get all fields for a content type using REST Is there any way to get all fields attached to an entity in D8 (including widget types), using REST services? I've tried the following endpoints, but none of them had the list of fields:

/entity/node_type/{node_type}
/entity/entity_form_display/{entity_form_display}
/entity/entity_form_mode/{entity_form_mode}

I need this if for an app that will generate dynamic forms, based on what's defined in the Drupal backend.

The /entity/entity_form_display/{entity_form_display} should works.

Example:

/entity/entity_form_display/node.article.default?_format=json

It will return json like this:

{
"uuid": "058dd73d-366d-466d-9393-ad0d5d44e928",
"langcode": "en",
"status": true,
"dependencies": {
    "config": [
        "field.field.node.article.body",
        "field.field.node.article.comment",
        "field.field.node.article.field_image",
        "field.field.node.article.field_location",
        "field.field.node.article.field_tags",
        "image.style.thumbnail",
        "node.type.article"
    ],
    "module": [
        "comment",
        "image",
        "path",
        "text"
    ]
},
"id": "node.article.default",
"targetEntityType": "node",
"bundle": "article",
"mode": "default",
"content": {
    "body": {
        "type": "text_textarea_with_summary",
        "weight": 1,
        "region": "content",
        "settings": {
            "rows": 9,
            "summary_rows": 3,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "comment": {
        "type": "comment_default",
        "weight": 20,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "created": {
        "type": "datetime_timestamp",
        "weight": 10,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "field_image": {
        "type": "image_image",
        "weight": 4,
        "region": "content",
        "settings": {
            "progress_indicator": "throbber",
            "preview_image_style": "thumbnail"
        },
        "third_party_settings": []
    },
    "field_location": {
        "weight": 121,
        "settings": [],
        "third_party_settings": [],
        "type": "options_select",
        "region": "content"
    },
    "field_tags": {
        "type": "entity_reference_autocomplete_tags",
        "weight": 3,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "path": {
        "type": "path",
        "weight": 30,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "promote": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 15,
        "region": "content",
        "third_party_settings": []
    },
    "status": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 120,
        "region": "content",
        "third_party_settings": []
    },
    "sticky": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 16,
        "region": "content",
        "third_party_settings": []
    },
    "title": {
        "type": "string_textfield",
        "weight": 0,
        "region": "content",
        "settings": {
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "uid": {
        "type": "entity_reference_autocomplete",
        "weight": 5,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    }
},
"hidden": []
}


Feeds import should delete non-existent nodes and not insert new nodes Use case:
Drupal 7
Importing nodes from an XML source.
Every Wednesday 18 PM: run import and add new nodes.
Every hour: run import and delete non-existent nodes AND do NOT add new nodes.

I'd appreciate some help since after a lot of testing and searching I'm still not getting this to work properly.

I'm using two importers: one to import (no problems) but I can't get the second one to delete any nodes.

EDIT: Sometimes trying to formulate the question for someone else, pops up new ideas!
Could the problem be that you simply can not use two feeds for one content type?

Short answer: importing nodes and deleting nodes no longer included in the feed needs to happen with the same importer.

Long answer:

When performing an import, Feeds indexes the imported items in the feeds_item table. Each item in this table belongs to a specific importer and - in case the importer was attached to a content type - also to a specific feed node.

When the importer is configured to clean up items that are no longer in the feed, it loads all item ID's into memory for that specific importer (and feed node) at the start of the import. During the import, Feeds crosses of each item from the clean list that it has seen.
At the end of the import, it cleans up the items that remained on the clean list.

When you use one importer to import a list of items, these items are then owned by that importer. When you then run a second importer for the same content type, it will own none of the items that were created/updated with the first importer at the start of the import. If the second importer doesn't own any of the items, there is nothing to delete after the import.

Note: ownership of items can be "transferred" from one importer to another. For example: items that were originally created by importer 1 and later updated by importer 2 are then owned by importer 2. If importer 1 updates them later, importer 1 owns them again.
So using two importers to update the same content makes the "delete non-existent" feature unpredictable.


Drupal 8 migrate language: switch all nodes to the default lang Where testing the migration from drupal 7 to drupal 8 and everything almost works, except i'm running into a language problem.

I have two different languages enabled in Drupal 7, English(Default) and Dutch, but only for the interface, there is no multi-language setup for nodes.

Now, when i imported the content in drupal 8 with the same two languages enabled, i get to see the content, but it is dived between three types:

Not specified
Dutch
English

I want to see all the content without selecting a language(via url, session, ..). So, how do change it so i can view my nodes without a language prefix in the url ?

I already tried messing with the database and changing the 'langcode' to 'und' and that works, but it breaks many other things. I just want to see site.tld/my-cool-url-alias without anything else.

You need to change your language selection criteria in this admin setting:

Admin -> Configuration -> Regional & Language -> Language / Detection and Selection Tab

You can turn off or configure the URL settings as you want.  With no standard detection, the default language should be shown.

You probably want to turn on the administration language detection option.  This allows admin users to select their preferred admin language.


Roles in Features: Are they always imported in alphabetical order? This is a request for more information outside of what was given here: User roles and keeping their IDs when using features

Basically, it's the age-old problem of storing Roles in Features, and then migrating or importing them into a new site.

Based on some observations of mine when putting roles into a feature failed, it seems like Drupal takes the Role Feature and imports the stored roles in alphabetical order.

For example, I have some roles on my site that I stored into a feature. They had been originally created and added to my development site in this order:

administrator
moderator
subscriber
training
announcer
blogger
manager

However, when I migrated the Features code to a new version of the site on a fresh database install, Drupal took the roles Feature I created, and imported the roles it contained in the following order:

administrator RID -> 3
announcer RID -> 4
blogger RID -> 5
manager RID -> 6
moderator RID -> 7
subscriber RID -> 8
training RID -> 9

Is this normal behavior? And, if I just organize my roles into Features in alphabetical order, can I expect them to always be reimported in the same proper RID heirarchy?

Roles being imported in alphabetical order has been my experience, too.

But counting on autoincrement IDs to be consistent between multiple sites is never a good idea.

I recommend, instead of relying on the autoincrement IDs to be generated in a particular order, to avoid using autoincrement IDs.

For Drupal 6 and Drupal 7, the Role Export module turns Role IDs into hashes of machine names, so they're consistent from site to site, regardless of import order.
For Drupal 8, work is in progress to eliminate autoincrement Role IDs altogether.


How can I float a specific field to the right of another field For example, I have one field in my content type that is a boolean value of "Is this employee certified" next to this field I'd like a Pop-up Date that shows the expiration field. I've created both fields for my content type but I have not seen anything in the CSS that allows my to float or align fields. Any help would be greatly appreciated.

Can I do this with Views? Or with CSS? Thank you

You can just use CSS for this. You will need to find the specific element ID or class for the containing element (div for example) for each of the fields (you can find this out using Firebug with Firefox), then create a CSS rule for each of those elements such as:

#field1 {
  float:left;
  width:150px;
}

#field2 {
  float:left;
  width:150px;
}

You will probably need to then use the CSS rule clear:left; for the field or element that follows after them.


Specifying parameters for block_load UPDATE: Following Shawn Conn's advice I was able to render a specific block changing

$res_output = drupal_render($res_output);

to

$res_output = drupal_render($output);

But I'm still unable to render a Book Navigation block. I was able to figure out how to render a specific block using the url to it's management page. On a block with the url

https://example.com/admin/structure/block/manage/block/103/configure

I used

$block = block_load('block', '103');

and that worked. However based on

https://example.com/admin/structure/block/manage/book/navigation/configure

I tried

$block = block_load('block', 'navigation');

and

$block = block_load('book', 'navigation');

and

$block = block_load('block', 'book','navigation');

with no luck.

I'm attempting to load a Book Navigation block programmatically inside another block. After doing some research it seems that I need to take advantage of the bload_load function. I'm using

$block = block_load('book', 'navigation');
$output =_block_get_renderable_array(_block_render_blocks(array($block)));
$res_output = drupal_render($res_output);
print render($res_output);

However there is no output. I have a feeling that the parameters for block_load are incorrect. I based them off of what the URL contained

/admin/structure/block/manage/book/navigation/configure

The problem isn't with block_load(); you've specified the correct parameters with the function (the module is 'block' & the delta for the block is 'navigation'). The problem is your typo prevents the render array going to the print_render(). It should be:

$res_output = drupal_render($output);


Is there any gain using Memcached module when APC is running good on large Drupal 7 site (one server) I am successfully using the APC Cache module on my prod website (single server). APC is performing good, caching is done very well. I wonder could I gain anything more by implementing Memcache.

I tried it briefly on dev server, I see they can run one with another (Memcached Admin shows many hits in log). But i do not see any performance gain (haven't done precise measurements).

I should mention it is pretty large site, i use 256MB for APC (sometimes cache use is almost full), there is many content types, fields, nodes(over 10k), contrib modules (425 tables in db).

I am pasting at the end of the question my settings.php config (dev, prod just have not memcached implemented). There seems not much logic if i use cache_default_class twice, as Memcache will be used (declared lately).

So - have anyone used those two together when using one server? Is there any performance gain ? What are config ?

In addition, Memcached Readme.txt suggests using

$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

but APC Readme.txt does not suggest that. I wonder why ?

Here is my code (using APC for Drupal backend cache)

# APC
$conf['cache_backends'] = array('sites/all/modules/contrib/apc/drupal_apc_cache.inc');
$conf['cache_default_class'] = 'DrupalAPCCache';
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

# Memcache
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Putting the cache_form on the database is a good idea. I will help to prevent errors like this: http://drupal.org/node/500646

APC vs Memcache when it comes to the drupal cache mainly comes down to a persons preference. Mine is towards memcache because it allows for a multiple web head server setup. Performance wise APC will usually be a touch quicker, but my vote is still for memcache even on single server setups.


Can't use file field in custom form - gives AJAX errors I'm building my own form for editing certain fields on a node type, and I'm using field_attach_form() to add the fields from that node type to my form.

Use field_attach_form() to get the fields added to the $form array, and then I hide the ones I don't need by setting them to '#access' => FALSE. For all the textual fields, selects, etc., there's no problem. But when I use a file field (for image uploads), and someone selects a file and clicks 'Upload' on that file field, I get the following two errors:

Notice: Undefined index: field_picture in file_ajax_upload() (line 268 of /path/to/drupal/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 277 of /path/to/drupal/modules/file/file.module).

I noticed over on drupal.org, merlinofchaos mentioned that a user could use form_load_include() to include an include that needs to be loaded with the particular form (see: http://drupal.org/node/1161430#comment-4540578), but that was more because that guy additionally had something else he was loading, I think.

The form is built in mymodule.pages.inc, and is called through a menu callback at a path like /admin/config/mymodule/edit-form. What am I missing?

This is a bug in Drupal. The patch in comment #6 works.


How to add a new user permission "Translate own nodes" ? Looking for this Translation own nodes module but for Drupal 7.

The goal is to create a new permission to "Translate own nodes".

The basic method followed by that module should work (custom access callback + hook_menu_alter), but the code would need updating for D7.

From a quick scan of the code (so there may be other things that need updating) hook_perm is now hook_permission and hook_nodeapi has been replaced by serveral hooks (in this case only the 'prepare' op is used, so hook_node_prepare is the only one required here).


Alter site logo path using drush I'm using drush to automatically build Drupal 7 sites.  I want to have each of the new generated sites use a custom logo.  I've been searching for a drush command that will allow me to set the path for the logo to a folder in the .../sites/siteName/files/  folder, but cant find one.  Can this be done with drush?

No, there's no such command AFAIK.

Logo path is stored in the variable table along with all theme settings as an array. For example, My Theme will store all its settings, including log_path, in the theme_my_theme_settings.

If you know all the settings for the theme you can use the vset drush command to set your theme settings variable with the right value.

This is an example of a theme settings variable value for a subtheme from Zen theme:

array (
  'toggle_logo' => 1,
  'toggle_name' => 0,
  'toggle_slogan' => 0,
  'toggle_node_user_picture' => 0,
  'toggle_comment_user_picture' => 1,
  'toggle_favicon' => 1,
  'toggle_main_menu' => 0,
  'toggle_secondary_menu' => 0,
  'default_logo' => 1,
  'logo_path' => '',
  'logo_upload' => '',
  'default_favicon' => 0,
  'favicon_path' => 'public://favicon_1.ico',
  'favicon_upload' => '',
  'zen_breadcrumb' => 'yes',
  'zen_breadcrumb_separator' => ' › ',
  'zen_breadcrumb_home' => 1,
  'zen_breadcrumb_trailing' => 0,
  'zen_breadcrumb_title' => 1,
  'zen_skip_link_anchor' => 'main-menu',
  'zen_skip_link_text' => 'Jump to navigation',
  'zen_html5_respond_meta' =>
  array (
    'respond' => 'respond',
    'html5' => 'html5',
    'meta' => 'meta',
  ),
  'zen_rebuild_registry' => 0,
  'zen_wireframes' => 0,
  'favicon_mimetype' => 'image/vnd.microsoft.icon',
)

If you want to use vset with an array see this hint:

php -r "print json_encode(array('drupal', 'simpletest', 'leftandright', 'category'));"  | drush vset --format=json project_dependency_excluded_dependencies -


Views: Insert Profile2 information in a node I have a  problem and here's my graphical illustration of it:

I have tried many things that didn't work. I think the answer has something to do with adding a relationship with a node field, but I don't know how to get it to work here.

You need to have an entity reference field on the node type that allows you to reference a user as the creator of the necklace.
Then you want a node view that has a contextual filter of nid, that uses node id from the url as a default value when no contextual filter value is provided.
Then you can add a relationship to the user via the entity reference field you added.
Then add a relationship for the profile2 profile, so you can use the profile fields in your view.
Add a block view display.
Add the block to your node pages.


How to redirect all URLs to a new domain I'm shutting down an old site and want to redirect all URLs to the homepage of a new domain. Is there a module or quick php snippet that can do just that?

The problem with trying to do it with PHP or a module is that PHP doesn't handle every request; for example, if someone deep linked to a file, no PHP solution would help.

So the easiest (and most complete) way to do this is actually with Apache (or whatever web server you happen to be using):

RewriteEngine on
RewriteCond %{HTTP_HOST} ^old\.example\.com$
RewriteRule ^(.*)$ http://new.example.com/ [R=301,L]

You can do this in the host configuration file or the .htaccess file: assuming the old site is a Drupal site, you'll want to place everything except the first line immediately after RewriteEngine On (around line 58 in Drupal 7.x).


Ubercart product quantity count in product view page show as smsung 2/10 sold? I added a product and say it has count of ten(of that product), If one is bought, then I want to show in the product view page out of 10/1 sold like that.

Is there any contributed modules available, or custom way to do it? I can add the quantity as field in the product content type, but what do I do after that?

This is not an answer, but you can find the stock level using the below code, just put in the node.tpl.php, and print the var $stock_html in a proper place, probably in node-product.tpl.php <?php print $stock_html ?>  .

<?php
if ($node->type == 'product') {
  $arr_sku = uc_stock_skus($node->nid);
  $stock_html .='
';
  foreach($arr_sku as $sku){
    $stocklevel = uc_stock_level($sku);
    if ($stocklevel) {
      if ($stocklevel < 1) {
        $stocklevel = ''.$stocklevel.'';
      }
      $stock_html .='
'.$sku.'	:&nbsp;&nbsp;'.$stocklevel.'
';
    }
  }
  $stock_html .='
';
}
?>

or you can try this http://www.ubercart.org/comment/60577


Content field value as background color I have a content type with 4 fields

1.featured_pic
2.company_logo
3.background_color

I'm using views for the teaser rewriting the result.

           {{ featured_pic }}

      {{ company_logo }}

However the background color is not being picked up. How can I use it as an inline style value.

or is it possible to pass the value {{ background_color }} to jquery

Looks like the Views text area filters style="anything" out to prevent XSS attacks. If you create a template file for your view, I believe it will work.

As pointed out by @4K4

  If you put a twig variable inside of a style attribute standard
  sanitizing won't prevent . To protect against this you need to
  filter even brackets. See XSS attacks and style attributes

Therefore, you need to make sure your field is not a text field, where the user has the power to write/put whatever they want. You should use a Select list field or better yet use a color field.


How can I find out the machine names of user variables? I'm creating a custom user profile page and I know how to print certain items attached to the user like

$user_profile['user_picture']

but I don't know the names of any of the other fields. Is there a way that I can view a list of user profile field machine names?

All of the user variables are located in configuration->People->Account Settings->Manage Fields. So simply look at them over there.


Render tokens in hook_node_view I am creating the following pseudo field in hook_node_view:

function user_guides_node_view($node, $view_mode, $langcode) {
    $node->content['field_mytest'] = array('#markup' => '
This is my test

[current-page:title]
');
}

This is the rendered result:

This is my test
[current-page:title]

How can I get the value of the token to be displayed instead of the token itself?

You can use token_replace() for that. As you're using a global token (no context required) it's very simple:

$markup = token_replace('
This is my test

[current-page:title]
');
$node->content['field_mytest']['#markup'] = $markup;


Breaking on to new lines? If I have a long line of code that exceeds 80 characters, like this:

$last_response = '' . t('Last response: ') . '' . format_interval((time() - $last), 1) . t(' ago');

Should I break it on to a new line and indent once? I'm sure I've read this in the coding standards somewhere, but now I cannot find where I read it, if I did, like this.

$last_response = '' . t('Last response: ') . ''
  . format_interval((time() - $last), 1) . t(' ago');

The answer is yes, you should break and indent.

For the more details, including exceptions to this rule, see the official Drupal coding standards on line length and wrapping and indenting.

A handy tool to check whether your source code follow the official Drupal codings standards is Coder.  It is also available as SaaS, as part of PAreview.


Other related content block using taxonomy I have a content type call "procedure" and a taxonomy vocabulary call "services". I was able to build a block using Views that will show me all the related nodes sharing the same term from the vocabulary "services".

Now, I want to build a block showing "other procedures" that will list the nodes not sharing the same term, but having terms from the same vocabulary "services".

Note: in the first block I use the "Has term ID" argument and the "NID" argument.

I don't see how can I "negate" an argument. What am I missing?

I finally figured it out.

Add the fields to your view (title, body, etc)
add a relationship to "Taxonomy terms on the node" (do not check required)
add the arguments (now contextual filters) the "Taxonomy term: Term ID" (use relationship)
set "Provide default value" to "Taxonomy term ID from URL"
uncheck (to save on the load, optional) "Load default filter from term page"
check "Load default filter from node page, that's good for related taxonomy blocks"
set the "Limit terms by vocabulary" and pick the vocabularies
select "Filter to items that share any term"
Scroll down to the "More" section and check "exclude" that way all TIDs will be shown, but the one on the argument.

Note: I also added the exclusion on the NID of the node where I am showing the block with the other related nodes tags with terms from the same vocabulary.

Thank you.


Load Aegir's site credentials from a php function I'm using Aegir and want to inject some data into a site's vhost.
And I managed to do it thanks to this post.

My problem is I can't find an Aegir function to load a site's dabase configurations from this Aegir functions listing to do it programmatically on each site-verify.

I need to find a function or method that would return a site's data:

db_name
db_user
db_passwd
etc

I tried Provision_Config('mysite.com') but I have a template argument missing error.

Does anyone know which function I should use to get the data?
I usually use drush sql-connect in ssh, but here I'm not sure it would be a clean way as it should be in a php script.

The goal is to make Drupal work with multi-site / multi-folder (I'm aware of that post and patch, but my solution seems to work for me without having to patch anything):

<VirtualHost *:80>
  DocumentRoot /var/aegir/platforms/myplatform

  ServerName mysite1.com
  SetEnv db_type  mysql
  SetEnv db_name  mydbname_1
  SetEnv db_user  mydbname_1
  SetEnv db_passwd  *********
  SetEnv db_host  localhost
  SetEnv db_port  9854

  # Credentials from other Aegir's site
  # located in a subfolder /blog.
  <Location /blog>
    SetEnv db_type  mysql
    SetEnv db_name  mydbname_2
    SetEnv db_user  mydbname_2
    SetEnv db_passwd  *********
    SetEnv db_host  localhost
    SetEnv db_port  1258
  </Location>

</VirtualHost>

Installing sites in sub-directories is supported in Aegir 2+ without any such hacking. Just enable the "Site subdirectories" feature, under the 'experimental' group at admin/hosting/features.

That said, to answer your question, DB credentials are available via drush_get_context('site').


Different currency per-product in Ubercart Vanilla ubercart configuration allows a single currency for all products, how can I use a different currency per-product. For example, I want to use USD for books and GBP for electronics, both in display and payment processing.

P.S. I don't think it is a duplicate of Multiple currency  displayed in ubercart product page :P

There isn't really a good way of dealing with this. One thing you need to figure out is what to do if you have multiple currency in the cart, since ubercart, payment methods etc can't handle this.

If you want an alternative currency for some products, one way of doing that would be to add some options CCK fields which holds the price and currency. Then you could hook_currency_handler_alter and hook_currency_handler_format to handle how the price should be displayed.

This is no easy task and you need to alter a lot of things to make sure the proper context is available to be able to load the node and figure out how the price should be displayed.

In other words, it's a real pain in ubercart and there isn't a good way of doing this really. The above is probably the best solution though.


How do I show 2 images on row 1 and 3 images underneath on row 2 with Views? I need to create a page on my Drupal website which shows colleague images (colleague profile pics).

I want to position 2 colleagues pics next to each other on row 1 then underneath show 3 images on row 2, as shown in this picture:

I have set up a content type called Colleagues, which has fields of Title and Image. And I have set up a View to read that content and display the images, and the title underneath.

I can display them in whatever order I need, but how do I display them so that there are 2 at top and 3 underneath?

The only way I can think of is to add a field called Row Number, and create 2 Views for each row and display them accordingly, but that seems messy.

Can anyone help?

You can define attachment display of view, in which u can display only 2 images with offset 0 under Pager section. and in page you can define image to show as 3, with offset as 2.

As attachment loads above the page, so it will show the structure accordingly.


How do I put a taxonomy term on a panel page? I'd like to put several hand-picked taxonomy terms on a panels page, each term as a panels pane, showing their descriptions, with a more link to the term's view page, and maybe some of the fields that I have added.  Is there any module to do this?

Right now for each term I have to create a page, panelize it, add a view pane of the term to it, and then add the page to the panels I want them to show up. Seems to be working nicely enough but still too troublesome for ordinary editors to do it themselves.

Create a Page
Give it a %term argument and map it to a taxonomy term
Create a view pane that takes a taxonomy term as argument.
Create a mini panel that requires a taxonomy term argument.
Add the View to the mini panel. Configure it to use the taxonomy term.
Add the mini panel to the Page.


What is rewriting my user related URLs? My main username is 'bw_admin'. If I visit my login page at localhost:8888/mysite/?q=user I would be able to login but after my login I can't view the account page. Instead I get a HTTP500 internal server error. What I notice it that the underscore of my username is being deleted automatically so I would be getting localhost:8888/mysite/?q=user/bwadmin instead of localhost:8888/mysite/?q=user/bw_admin.

after getting the error if I would just edit the bad URL into the URL of the mainpage of the site I can go on while logged in as admin. But it's important for future user to not have this problem so they won't panic

Here's a list of the modules that I've installed in case this might be a typical problem related to a certain module.

addthis
addtoany
admin_menu
advanced_help
auto_nodetitle
autoload
cck
content_profile
context
ctools
devel
devel_themer
fckeditor
filefield
google_analytics
image
imageapi
imagecache
imagefield
imce
imce_wysiwyg
insert
jquery_ui
jquery_ui_dialog
jquery_update
lightbox2
menu_breadcrumb
module_filter
nice_menus
oauth
panels
pathauto
token
twitter
views
webform
wysiwyg
wysiwyg_imageupload

The module that creates a URL like localhost:8888/mysite/?q=user/bwadmin (or localhost:8888/mysite/user/bwadmin, with clean URLs enabled) is the Pathauto module, which creates path alias for user, node, and taxonomy term URLs.

Check the module settings; there is a set of options that allows replacing some specific characters that would cause some problems; one of those characters is the underscore. In your case, the module is set to strip off underscores from the path alias it generates.


How do I delete all menu links from a menu using the menu machine name in Drupal 8 I trying to get the existing menu items and then delete them in bulk but I'm getting an error trying to load them.

$query = \Drupal::entityQuery('menu_link')
->condition('menu_name', 'mycustommenu')
// Order by weight so as to be helpful for menus that are only one level deep.
->sort('weight');
$result = $query->execute();

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "menu_link" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 125 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

Can someone suggest how I might do this better thanks.

$mids = \Drupal::entityQuery('menu_link_content')
  ->condition('menu_name', 'browse')
  ->sort('weight')
  ->execute();

$controller = \Drupal::entityTypeManager()->getStorage('menu_link_content');
$entities = $controller->loadMultiple($mids);
$controller->delete($entities);


path aliases in drupal 7 I want to calculate the path aliases for array of nids. But it always give me the path for latest content. Actually I can not get all the nids. My array structure is like below. When I used the command product_childnid = array_pop(array_keys($result['node'])); I always get the 100 nid but I want all of them for path aliases.

Array
(
[node] => Array
    (
        [78] => stdClass Object
            (
                [nid] => 78
                [vid] => 78
                [type] => product
            )

        [80] => stdClass Object
            (
                [nid] => 80
                [vid] => 80
                [type] => product
            )

        [82] => stdClass Object
            (
                [nid] => 82
                [vid] => 82
                [type] => product
            )

        [84] => stdClass Object
            (
                [nid] => 84
                [vid] => 84
                [type] => product
            )

        [86] => stdClass Object
            (
                [nid] => 86
                [vid] => 86
                [type] => product
            )

        [88] => stdClass Object
            (
                [nid] => 88
                [vid] => 88
                [type] => product
            )

        [90] => stdClass Object
            (
                [nid] => 90
                [vid] => 90
                [type] => product
            )

        [92] => stdClass Object
            (
                [nid] => 92
                [vid] => 92
                [type] => product
            )

        [94] => stdClass Object
            (
                [nid] => 94
                [vid] => 94
                [type] => product
            )

        [100] => stdClass Object
            (
                [nid] => 100
                [vid] => 100
                [type] => product
              )
          )
  )

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'product');
$query->propertyCondition('status', 1);
$query->fieldCondition('field_product_sub_cat', 'tid',array($leaf_nodes));
$result = $query->execute();
if (isset($result['node']))
{
  $product_childnid = array_pop(array_keys($result['node']));
}
$path = 'node/'.$product_childnid;
$product_alias = drupal_get_path_alias($path);

You have to iterate over all nodes in $result to do that. array_pop() only returns the last item in $result. So you'll have to do something like this:

$paths = array();
if (isset($result['node']))
{
  foreach($result['node'] as $key => $node) {
    $paths[$node->nid] = drupal_get_path_alias("node/$node->nid");
  }
}

After this $paths will contain an array of keys that map to each node id with a value that corresponds to its alias path.


ajax update seperate page when a button is clicked on a popup I created a content type that is used to display a list of videos hosted on brightcove. I have a module that is setting a cookie for the anonymous user when they watch one.

I created a module that will display the video that they clicked in a popup. Inside this popup window there is a button to go to the next video. When they clicked the video that launched the initial popup I can use jquery to change a div class to get a viewed icon to appear next to the video link no problem.

When the "next video" button is clicked I have it play the next video in the same popup. However, I would like to have the "video viewed" icon appear without a refresh on the originating page.

You can see this in action at http://www.lynda.com when you watch one of their videos. You click a video on the course list, a popup appears and you can click the next video button. A viewed icon will appear without refresh on the course list (not the popup).

How do I use ajax in such a way that when a button is clicked it updates a different page? In the pop-up I am passing a video ID as well as the drupal node id of the course the video belongs to.

If you are using JavaScript to open your new window, you can assign that window a name and refer to its parent (or refer to it from the parent, as well). One site that explains this is at http://www.codeproject.com/Articles/25388/Accessing-parent-window-from-child-window-or-vice


Wysiwyg (ckeditor) disappeared after drush rr I was restructuring the modules directory (moving modules from /sites/all/modules/ to /sites/default/modules/) because we are adding a multi-site and do not want to share all the modules.  After moving them I ran drush rr in the /sites/default/ directory and then drush cc all for good measure.

Everything went fine except that now on all of the content editor forms the rich text editors are all gone.  I can click "switch to plain text editor" and it works fine, but CKEditor is now completely gone.

I tried doing drush pmu ckeditor and then drush en ckeditor -y and cleared cache again but for some reason the rich text editors still appear completely blank.

I checked the chrome inspector console for errors and found that the site is still looking in the /sites/all/ sub-directories for the module.

/sites/all/modules/custom/custom_cke_plugin/ckeditor/custom_cke_plugin/plugin.js?t=DAED Failed to load resource: the server responded with a status of 404 (Not Found)

ckeditor.js?nviice:219 Uncaught [CKEDITOR.resourceManager.load] Resource name "nyuslink" was not found at "/sites/all/modules/custom/custom_cke_plugin/ckeditor/custom_cke_plugin/plugin.js?t=DAED".

Has anyone had issues with moving CKEditor module and found any resolution?

Go to yourwebsite.com/admin/config/content/ckeditor/editg

In there you probably need to change the path to ckeditor. As you can see from the screen shot the %m stands for /sites/all/modules/ckeditor

so you need to erase %m/ckeditor and instead put /sites/default/modules/ckeditor/ckeditor

Click image to enlarge