Why when I do a configuration export does the config.tar.gz in tmp not get copied to the sync folder? This happens when I use the UI and drush cex. The config.tar.gz is created in the tmp folder but nothing is created in the sync folder that I created in sites/default.

I have searched for similar tickets here, on Drupal.org and searching in google! I find references to folder and file permissions (I have tried 777 on most) and references to a .htaccess file in the sites/default folder with specific content.

The content my .htaccess file in sites/default is:

# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>
# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
    # Override the handler again if we're run later in the evaluation list.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

I am using the DDEV environment to create docker containers on my local Ubuntu 10.04 VM (VirtualBox) on my Windows 10 PC. I use the DDEV default settings.php for Drupal 8. I then added the following lines:

// Config sync directory.
#$config_directories['sync']='sites/default';
$config_directories = array (
    CONFIG_SYNC_DIRECTORY => 'sites/default',
);

// Configure private file path
$settings['file_private_path']='sites/default/private';

// Configure trusted host patters to prevent HTTP HOST header attacks
$settings['trusted_host_patterns'] = [
    '^<projectname>\.ddev\.local$',
];

I have tried variations of the $config_directories definition including the commented out version. I also defined the sync directory to be 'sites/default/sync'. I have created the 'sites/default/sync' directory. I have tried deleting the config.tar.gz in the tmp directory which gives the log message 'The file tmp/config.tar.gz was not deleted because it does not exist.' and then creates the config.tar.gz file in the tmp directory.

I have tried find . -name *.tar.gz to search all the directories for any such files in case it has put it somewhere unexpected and no luck!

OK so for my versions:

Ubuntu 18.04, DDEV 0.18.0 (Nginx 1.14.0, PHP 7.1.16-1+0~20180405085551.16+jessie~1.gbp4937aa, Database 5.5.5-10.1.28-MariaDB ), Drupal 8.5.5. I have done these tests on a standard Drupal installation with the only additional module being Backup and Migrate 8.x-4.0. I have enabled a few of the core modules not enabled by the standard installation (e.g. Media).

There don't appear to be any messages in my latest Drupal error log for today (my most recent test of this bug).

Is there anything else I can supply that might help diagnose what I am doing wrong?

The best way to store configuration is to store it outside of Drupal root directory.

For example you will have next project structure:

Where:

config/sync is a directory with your sync configuration.
public_html is a directory with your Drupal 8.

In your setting.php just add this

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

And export your active configuration using drush

drush cex

That's all. In config/sync directory you will a files list of all your configuration.


How to automatically create nodes according to related content types? I am very new to Drupal. I have a situation where I have 3 content types, say A, B, C.

For each node instance of type A, there should be 3 corresponding nodes instances of type B. And for each instance of type B, there should be 5 corresponding nodes instances of type C. So in total 1 + 3 + 15 = 19 nodes.

Is it possible to automatically create the B and C node instances when the A node is created? And it is automatically possible to delete them if A is deleted? In other words, I would like to create tree-like instances of nodes.

Is this possible in Drupal? Is there a module for this, assuming I am creating the 3 content types A, B and C? Alternative solutions/ideas are welcome too.

In order to relate content to each other you could try Relations module. But you'll have to extend it in order to automatically create the linked node and delete them if the master node is deleted. Take a look over the docs of this module.


Ajax function not returning any html I'm trying to develop an Ajax process in a Drupal Module. Here's the code :

function My_Module_menu() {
  $items = array();

  $items['route/to/ajax/%'] = array(
    'page callback' => '_MY_MODULE_processing',
    'page arguments' => array(3),
    'type'  => MENU_CALLBACK,
    'access arguments' => array('acces content'),
    'delivery callback' => '_MY_MODULE_listing'
  );

  return $items;
}

function _MY_MODULE_processing($region='110') {

  // Executing some operations to retrieve a list of NIDs
  // retrieving the nodes
  $nodes = node_load_multiple ($nidList);
  return ($nodes) ;
}
/**
 * Here is the templating part
 * @param unknown $nodes
 */
function _MY_MODULE_listing ($nodes){
  $build = array();
  $nodeList='';
  foreach ( $nodes as $node ) {
    $nodeList = $nodeList.'<option value='.$node->nid.'>'.$node->title.'</option>';
  }
    $build['content'][]=array(
      '#prefix'=>'',
      '#suffix'=>'',
      '#markup'=>$nodeList,
    );

  return ($nodeList);
}

I don't get any response with this. I've run debugging function and it goes inside every function. First _MY_MODULE_processing then _MY_MODULE_listing.

How can i return a correct response ?

Got it. I returned the answer with ajax_deliver :

function mij_add_aide_list_proposition($nodes){
    // Magic stuff goes here (construction of $nodeList)
    $build['content'][]=array(
      '#prefix'=>'',
      '#suffix'=>'',
      '#markup'=>$nodeList,
    );

  //$test=drupal_render($build);
  ajax_deliver($build);
}

If someone finds another way, I'm open to any change !


How to write PHPUnit test for any function that has external dependencies? I have 1 function that returns value of any field of particular content type. For this I need to load my current user and a node from where I will retrieve value.

But loading user calls User class and when I run the test, it says undefined method - user_load.

My function is:

public static function get_ctype_field_value($field) {

    $user = user_load(\Drupal::currentUser()->id());
    $ulm = get_type_id($user); // another function in some class, return value 445
    $local_market = \Drupal\node\Entity\Node::load($ulm);
    $llf = '';
    if ($local_market) {
      // Get the field value from the LM.
      if ($local_market->hasField($field)) {
        $localmarket_field = $local_market->$field->value;
      }
    }
    return $localmarket_field;
  }

AND my test function is:

class MyControllerTest extends UnitTestCase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node'];

  /**
   * Users to use during this test.
   *
   * @var array
   */
  protected $users = [];

  /**
   * Nodes to use during this test.
   *
   * @var array
   */
  protected $nodes = [];

  protected function setUp() {
    parent::setUp();
    $container = new ContainerBuilder();
    $methods = get_class_methods('\Drupal\Core\Entity\EntityManager');

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

  }

  public function test_get_ctype_field_value() {
    $originalString = 'field_vat';
    $expectedResult = '10.00';
    $econtroller = new myController(); //controller where function resides
    $this->account->expects($this->once())
      ->method('user_load');
    $this->users[] = $this->account->load(1);
    $result = $econtroller->get_ctype_field_value($originalString);
    $this->assertEquals($expectedResult, $result);
  }
}

Please suggest any way to write PHPUnit test for this function.

The error I'm getting is:

  Error: Call to a member function load() on null

The code is dependent on Drupal's service container existing, and thus a container needs to be instantiated and used. This is possible in PHPUnit tests using the \Drupal::setContainer() method, and creating a container object.

use Drupal\Core\DependencyInjection\ContainerBuilder;

protected function setUp() {
  parent::setUp();

  $this->account = $this
    ->getMockBuilder('Drupal\user\Entity\User')
    ->disableOriginalConstructor()
    ->getMock();

  // Create a new container object.
  $container = new ContainerBuilder();

  // Add a service into it.
  $container->set('current_user', $this->account);

  // Let Drupal use your mock container.
  \Drupal::setContainer($container);
}


How to create a lightweight domain access alternative in Drupal 7 I have a password protected site mainly used for internal management of projects, but have regularly the need to publish some of its content for clients.

For simplicity sake, I would prefer to keep all content in the same database and site. However, the published content should be viewable from another domain name.

The contrib module 'Domain access' is too heavy for my needs. I'm looking for an alternative that 'simply' allows content to be published to a second domain using something like a setting or toggle per entity.

Experiences in this area are very welcome.

Out of the box drupal 7 installs are domain agnostic (don't save absolute urls in content or as paths). Assuming you haven't got any custom server directives or alternate domain with a need for a different relative url, you could try either:

A) Create a separate content type, if content managers know up front what content will need to be visible.

B) But if they don't know up front (and since you can't easily convert a node from one type to another), you could try using a taxonomy field to tag content for visibility. Then use taxonomy access lite module (https://www.drupal.org/project/tac_lite) to grant access to nodes tagged with a specific term to anonymous users.


Drupal website is broken on localhost I have moved a drupal website from live server to localhost.

But the problem I am facing is that everything is broken. no css, no images only text is visible on pages.

On my live website when I click on login button a popup for login appears. But on local host its not working. I have tried using different login URLs but non of them worked for me.

Here is a URL of one image : localhost/sites/default/files/Screen%20Shot%202015-02-24%20at%206.08.54%20PM_0.png

Similarly I have viewed source code of page and here are URLs of CSS and JavaScript files

localhost/sites/default/files/css/css_UCtZrZRD9npGm4D7o8VXPkl5qDJq-m8IlhuR9ccf_tY.css

localhost/sites/default/files/js/js_0gj6QcpfRH2jzTbCQqf7kEkm4MXY0UA_sRhwPc8jC1o.js

These images and files are not found in this location, is this a cache problem ? All these files and images are missing from this location : localhost/sites/default/files

  Note : Most of you are pointing me to following Path :

admin/config/media/file-system

  Here is what I have

Public file system path : sites/default/files
Temporary directory : /mnt/tmp/test

  Now should I make both these paths empty ? or change the path ?

It seems that drupal can't process your files due to not writeable file system paths.
Go to admin/config/media/file-system and specify public and temporary directories.
After that clear all cache here admin/config/development/performance.


How to redirect to content if view have 1 result? Views page show content.
How to redirect to content page if views has only one result?

In your theme's themename.theme file add:

At the very top add:

use Drupal\views\ViewExecutable;
use Symfony\Component\HttpFoundation\RedirectResponse;

Then add:

/*
 * Implements hook_views_pre_render()
 */
function THEMENAME_views_pre_render(ViewExecutable $view) {
    if($view->id() == "view_name" && $view->current_display == 'view_machine_name') {
      if (!empty($view->result) && count($view->result) == 1) {
        $url = $view->result[0]->_entity->toUrl()->toString();
        $response = new RedirectResponse($url);
        $response->send();
      }
    }
}

Clear the cache so changes kick in.

my_module/src/Controller/ViewPageController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Cache\CacheableRedirectResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Defines HelloController class.
 */
class ViewPageController extends ControllerBase {

  public function content() {

    $view = Views::getView('view_name');
    $view->setDisplay('view_machine_name');
    $view->execute();

    if (!empty($view->result) && count($view->result) == 1) {

      $url = $view->result[0]->_entity->toUrl()->toString(TRUE);
      $response = new CacheableRedirectResponse($url->getGeneratedUrl());
      $response->getCacheableMetadata()->addCacheTags($view->getCacheTags());
      $response->addCacheableDependency($url);
      return $response;

    }
    else {

      return [
        '#type' => 'view',
        '#name' => 'view_name',
        '#view' => $view,
        '#display_id' => 'view_machine_name',
        '#embed' => TRUE,
        '#cache' => $view->getCacheTags(),
      ];

    }

  }

}

This is the view_machine_name.


Custom pseudo field not rendered when no other field has content Usecase: I want to have a title field in view mode administration to be able to place it between some other fields. This field has different content depending on node type, view mode and some other fields which is handled by a custom function.

Solution so far:

 /**
 * Implements hook_entity_extra_field_info().
 */
function mymodule_entity_extra_field_info() {
  $extra = array();

  foreach (NodeType::loadMultiple() as $bundle) {
    $extra['node'][$bundle->Id()]['display']['mymdoule_title'] = array(
      'label' => t('Extra title'),
      'description' => t('Display the title of the node e.g. in teaser'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}

And then

/**
 * Implements hook_ENTITY_TYPE_view for nodes
 *
 *  - render our pseudo fields
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  // if our pseudo field is used we use our costum class to build the render array
  if ($display->getComponent('mymodule_title')) {
    $nodeCustomisation = new NodeCustomisation($entity);
    $nodeCustomisation->titleExtraField($build, $view_mode);
  }
}

It is working as I can see my pseudo field when I go to the view mode administration page of any content type. I can place the field somewhere and it is rendered.

Problem:
As soon as the pseudo field is the only field with content when viewing a node in this view mode nothing is rendered but the node wrapping <article>-tag from node.html.twig. The array {{ content }} in this twig template is empty although the pseudo field should have content for sure - when I add a node field to the view mode which has content I see my pseudo field again.

So I found my fault - when you describe a field the render array needs to have an array of field items. So the $build-array needs to look like this:

$build['igb_title'][] = array(
      '#type' => 'html_tag',
      '#tag' => 'h2,
      '#value' => $entity->label()
    );

In field_group_remove_empty_display_groups it is checked if a field as at least one item:

$has_items = isset($element[$name][0]);

If $has_items is false the field group is emptied if there is no other field with a value. I think I might need to go deeper into this render array thing...

Best,
Tobias


How to create a node revision view with a "Node" row style? Is it possible to create a node revision view with a "Node" row style?

This does not seem to be an option in the Views interface. "Fields" is the only options presented for this type of view. Is there a reason why this is not technically possible or is it just not currently implemented?

I believe the answer to my original question is no, it is not possible (please update if Views changes to allow this).

To accomplish what I needed, I ended up creating a custom module instead of using Views. I lifted the query that Views had generated as this was essentially what I needed. After returning the nid's of the nodes in question, I have drupal theme the nodes:

theme('node', $node, $teaser, $page);

Add each themed node to an array, $items, and then theme that array into an unordered list:

$rendered_list = theme('item_list', $items, NULL, 'ul', array());

I then set the block's content to that returned list.

$block['content'] = $rendered_list;


How do I hide the code of my theme? Is it possible to hide the code of the theme that I have created for my client? In other words, when I open the page with firebug I dont want to see the HTML and all the CSS of my theme, also when I click with the right mouse button.

No, the browser needs to download the markup and stylesheet to do its job, and you shouldn't try this kind of thing, It doesn't work and is annoying to site visitors.

Please read the answers on this similar StackOverflow question: https://stackoverflow.com/questions/6597224/how-to-hide-html-source


Illegal string offset block region I've made a custom module for Drupal 6 that has a custom form, which works perfectly.

I've tried to add the form in a block using the following code.

function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
    switch ($op) {
       case 'list':
          $blocks[0]['info'] = t('BLOCK INFO');
          return $blocks;
       case 'view':
          $blocks['content'] = drupal_get_form('mymodule_form');
          return $blocks;
   }
}

I can see the block in the admin page, and I can move the block to the different regions and everything seems to work, except for a list of warnings I get every time I change the region of the block.

  warning: Illegal string offset 'region' in block\block.admin.inc on line 101.
  warning: Illegal string offset 'status' in block\block.admin.inc on line 101.
  warning: Illegal string offset 'status' in block\block.admin.inc on line 102.
  warning: Illegal string offset 'weight' in block\block.admin.inc on line 103.

How can I fix these warnings?

I think these warnings happen because block.admin.inc is trying to access a non existent key ("region", "status"...etc). How can I remove said warnings? I have looked into some threads but their solutions have not worked for me.

The problem was due to the PHP version being used. It seems that Drupal 6 has some problems with PHP 5.4.


How can I add a new value to a multi-value field programmatically? I have a multi-value textfield that stores the user agent string.  I want to store the user agent every time the user logs in (this may not in fact be a good idea, but for sake of example).

The following code will save the user agent, but only in the first position. It replaces the old value instead of creating a new one.

function MYMODULE_user_login($account) {
  $account->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  $account->save();
}

How can I add a new value each time this is called?

Using this:

$account->get('field_useragent')->appendItem($_SERVER['HTTP_USER_AGENT']);

However, that doesn't seem like a good idea to me. Over time, that list will grow big, multi-value fields don't scale that well. All values are always loaded, on save, all values are inserted again into the database.

Maybe you want a list of unique user agents, but even that is hard to control with versions and so on. If you want a log, then save it somewhere else in your own table.

http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf doesn't have this yet, would probably make sense to add it.


How to add dynamic fields with condition? I have a website that is about automobiles, I want when a user choose a brand drupal shows some of its models:

This image show an example:

for example I want when a user selected BMW drupal shows BMW's models in other select tag dynamic. and for example selected Lamborghini  drupal shows Lamborghini's models.

I mean a tree stystem

I would recommend you to use any one of following modules.

Hierarchical Select

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Simple hierarchical select

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Taxonomy Term Reference Tree Widget

  This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


Block view for only the images uploaded to the image field of the current node I am working in Drupal 8.

I have a content type defined with an image field. For each page of that content type, I upload one or more images for its image field.

I want to create a block view in Views that presents images in a grid. How do I filter the block view so that the only images displayed are the ones for the image field of the current node? The block will be placed in the block layout for this content type. It is easy to create a view that creates a grid with images from all pages of this content type. I am stumped on how to filter the view so only images for the current mode are displayed.

Got it figured out. In Views, goto Advanced,Contextual Filters. Select Node ID. Select "Provide default value". Select "Content ID from URL".

To only display this field only using Views, goto Content Type, and under Manage Display, set the both the label and format for the image field to hidden.


Control the data facebook fetch and post on "share" I am building a drupal 7 site using Addthis module, Meta tag module and Open Graph meta tag module

When clicking on the facebook share button - facebook fetch the relevant image properly, but a lot of text data.

Some data is duplicated data.
For example, the author name is fetched twice (e.g. "Admin Admin")

In addition, the labels of the field are fetch as well.
For example: "description: text text text".
I prefer without the label: "text text text".

How can I control the text data / fields that facebook fetch?
prevent duplicated data?  prevent fetching the labels?

Ok, so the problem was that on the admin -> configuration -> Metatag -> open-graph.  I had the token [node:summary] on the description field.
I do not have a field on my site called summary.
This token just fetch a lot of information from the content / view and post it.

I removed it, change it to tokens I wanted, add some text to make the output more readable, and that's it.

After that, it took time for the site to update with the changes..


How can I limit the password reset attempts? I have Google Recaptcha, but some users try to recovery password too often. I didn't find any solution for this problem. I want to make 5 attempts limit for this.

You can use the Flood Control module for it.

Flood Control provides an administration interface for hidden flood
control variables, like the login attempt limiters and any future
hidden variables.


How change Drupal Context with a button? Context is great for delivering content to the right part of my site in the right circumstances, in the right order and to the right user.

I'd like to be able to add the ability for a user to toggle Context using a link I create - a button - to cause certain blocks to appear, disappear or be be re-arranged - via Context.

I have researched and experimented for hours and can't find a solution.

In what ways I can I change Context with the press of a button?

Context Flag

This module provides integration between the Context and Flag
(3.0+ only for the moment, if there is interest in it support for 2.0
may be added later) modules.
When enabled it creates new Context conditions which can be triggered
based on the value of one or more Flags applied to nodes, currently
active users, or user profile pages.


Is it possible to use an Image Style in a text field? Image Styles is a great feature in Drupal. Is it possible to apply a preset Image Style to an image that is brought into a long text type field that uses WYSIWYG in Drupal 7? That is, for use in the basic node, not in a View.

Currently, we're using the IMCE WYSIWIG bridge to insert images in the textfield, and there seems to me no way to indicate what preset Image Style to use.

It depends on what you mean by "possible" :-).

The Scald module (integrates with the WYSIWYG CKeditor) uses something called "contexts" that in turn makes use of the preset image styles.  So it is certainly possible to do this if you use Scald to insert images into WYSIWYG.

Scald has a drag'n'drop UI that allows you to place an image (or "atom" in Scald-speak) into WYSIWYG. When you do that, you can set its legend (i.e. caption), context and alignment (see sample dialog below):

In this case, the "Context" is set to "Full page". which I have associated with the preset Image Style known as "Large 480x480".

Below, you can see the markup that is generated by Scald as a result of this, and you can see that it links to the image using the path:

public:://styles/large/public/thumbnails/image/fredespenbenth.jpg

the styles/large path is indeed the image cache for the preset "Large 480x480" image style.

This is the caption that will appear under the image..

Now, as you can see, Scald is doing this, so it must be possible.

And you can (to some extent) do the same thing without Scald by inserting similar markup "by hand" or with the help your own custom module.  But Scald has in place additional magic to regenerate that style of the image in the image cache if it does not exist.  If you do this just by inserting the markup, you can't be sure that the image exists in that style, so you have to use other means to make sure the image cache is populated with the styles you actually use.  (For example sniffing for URLS pointing into the cache in hook_preprocess_node(), and regenerate those that are missing.)


How do I retrieve values of a taxonomy field inside a field collection of a profile2 node? Can someone tell me how can I retrieve values of a taxonomy field inside a field collection of a profile2 node?

Thanks

You could try using entity_metadata_wrapper to load the profile2 entity.

You could then drill down to the field value on the field_collection.

Something like:

$profile = profile2_load_by_user($account, 'main');
// Use entity metadata wrapper, because it's awesome.
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
// We can access the term as the "value" of the field_collection child field
$term = $profile_wrapper->get('field_my_field_collection')->field_my_taxonomy_term->value();
// Just print out the term for now
drupal_set_message('<pre>'.var_export($term,1).'</pre>');


Syntax for referenced variables in hook_commerce_physical_order_weight_alter? I'm trying to add a fixed weight to all cart order for shipping. I know I need to implement hook_commerce_physical_order_weight_alter() but I'm unsure of how to implement the function in a custom module. I have been testing this code in the devel php exectute window

global $user;
$order = commerce_cart_order_load($user->uid);
$weight = commerce_physical_order_weight($order, $unit = 'oz');
function commerce_physical_order_weight_alter(&$weight, $order, $unit){
if ($weight['weight'] >0)
{$weight = $weight + 6;}
}
dpm($weight);

Where I am confused, is passing the variable by reference. From what I understand, this should be enough to increment the weight but it returns the unadjusted weight

I can grab all of the stuff I need outside the function, but I'm unclear about passing the variable by reference and how to use that syntax for my purpose. I know that this means that the function returns a modified variable. It doesn't look like the function is called since I've tried to put the dpm in a condition inside the _alter function and it doesn't run.

Thanks the help so far, and I appreciate the earlier answers.

If your hook_commerce_physical_order_weight_alter is not fired (remove if to double check that it's not), check if commerce_physical_order_weight() is fired as alter hook is right at the end (so add dpm() or die() at start of the function):

    function commerce_physical_order_weight($order, $unit = 'lb') {
      // ...
      // Allow other modules to alter the weight if necessary.
      drupal_alter('commerce_physical_order_weight', $weight, $order, $unit);

if it is not fired, that means the problem is somewhere else, so check if commerce_physical module is enabled and configured properly and you've the right dependency to it,
if it is fired, then check that:

your module is exactly called add_shipping_weight,
the module file included (add hook_init() or die() to check)
clear your caches (Drupal caches, memcached/redis if used, etc.), so list of hooks can be updated (it's a common mistake)


What is the benefit of Node Blocks module versus adding content to blocks in body field? What is the benefit of Node Blocks module versus adding content to blocks in body field?

It seems like the functionality is identical?

Either create content, and use it as a block.

Or create a block and add content to it.

Nodeblock

  This module allows you to specify content type(s) as being a block. This > allows > the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

Also, based on above I imagine that you don't need to assign the block a region and a "display only on url". (I could be wrong, never used this module).


Checked checkboxes after form submit i have a basic admin form, which shows all content types with checkboxes and save button:

function MYMODULE_admin_settings() {
    $types = node_type_get_types();

    $form['content_types'] = array(
        '#type' => 'fieldset',
        '#title' => t('Content types'),
        '#description' => t('test'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
    );
    foreach ($types AS $typename => $type) {
        $form['content_types'][$typename] = array(
            '#type' => 'checkbox',
            '#title' => $type->name,
        );
        }
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
        );
        return $form;

}

When i submit i want to save checked content types somewhere(i don't know what is the best way - save to database or somewhere else like variable_set). And the question is how to show checked content types after submit form - #default_value. For example if i check Article and Basic page c.types submit it and save them to db i want to see them checked after page reload, how can i do this?

Most core (and contrib) modules make use of the system_settings_form() function which handily wraps around a form, and saves element values as variables automatically.

function MYMODULE_admin_settings() {
  $types = node_type_get_types();

  $form['content_types'] = array(
    '#type' => 'fieldset',
    '#title' => t('Content types'),
    '#description' => t('test'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  foreach ($types as $typename => $type) {
    $form['content_types']["MYMODULE_settings_$typename"] = array(
        '#type' => 'checkbox',
        '#title' => $type->name,,
        '#default_value' => variable_get("MYMODULE_settings_$typename", 0)
    );
  }
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
  );

  return system_settings_form($form);

}

You can then grab the value anywhere else in code like this (using the 'page' content type as an example):

$val = variable_get('MYMODULE_settings_page');

Which is a bit counter-intuitive. You might want to make use of a checkboxes type instead, e.g.

$options = array();
foreach ($types as $typename => $type) {
  $options[$typename] = $type->name;
}
$form['content_types']['MYMODULE_content_types'] = array(
  '#type' => 'checkboxes',
  '#title' => $type->name,
  '#options' => $options,
  '#default_value' => variable_get('MYMODULE_content_types', array())
);

Then you can get an array of all selected content types like this:

$selected_types = array_filter(variable_get('MYMODULE_content_types', array()));


Moving Drupal in a sub-directory I want to install Drupal 7 in a new directory of my site, using the same database account used in my previous Drupal site. Will this cause any data loss?

If you are going to move the Drupal files from a directory to a sub-directory, you should not have problems of lost data, which means the database still contains the data for user accounts, and for the created nodes.

Keep in mind, though, that some database tables contain absolute paths/URLs. Moving Drupal files to a sub-directory means that some URLs change, such as the ones to access uploaded files. The cache for the visited pages contain the absolute URL of the page; changing the directory where Drupal is installed means changing the absolute URL of pages, and not allowing Drupal to get the page content from its cache.

I would not talk of lost data, but rather of database references that need to be updated.


Drupal menu callback create node permissions I am creating a small menu, where I want to give access to a menu item when your are an authenticated user.

So I gave permission to authenticated users to create nodes of the type 'donation', but how would I formulate that in the menu acces arguments ?

$items['donate/%'] = array(
    'title' => 'Donate',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_donate_form'),
    'access arguments' => array('create donation'),
    'type' => MENU_CALLBACK,
);

Don't use access arguments. Use user_is_logged_in() as access callback.


Create A Block To Add Field Collection Item I want to create a block that would hold links to add different field collection items. How would i do this? I am new to drupal, please point me to right direction or help me get started.

Have you tried the Views module yet? You can easily create blocks and add whatever field items you want through it. It's a very powerful and at times complex module so you can refer to the nodeOne video tutorials. Good luck!


User cannot change password due to lack of "current" password If a user signs up & login with a 1-time login link (Since the site is configured to moderate users), and if they don't set their password and navigate away, they can no longer come back and set a password as Drupal will now require their "current" password (which obviously does not exist).

Is there any way around this? Not have Drupal ask for a "Current password" when none is set, perhaps?

Not requiring the current password seems like a huge security problem. Anyone who turns their back to the computer for a moment can have their password changed without their knowledge.

A user that finds oneself in this situation will need to request a new one time login link.

I would also suggest the box where a new password is entered should be better highlighed if this is a common problem.


How do I prevent a menu item from appearing? I have a View with a page display. I placed the path of that page view in a menu item. I placed this link under the menu path Primary Links > Apps > Home > Admin View.

In the View defaults section, I set two roles to be able to view the page: administrator and a custom admin role I created.

I have a user that does not have the administrator or the custom admin role. They can see the Home menu item, but they can also see the Admin View. If they click on Admin View, they receive the error "You are not authorized to access this page."

I thought that in Drupal 6 menu items do not appear unless the user has access to them. I have another View for Project Manager Admin, and my user does not see that menu item.

Does anyone have any suggestions regarding where to start debugging this problem? I would like for the Admin View menu item to not appear for my user because my user does not have access to it.

I have tried logging on as the user in question in a different browser and on a different machine, and I can still see the menu item.

Thank you!

I deleted the menu item in question, and then I re-created it.

I could see the menu item when logged on as my self.  I could NOT see the menu item when logged on as the user in question.

Deleting the menu item and re-creating it caused my issue to go away.


How to rewrite the out put of field in view In view for title, I have rewrite the output as link and passing other view link. But after doing this also its not taking to the page link for that node.

Why is this? I am doing mistake?

I think in your view's Configure field section of Content: Title you already checked the following option.

Link this field to the original piece of content

If this option is checked then mostly your rewrite the output won't work. Please check that.

Hope this will help you..


Filtered html with class attribute not being stripped? How to extend "filtered html" by ability of using class attribute? I can't let user have full html, but classes seem to be useful.

I found way of implementing of filtering system:
http://definitivedrupal.org/node/90

but I still hope there's easier way like just a checkbox [x] don't filter class attribute.


Webform: request submitted values in all page breaks I have multiple page breaks in a webform.
Can I get all the values submitted in all previous page break? Actually I can get only the values for one previous page break(the last one submitted).

For example if i'm in the page break 4 only can request the values submitted in page break 3 not in all the previous (2 and 1). The other values are not present.

I'm using the hook_form_alter.

Getting the info from $form_state["input"]["submitted"]

    function custom_module_form_alter(&$form, &$form_state, $form_id) {
      if(substr($form_id,0,20 ) == 'webform_client_form_') {
        dsm($form_state["input"]["submitted"]);
        //Only info from one page break(previous)
      }
    }

You can retrieve submitted values across all pages from $form_state['storage']['submitted'].

Note that this represents values from past pages and not the current page. Here is the code I use to get them all (past & current) page values into a single array:

$values = _webform_client_form_submit_flatten($node, $form_state['values']['submitted']);
$values += $form_state['storage']['submitted'];


Custom exposed filter to select expired nodes In my Drupal 7 website I have a content type called "offer" that has a date field called "deadline".

When the current date is greater than deadline, then the offer is expired.

I would like to make a form with Views where I can put a radio button like this:
Expired: yes   no

Is it possible to do that?

I know that a solution could be to make a new field, to call that "expired", and finally to make a cron to set the value on yes when the node deadline is lesser than the current date.
I was looking for something easier...

I made some steps forward.
The solution should be using the grouped filters, but it doesn't allow me to chose the relative date:

What about running a cron task that sets the status of offers to  unpublished once the expiry date has passed.

Then the view can simply filter on whether or not the node is published.

If you don't want to go down that route then alternatively create a filter based on date and then with a little jQuery hide that and add some radios. Then when the radio is changed set the date filter to the appropriate value and submit the form.


Image styles return Access Denied I'm using the Insert module to allow users to insert images with a specific image style into a page. After upgrading to Drupal 7.20, the images are not stored in the files/styles folders, and the image url returns a 403 (access denied) error. I checked the folder permissions, and they are all set to 777.

It is always recommended to read the release notes of the new release before updating, to make sure that the update doesn't break some of the current features.

The release notes of Drupal 7.20 mentions:

  The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. (As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD.)

You can add the following line to your settings.php to get the images in the site working:

$conf['image_allow_insecure_derivatives'] = TRUE;

but it would be as good as updating the core and not using the updates ;-)

Some useful links from the page:

#1923336: Insert module doesn't work with Drupal
7.20 - contains a working patch to solve this problem.
#1923554: New anti-DoS measure breaks for some file
URIs.
#1923936: Responsive images and styles module doesn't work with
Drupal 7.20

UPDATE:

From the release notes of Drupal 7.21, the update includes fixes for incompatibilities introduced in the Drupal 7.20 security release only. So, it is recommended to update to the latest version i.e. 7.21 to use the security fixes in version 7.20.


How to create a custom field that gets URL counts from LinkedIn on external articles? My site has a content type named News, which receives news from external RSS feed. Therefore, content type News has the following fields:

Title = article title (i.e. Hapag-Lloyd orders five container ships for more Panama Canal trade)
URL = external url field (i.e. http://www.reuters.com/article/2015/04/20/hapaglloyd-ships-idUSL5N0XH3XQ20150420)
Source = external website source (i.e.Reuters)

I would like to create 3 fields in the content type that shows count of article has been shared on LinkedIn in using the following function:

http://www.linkedin.com/countserv/count/share?url=http://www.reuters.com/article/2015/04/20/hapaglloyd-ships-idUSL5N0XH3XQ20150420&format=json

Return

{"count":28,"fCnt":"28","fCntPlusOne":"29","url":"http:\/\/www.reuters.com\/article\/2015\/04\/20\/hapaglloyd-ships-idUSL5N0XH3XQ20150420"}

Fields to be displayed:

count (i.e. 28)
fCnt (i.e. 28)
fCntPlusOne (i.e 29)

I managed to create a custom module for this with specific fields for twitter an linkedin. The module will call the JSON function every time the node is saved.

Additionally, a cron has been set up to be run every 5 minutes and re-save the nodes which make the node to be updated with the right count.


Cron running by itself? My Drupal 7 instance was getting slow. I realised that the problem was a cron job running. However, why is cron running when I'm browing the site? It shouldn't be, surely? It should only run when I run cron.php.

I don't have poormanscron running or anything else that I am aware of that could be kicking off cron. Any ideas of what could be causing this on Drupal 7?

In Drupal 7 cron is run by Drupal by default.

You can configure it at: admin/config/system/cron

It is preferable to disable that cron and run it automatically from the server in some way.
That method is really only preferable if for any reason you have no other choice.

That said, you really should be automatically running cron regularly.
Not necessarily every hour but at least once a day.


Why is "/es" showing up twice in my URLs? I have a bilingual website using locale.

I have a content type that has the "link" field.

I have an Image Slider created with Views with the link as one of the fields.

The url in the link field is "services".
In English, this works fine and goes to

www.domain.com/services

While viewing the view in Spanish, it adds "/es" to the URL twice

www.domain.com/es/es/services

Instead of:

www.domain.com/es/services

Is this an issue with pathauto? Views? Link?

In case anyone is having a similar issue, this is how I fixed it.

There may be a better way to do this but I can at least say that this worked for me.

Situation:

So let's say that there is a view that contains two fields. "Path" (for the path to the node being listed) and the "Name" (Arbitrary text field).

The value of the "Path" field contains something along the lines of "/services" (English) or "/es/services" (Spanish). I exclude it so I can link the outputted title as a link to that path.

My Initial Situation:

I INITIALLY did what seemed logically correct (and what usually works). I chose to "Output this field as a link" and chose the "Path" token (under "Re-write results").

For some reason, using this was outputting the path incorrectly,

Solution:

Interestingly, doing the following fixed it:

Rather than selecting "Output this field as a link" and specifying the value of the "Path" field as the "Link path", I re-wrote  the results entirely by coding it by hand.

It baffles me since to me, it appears that doing both of these methods should produce the same results.

Regardless, if you have the same issue I had, this will definitely work.

PS: Modules I have enabled that may have contributed to this:

Views
Pathauto
Locale (for multiple languages)
Links


UPDATE database field with value from other table I'm basically trying to build a query which looks something like:

UPDATE table_a, table_b
SET table_a.value = table_b.value
WHERE table_a.id = table_b.id;

It seems that a query like this is functionally equivalent:

UPDATE table_a
INNER JOIN table_b
  ON table_a.id = table_b.id
SET table_a.value = table_b.value;

The thing is that I can't figure out how the UpdateQuery allows me to attach a second table like that. I tried just adding a ->join('table_b') to my update query object, but I'm told that method is undefined. Argh.

I've ended up cheating by using db_query(), though I'm still curions to know if there's a way to do this properly using the API.

Given the specific nature of your SQL statement, it would appear db_query() is the way to go. Just be sure to do it as an update hook in your .install (so you can drush updb) to implement smoothly.


Show menu only when user ticks the checkbox I have a menu for user to enter user details which should visible only to logged in user, it works fine. Now I want to add another restriction where I want menu to be displayed only to the user who ticked the checkbox during registration (i.e.,) In registration form there will be a checkbox when user tick the checkbox the menu should be visible otherwise menu should not be accessed by use. I tried following code but not working.

 function my_module_form_alter(&$form, &$form_state, $form_id) {
   if($form_id = 'user_register_form'
   $form['checkbox1'] = array (
      '#title' => 'XYZ',
      '#type' => 'checkboxes',
      '#options' => array('Sell themes'),

   );
 }
 function my_module_user_register_form_submit_handler($form, &$form_state) {
   $check = $form_state['complete form']['checkbox1'][0]['#checked'];
 }
 function check() {
   if($check !== 1) {
   return TRUE;
   }
   return FALSE;
 }
 function my_module_menu_alter(&$items){
   $items['node/add/detail']['access callback'] = 'check';
   $items['node/add/detail']['access arguments'] = array(1);
 }

$check return 1 if checkbox is ticked. But it is not working. Please Correct my mistake. Thank You

Go to admin/config/people/accounts/fields and add a boolean field.
In your MYMODULE_form_alter() add a '#type' => 'checkbox' form field and a custom submit handler.
Inside that custom submit handler save the checkbox value into the user's boolean field from step 1.
Inside your MYMODULE_menu_alter() call global $user and check that field's value $user->field_sell_themes and build the access control accordingly.


loading newer jquery with hook_js_alter() breaks file upload on node edit form I'm using hook_js_alter() in my theme template.php to load jquery 1.7 to my frontend only, and I've noticed that doing this breaks filefield uploads.

More specifically, once you select a file and click upload, the file will upload but the spinner just keeps looping.  If you click preview during this, then after the refresh you'll see the link to the file and the "remove" button.  If you click remove here, you'll see the same issue with the spinner continuously looping.  Hit preview again, and it'll refresh with the file removed.

I tested this method with jquery 1.5.2 as well and had the same problem, so its not a jquery problem.

This problem does not exist if using the dev branch of jquery_update module to load jquery 1.7.  But the issue with using this is it breaks field_ui and views functionality, so is not an option.

My code (very simple) is as follows, any ideas?

function mytheme_js_alter(&$js) {
    if (isset($js['misc/jquery.js'])) {
        $jsPath = 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
        $js['misc/jquery.js']['data'] = $jsPath;
        $js['misc/jquery.js']['version'] = '1.5.2';
    }
}

Worth noting, Drupal is released with a particular version of jQuery.
You generally can't add a newer version of jQuery without refactoring some core js files.

http://drupal.org/project/jquery_update

provides those core patches and more recent jQuery versions.


Hook_theme in module not working I have a ctools plugin in a module folder. I have a theme call in the .module file:

function vimn_article_theme($existing, $type, $theme, $path) {
  dpm($path);
  return array(
      'vimn_article_template' => array(
      'template' => 'vimn_article_template',
      'path' => $path . '/templates',
      'variables' => array('title' => NULL),
    ),
  );
}

and then in the template file vimn_article_template.tpl.php

<div class="test" <?php print $title; ?>>

What am I missing here to get this to work?

The module name is vimn_article
My ctools plugin in is plugins/content_types/prevnext.inc
my template file is located in vimn_article/templates

Your only defining the function, your not calling it.

   print theme('vimn_article_template', $vars);

Think you also have to implement hook_theme_registry_alter() for Drupal to pick up your template.

Maybe you can use a process function to assign this to a variable for the template.

function YOURMODULE_preprocess_HOOK($variables) {
   $output = theme('vimn_article_template', $vars);
   // etc, etc...
}


jquery cannot hide span attribute in Drupal 7 What is wrong with this jQuery code and why can it not hide the span attribute?

jQuery(document).ready(function($){
    $('span.fieldset-legend').hide();
});

Heck, just trying to hide the entire span and it still does not work!

jQuery(document).ready(function($){
    $('span').hide();
});

If it helps, I am trying to hide a horizontal item in a horizontal group.

I can confirm that my jQuery is generally working.  For example, the below works fine

alert('test');

This also works fine

jQuery(document).ready(function($){
    $('p').hide();
});

Just a wild guess but

jQuery(document).ready(function($){
  $('span.fieldset-legend').hide();
  console.log('Hidden the spans');
});

Try the above code and see if "Hidden the spans" gets output on your javascript console. If it does, then the module you're using (Horizontal Groups? or whatever) is tampering with the spans and perhaps showing them after your code has run and hidden them.


How do I create a site inside another one? I have a Drupal site (example.com). There is some content, and there is a page at example.com/projects/abc.

What I want to do is create another site on example.com/projects/abc/NEWSITE.

How can I do that?

Normally, I can create folders via FTP such as projects->abc->NEWSITE, but there is content on example.com/projects example.com/projects/abc.

It's possible, but usually not really recommended solution - as we have subdomains/multisites in Drupal.

But basicly only thing that will probably need small adjustments is .htaccess,
make sure to edit RewriteBase variable. Check out these links:

Same/Similar topics here:

How to get Drupal 7 installed in a sub-folder / sub-directory properly?

https://stackoverflow.com/questions/4122488/a-drupal-site-inside-another-drupal-subdirectory

https://www.drupal.org/node/600966

Configuring .htaccess to ignore specific subfolders: https://www.drupal.org/node/30334

https://stackoverflow.com/questions/2718406/how-to-exclude-a-folder-on-drupal-site-so-that-drupal-does-not-recognise-it-its

Also if You decide to go for multisite -> read this one: https://www.drupal.org/docs/7/multisite-drupal/multi-site-in-subdirectories

Hope this will help You :) Good luck!


Drupal web cluster with memcached. memcached failover? Running Drupal 7 sites (under Aegir) and I'm investigating a method to scale out the web boxes horizontally, so that any Apache server can process a request for any Drupal site. We're currently at ~50 Drupal sites on our platform. All sites also run through Varnish.

At the moment with our single-server setup I have memcached installed locally on the Apache box.

If we add further Apache boxes and each has their own memcached instance, it's likely that cached content in memcached will be different on each different host.
The way around this is to run memcached on our Varnish or database instance, though on our Varnish box makes most sense.

From the settings.php config I can presumably specify multiple memcached servers in the memcache_servers array:

// make MemCacheDrupal the default cache class
$conf['cache_default_class'] = 'MemCacheDrupal';

// Key Prefix: edit this for multisite use.
$conf['memcache_key_prefix'] = $databases['default']['default']['username'];

$conf['memcache_servers'] = array(
    '127.0.0.1:11211' => 'default',
);

How does Drupal choose which memcached server to use from this array?

What I'm looking for is the ability to specify a failover memcached server. So if the primary "shared" memcached instance is down, say we take our Varnish VM down for maintenance, then it starts using another cold memcached instance.

Or as an alternative is there a way for Drupal to failover to using the database cache instead of memcached?

If you might want to setup a memcache cluster, consisting of multiple servers. The idea is that you have more than one server in the cluster and if one of the servers is offline for some reason the others will be used.

This is fairly easy to setup and is documented in the memcache module as well, the config could look something like this:

$conf['memcache_servers'] = array(
  '10.0.0.1:11212' => 'default',
  '10.0.0.2:11212' => 'default',
  '10.0.0.3:11212' => 'default'
);
$conf['memcache_bins'] = array('cache' => 'default');

PHP will handle the clustering, so you wouldn't need to do anything. This means that if a server dies, that cache wont be available, but will automatically be generated on one of the other servers.

One of the ideas with memcache is that you can pool the memory of multiple servers to create a single shared pool.

In your example, you could also use your webservers as a memcache cluster, but that would require that the webservers can talk to each other. Usually when you require multiple servers, you also want to have separate memcache servers, so you can optimize the servers for their specific task.


An explanation on user_save() works I was writing on a module for drupal and i had to update some fields in the user-object. I first tried this code:

$account = user_load($user->uid); // Loading account
$edit = array(
  'gitlab_refresh_token' => $response_data['refresh_token'],
);
user_save($account, $edit);

This did not update the the field.

Then i found this code on the Internet:

$existingUser = user_load($user->uid);
$existingUser->data['gitlab_refresh_token'] = $response_data['refresh_token'];
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

This code works. But the question is why?

The documentation for user_save() says, that $edit just needs to contain an array with key/value pairs of what you want to change and it will be put in the user's data field,
and that is what i did, right?

The first snippet doesn't work because Drupal doesn't use any 'gitlab_refresh_token' array index, and it doesn't know any field with that name. If you were trying to change the value of a field added with the field UI, the array needs to have a different structure, to be saved.

The second snippet works because Drupal effectively uses that array index, as also said in the documentation.

  Key / value pairs added to the $edit['data'] will be serialized and saved in the {users.data} column.

// Prepopulate $edit['data'] with the current value of $account->data.
// Modules can add to or remove from this array in hook_user_presave().
if (!empty($account->data)) {
  $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
}


How to solve "Query failed" error in drush sql-sync output? This is a follow-on to my earlier question on this site.  I hope posting it as a new question is appropriate.  I'm trying to clone an existing drupal installation into a place on my mac with the commands:

echo "Pushing private files"
/usr/local/bin/drush core-rsync @hpc.dev:%private @hpc.local:%private
echo "Pushing webroot files"
/usr/local/bin/drush -y core-rsync @hpc.dev @hpc.local
echo "Pushing database"
/usr/local/bin/drush -y sql-sync --no-cache @hpc.dev @hpc.local
echo "Clearing Drupal cache"
/usr/local/bin/drush -y @hpc.local cc all

The sql-sync bit is failing with the following error:

Copying dump file from Source to Destination.                                      [ok]
Starting to import dump file onto Destination database.                            [ok]
/usr/bin/php /usr/local/drush-master/drush.php --php=/usr/bin/php  --backend=2        [notice]
--verbose --yes --strict=0 --root=/Users/cook47/Sites/drupal-test/html
--uri='http://localhost/~cook47/drupal-test'  sql-query
--file=/tmp/hpc-drupal-dev_20160302_175129.sql.gz --file-delete 2>&1
Executing: gzip -d /tmp/hpc-drupal-dev_20160302_175129.sql.gz
Executing: mysql --defaults-extra-file=/private/tmp/drush_wKQDuq --database=hpc-drupal-dev --host=localhost --silent  < /tmp/hpc-drupal-dev_20160302_175129.sql
Query failed.                                                                      [error]
Command dispatch complete                                                             [notice]
Command dispatch complete                                                             [notice]

The sql file does exist.  I think the problems is that --defaults-extra-file part, because when I run that last command by hand, I get this:

cook47@rcmac (Downloads ):  mysql --defaults-extra-file=/private/tmp/drush_wKQDuq --database=hpc-drupal-dev --host=localhost --silent  < /tmp/hpc-drupal-dev_20160302_175129.sql
mysql: [ERROR] Could not open required defaults file: /private/tmp/drush_wKQDuq
mysql: [ERROR] Fatal error in defaults handling. Program aborted!

I have no idea where that --defaults-extra-file=/private/tmp/drush_wKQDuq comes from.  It's nowhere earlier in the output.  The directory /private/tmp/ exists and I can write to it.  Here is the 'local' array alias in my hpc.aliases.drushrc.php file:

$aliases['local'] = array (
  'root' => '/Users/cook47/Sites/drupal-test/html', //CHANGEME
  'uri' => 'http://localhost/~cook47/drupal-test', //CHANGEME
  //'remote-host' => "localhost",
  //'remote-user' => 'cook47',
  'path-aliases' => array (
    '%drush' => '/usr/local/bin/drush', //CHANGEME
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%private' => '../private',
    '%dump' => '/Users/cook47/Sites/drupal-test/drush-dump.sql',//CHANGEME
  ),
  'target-command-specific' => array(
    'sql-sync' => array(//CHANGEME
      'enable' => array(),
      'disable' => array(
      ),
    ),
  ),
  'command-specific' => array(
    'rsync' => array(
      'mode' => 'vrlzOk',
      'exclude-conf' => 1,
    ),
  ),
);

Anyone able to resolve this or point me to how to resolve it?

The reason you get a 'file not found' error when you run the import by hand is that Drush automatically deletes its temporary files when the command completes. So, the error you are seeing there is different than the 'Query failed' error you are getting from Drush.  Also, note that the --defaults-extra-file contains the credentials for your mysql connection, whereas the file shown at the end of the line is the actual sql dump.

If you'd like Drush to keep the sql file around, you can specify your own location for it; in this instance, Drush will not delete the file when it exits.  Use the option --target-dump=/path/to/mydump.sql.  It is unclear to me from your pasted output above whether or not your %dump option is being respected (since the path used is different than the one shown in your site alias). If %dump is not working, you could try moving this to your target-command-specific options, although if you do this, the key should be simply dump, not %dump. If your sql dump file is not being deleted, then disregard this advice.

If you want to try to re-import your local dump file, you could do this:

$(drush @hpc.local sql-connect) < /tmp/hpc-drupal-dev_20160302_175129.sql

If you do this, you should get the same 'Query failed' message. $(drush @hpc.local sql-connect -d) might give you more information.

The cause of the 'Query failed' message could be a number of things, but it's most likely a mismatch in the mysql version on your host vs. your local system, or (less likely) an encoding mismatch (e.g. if your dump is in utf-8, and that encoding is not available on your local system).


Adding a link with nid in Global: results summary in Views I have a Views block listing a certain amount of nodes, and I've added a header field: Global: Result summary.

I am on the page: http://myexample.com/node/145 for example and with the header field, I want to link to: http://myexample.com/node/145/events. I have put the following code in the field:

(@total)

But this omits the nid and goes directly to:
http://myexample.com/node/events.

Does anyone know how to pass a URL argument for that field? I would ideally want to use arg(1).

Because the header uses the default Drupal PHP interpreter, Views variables aren't available there like they are in the arg php code. You can get them by doing something like this:

<?php
global $current_view;
print $current_view->args[0];
?>

Update: If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

Also if you use Global: Text area with PHP filter enabled this should work:

@total


Add signature to features I love to work with features! I often work with several colleges on the same feature and I'ld like to add a signature to the features. So we can see who worked last on the feature (without having to dig in Bitbucket).

It must be possible since the example Features do so:

But all I get are Unavailable signatures :(

Any one know this magic?

I wrote a patch which will allow users to enter an "Author" name when creating/updating a feature.
When provided, the signature will take the Authors value, if not fallback on standard workflow.

Setting the signature was my goal and I succeeded.  For those interested, here is the patch:

diff --git a/sites/all/modules/contrib/features/features.admin.inc b/sites/all/modules/contrib/features/features.admin.inc
index a4203a0..3c5c913 100644
--- a/sites/all/modules/contrib/features/features.admin.inc
+++ b/sites/all/modules/contrib/features/features.admin.inc
@@ -168,6 +168,15 @@ function features_export_form($form, $form_state, $feature = NULL) {
     '#size' => 30,
     '#element_validate' => array('features_export_form_validate_field'),
   );
+  $form['info']['author'] = array(
+    '#title' => t('Author'),
+    '#description' => t('Examples: Patrick, John'),
+    '#type' => 'textfield',
+    '#required' => FALSE,
+    '#default_value' => !empty($feature->info['author']) ? $feature->info['author'] : '',
+    '#size' => 30,
+    '#element_validate' => array('features_export_form_validate_field'),
+  );
   $form['advanced'] = array(
     '#type' => 'fieldset',
     '#title' => t('Advanced Options'),
@@ -832,7 +841,7 @@ function _features_export_generate($export, $form_state, $feature = NULL) {

   $module_name = $form_state['values']['module_name'];
   // Directly copy the following attributes from form_state
-  $attr = array('name', 'description', 'package', 'project path');
+  $attr = array('name', 'description', 'package', 'project path', 'author');
   foreach ($attr as $key) {
     $export[$key] = isset($form_state['values'][$key]) ? $form_state['values'][$key] : NULL;
   }
@@ -1083,7 +1092,10 @@ function features_admin_form($form, $form_state) {
       '#disabled' => $disabled,
     );

-    if (!empty($module->info['project status url'])) {
+    if (!empty($module->info['author'])) {
+      $uri = check_plain($module->info['author']);
+    }
+    else if (!empty($module->info['project status url'])) {
       $uri = l(truncate_utf8($module->info['project status url'], 35, TRUE, TRUE), $module->info['project status url']);
     }
     else if (isset($module->info['project'], $module->info['version'], $module->info['datestamp'])) {


How to change a file field value with entity_metadata_wrapper I need to remove a file field value, and instead, assign a new value to it. The file field contains video and the new video is in the videos directory.
This is my code to delete a file field value (which works well)

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

But this code which assigns a new value, reports an error. I get this code from How to set value of file field with entity_metadata_wrapper

    $node = node_load(37);
    $realpath="";
    if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
      $realpath = $wrapper->realpath();
    }
    $file_path = $realpath."\\video_file\\sarmaye.mp4";
    $file = new stdClass;
    $file->uid = $node->uid;
    $file->filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file->uri = $file_path;
    $file->filemime = file_get_mimetype($file_path);
    $file->display = '1';
    // Make it permanent, otherwise it will get deleted later.
    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
    $file = (array) $file;
    $items = array($file);
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_video->set($items);
    $ewrapper->save(true);

But it reports this error

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'D:\xampp\htdocs\MySiteName\sites\default\files\video_file\sarmaye' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => sarmaye.mp4 [:db_insert_placeholder_2] => D:\xampp\htdocs\MySiteName\sites\default\files\video_file\sarmaye.mp4 [:db_insert_placeholder_3] => video/mp4 [:db_insert_placeholder_4] => 4877369 [:db_insert_placeholder_5] => 1 [:db_insert_placeholder_6] => 1468934410 ) in drupal_write_record() (line 7361 of D:\xampp\htdocs\MySiteName\includes\common.inc).

You have to set the uploaded file object rather then the initial file object. Please check the return value of file_save() function.

The error explained that there is duplicate key uri, which means the code is trying to save the initial file object again.

$ewrapper->field_video->set() only accept (array) $file but not $items.

$file = file_save($file);
$file = (array) $file;
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_video->set($file);
$ewrapper->save(true);


How to pass the node id from a View Block to an associated Views Attachment for use in filters so that both operate on same content node id? What would I need to do to pass the node id from a View Block to an associated Views Attachment for use in the filters in the Attachment View so that both operate on same content node id?

My specific example is for generating preview/teaser output from a media gallery with a certain tag:

The title of the latest gallery with that tag
The latest 3 thumbnails of that gallery

(I know how to build a block view to fetch thumbnails from galleries (i.e plural) that have a certain tag - my solution is here: https://drupal.stackexchange.com/a/13559/1082 I am using the Acquia Media module)

BUT what I don't know how to do is to get the title latest gallery (singular) with a certain tag followed by the latest 3 thumbnails of that gallery.

I attempted to create a block view that fetched the title of the gallery with the certain tag and I also created an view attachment to fetch the thumbnails of that gallery. But I could not work out how to pass the node id of the gallery from the block view to the attachment for it to use in its filters when fetching the thumbnails.

I tried various options including enabling the attachment to inherit arguments and filters from the block view and also contextual filters but no success so far.

Further to this, I may wish to out put more than one gallery in the teaser/preview but if I set the count to more than one on the view block I get the other gallery titles listed together followed by the thumbnails. I would want each gallery in turn to display the title followed by thumbnails that belong to it.

I would prefer to do this all withing Views i.e. not have to use PHP. I would want the solution to be as forward compatible as possible, i.e. not break with future updates - if we can stay within Views then the migration to those might be easier.

Since the attachment is linked to a specific view block, it should gain access to the information in the block.  You can inform the block of the node ID by using contextual filters.
1. In the block  add a contextual filter of the type content:nid.
2. Since blocks do not have paths you must explicitly tell the block to find the display node, so under form heading of "When the filter value is not available", choose "Provide default value" and select "Content ID from the URL".  This should provide the Node ID to the view block.


Truncate tables before uninstalling a module in Drupal 8 I'm developing a module in Drupal 8, and because it handles quite a few relations between entities, I always need to add a bit of test data before being able to test the forms for the actual entity I'm working on after a uninstall/reinstall of the module. During install I can add this data in the module.install->xx_install hook. But during uninstall I get the error

"The following reasons prevent the modules from being uninstalled: There is content for the entity type..."

I tried implementing the uninstall hook and truncate the table there, but it seems the check for existing content is done before this hook runs. How can I truncate the necessary tables without having to do it manually? Having to do it manually slows down development quite a bit. Alternatively, is there a way to speed up development of the entity forms and relations so that I don't always have to install/uninstall the module to see changes?

That's a known issue right now.

There's no way right now to hook into that automatically. And it came up a few times already here too. See this question for example: Module uninstall dependencies

Beside a form or a drush command to do the cleanup, there really isn't much that you do right now, other than improving core. What I'd like to see is a message on the uninstall confirmation form that tells you that it will delete all records of entity type N and then does so in a batch before actually uninstalling. See the referenced flag issue in the other question and my repeated suggestions to open an issue, but so far, nobody could be bothered with doing that. And I didn't find time myself either.

Update

Drupal 8.2 now offers a link on the uninstall form to delete all entities of the given type.


How do I add custom keywords in the URL? For a sake of SEO, I need to be able to dynamically pass random keywords to the URL. For example, instead of the classic variable=value couples in a query (e.g. /my-node-title?selected=random-seo-keyword), I need to use a good-looking path like /my-node-title/random-seo-keyword, where my-node-title is a URL / path alias of node/xxx but random-seo-keyword does not exist in the structure and may not be predefined.

Then, on the server I handle and split the URL parts with a script. The only problem is that currently Drupal 7 returns a 404 error in such cases.

You can alter your paths by using hook_url_*_alter() hooks.
Have a look at hook_url_inbound_alter() and hook_url_outbound_alter().


More Stories appears when a user scrolls on a half page More Article Box (More Stories) appears when a user scrolls on a single post at least 400px. The box appears in the right bottom corner and it can show one or more posts related with the current one.

Is there a module like this for Drupal 7?

You can give the drupal infinite scroll module with views a try . Then tweak a bit to suit ur needs for scrolling


How can I build an accordion without Javascript using the Field Group module? I'm using the Field Group module to make accordions on my site, but it loads JQuery and slows the page down. Is there a way to do this without JS?

Yes, you can use the HTML 5 details tag.
On the content type display administration page, create a field group.
For the Format, chose HTML element.
For Field group label, enter the text you want to show to click to display the rest of the text.
For the Element, enter details.
For Show Label, select Yes.
For Label element, enter summary.
To style with CSS, add extra CSS classes as needed.


403 page when clicking on activation link in email When a user creates an account, they must activate their account by verifying the email. The token in that email is the default one, i.e. [user:one-time-login-url]

But when the user clicks on the link in their email, they get the 403 page (= You are not authorized to see this page).

Can anybody explain why this 403 page shows up?

You have to give the right to anonymous role to view published content

your_domain/?q=admin/people/permissions

then, tick view published content


How do I fill form elements via onblur events? I have a user form in which I have to fill all information related to a user. I have only the email address, and I'd like all other fields to be filled when I enter the email address by using the onblur event. So I have to create a module that is called after I have filled email on the form. Via the module I will fetch all other field data.

You just need to AJAXify the form. Take a look at this article for more info on Drupal AJAX forms. To actually look up the user info you can just use the user_load_by_mail() function (more info).


Which table stores the content type fields? I have a content type in drupal 8 and which table stores the content type fields and type in drupal 8 ? Unlike in drupal 6 (in which there will be tables specifically for content types) like content_type_contenttypename its not creating the table and fields . Where will be these fields and data types stored in drupal 8 ??

Drupal 8:

Content type = Bundle
Node = Entity
Base fields are in one table: [entity]_field_data
Bundle fields are in seperate tables: [entity]__field_name

Bundle fields are stored in the same table for all bundles of one entity and can be shared between bundles of the same entity but not with another entity.


How do I display a help text with field form? Is there a way to bring up a help message next to a form field as below?

FooForm.php

$form['field_foo'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Foo'),
    '#required'      => true,
    '#default_value' => 'foo',
    '#help_text' => 'Help text for Foo field',
);

Use #description attribute.

$form['field_foo'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Foo'),
  '#required'      => true,
  '#default_value' => 'foo',
  '#description' => t('Help text for Foo field'),
);


Custom Rules Actions to set content to unpublished Is there a way to write a custom Rules Action with this conditions.

Default: Content Type X is set to create unpublished content.

RULES

Event: After saving new content
Condition: when a content of type X is created
Action: Set status to published

Even though your Rules question could be like an exercise for a training session like "Getting started with Rules in D7", the most recent release of Rules for D8 (= Alfa 3) does not support this yet.

However, as a work-around, you could implement the very same logic if you'd adapt the configuration of your content type X so that the default is that newly created content is published right away.

Note: if your goal is to "let anonymous users access unpublished contents" (as in your comment below this answer), then the view_unpublished module could be a possible alternative. As per its project page: it allows you to grant access for specific user roles to view unpublished nodes of a specific type.


How do I mark a database query with a tag? How do I mark a database query with a tag so that I may alter it via hook_query_alter? I get the concept, but does anyone know what the syntax is? A working example would be helpful. Thanks.

In case you're struggling to find the documentation, the class is called SelectQuery, and you're looking for the addTag function.

$query = db_select('table', 't')->fields('t')->addTag('my_tag');

Then in your query alter:

function MYMODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('my_tag')) {
    // Do something...
  }
}


Drupal 7: facebook comment for article only I need Facebook comment for Drupal 7.

Which one can I use?

If I use above code it shows me comment of any article for all article.  I need to display comment for article.

In Drupal 7 you can use

Facebook Comments Box : This module gives your site the ability of using Facebook's Comments Box social plugin. It will create a block just configure only for article. You can check this video
Facebook Comments Social Plugin : Implement Facebook commenting with settings on the level of both content type and node.
Using Facebook plugin code

NOTE :

YOUR_URL : Updated current URL based on each article.


Language switching does not work when browser language is configuired in drupal 8.3.7 Language switching fails after enabling browser on  Detection and selection

  /admin/config/regional/language/detection

Exisiting :

On switching language from the browser the url changes but the content remains the same

E.g, Default language browser is Germen.

mywebsite.com mywebsite.com/about etc shows German content.

While swiched to English url changes to mywebsite.com/en mywebsite.com/en/about etc

It shows Germen content instead of English.

Expected

On browser configured with Germen as default language, the site url should be mywebsite.com/de.

When I swich to the English website, it should show English content

Please find the configuration.

It is very obvious why this is happening. Language selection process the language detection systems from top to bottom. (Top has highest priority.) Your configuration means that the browser will always be selected first and that url and user settings are ignored.

If you move browser below user (drag with the arrows icon), the processing order will be:

url
user (if url resolved no language)
browser (if user had no language configured)


IS there a replacement for 'taxonomy_node_get_terms_by_vocabulary' in Drupal 7? The closest I have come is taxonomy_term_load_multiple but the conditions argument will be deprecated in V8.  They now recommend EntityFieldQuery as a replacement.  I am new to coding and have not worked with setting up the conditions for the query and am having trouble finding documentation/tutorials.  If a simpler function exists, I would prefer to use it.  Answers addressing a function or how to use EntityFieldQuery are welcome.

Thanks

I don't think an EntityFieldQuery would work in this case as you'd be trying to reference two types of entity in the same query (which cannot be done currently). The easiest way would be to build up the query yourself:

function taxonomy_node_get_terms_by_vocabulary($node, $vid) {
  $terms = &drupal_static(__FUNCTION__, array());

  if (!isset($terms[$vid])) {
    $terms[$vid] = array();
  }

  if (!isset($terms[$vid][$nid])) {
    $query = db_select('taxonomy_term_data', 'td')
      ->fields('td', array('tid'))
      ->condition('td.vid', $vid)
      ->condition('i.nid', $node->nid)
      ->orderBy('td.weight');

    $query->join('taxonomy_index', 'i', 'i.tid = td.tid');

    $terms[$vid][$nid] = taxonomy_term_load_multiple($query->execute()->fetchCol());
  }

  return $terms[$vid][$nid];
}


How can I display multiple images of single image field each in a different row? I need to render multiple images that belongs to single image field, each on its own views row.

While on a view single field setting, inside "Multiple field settings", uncheck " "Display all values in the same row", But all values are still displayed on same views row.

How can it be done in Drupal 8?

Well, on the same view, on English side of the website the view displays same field, of same field of the same node ID, on separate view rows.

Problem disappeared after the field configured to be to be translate.

Now display every item (image) on its own views row as expected.


Assessing admin when site is not hosted in the root of the domain We set up a site with a url like www.mysite.com
the site is being served by a proxy to come up as

www.theirsite.com/mysite/

We set $base_url  to www.theirsite/mysite

This is working correctly to load all the assets on the page but does not work on the admin.

The admin login and all pages on the admin try to post to the root of www.theirsite.com
so for instance the /user page tries to post to
www.theirsite.com/user
this is obviously not working.

We tried clearing the cache on drupal to rebuild all urls as was recommended on many sites, but did not have any effect.

We are hosting our site via iis7 on windows.
The version of Drupal is 7.2

What can be done to fix the admin form urls?

Our solution was to create a virtual folder mysite and host the site as
www.mysite.com/mysite

After that the proxy was pointed to the new virtual folder.  This made the admin work correctly.

This is not a satisfying answer as it still leaves unanswered how to control the admin form urls


How to display a field of the parent store in my module? I have a Drupal 8.7 site with the Drupal Commerce 2.14 module.

I created a marketplace (several merchants on the same site). In the store type, I created a "Text (formatted, long)" field with the machine name field_terms_and_conditions.

In this field, the merchant writes his general conditions of sale, which the customer will have to accept during the order process.

When the customer orders in several stores, this will create several shopping carts (the name of the store is displayed above each shopping cart). It works very well. Now that Drupal Commerce is handling the address book, the orders are very fast.

Currently I have created a view that displays the contents of the field field_terms_and_conditions on a page. I also created a custom module to display a checkbox with a link to the general conditions of sale in a modal window.

I want to directly render the field field_terms_and_conditions in the modal window without using a view. How to do this ?

/src/Plugin/Commerce/CheckoutPane/MarketplaceTermsAndConditions.php :

<?php

namespace Drupal\commerce_marketplace_terms_and_conditions\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "marketplace_terms_and_conditions",
 *   label = @Translation("Marketplace Terms and Conditions"),
 *   default_step = "review",
 * )
 */
class MarketplaceTermsAndConditions extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 'auto'
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['marketplace_terms_and_conditions'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @terms.', ['@terms' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

Sounds fun, Here is an option to do this.

1) make a controller :
routingfile:

my_module.store_terms:
  path: '/store-terms/{store_id}'
  defaults:
    _controller: '\Drupal\my_module\Controller\StoreTermsController::showTerms'
    _title: 'Terms'
  requirements:
    _permission: 'access content'

In the controller:

use Drupal\Core\Ajax\AjaxResponse;

use Drupal\Core\Ajax\OpenModalDialogCommand;

public function showTerms($store_id) {
  $store = \Drupal::entityTypeManager()->getStorage('commerce_store')->load($store_id);

  $terms = $store->field_terms_and_condition->value;

  $render_array = [
    '#markup' => $terms
  ];
  $response = new AjaxResponse();
  // Show a dialog box.
  $dialogText = $render_array;
  $dialogText['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $response->addCommand(new OpenModalDialogCommand('Terms and Conditions',
   $dialogText, ['width' => '500']));
  return $response;
}

then back in your  buildPaneForm method:

$attributes = [
  'attributes' => [
    'class' => 'use-ajax',
    ],
];
$link = Link::fromTextAndUrl(
  t('terms and conditions of the store "@store_name"', ['@store_name' =>
   $store_name]),
  Url::fromUri("internal:/store-terms/".$store_id , $attributes)
  )->toString();


Trouble aligning text with WYSIWYG I have added TinyMCE to work with one of my text formats, and I added the different alignment buttons. When I try to center some text it adds "text-align: center" to the p... but when I save it, it goes back to normal. I would like to fix that to be able to align text and images. I installed a module called WYSIWYG Filter and added "text-align" in Text properties... still doesn't work. I also added "p[style|text-align]" to the "HTML elements and attributes" section... still doesn't work.

Any ideas of what could I be missing?
...I'm using Drupal 7 BTW

If you're using the filtered HTML input format, that would be stripping it out.

If not, it sounds like your markup is weird. The way you describe it, what might work if it read
 (not that I recommend this) reads
. I think WYSWIG editors tend to prefer classes to putting styles right in the markup, so I'd do something like
 and add .centered-text{ text-align:center } to your stylesheet.

I would double-check your site with a DOM inspector to make sure your style on your
 isn't being overridden by a stylesheet. If nothing else works, you could use a different editor. jWYSIWYG, openWYSIWYG, Whizzywig, and nicEditor use align="wherever" instead of style="text-align:wherever" which might work (again, I don't recommend this, but it's a potential short-term solution. For reference, MarkItUp and WYMeditor don't offer alignment buttons, and CKEditor, FCKEditor, TinyMCE, and YUIeditor do it the "right" way, using style="")


How to set programmatically multiple arguments for views contextual filters How to set programmatically multiple arguments for views contextual filters?

I can do it with one argument, it works great, but not with multiple arguments.

I want to select all nodes created by a list of people, but views only takes first in array into consideration:

$array = array(3250,32);
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();

Am I doing something wrong?

First you should set this option:
View → Advanced → Your Contextual Filter → More → Allow Multiple Values.
Then when passing array should be with '+', so, your example:

$array = array('3250+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();


Skip A Custom Checkout Page So I thought I had been pretty clever when in the code for a custom checkout pane, in a custom checkout page, I did this:

function checkout_pane_giftaid_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  if($showPane==1){
    //show something awesome
  }
  else {
    $checkout_pages = commerce_checkout_pages();
    commerce_order_status_update($order,'checkout_payment');
    $url = 'checkout/'. $order->order_number  . '/' . $checkout_pages['gift-aid']['next_page'];
    drupal_goto($url);
  }
}

If showPane is equal to 1 it displays the Pane's content, if not it directs you to the next checkout page. This however has presented an issue because I have two custom checkout pages.

The result of this is if you are on 'custom page 2' and press 'Go Back' it goes back to the previous page ('custom page 1'), but if $showPane=0 on this page then the else statement means its set to forward. So a user hits 'go back' on 'custom page 2' and what they see, is this page reload (actually it has gone back to 'custom page 1' where it is told to go to the next page, 'custom page 2').

So my question is this: clearly I have not gone about 'skipping' custom checkout pages in the right way, how would I do it properly?

You can use hook_commerce_checkout_router() to skip Commerce Checkout pages.

See the advanced example here: Skipping a Commerce Checkout page in the checkout workflow

/**
 * Implements hook_commerce_checkout_router().
 *
 * Skip the registration checkout page unless required.
 */
function MYMODULE_commerce_checkout_router($order, $checkout_page) {
  global $user;

  if ($checkout_page['page_id'] == 'registration' && $user->uid) {
    $registration_required = FALSE;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      if ($line_item->line_item_label == 'Conference Attendee') {
        $registration_required = TRUE;
        break;
      }
    }
    if (!$registration_required) {
      $order = commerce_order_status_update($order, 'checkout_' . $checkout_page['next_page'], FALSE, TRUE, t('Conference Registration was skipped - not required for these products.'));
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }
}


What's the prupose of the version property of a theme library? Reading the 2 articles below, I'm creating a new theme.

Defining a theme with an .info.yml file
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

In the example below, I don't understand what is the purpose of the version property of the global-styling library :

global-styling:
  version: 1.x
  css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

Is it a reference to the site version with which this library is compatible ?

Is it the version of the library itself ? And in this case, when will it be used and for what ?

For Javascript files, version would allow modules that implement hook_library_info_alter() to check if the version of the JavaScript file is older than the one the module is trying to add, for example with code similar to the following. (It's the same code the documentation page reports as example.)

  // Update Farbtastic to version 2.0.
  if ($extension == 'core' && isset($libraries['jquery.farbtastic'])) {
    // Verify existing version is older than the one we are updating to.
    if (version_compare($libraries['jquery.farbtastic']['version'], '2.0', '<')) {
      // Update the existing Farbtastic to version 2.0.
      $libraries['jquery.farbtastic']['version'] = '2.0';
      // To accurately replace library files, the order of files and the options
      // of each file have to be retained; e.g., like this:
      $old_path = 'assets/vendor/farbtastic';
      // Since the replaced library files are no longer located in a directory
      // relative to the original extension, specify an absolute path (relative
      // to DRUPAL_ROOT / base_path()) to the new location.
      $new_path = '/' . drupal_get_path('module', 'farbtastic_update') . '/js';
      $new_js = [];
      $replacements = [
        $old_path . '/farbtastic.js' => $new_path . '/farbtastic-2.0.js',
      ];
      foreach ($libraries['jquery.farbtastic']['js'] as $source => $options) {
        if (isset($replacements[$source])) {
          $new_js[$replacements[$source]] = $options;
        }
        else {
          $new_js[$source] = $options;
        }
      }
      $libraries['jquery.farbtastic']['js'] = $new_js;
    }
  }

Technically, the same type of code could be used to check which CSS file version is being used, before replacing it with a different one. I can imagine doing that for an external CSS file, for example when a specific version used from a library causes problem with other libraries. I haven't seen a module using similar code, though.

Otherwise, version has only identification purposes, much more helpful when a module implements hook_library_info_build() to dynamically load different versions of a CSS file.


Why do Drupal core functions get node object instead of nid as argument? Most (if not all) of Drupal functions accept $node object instead of $nid as argument, like node_type_get_name($node), so we should first write node_load($nid) and send its long output to the functions, whereas they can call the node_load() function themselves and reduce number of developers' codes. What's the reason?

I think it's to avoid the repetition of node_load that could occur.

I searched a little in the source and you can see node_type_get_name($node) is called from others functions which also take a $node object argument, node_promote_action for exemple

function node_promote_action($node, $context = array()) {
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
}

It seems DRY to me. Imagine you gave a nid as argument in node_promote_action :

function node_promote_action($nid, $context = array()) {
  $node = node_load($nid);
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($nid), '%title' => $node->title));
}

And then node_load again in node_type_get_name :

function node_type_get_name($nid) {
  $node = node_load($nid); // repetition
  $type = _node_extract_type($node);
  $types = _node_types_build()->names;
  return isset($types[$type]) ? $types[$type] : FALSE;
}

With nid as argument, each time a node related function (A) need to process some node's properties (often if not always), they would call node_load. This would lead to unnecessary repetition when another node processing function (B) is called inside the first (A), just like in the above example.