Add new column "Block description" on block layout page

That's a form. Themed as table. So I managed to do what you want via hook_form_FORM_ID_alter.

Thing is, I can't find the block description or admin label inside the block entity. So that's left. I hope you can find a way or maybe you can specify what "Block Short Description" is supposed to be.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_block_admin_display_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Add header column.
  array_splice($form['blocks']['#header'], 1, 0, 'Description');

  // Go through all blocks.
  foreach ($form['blocks'] as $bid => $block) {

    // Skip non-block elements (like '#header' or 'region-name').
    if ($bid[0] != '#' && !strpos($bid, '-')) {

      // Load block.
      $entity = \Drupal\block\Entity\Block::load($bid);

      // Load description.
      // ksm($entity);
      // Can't find one. Take the label for now. Let OP figure this out themselves.
      $description = $entity->label();

      // Add description column to row.
      // @see https://stackoverflow.com/a/3354804/2199525
      $array = $form['blocks'][$bid];
      $form['blocks'][$bid] = array_slice($array, 0, 2, TRUE) +
        ['description' => ['#markup' => $description]] +
        array_slice($array, 2, count($array) - 1, TRUE);
    }
  }
}

Answer updated to display content type restrictions.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_block_admin_display_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Add header column.
  array_splice($form['blocks']['#header'], 1, 0, 'Description');

  // Go through all blocks.
  foreach ($form['blocks'] as $bid => $block) {

    // Skip non-block elements (like '#header' or 'region-name').
    if ($bid[0] != '#' && !strpos($bid, '-')) {

      // Load block.
      $entity = \Drupal\block\Entity\Block::load($bid);

      // Load visibility settings.
      $conditions = $entity->getVisibilityConditions()->getConfiguration();

      // Load content types.
      $types = [];
      if ($node_types = isset($conditions['node_type']['bundles']) ? $conditions['node_type']['bundles'] : FALSE) {
        $node_types = Drupal\node\Entity\NodeType::loadMultiple($node_types);
        foreach ($node_types as $node_type) {
          $types[] = $node_type->label();
        }
      }

      // Set description.
      $description = 'Content types: ';
      if (!empty($types)) {
        $description .= implode(', ', $types);
      }
      else {
        $description = '- no content type restrictions -';
      }

      // Add description column to row.
      // @see https://stackoverflow.com/a/3354804/2199525
      $array = $form['blocks'][$bid];
      $form['blocks'][$bid] = array_slice($array, 0, 2, TRUE) +
        ['description' => ['#markup' => $description]] +
        array_slice($array, 2, count($array) - 1, TRUE);
    }
  }
}


I can see in your output that you are trying to update to a specific version of Composer and it also prompting an "Access Denied" shortly after:
PS C:\> composer self-update 1.4.1
Upgrading to version 1.4.1 (stable channel).

Unable to write "C:\ProgramData\ComposerSetup\bin\composer.phar". Access is denied.

So it looks like that command already failed. You may have to manually install Composer on your machine if you run in such permission errors and move the composer.phar executable to the appropriate directory.
PHP 7.3
Please also see this GitHub issue for the ErrorException that you are facing: PHP 7.3 breaks composer with continue/targeting error (solution: downgrade to 7.2) #7783

[ErrorException]
"continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

In that issue it states that you will need at least Composer version v1.6.0 or up to be compatible with PHP 7.3.
Composer v1
Is there any reason why you need an old v1.4.1 version? If not then for now I suggest you rollback to the latest stable version of Composer v1 as per @Kevin's comment, which you can do by running:
composer self-update --1

Which should currently give you Composer v1.10.17, or again if that fails download the latest v1 manually.


Is there a firm or preliminary decision on which modules will leave Core for 8?

There is an issue report for that ([Meta] Make core maintainable), but nothing has been decided yet. As you can see, there are different opinions about what to remove, and what to keep.
catch, the latest maintainer added to Drupal 8, expressed his opinion on that; the same did Dries, chx, Crell, and eaton (just to cite some of them). There is an agreement about some of the modules to remove, but there isn't a complete agreement.

That issue report is not marked as postponed, and a new issue report has been opened (Establish heuristics for core feature evaluation).


Need CKEditor to encode special characters

A clean solution would be to alter your twig template to include escape. There are plenty of examples in that guide.


"recommended-project" installs drupal into the /web subdirectory, but hosting solution directs traffic to webroot

When you use the drupal/recommended-project template to create a Drupal project via Composer, you can use a different directory for the server document root.
Instead of running composer create-project drupal/recommended-project my-project:

Run composer create-project drupal/recommended-project my-project --no-installation
Edit the composer.json file found in the my-project directory to replace any occurrence of web/ with public_html/
Inside the my-project directory run composer install
Copy the content of the my-project directory (including any subdirectory) into the directory containing the server document root directory

This is described in Using Composer to Install Drupal and Manage Dependencies.

If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the --no-install flag when running composer create-project. For example, it is possible that you want to rename the subdirectory 'web' to something else.
To do that:

Run composer create-project --no-install drupal/recommended-project my_site_name_dir
Change directories to my_site_name_dir and edit the composer.json file to suit your needs. For example, to change the sub-directory from 'web' to something else, the keys to modify are the 'extra' sub-keys 'webroot' and 'installer-paths'.
Run composer install to download Drupal 8 and all its dependencies.


Linking to jQuery in block breaks Gallery formatter

There's a few issues there. Drupal ships with jQuery so no need to include it twice. If you need a later version, use the jquery_update module. Also, JavaScript in D7 should be wrapped in a jQuery namespace as per the documentation here https://drupal.org/node/756722


Problem with creating page for the path of page display of a view

I infer: you have created the view for listing the contents of library content type, now you are embedding that view in the page template file for theming the contents listed on the page created by view. If this is the case than you are doing the things in incorrect way.

Possible cases for creating the template file for views page:
1. Theme the contents rendered by views on http://www.yourdomain.com/library page: For this you need to create template file as per the views template suggestion, also its best to create the template for view from the suggestion generated by view at Theme: Information as below:

The suggestions for creating the template in the below image is based upon the "test-contact" page I have created in views:

2. Theming the content created for library content type: If you want to theme the contents that is rendered while creating a nodes of library type than you need to create the node--library.tpl.php. This template will be just for theming the contents of library content type created originally (not for the content listed on library page created from views) and it wont have any impact on your views page.

  Now coming to your issue of page at `library/math' does not show math books:

Check if the result in your created view displayed correctly (to confirm that the contextual filter is working fine) on passing math as argument to "Preview with contextual filters" (present at bottom of view).
Make sure that the path of page that you are creating from view is
/library, and for testing purpose you can try changing the path
temporarily to /library123 (If changing the path, than test the
result at yourdomain.com/library123/math page)
Remove the template you have created for embedding the view (as it doesn't seems to be needed, at least as of now)
Clear the cache and check again (not needed logically but no problem for testing purpose)


One of the easiest ways to make sure no emails are going out is to add

Mailcontrol (https://www.drupal.org/project/mailcontrol) which lets you specify what emails go out.

or

Maillog (https://www.drupal.org/project/maillog) which logs all emails and has an option to not send any emails to users. This will prevent all emails from leaving the system and log them if needed. It was designed to test sites but works well in this use case also.

Your other option is to go through and handle them one by one via code. There is no easy button inside of Drupal that will just turn off the service that I know of.

Sorry to just recommend a module, but given your needs this seems like a pretty obvious choice.


mark single form field as cause of error on form validation

You must use a field name like this:  'parent][element'

In your case,

$field_name_error_box = $field_name . '][order_amount';

should work.


If the final addresses are known to be static, you could use destination specific information to identify each link

http://css-tricks.com/snippets/css/style-links-depending-on-destination/

If they include nodes of random values though, this might not work unless you can force the paths for the nodes to be predictable.


Adding a Serial (cck field) to the Page Title

Checkout auto_nodetitle, you could add the serial field as a token to the node title automatically.

The rest should then just fall into place.


How can I display "new" or "update" in the view that overrides admin/content/node?

Just use the "Content: Has new content" field, the same field used from the view that emulates the tracker page.


You could run the cron URL that Drupal provides in Administration > Configuration > System > Cron.

And in your crontab, instead of invoking the cron.php file individually (won't work), you just have to invoke a URL. This can be done with wget, lynx, curl, etc. E.g.:

With wget:

0 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=<key>

Configuring cron jobs using the cron command


If you want to alter the validation you can use hook_form_alter to add/alter the validation handlers used for the form.

To change the product you can use one of the entity hooks: hook_entity_insert is probably the one you want to use, but there also is one for update, presave and delete, and they also exist in a variant specific for commerce products: hook_commerce_product_insert


When page is not node entity site breaks

getType() takes no arguments.

What you want to do is:

  if (isset($vars['node']) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

That will check that the node object exists in the variables array, and getType returns location.

You could go a step further and ensure the type on the off chance that $vars['node'] could get set to anything not an instance of NodeInterface, which getType would not be available for and throw another error.

  if (isset($vars['node']) && ($vars['node'] instanceof NodeInterface) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

Be sure to include NodeInterface with a use statement at the top of the file.

See more about getType().


How to create a module in HTML directly?

No there is no way to create a Drupal module without creating the associated .module (a PHP file) and .info files. If you want your JS file to be inserted on all pages, you can have an empty .module file and add a scripts[] = myscript.js enty in the .info file. Keep in mind that Drupal is a CMS, designed to let site administrator manage content. what you are trying to do looks like embedding a JavaScript application on pages of a site whose content is managed with Drupal. While Drupal is extensible, it is very opinionated on how to build custom page.

Since you module actually mixes JavaScript and HTML, the clean way would be to have the required PHP boilerplate code to produce the HTML markup (ie. register a theme template hook and provides its default implementation) while ensuring the JavaScript file is included on the page whenever you template is rendered. Then have the required PHP code to produce a page containing your markup.

MODULE.module

/*
 * Implements hook_menu().
 */
function MODULE_menu() {
  return array(
    'my-app' => array(
      'page_callback' => 'MODULE_page',
    )
  );
}

/*
 * Page callback for MODULE app page.
 */
function MODULE_page() {
   // A simple page containing a single element rendered from out own template.
  return array(
    '#theme' => 'MODULE_app',
    '#ngApp' => 'myApp',
    '#ngController' => 'myCtrl'
  );
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    'MODULE_app' => array(
      'template' => 'MODULE_app',
      'variables' => array(
        'ngApp' => 'myApp',
        'ngController' => 'myCtrl',
      )
    ),
  );
}

/*
 * Implements  hook_preprocess_HOOK().
 */
function MODULE_preprocess_MODULE_app(&$varialbles) {
  // Add required libraries, with
  drupal_add_js(...);
  // Add the custom JavaScript to the page.
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/MODULE-app.js');
  // Add settings for the rendered element to the page.
  drupal_add_js(array('MODULE' => array($variables['id'] => array(
    'ng-app' => $variables['ngApp'],
    'ng-controller' => $variables['ngController'],
  ))), 'setting');
}

MODULE-app.tpl.php

<?php
/**
 * Add documentation here explaining what this template is and what
 * is expected from any overriding implementation (like having a root element
 * with the ng-app and ng-controller attributes, and what's available in the scope).
 */
?>
<div ng-app="<?php print $ngApp; ?>" ng-controller="<?php print $ngController; ?>">
    First Name: <input type="text" ng-model="firstName">

    Last Name: <input type="text" ng-model="lastName">

    Full Name: {{firstName + " " + lastName}}

MODULE-app.js

Drupal.behaviors.MODULEApp = {
  attach: function(context, settings) {
    // Bootstrap the Angular app for any instance or our element.
    settings.MODULE.forEach(function(variables) {
      var app = angular.module(variables['ng-app'], []);
          app.controller(variables['ng-controller'], function($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
          });
    });
  }
}


Is there a way to set up a default layout for a scholar site in Open Scholar?

Assuming you're using the web-based installer here, it is possible to update this but you're going to have to do it by editing the install profile script. In your sites directory, you're looking for the file:

/docroot/profiles/openscholar/openscholar.profile

You're going to want to add a function, openscholar_profile_final() here (following this guide: http://drupal.org/node/67921) and add a function to add your blocks in:

db_query("INSERT INTO {blocks} VALUES ('blockname', '0', 1, 0, 1, 0, 0, 1, 'my*', '')");


how to programmatically set a group audience

First in your .install when creating your content type, add:

og_create_field(OG_AUDIENCE_FIELD, 'node', 'bundle_name_of_your_content_type');

Then when you need to assign a fresh new content of your content type to an existing group, you can do it in two ways:

1) Found it http://drupal.org/node/1249396#comment-4885442 and thanks to tenken

$node = node_load($nid);
$values = array(
  'entity type' => 'node',
  'entity' => $node,
  'state' => OG_STATE_ACTIVE);
og_group($gid, $values);
node_save($node);

2) Maybe less sexy

$node = node_load($nid);
$node->group_audience['und'][0] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE,
  'created' => mktime());
node_save($node);

Cheers


How to add metatag module data to the Search API indexes

I do it like this:
First

  function HOOK_search_api_alter_callback_info() {
  $callbacks['search_api_alter_add_keywords_field'] = array(
    'name' => t('Keywords field from metatag module'),
    'description' => t("Adds Keyword field from metatag module to indexed data."),
    'class' => 'SearchApiAddKeywordField',
  );
  return $callbacks;
}

Second

class SearchApiAddKeywordField extends SearchApiAbstractAlterCallback {
  public function alterItems(array &$items) {
  foreach ($items as $id => &$item) {
      if (!isset($item->metatags[$item->language]['keywords']['value'])) {

        $item->search_api_keyword = NULL;
        continue;
      }
      $item->search_api_keyword = strtolower ($item->metatags[$item->language]['keywords']['value']);
    }
  }

  public function propertyInfo() {
    return array(
      'search_api_keyword' => array(
        'label' => t('Keyword field'),
        'description' => t('Add keyword field to index.'),
        'type' => 'text',
      ),
    );
  }

}

After Clear cache go to you index filters and check: Keywords field from metatag module
If Boost settings need to be changed (to give more importance to the field) do it now.
Index Again
Go to the search results view - the view you created to list indexed content.
Assuming that you have fulltext search filter in "Searched fields" select the new "field" Keyword field
Test the things out.


If you installed the Devel module, there should be a submodule on the admin/modules page called Devel generate:

Enable it, and you should have some new menu entries in admin/config/development for generating fake conent, menus, terms, users, and vocabularies.


Domain Access with URL Alias - same content, but with different automated aliases

I believe this is exactly what the Domain Path module is for.

According to the module page:

  The Domain Path module allows the creation of separate path aliases per domain for nodes created using the Domain Access module.

However, it looks like this module provides the option per node, rather than offering different pathauto patterns which I think is what you want. There's a postponed request in the issue queue for pathauto integration that offers a partial patch, but it's offered as an anti-proof-of-concept, it seems.


Node reference field auto complete in views

Views Autocomplete Filter done the tricks.

Add autocomplete functionality to the views filter text fields.


Trouble adding markup in a node with hook_node_view()

hook_node_view() is only called within modules that define node content types (ie. through hook_node_info().

What you want to use is hook_node_view_alter(), and render the content in your template file like Mike Vranckx suggested.


How can I access language currently viewed in Views Customfield: PHP Code?

The standard way to display text strings in Drupal is using the t() function. You should enter your text in English and it will be translated to the corresponding string in the current user's language.

If you still want to know the current user's language, you can load the user like this:

$user = user_load(uid);

and the language will be available on

$user->language


How to force a menu parent link to be non-clickable?

You can take look at Special menu items.

User can create a new menu item and place either "nolink" or "separator" to the Path field, without quotes.
Nolink item will be rendered similar to a normal menu link item but there will be no link just the title.

Here is another module you can check: Content Menu

You can create a new menu item as

URL – With the traditional menu item form
Dummy – As a dummy menu item (with simple dummy link target)
New NODETYPE – directly create a new content for the new item


Thanks to Clive comments, and as explained in Drupal, Drush aliases and how to use them, I solved it as following.

Add an alias conf file named sitename.aliases.drushrc.php in .drush folder in your home directory :

/**
 * Local
 */
// The site in sites/default/
$aliases['default.local'] = array(
  'uri' => 'default',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);
// The site in sites/sitename/
$aliases['sitename.local'] = array(
  'uri' => 'sitename_URI',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

Don't forget to clear cache : drush cache-clear drush.

Test your alias : @sitename.local status.

Now you can run i.e @sitename.local mb mymodule hook1 hook2 --write

Really powerful !

See Drush multi-site aliases for complete configuration of local/remote aliases


Webform: send uploaded files as attachments

Or you can use Mail System and Mime Mail modules. A "Include files as attachments" checkbox will appear in Webform E-Mails configuration.


Drupal 7: Permissions when Apache is running as user account

If you're on a shared host this is to be expected, a lot of them operate like that.

Most use suEXEC as the Apache PHP handler which is what makes the web user have full read/write rights over the whole document root. Unless you have access to change the Apache PHP handler (or at least its settings) I doubt you'll be able to change this yourself.

Your hosting provider might do it for you if you get in touch with them, but going on past experience they're normally reluctant to change this sort of thing (in the case of a shared server they might not even be able to do it on a site-by-site basis).


Shouldn't be too hard with a Views Relationship.

As you've mentioned, your View should show content (nodes). Here are the rough settings, as I see it:

Filters: Published or Admin; Content Type: Diary
Display: Fields
Relationships: Content-food nodereference field
Fields: Food (no reference...from the diary content type); calories (from the referenced food field)

That should about do it. I usually have to tweak Views relationships a bit to get them to work perfectly, so it's a bit tough for me to get it exactly right without seeing your content.

Best,
Scott


How to migrate a book from Drupal 6 to a menu in Drupal 7

To begin with we define a class derived from Migration.

<?php

/**
 * To define a migration process from a set of source data to a particular
 * kind of Drupal object (for example, a specific node type), you define
 * a class derived from Migration. You must define a constructor to initialize
 * your migration object. By default, your class name will be the "machine name"
 * of the migration, by which you refer to it. Note that the machine name is
 * case-sensitive.
 *
 * In any serious migration project, you will find there are some options
 * which are common to the individual migrations you're implementing. You can
 * define an abstract intermediate class derived from Migration, then derive your
 * individual migrations from that, to share settings, utility functions, etc.
 */
abstract class MenuMigration extends DynamicMigration {

public function __construct() {

# Always call the parent constructor first for basic setup.

parent::__construct(MigrateGroup::getInstance('Menu'));

}
}

We now create a class that extends the above.

class EducationalGuideMigration extends MenuMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

# Human-friendly description of your migration process. Be as detailed as you like.

$this->description = t('Migrate the "Studies Guide" menu');

We create the mapping in the database and our query.

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'mlid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Menu link ID',
                       'alias' => 'ml'
                      )
    ),
    MigrateDestinationMenuLinks::getKeySchema());

$query = Database::getConnection('default', 'migrationDB')
           ->select('book', 'b');
$query->leftJoin('menu_links', 'ml', 'ml.mlid = b.mlid');
$query->fields('b', array('nid', 'mlid'))
        ->fields('ml', array('menu_name','mlid', 'plid', 'link_path', 'router_path', 'link_title','options', 'module', 'hidden', 'external', 'has_children', 'expanded', 'weight', 'depth','customized', 'p1', 'p2','p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'updated'))
        ->condition('bid', 30, '=')
        ->orderBy('ml.mlid');

As you can see we create our mapping based on the mlid (menu link id) primary key. You can find this key in the menu_links table and the book table. The book table holds only keys, namely nid, mlid and nid. The menu_links table holds all the info pertaining any sort of navigation menu in your drupal site, from your custom menus to administrative ones.

Luckily, Migrate provides us with a migration class for our mapping called "MigrateDestinationMenuLinks".

We use left join to join the two tables mentioned above. Obviously we need to know from which book we have to get our data so the book with id=30 is the one I was interested in.

We then execute the query and provide the destination menu plus anything we won't migrate (these unmigrated fields get default values).

# Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query);

# Set up our destination menu
$this->destination = new MigrateDestinationMenuLinks();

/**
 * SOURCE FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedSources(array ('module', 'options', 'has_children', 'depth','hidden', 'updated', 'external', 'customized', 'expanded', 'link_path', 'router_path', 'mlid', 'menu_name', 'mlid'));

    /**
 * DESTINATION FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedDestinations (array('module', 'options', 'has_children', 'depth','hidden', 'updated'));

Now it's time to map the fields that we do need to migrate.

  /**
 * FIELDS TO BE MIGRATED
 */

$this->addFieldMapping('menu_name')
        ->defaultValue("menu-studiesguide");
$this->addFieldMapping('plid', 'plid')->sourceMigration($this->getMachineName());
$this->addFieldMapping('link_path', 'link_path');
$this->addFieldMapping('router_path')->defaultValue('node/%');
$this->addFieldMapping('link_title', 'link_title');
$this->addFieldMapping('external')->defaultValue('0');
$this->addFieldMapping('expanded')->defaultValue('0');
$this->addFieldMapping('weight', 'weight');
$this->addFieldMapping('customized')->defaultValue('1');
$this->addFieldMapping('p1', 'p1')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p2', 'p2')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p3', 'p3')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p4', 'p4')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p5', 'p5')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p6', 'p6')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p7', 'p7')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p8', 'p8')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p9', 'p9')->sourceMigration($this->getMachineName());

In the menu name mapping we provide as a default value, our menu's machine name. (whatever name you gave is appended with the "menu-" prefix by Drupal).

Now you will notice that for the fields plid and p1 to p9 I have added this argument:

->sourceMigration($this->getMachineName());

First of all plid and p1 to p9 are all menu link ids. Plid is the immediate parent of every mlid and p1 to p9 is essentially our navigation menu for every menu branch.

What the argument does is pretty simple. It prety much tells our migration, "You know what, I got all the mlids from the query so any parent id you create is gonna be one of those menu link ids". (Note: that is why in our query we order by mlid).

So now ok, we have our menu, however the menu items are supposed to have links that correspond to nodes right? Well the book I had to migrate had 2 different content types which I also migrated, but their nodes were not assigned to these menu links. Also the nids I can get from the Drupal 6 are not the ones I need to assign to my menu links. So what do we do? Enter prepareRow().

function prepareRow($row) {

    $current_nid=$row->nid;

    $querymmi = Database::getConnection('default')
            ->select('migrate_map_idrimata', 'mmi');
    $querymmi->fields('mmi', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

    $resultmmi = $querymmi->execute();

    if($resultmmi->rowCount()==0){

        $querymms = Database::getConnection('default')
            ->select('migrate_map_studies', 'mms');
        $querymms->fields('mms', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

        $resultmms = $querymms->execute();

        if($resultmms->rowCount()==0){
            print "EVALA TH XAROULA EDW \n";
            print "path: node/9118 \n";
            $row->link_path = "node/9118";
        }

        else{
            print "STUDIES PATH INSERTED SUCCESFULLY \n";
            $row->link_path = "node/" . $resultmms->fetchField(0);
        }
    }

    else{
        print "IDRIMATA PATH INSERTED SUCCESFULLY \n";
        $row->link_path = "node/" . $resultmmi->fetchField(0);
    }
   }

So what we do here is this. Every time you migrate nodes a migrate map is created that corresponds drupal 6 nids to Drupal 7 ones. So we query those tables (as I mentioned earlier my book had 2 different content types) and we compare every nid we get from this migration's query with the source nids from our map tables.

We use this "if" condition to handle any case where no results are returned in our comparison:

if($your_result_variable_here->rowCount()==0)

The first condition checks if we have nids from our first map table, if not go check the other one.
The second does the same check, but the reason to actually have it there is to provide a default value to a menu link if our condition doesn't return true (highly unlikely but it happens).

And finally how do we provide the correct nid to our menu link? Well be it either a default value or one of the node ids this is what we do:

$row->link_path = "node/" . $resultmms->fetchField(0);

Get the link_path field from every row of our query, concatenate the string "node/" with the nid that we get from our result set. The fetchField(array index # here) does that.

So that was it. Hope my explanation was clear enough and it actually helps out.


List of users who signed-up last month, or last year

I believe you can create a View of Users. Group by signup date.


CCK Filefield source->IMCE No option to browse server unless UID1

Yes, it was me being stupid...

I didn't check the 'role profile assignments' at admin/settings/imce

:(


Resolve the error "An illegal choice has been detected..."

The problem is most likely because of a requirement for FAPI AJAX which is documented in AJAX Forms in Drupal 7, though can be easily missed.

  Changes to the form must only be made in the form builder function (ajax_example_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

The fact that you're setting the form element [#options] in the AJAX callback is definitely a problem. The AJAX callback should only return the array or HTML to be printed, not change the form. That callback should only contain the return statement.

The changes to your form should be made in the form_alter. Also, you should use the form_state array to check whether a value has been selected for your first dropdown. This will be updated during an AJAX request.

I recommend looking at the examples module, as well as these pages for more information on AJAX in FAPI. It can definitely be tricky.

AJAX Forms in Drupal 7
AJAX Framework


Advanced mode means

  Set the Views settings to more developer-oriented values.

You can check the definition of this in views module Drush folder views.drush.inc file.

  $items['views-dev'] = array(
    'callback' => 'views_development_settings',
    'drupal dependencies' => array('views'),
    'description' => 'Set the Views settings to more developer-oriented values.',
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
    'aliases' => array('vd'),
  );

Once drush vd command is executed following variables are set.

  variable_set('views_ui_show_listing_filters', TRUE);
  variable_set('views_ui_show_master_display', TRUE);
  variable_set('views_ui_show_advanced_column', TRUE);
  variable_set('views_ui_always_live_preview', FALSE);
  variable_set('views_ui_always_live_preview_button', TRUE);
  variable_set('views_ui_show_preview_information', TRUE);
  variable_set('views_ui_show_sql_query', TRUE);
  variable_set('views_ui_show_performance_statistics', TRUE);
  variable_set('views_show_additional_queries', TRUE);
  variable_set('views_devel_output', TRUE);
  variable_set('views_devel_region', 'message');
  variable_set('views_ui_display_embed', TRUE);
  $message = dt("Setup the new views settings.");
  drush_log($message, 'success');

You can do it with out using drush command too by navigating to "admin/structure/views/settings"


How to refresh entity from entity_load(), reloading the entity as it is now?

There is entity_load_unchanged(), which does a reset cache itself as well, but however only for that specificy entity id.

This is already available by default in presave and insert/update hooks as $entity->original.


Best Approach for View Caching using a Proximity Filter

How about this module:
https://www.drupal.org/files/images/Views_content_cache.png

Without testing it I cannot tell if it will expose the 'nearby' state as a filter for for the update cache  function but looks like a good place to start:


When should I use Backdrop CMS rather than Drupal 8?

Backdrop CMS is a good choice if:

You are currently spending a lot of time managing your configuration using Features module. Backdrop includes built-in Configuration Management tools that allow you to deploy configuration across environments using JSON files, which should save a lot of time compared to Features.
Your needs are met by the current selection of Backdrop Contributed modules or you are capable of porting modules to Backdrop (it takes a few hours per module generally speaking). References from: Lullabot, Tag1, and Backdrop documentation.
You are familiar with Drupal 7 code and would like to transfer that knowledge to a newer system that will be supported in the future. Backdrop code is nearly identical in concepts, though there are several new additions to manage configuration. Drupal 8's code base is significantly different in many fundamental concepts.
You have an existing Drupal 7 site that you would like to upgrade. Backdrop includes an upgrade path (via update.php) that can upgrade your existing Drupal 7 site to Backdrop. Drupal 8 does not include an upgrade path from Drupal 7; the plan is to provide migration tools to move from Drupal 7, but at this point, it is not yet working. Backdrop does not yet have a port of the Migrate module, but it probably will in the future (since porting modules from Drupal 7 is fairly trivial).
You want to upgrade/build a site right away. Backdrop 1.0 had been out for about 2 months now and is stable. Drupal 8 may be coming out some time later this year (though we can only estimate the date). Drupal 8 does not yet support upgrades even between beta versions, so if you build a site on it now, you won't be able to upgrade it when the final version comes out.

Other features that Backdrop includes:

Backdrop is slightly faster than Drupal 7 out of box because of it's lighter core. Generally it's about the same speed as D7 but since D8 is slower than D7, Backdrop is faster than D8.
Backdrop has a built-in Panels-like module (Layout) that replaces the old Block system. Blocks are given new powers like contextual information, advanced conditional selection, multiple instances, control over markup, and config-based settings.
Updated libraries (e.g. new jQuery versions).
Responsive, HTML5 elements, and better mobile support out of the box.
All the other features listed on the Backdrop CMS homepage.


The easiest way to do this is to use $form_state. In your formBuild() method, you have an if/else or switch based on something like $form_state['step'] and display different form elements. Then you either have the same in your submit callback or have multiple submit callbacks, that do something to an object in $form_state that you're building, change the step and set the $form_state['rebuild'] flag to TRUE.

There are a few downsides to that approach, which is why (among other reasons) the ctools form wizard was created. It can get complicated if you have multiple steps and have to define all of that in a single form function/class and everything happens in POST requests.

What the ctools form wizard does is group multiple, separate forms together and control the navigation from one to the other. You also use the ctools object cache to store your object instead of $form_state, because that is no longer shared across your forms.

While that system doesn't exist yet, the ctools object cache has been ported to 8.x and is now called user tempstore, available as a service: \Drupal::service('user.private_tempstore') (before 8.0-beta8 called user.tempstore). This is a layer on top of the expirable key value store that introduces ownership of stored data in there. So this is what powers the well known message in views that a different user is currently editing that view and it's locked for that reason. Another advantage over using $_SESSION for that is that your data only has to be loaded when needed, when you are editing 3 views, then using $_SESSION would mean that you have to load and carry them around on every single page request.

If you don't need that, then you could rely on the session or also directly put it in an expirable key value store ($form_state is stored there now as well, not a pseudo-cache as it was in 7.x).

The configuration system however isn't a good match. That is not meant for per-user content (or content at all) as it doesn't really scale to store thousands or tens of thousands of records and might make some assumptions to pre-load everything it might need on a given page request (not yet, but there is an issue to make that happen)


I believe the = function (context) bit needs to include the attach:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      alert('say something pretty please');
    }
  };
})(jQuery);


How do I make a mini-panel pane a title?

OK, found it.

It wasn't in the pane settings as I thought (I was looking through loads of Panel documentation). Right at the top of the Edit Mini Panel page there is a dropdown menu called Title Type. You can set this to 'From Pane'.


So far you've translated only the menu configuration consisting of Label and Description. The menu language select box is for the original language of the menu, in your case English.

The translation of menu links works independently by translating the menu links themselves, which is content translation and works the same as for nodes. You see a Translate tab when you click on Edit for a menu link in the main screen of the menu (after you've enabled content translation for custom menu links in admin/config/regional/content-language as you've already done).

The menu items are the same for all languages. If you want to have a different set of menu links for each language then you have to use separate menus.


Custom entity datetime field in calendar

EntityViewsData provides the information for views for entity types, so that they are included in views. For datetime basefields this is not working at the moment, because of this issue https://www.drupal.org/node/2489476. So you need to provide the data in a hook_views_data or by extending EntityViewsData. From the documentation:

  argument: Specifies a handler to make it available to Views as an   argument, or contextual filter as it is known in the UI.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_data/8.3.x

You've mentioned that you have a working example if you use a field configured in UI, so you could try to copy the views data.


Outputting multiple content fields all wrapped in a div

Multiple ways to achieve this.

By creating a node tpl file for that particular content type.
By creating view.
But i think the best and easiest way is creating group in manage display. Check field group module.

Procedure to create group.

Go to structure->content types->content(ex-blog)->manage displays.
Add a new group of div type.
Drag the required field like field2 , field3 etc under it.

Print in tpl file.

It will be easy to find out if you will update the code snippet of node--case-study.tpl.php file.

I think you need to first check by printing

echo '
';
print_r($content);

and use this for

  <?php print($content['field1']); ?>

 <?php
    print($content['field2']);
    print($content['field3']);
    print($content['field4']);
 ?>


Show and require field if birthday (date field) is less than 18 years old

Here is a working solution. Huge thanks to @nikathone for assistance.

/**
 * Implements hook_form_FORM_ID_alter() for record_node_form.
 */
function mrpeanut_form_record_node_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['field_dob']) && !empty($form['field_minor_agreement'])) {
    $form['field_minor_agreement']['#prefix'] = '
';
    $form['field_minor_agreement']['#suffix'] = '
';
    $is_younger = TRUE;
    $values = !empty($form_state['values']) ? $form_state['values'] : array();
    $dob_date_combo_element = &$form['field_dob']['und'][0];
    $dob_date_combo_element['#ajax'] = [
      'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
      'wrapper' => 'edit-field-minor-agreement-wrapper',
      'effect' => 'fade',
    ];

    if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
    }

    $form['field_minor_agreement']['und']['#access'] = $is_younger;
    $form['field_minor_agreement']['und'][0]['#required'] = $is_younger;
  }
}

/**
 * Ajax callback for minor agreement.
 */
function mrpeanut_form_record_node_form_minor_agreement_callback($form, $form_state) {
  return $form['field_minor_agreement'];
}


Can you make a block appear only in a specific content-type

In the block configuration page, select the content type like this picture:


Drupal 7, superfish menu hidden in garland theme

In page.tpl.php page search with keyword menu,

 <div id="main-menu" style="z-index:99">

you can put style z-inex here.


You can go to configuration -> account settings -> manage fields and add your field. then in the settings check it to show in registration form

admin/config/people/accounts/fields


Email all users when a new content is published in Drupal 7

You can use the Rules module, a more powerful version of actions and triggers.
Configure a rule as follows:

React on event: (Node) After saving new content
Action: (System) Send mail to all users of a role

However, you cannot select the authenticated role here.  Instead, you will have to add another role to your site and use it instead.  (You can create another rule to automatically add that role upon registration.)
Also, note that the Rules module has this warning about sending too many mails:

WARNING: This may cause problems if there are too many users
of these roles on your site, as your server may not be able
to handle all the mail requests all at once.

So if you have a lot of users this probably isn't a good solution.


Debugging your code under SimpleTest when the behavior is different

I have a provisional answer to this, although I'm hoping someone will supply a better one than this one.

First of all, setting XDEBUG_CONFIG as an exported environment variable will let you stop your test script, but not your actual Drupal code.  The reason is sort of ugly.  SimpleTest interacts with your code using its own mini-browser.  So your SimpleTest test runner is as completely isolated from your Drupal application as your browser at home is isolated from the web server you get your page from.  There's no connection at all.

So how do we use xdebug via a browser?  One way is to set a get parameter, and add the XDEBUG_SESSION_START variable to your URL, like this:

  http://my-site-i-want-to-test/node/42?XDEBUG_SESSION_START=my-key

When your test web server sees XDEBUG_SESSION_START, and you have your server set up to connect with your IDE, your server connects up with your IDE, and away you go.

So, here's my not-really-very-good solution to the problem: I get drupalGet and its twins to add XDEBUG_SESSION_START to the string SimpleTest uses to communicate with your server.

SimpleTest is actually using PHP's curl extension to create its mini-browser. If you look at the implementation of drupalGet in WebTestBase.php, you'll see something like this:

  protected function drupalGet($path, array $options = array(), array $headers = array()) {
    // We re-using a CURL connection here. If that connection still has certain
    // options set, it might change the GET into a POST. Make sure we clear out
    // previous options.
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));

    // lots of stuff omitted here...

    return $out;
  }

The $options argument gets passed to $this->buildUrl(), which takes the regular format for URL options.  We need to add something to the query string, so we need to pass

$options = [
  'query' => [
    'XDEBUG_SESSION_START' => 'my-key',
  ],
];

This unfortunately requires you to edit your test and pass $options whenever you want to get control of your application via your debugger.

A slightly better solution is to override drupalGet() in your test class, since AFAICT, all the other drupal*() methods ultimately call drupalGet().  In your overrided version, you just append the 'query' info above to the $option array that is passed to it, and then call the original method.  You can even watch for a environmental variable in your SimpleTest test script, and only add the 'query' string when you see it.


Migration from source YML: implode all values of each array element nested inside an parent array

The documentation examples of concat plugin use a flat, non-associative array of strings as source, you are trying to concat a nested array of JSON objects. You could try to subprocess your tags to only fetch/concat the displayName from them


How to remove "FILE NAME SUGGESTION" from rendered HTML

I found the reason why "FILE NAME SUGGESTION" was still output.
It is because a following code still remained in template.php in Zen(not sub theme).

$GLOBALS['conf']['theme_debug'] = TRUE;

I didn't coded it by myself. So, I guess the code was added when I install some module(probably Theme developer?).

Anyways, when I comment out it,  "FILE NAME SUGGESTION" disappered.


How to control the order in which the markup for fields appears in the outputted html source for content?

You can change tho order these fields are displayed from Manage Display (admin/structure/types/manage/CONTENT TYPE/display). Edit the weight there and the fields should be displayed in the selected order on the node view page.

Edit: In the fields screen (admin/structure/types/manage/CONTENT TYPE/fields) the weight is used for displaying the form fields in the edit/add content type form.


Undefined index: und on .tpl.php for content type

I fix it by

add

!empty( )

like this

$img_url = !empty($node->field_icon['und'][0]['uri']) ;


Validate a custom type node before submitting

In Drupal 8 the hook hook_node_validate() has been removed. Here are some suggestions.

Reference: hook_node_validate() and hook_node_submit() have been removed.

Field constraints

If you're trying to validate an individual field,  use a constraint.

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function custom_general_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter node.page.field_service.
  if ($entity_type->id() === 'node' && $bundle === 'page') {
      $fields['field_service']->addConstraint('CustomAssignableService', []);
  }

Entity constraints

For general constraints on the entire entity or constraints which are not specific to a single field.

/**
 * Implements hook_entity_type_alter().
 */
function custom_general_entity_type_alter(array &$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('CustomAuthorizedTerritory');
  }
}

Form validation

The "constraints" will always validate the field / entity no matter the form / method with which you use save the entity.

Additionally, you can provide form validation using a hook_node_form_alter() to improve the UX with nice error messages.

Note: These are "form-level" validations and are only applied when the node is created / updated from a said form. Users might be able to bypass these restrictions while saving the node using web services or other forms (if any).

// In the mymodule.module file.

/**
 * Implements hook_form_FORM_ID_form_alter().
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'mymodule_node_form_validate';
}

function mymodule_node_form_validate($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->getType() == 'custom_content_type') {
    if ($form_state->getValue('some_property') !== '123') {
      $form_state->setErrorByName('some_property', t('Property must be 123.'));
    }
  }
}


How do I translate empty text of a view?

If this view is showing inside of a block then make sure you have the translation "Make this block translatable" is checked, and what ever language you want to translate to is also checked.
hope this helps.


Expand +/- button for taxonomy display in a page

You want to try to use Views Accordion:

  Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.

  For Drupal 7 the module integrates the jQuery UI Accordion plugin as a
  views style plugin. You can configure the options provided by the
  jQuery UI plugin.

  For Drupal 6 the module used it's own jQuery code, so a different set
  of features is available for D6.

Views can override the default taxonomy pages, or you can try to create your own grouped taxonomy listing which uses this display plugin.


You need to use truncate_utf8() using $wordsafe = TRUE;

  $wordsafe Flag to truncate at last space within the upper limit. Defaults to FALSE.


Taxonomy dropdown to match the related content (in a views with exposed filters)

Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings


I didn't find out why my order views disappeared, but I was able to import them back using configuration synchronization :

https://www.drupal.org/node/2917828#comment-12321847


I am not sure if you use drupal 6 or 7

You can configure this:

go to:  http:/your.drupal/admin/user/permissions
CTR + F do search on page and search for this both permissions:
unpublish current revision
delete archived revisions

But if also admins should not see this any more, you have to modify code:
(here for Drupal 6)

edit sites/all/modules/revisioning/revisioning_theme.inc
search for: unpublish current revision
4 rows below you will see:  $links[] = $link;
change it to: // $links[] = $link;
now search for: delete archived revisions and do the same
save and done


"Node Recommendation" Module alternatives

There are two excellent modules, both compatible with Drupal versions 6 and 7:

If you want to display similar nodes calculated by the actual node content, try Similar entries
If you want to display similar nodes calculated by some sort of taxonomy setup, try Similar By Terms

There's also Relevant Content, a module which allows you to configure the recommended nodes based on many different things, with different block configurations and stuff for dealing with CCK. I haven't used it, but I've heard it's quite good.


Is there an anti-spam advantage of using reCAPTCHA module instead of just CAPTCHA by itself?

The biggest advantages of using reCaptcha is the built in support for people who are visually impaired and the ability to evolve without your intervention. ReCaptcha continuously changes to fight of spam bots.


Authenticated users missing from users_roles table

It is not an "issue" - but the authenticated user role is not registered in the users_role table.  For this type of user, the status is determined by the field statusin the users table.

AFAIK, every user registered in the users table is considered having the "authenticated user" role, so there is no need to explicitly register this role in the  users_role table. Instead, users having this should have their status set to "blocked" when you want to "strip" them of any grants.


Translation for node references not working properly

The only solution I found is to remove all elements in field collection of translated node and add them once again - with properly translated elements/values.


Increase Product Quantity based on attendees added Drupal Commerce

If you want to do this solely via Rules, then you'd likely need to write a custom Rules action that can count those attendees and apply an appropriate price adjustment to the unit price of the line item. If you want to bypass Rules completely, you can change your price calculation process to support module based alterations and write custom code that hooks into the sell price calculation process via hook_commerce_product_calculate_sell_price(). The challenge here is that you aren't getting these attendees until the checkout form, so you'll want to make sure the customer has a chance to review the final price before paying.


PDO requires that you use single quotes, e.g.

db_query("SELECT FROM_UNIXTIME(`created`, '%Y') as year, FROM_UNIXTIME(`created`, '%m') as month, FROM_UNIXTIME(`created`, '%d') as day FROM users ORDER BY `created`");


Found that there is additional step: you have to add/enable that relationship at View GUI->Advanced->Relationship


How to bypass Drupal page cache if a certain cookie is set on a shared domain?

I would suggest looked at the Single Sign options of Drupal or implement some code that logs you into Drupal when they login to the non-Drupal site.

EDIT: first, boostrap Drupal and then run this function:

function drupal_user_login($username, $password)
{
    $uid = user_authenticate($username, $password);
    if($uid)
    {
        $form_state = array();
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);

        return true;
    }
    else
    {
        return false;
    }
}


Migrate callbacks() with addFieldMapping for destination_dir

Maybe you can use file_class like this

$this->addFieldMapping('field_yourimage_field', 'fidsarray');
$this->addFieldMapping('field_yourimage_field:file_class')
->defaultValue('MigrateFileFid');

The you have to implement prepare row to get the managed file fids you want to import like this

public function prepareRow($current_row) {
 if (parent::prepareRow($current_row) === FALSE) {
  return FALSE;
 }
 //sample code to get the file ids. it may be different in your case
 $fidsarray= array();
 $fidsarray = explode(",", $current_row->columnwith_file_ids_comma separated);
 $current_row->fidsarray=$fidsarray;
}

if you dont have managed files and therefore fids available other options can be used too.
See https://www.drupal.org/node/1540106


How to combine 2 exposed filters (String and Taxonomy field)

Yes,by default drupal handled this.
in Filter criteria in your views  click and hold arrow sign beside add.open   menu with And/Or, Rearrange.In this section(Rearrange filter criteria) you can determine gorup for your filter and  criteria between your filters.


I spent countless hours figuring it out as well; the solution was so dumb simple !

Edit your theme's ".info" file and add :

features[] = main_menu
features[] = secondary_menu

Otherwise main_menu and secondary_menu doesn't display at all.

Hope that helps.


this will not work because the menu are build during the cache clearing, thus the url cannot be dynamic.

i instead use an EventSubscriber on Kernel::REQUEST and redirect the user if need be.


How to make a responsive theme in Zen 5? Modules and procedures to keep or to leave from older Zen versions

I would avoid getting confused.  Zen Grids is not the same as the panels module.  The fences module just makes it easier to override the default field html output.  The responsive menu you showed is just css and a media query.

A little zen might help also, take a deep breath and repeat after me, "It is all just css."


To add and then group fields in views, you can do the following (if not using a view mode/template).

Add all the fields you need, and mark each of them "Exclude from display".

Add another field of type 'Custom text'. DO NOT exclude this one.

Click on the 'Custom text' field to open its options.
Inside the textarea there, you can input custom html using the tokens from the fields above to populate it. You can find the values you'll need for replacement if you click on the "Replacement patterns" dropdown just below the textarea.


How To Set Order State Completed after Notification?

Unfortunately, the "Default" order workflow for Commerce 2.x is fairly naive. It only has states for Draft (i.e. shopping carts), Completed (i.e. any placed order), and Canceled. If you need more states, you'll need to supply an alternate workflow. Core ships with a "Default, with validation" workflow you can set for your order type that includes a "Validation" step you could make use of instead.
Generally speaking, it's likely your payment gateway module shouldn't be controlling the actual order state transition. It can and should update the payment transition, and then a separate module specific to your site can be responsible for defining exactly what you want your workflow to be and automating the transition based on the order paid event (cf. OrderEvents::ORDER_PAID).


Setting the admin theme only inside the overlay

The Overlay Theme module would probably be ideal:

  Overlay theme is a small module that provides an option to set the theme of modal frames provided by the core Overlay module, different from the default which is the Administration theme.

Using that you could set your default admin theme to the same as the front end, and set the overlay theme to what ever you like.


Set a content type's teaser image (right outlined)

What you will want to do is go to your views admin page for that view.

If the view is built using fields simply click on that field and select:

Style Settings
Check the box titled "customize field HTML"
You can modify the view to display it as a div or leave it as is
Check the box titled "create a css class"
Type in a css class
Click apply. And save the view.

Now you can go to your theme .css file and create a new css rule to position the image. And should apply for all future views with that css class for that field.

Let me know if you need further help.


You might be able to customize the excellent tutorial on the use of Ajax for Like and Dislike using voting API by Amitav Roy. His primary purpose is to show the reader how to use AJAX, but the code is solid and seems to suit your purpose.


Making a custom views field handler click sortable (getting an error when clicked)

Because this data is not stored in the database (it's just a dummy field that returns the result of some calculations) you can't make it click sortable as there is no database column to 'order by' in the SQL statement generated by the view.

There must be a way around this but it's likely quite complicated and beyond me at the moment.

If you have a custom handler that does something to change the way you display existing field data you can make it click sortable by overriding the click_sort($order) function in your handler class.

My mymodule.views.inc now looks like the below (where 'real field' is the name of the field included in the view, before the custom field created by my handler, but excluded from display)

<?php

function mymodule_views_data() {

    $data = array();

    $data['node']['mymodule_handler_myname'] = array(
        'title' => t('Score'),
        'help' => t('Makes score values human readable'),
        'real field' => 'value',
        'field' => array(
          'handler' => 'mymodule_handler_myname',
          'click sortable' => TRUE,
        ),
    );

    return $data;

}

?>

and my mymodule_handler_myname.inc looks like

<?php

class mymodule_handler_myname extends views_handler_field {

    /**
    * Loads additional fields.
    */
    function query() {

    }

    function click_sort($order) {

        $this->query->orderby[] = array(
            'field' => 'field_name', // here may be a field, or some SQL clause e.g. FIELD(str, str1, ...)
            'direction' => strtoupper($order),
        );

    }

    /**
    * Renders the field handler.
    */
    function render($values) {

        if (isset($values->field_name)){

            switch ($values->field_name){
                case 2:
                    $vote = 'Yes';
                    break;
                case 0:
                    $vote = 'No';
                    break;
                default:
                    $vote = 'Maybe';
                    break;
            }

            return t($vote);

        }
    }
}

?>

This wrecked my head for a full day so hopefully it's helpful to someone in the future.


How can I create a recommended project in the root directory?

If wwwroot is empty you can simply run the following command from inside this directory.
composer create-project drupal/recommended-project .

The . at the end says: current directory.


Try adding '#wysiwyg' => TRUE,

Also i think you need to keep '#type' => 'text_format', instead of textarea.


Views AJAX functionality works, but nothing changes at all

Solved. View used permission that whas removed. Internally Drupal used different (admin related) to access this View. Strange that View was rendered, IMO exception should be thrown (in case of missing permission)


Call to undefined function entity_create()

As Gulok said, check if the module entity is installed and enabled.

Be sure to add entity as a depencencie in your .info file as well.


Module listing page leading to php timeout

The solution to this was to increase the RAM in the server. We were using a container and the container was very restrictive in the amount of available RAM.


Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous

You have to add alias in MigrateSQLMap

$this->map = new MigrateSQLMap($this->machineName,
   array(
       'uid' => array(
           'type' => 'int',
           'not null' => TRUE,
           'alias' => 'u',
       )
   ),
) ;


Accessing content for a specific node revision via a relationship in Views

One thing you could try is creating a class that extends views_handler_relationship and override it's query() method using logic that's specific to your use case rather than the generalised logic that's in views_handler_relationship->query().  Then change the "handler" in your relationship declaration to point at your subclass.

Hope it helps.


How can I hide a nodereference url link for users who have already created a node

One solution that comes to mind includes using the nodereference_url_create_link function that is included in the Node Reference URL Widget module. From the documentation of the specific function:

/**
 * Helper function for themers to easily create a link.
 *
 * This function should be used in custom themes, rather than making manual
 * links because it first checks a user's access before showing the link. If
 * the user does not have access to create the node then an empty string will
 * be returned.
 *
 * @param $node
 *   The node object that will be referenced.
 * @param $field_name
 *   The name of the Node Reference field.
 * @param $type_name
 *   The name of node type that contains the Node Reference field.
 * @param $attributes
 *   Optional. An array of additional attributes to add to the link.
 */

You can use this in the node.tpl.php file for the Job Posting content type (which should be along the lines of node--job_posting.tpl.php if you're in D7 or node-job_posting.tpl.php for D6). The outline of the process should be as described below:

Hide the field at the top of your template file (you will render it later on if the user did not apply for the specific job).
Check if the user has already created an application node that references to the current posting.

The first step can be easily implemented by writing something along the lines of:

hide($content['YOUR_FIELD_NAME']);

at the top of your template file. Use a dpm($content); first to make sure that you are hiding the right field.

The second step is a bit trickier. The most elegant way that comes to mind is to use the Corresponding Node References module so that when you create a reference from the application to the posting, a corresponding reference from the posting to the application is also created (this can also be useful if you want to show all the applications that were created for a specific posting in the posting's page).

After you have "linked" the posting and the application with CNR, all you need to do is check if the author of the other postings is the logged in user. Specifically, you can use the node reference array in the $node object to get the referencing applications with node_load_multiple and then with a foreach loop compare each $node->uid against the uid of the logged in user.

There is a blog post in Drutácora that describes a similar process and includes relevant code snippets (it's not in English but you should get the basic idea from the code).


How to have new fields show with default content on new items?

Is it normal that the default fields will only work on NEW content items?

Yes, that is normal.

The way I work around that to update the OLD fields:

Go to the database and export the field table.

For format: select CSV (do not select "CSV for MS Excel")

Open the .csv file in Excel and make changes to the values.

To replicate a cel fast in excel, highlight 1 cel and move mouse to the right bottom corner of the cel (cursor will change to a +), then hold down left click and scroll down.

Import back to the DB and check-mark "replace table data with file".
In Drupal, clear/flush the caches to see changes.


A simple solution would be to cache the output instead of caching the block. This would be done in your hook_block_view implementation.

It could look like this:

...
$cache = cache_get('pref_pref_leader', 'cache_block');
// Return cache if possible.
if (!empty($cache) && isset($cache->data) && !empty($cache->data)) {
  return $cache->data;
}

// no cache, generate the output.
...
$content = ...;
$block = array(
  'subject' => 'Семерка лучших',
  'content' => $content,
);
// Cache for 30 mins.
cache_set('pref_pref_leader', $block 'cache_block', time() + 1800);
return $block;
...

See documentation for

cache_set
cache_get


In which contrib file/function should a class_alias() statement be placed so that it is always processed, regardless of the url being served?

So is there a better place than my_module.module where I can put the
class_alias( ) statements, such that they are always processed?

Put class_alias() in the class file (after the use statements before class {} or at the end of the class file).
*.module files are not loaded by the class loader, they are included later in the kernel bootstrap process.


You can do this by using Webform Hints module.

  This module allows users to enable automatic placeholders to
  textfields, textareas, select lists, and email fields within a webform
  created by the Webform module.


Alter custom menu links with a session variable

The menu links defined in yaml files are static. For dynamic menu links you have to use a menu link class:

src/Plugin/Menu/CustomMenuLink.php

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class CustomMenuLink extends MenuLinkDefault {

  public function getTitle() {
    return $this->t('Test-Link');
  }

  public function getRouteName() {
    return 'entity.node.canonical';
  }

  public function getRouteParameters() {
    $nid = rand(1,10);
    return ['node' => $nid];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}

This example is a menu link randomly selected a node between 1 and 10. For code depending on a session replace the cache max age with a context:

  public function getCacheContexts() {
    return ['session'];
  }

Point the yaml file to this class to replace the static details of the route with the dynamic methods defined in the class:

mymodule.links.menu.yml

mymodule.testlink:
  weight: 10
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\CustomMenuLink


How to update the current page to show new content?

I am not sure what functionality you are trying to build and if adding PHP code inside a Drupal node is the right way to do it. But assuming that is what you would like to do, here are the steps to achieve what you want:

Create a Drupal node (say the nid of it is NID) and add the following PHP code inside it

$table_name = arg(2); // This grabs the 3rd argument of the page menu path (note: the 1st argument is indexed 0)
print $table_name; // Replace this with PHP code to fetch and print data in the table represented by $table_name

When you are making table1, table2 etc links make sure the URL that they point to is node/NID/<table_name> where <table_name> is table1, table2 respectively.


Node edit form with entity reference - show more than just the title in the autocomplete box

You can do this by creating an entity reference view.

Firstly, create a new view that displays the content type 'organization'. Do not add a page, but rather add an 'Entity Reference' display.

Your view should now have a format of 'Entity Reference list'. Now add a relationship to organization_note, and then add the fields that you would like to see in the autocomplete list. When that is done click on settings in 'format', and select the field that you want to search on when typing in the autocomplete. This normally would be title. You can also rewrite the field values to your liking as you would probably need to for your use case, though I would leave title standard.

Now go back to the field settings for 'application', and edit the settings for the entity reference field to organization. In the 'Mode' for the 'Entity Selection' section, select 'Views: Filter by an entity reference view'. This will open a new select from which you select the view you created above.


Allow access for anonymous to custom user view mode

As you already guessed the permission is checked before building the content, so you will never be able to display any user data without that permission. (At lest not without some programming.)

You could try to grant the View user profiles permission to all user and then use the Field Permissions module and grant access per field. So you can show anonymous users only the fields they should have access to.

UPDATE:

As you have pointed out the above solution introduces some problems with privacy and some additional fields not being hidden on the user profile.

So another suggestion; Remove the Views access check. Views by default bypasses access checks on content (so Views without access checks are considered unsafe). Which might be of benefit to you here. As an alternative you can set a more generic permissions such as View published content to prevent errors from modules like Security Review.

Then under display choose Display Suite and your custom view mode.

You will end up with a View that shows the custom View mode with all selected fields, even for anonymous users. Yet the user profile at example.com/user/1 shows access denied for anonymous users.


Create a custom module with this code:

<?php

function MYMODULE_menu_alter(&$items)
{
  $items['blog']['page callback'] = "MYMODULE_blog_replace";
  $items['blog']['file'] = "MYMODULE.module";
  $items['blog']['module'] = "MYMODULE";
}

function MYMODULE_blog_replace()
{
  return views_embed_view('VIEWMACHINENAME', 'default');
}


How to avoid Exif data rotating images automatically after upload?

Please read this article - no module will be able to correctly interpret EXIF orientation, because there are too many "correct", widely used but contradicting interpretations. Even biggest brands have problems with this. Even if your site will not rotate image, browser still can.

To go around this problem, you can use Formatter Field module:

  For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

It's officially still in beta, but that's the best solution I know if you have no control over user's uploads. If you are the only one who uploades, just strip EXIF data (at least orientation part) and make sure you save your files without any, when preparing them for upload.


Export all views on a site to csv, json, spreadsheet etc

The Answer.

views_get_all_views()

The Script (save this as views_summarize.php or similar):

<?php
$views = [
  [
    'view machine name',
    'view name',
    'view desc',
    'base table',
    'display machine name',
    'display title',
    'display plugin',
    'php field the first',
  ]
];
foreach (views_get_all_views() as $view) {
  foreach ($view->display as $display => $data) {
    $views[] = [
      // 'view machine name'
      $view->name,
      // 'view name'
      $view->human_name,
      // 'view desc'
      $view->description,
      // 'base table'
      $view->base_table,
      // 'display machine name'
      $display,
      // 'display title'
      $data->display_title,
      // 'display plugin'
      $data->display_plugin,
      // 'php value in default field'
      $view->display['default']->display_options['fields']['php']['php_value'],
    ];
  }
}
$fp = fopen('views-summary.csv', 'w');
foreach ($views as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

Notes:

The returned $view object has properties nested within arrays and objects, make sure you shift gears accordingly in your query:

e.g.

$view->display['default']->display_options['fields']['php']['php_value'],

You can run this script with:

drush php-script views_summarize.php

Inspect the $view objects returned by views_get_all_views()

drush ev "print_r(views_get_all_views());"

Alternative uses

Site documentation is a tricky task, this approach is useful when documenting any pre-existing site configuration or content like rules, contexts etc...

A few hours later

Refined version of above script - outputs marker to indicate presence and location of php in views - yikes!

https://gist.github.com/gl2748/313b19bce1a99e42d94f


The Language Fallback Module solved this for me. Rather than translate a dozen nodes, this module allows you to translate only those nodes that require it and have the others fallback to a default.


How can I use a Drupal 6 database in Drupal 7 without upgrading that database?

Simply put, you cannot unless you are willing to rewrite a lot of Drupal 7 parts.

One thing you can do, is to implement cron jobs to export changes in version-independent format like XML on source site, and import them from XML at target site.

Alternatively, you can use Services module and make one page call the other to perform certain tasks, like user login or article reading.


I was having problems because I was making a copy of the original site and then updating the code in the copy. For some reason the code was not copying properly. The databases were also not exporting properly from PHPmyadmin.

This is how I fixed it:

My site was in hosting that had Cpanel. So using Cpanel I made an archive of the site. I then downloaded the archive, renamed it and then uploaded to create a new copy of the site. This copy was a perfect replica of the original, so it had no problems.
For the databases, I used this command to export them via mysql in the command line:

mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME > dump.sql

In this command, you mustn't have a space after -p. So your command might look like this:

mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

I then created new databases.
Finally, I imported the code into the new databases using this command

mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME < dump.sql


How do I attach some entity fields (or widgets?) to a form?

I think you can certainly use field_attach_form. Take a look at the $options argument that is explained in more detail in the _field_invoke documentation. For more information you can also have a look at this issue: https://drupal.org/node/1825844

You can include any field of any bundle into any form using this approach:

field_attach_form('node', $entity, $form, $form_state, NULL, array(
  'field_name' => 'field_sku',
));

When I last used this approach I remember having passed a copy of the original form into field_attach_form() in order to prevent my original form from being modified to much. Then I have copied only field element into my original form:

$form_tmp = $form;
field_attach_form('node', $entity, $form_tmp, $form_state, NULL, array(
  'field_name' => 'field_sku'
));
$form['field_sku'] = $form_tmp['field_sku'];

Just look at the mentioned functions to see what they do. I'm not sure if this last part is needed.

And one more link to explore:

https://api.drupal.org/comment/49363#comment-49363


How do I use bigdump.php with Acquia Dev Desktop?

If you want a web based solution for moving in database files, you should be using the Drupal solution for it:

http://drupal.org/project/backup_migrate

Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.

With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server, and to restore from an uploaded or previously saved database dump. You can chose which tables and what data to backup and cache data is excluded by default.


How to load JS as the first item in head tag?

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

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

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


views - how to filter by birthdays dependent on the current date

So it looks like a custom filter is in order. They are relatively simple to make. There are a few tutorials out there. Look up “custom views filter handler” here or elsewhere. I’ve made custom contextual filters and sort handlers several times. “Contextual range filter” and “Views Raw SQL”. You can look at the code for them on Drupal.org. I think this would be a good candidate for something worth releasing as an official module. You could call it “Anniversary Date Filter” or something.


How to restrict access to the site during development?

Make a module and paste following code in your module file:

<?php

/**
 * Implementation of hook_boot().
 *
 * Ask for user credentials and try to authenticate.
 */
function foo_boot() {
  require_once DRUPAL_ROOT . '/includes/password.inc';

  if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $query = "SELECT pass FROM {users} WHERE name = :name";
    $result = db_query($query, array(':name' => $_SERVER['PHP_AUTH_USER']));
    $account = new stdClass();
    foreach ($result as $row) {
      $account->pass = $row->pass;
    }
    if (isset($account->pass)) {
      if (user_check_password($_SERVER['PHP_AUTH_PW'], $account)) {
        return;
      }
    }
  }

  header('WWW-Authenticate: Basic realm="Development"');
  header('HTTP/1.0 401 Unauthorized');
  exit;
}

This uses HTTP Authentication and checks the Drupal Database for a valid username and password.

If you have any problems with PHP CLI, Drush or cron, you can add following code in the hook:

  // Allow cron through
  if (basename($_SERVER['PHP_SELF']) == 'cron.php') {
    return;
  }

  // Allow PHP CLI/Drush through
  if (isset($_SERVER['argc'])) {
    if (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)) {
      return;
    }
  }


If you want to go a site builder approach, one solution here is Views Infinite Scroll.

  Views infinite scroll allows you to load and display pages of any view
  inline, using AJAX (this has been called infinite scrolling, load
  more, autopaging, endless pages and more). The pager can be triggered
  with the press of a button or automatically as the user scrolls to the
  bottom of the view's content.

The caveat with this approach is you'd need to rely on a Views page configured with an Infinite Scroll pager set with the Automatically Load Content option. In other words, a static URL showing paged full content. That's pretty close to the functionality, but not perfect replication.


The wrapper containing the 'field-collection-container' class is added in field_collection_field_formatter_view() and because of this it seems that the usual theme functions (e.g theme_field, templatee_preprocess_field and template_process_field) are not able to alter the #prefix.

I've found that it is possible to alter the #prefix by altering the field collection field at the point it is attached the the parent entity by implementing hook_field_attach_view_alter() in our theme (in template.php):

/**
 * Implements hook_field_attach_view_alter()
 */
function MYTHEME_field_attach_view_alter(&$output, $context) {

  // First check we're dealing with a field collection field.
  if(!empty($output['field_link_collection'])) {

    // Now check for our specific field collection field.
    if ($output['field_link_collection']['#field_name'] === 'field_link_collection' ) {

      // Alter the prefix.
      $output['field_link_collection']['#prefix'] = '<div class="field-collection-container clearfix MYCLASS">';
    }
  }

}

Make sure you replace 'field_link_collection' with the machine name of your field collection field.

Field collections are entities themselves (containing fields) as well being fields attached to other entities which is incredibly powerful but I've found to be confusing when trying to alter specific things.

I think that in this case accessing theme_preprocess_field doesn't change anything as it's the wrong point in the render chain and the field is instead being rendered through field_formatter_view (I'm not certain that this is the case though, it may be more complex).

It might also be useful to look at the Display Suite module as it gives you much more control over the markup Drupal generates.

If you wanted to make this easier in the future, submitting a patch to the field collection module to declare a template in field_collection_theme() would help, this issue looks related.

UPDATE

Another method is to change the field display settings (in 'manage display' of the node) of the field collection field from 'field collection items' to 'fields only'. There should still be a wrapper div which you can amend the classes of by doing something like:

function MYTHEME_preprocess_field(&$variables) {
  if($element['#field_name'] == "FIELD_COLLECTION_NAME"){
    $variables['classes_array'][] = 'MYCLASS';
  }
}


How do I filter users by status not blocked?

The steps are:

View name: test
Show: Profiles
of type: All

Page title: test
Display format: table.

click "Continue & edit" button.

In the "FIELDS"

add the "Profile: User uid" field and add all fields related to the profile module.

Then add a relation in the path: Advanced-> RELATIONSHIPS

select the "Profile: User uid" field.

mark the checkbox "Require this relationship".

Click "apply (all displays)" button.

Then add a filter to "FILTER CRITERIA".

Seach and check the field: "User: Active"

We checked the checkbox: "Expose this filter to visitors, to allow them to change it"

Click "apply (all displays)" button.

Click "save" button.


How to limit and enable Commerce shipping options based on the customer's country?

The two crucial pieces of information:

The "Configure component" link alongside each shipping rate under admin/commerce/config/shipping (Store > Configuration > Shipping) is the place to set validation criteria for a shipping rate to appear as an option.
In these rules, countries need to be inputted as two-letter country codes not the full names.

In detail:

Set up the shipping rates and go to admin/commerce/config/shipping (Store > Configuration > Shipping)
For each one:

Follow the "Configure Component" link
"Add condition"
Commerce Order > Order Address Component Comparison
Address value = Shipping Address, Address Component = Country, and tick the Negate box at the very bottom if this is one for "everywhere but" (e.g. international rates)
Input the 2-letter country code under Value. You can see what this is by using Inspect Element on a country selector dropdown:


drupal_anonymous_user() gives you an object with a uid that is considered empty by PHP. This means, your call to user_save() will try to insert a new user into the database. The insert operation fails, because a user with the name user2 already exists in the database.


How to print the products (fields) on a node using a custom display

Hello @katerina and welcome to Drupal Answers.

You could use Display Suite and do the following:

Enable DS and DU UI modules
Create a new View mode for nodes, e.g. "Receipt"

For your content type, go to "Manage Display" > "Custom display settings" and activate the "Receipt" view mode for your content type

Now you should have, besides "Default" and "Teaser", the "Receipt" view mode available under "Manage Display" for your content type

Available directly under admin/structure/types/manage/PRODUCT_CONTENT_TYPE/display/receipt

You can now select the layout that suits you under "Layout for PRODUCT_CONTENT_TYPE in receipt", for example "Two column stacked"
You can use the available regions of that layout to lay the details out between the two columns
For the "Lending agreement" text, you would need to use a DS Code field, available under "Custom fields" > "Add a code field". You can enter your Lending agreement text in there, and then place that field in your header area.

That should be enough to cover the configuration of your custom display.

In order to get some URL access to that view, per product, you could use the View Mode Page module. Once you install it, you get a new configuration tab in your content type's "Manage Display" page, called "View mode pages".
There you can do the following:

Enter a URL patter under "URL pattern", e.g. 'node/%/receipt'

Save that configuration, clear all caches, and try to enter a URL for an available node, e.g. node/123/receipt
This should load that node using the view mode you configured above.

Hope this helps, good luck!


Batch API error: ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}

In our case, we had to turn off Cloudflare's Query String Sort option. See here --> https://support.acquia.com/hc/en-us/articles/360022037774-Resolving-Not-acceptable-format-json-error-HTTP-code-406-in-batch-operations

Here is the drupal issue too --> https://www.drupal.org/project/drupal/issues/2879023


Select option values loaded with AJAX call, shows error illegal choice has been detected

You need to use the in-build Drupal AJAX functions rather than writing your own. The Examples for Developers module has detailed examples you can copy.


Adding a Taxonomy term in a node via services

I'm not familiar with Services module or drupal's web service (I usually use Symfony for such Services), but I don't think there are any specific rules for such task.
Assuming there is a callback in your module which receives a data from external resource, e.g.:

function module_menu()
{
  ...

  $items['my-path/%'] = array(
    'title' => 'TITLE',
    'page callback' => 'myCallback', // this can be either `drupal_get_form` or your callback function..
    'page arguments' => array(1),
    ...
  );

  ...
}

and define that callback:

function myCallback($data /* assuming $data is an array, but It can be another type, JSON, XML... */)
{
  if(empty($data)) {
    // some dummy check
    return 'Invalid data';
  }

  $node = entity_get_controller('node');
  $node->type = 'MY_TYPE';
  // set other base fields such as author...

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $nodeWrapper->field_MYTEXTFIELD->set($data['text_field_data']);
  $nodeWrapper->field_TERMFIELD->set($data['term_field_data']);
  ....
  $nodeWrapper->save();

  ...

  // finally return response
}


Send data with post to other drupal page not working

Your code:

<div>
     <?php
         echo $_POST['priceUnit'];
     ?>
</div>

is probably in one of the tpl.php files. They are cached. You are not passing any data from any module to your template file, so Drupal cannot know it is not supposed to be cached. That's all.

Access post data in your module file, and pass it to your template properly, the "Drupal way" you can see in Examples, and you'll be good.

Also, I strongly suggest to remember that POST data is user-agent provided and you should never trust it. Especially not for things like price! There is a Drupal Form API to automate tests, but what you really should pass around is item's ID, and it's price should always come from your database, not from your user.

Price supplied by client is a recipe for a legal disaster.


How do I change the original language in PHP files and Twig files?

How do I tell Drupal that all my strings (PHP and Twig) are French strings?

You can not. There is no setting for that, the source code must be english.

Drupal does allow to translate the code/system-english to the actual english if you enable the checkbox when editing the english language. I don't know what that does exactly to potx and I don't think TMGMT supports it either.


Is it safe to use php within a Rules condition?

The PHP filter uses eval(). eval() gets a bad rap because it can be used insecurely. This post on SO goes into detail on that.
The answer to your question is that it could potentially be insecure, depending on the input provided, and how you have things configured. So getting rid of PHP filter altogether would be the ideal resolution (as it pretty much always is).
Getting your code out of the database and into version controllable files is extremely desirable, and is always considered better practice than using the PHP filter.
The proper way to provide rules conditions is to create a custom module, and implement hook_rules_condition_info(). If you're not a programmer then that might be a bit daunting, but at that point it's up to you to decide whether the risks outweigh either learning to do it yourself, or paying someone else to do it.


how to create path node/{some id}/add/{node_type} which loads node/add/{node_type} page

We can achieve this by creating route as below.

cust_group.route_name:
  path: '/node/{group_id}/add/{node_type}'
  defaults:
    _controller: '\Drupal\cust_group\Controller\CustNodeController:add'
  requirements:
    _permission: 'access content'   ( change permission according to your requirement)

And create a CustNodeController controller with method.

/**
 * Returns responses for Node routes.
 */
class CustNodeController extends ControllerBase {

  /**
   * Provides the node submission form.
   *
   * @param \Drupal\node\NodeTypeInterface $node_type
   *   The node type entity for the node.
   *
   * @return array
   *   A node submission form.
   */
  public function add($group_id, NodeTypeInterface $node_type) {
    $group_id =

    $node = $this->entityManager()->getStorage('node')->create(array(
      'type' => $node_type->id(),
    ));

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

}

make sure that {some id} != {node}.


How to add [google ads] in between the views slideshow after completing four slides

Use the HTML code of google adds . Copy and paste HTML code of google adds in the body of new content. You can also use ck editor.In views also select body field along with image field.
Also add global php in which add a if else conditon to show either image or body.


Feeds import should delete non-existent nodes and not insert new nodes

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

Long answer:

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

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

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

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


How to delete blocks and why some you can delete and others you can't?

J. Reynolds is right. These blocks are generated from code. This means this block is added programmatically through hook_block_info(). Some modules use this to define static blocks (like the login block or the "Created with Drupal" block). However some other modules implement this hook in a dynamic way. Views for example uses this to generate a list of all blocks in all (enabled) Views.

So even though you did not create them in code. Some of the modules you use do. Only blocks you have created using the Add block link on admin/structure/block can be deleted.

In order to remove a Views block from the listing, disable the View (or the block display in the view). I have no idea how to hide a block generated from Node as block. And I suppose there is not a real way to remove these blocks from the listing without writing a custom module.

You could attempt to create a custom module and implement hook_block_info_alter(), in which you unset all blocks you don't want. Maybe something like this:

function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  // Attempt to disable the login block by status.
  $blocks['user']['login']['status'] = 0;

  // If above doesn't work unset the block.
  // Array is built like $blocks[module][block_name]
  unset($blocks['user']['login']);

  // Disable all Views blocks (also used ones!!)
  unset($blocks['views']);
}

But to be honest, I doubt if it is worth the effort and it can lead to confusion in the future if expected blocks do not show up. So I'd advice just to leave it.


How do I show a Drupal 8 contact form on a page?

There needs to be a little more to the Contact Form entity for you to be able to display it.  The easiest way to get this is to install the Contact Storage module.  After doing this, your manage display options will include "Rendered entity" which will give you the contact form as you hoped and expected!


What are some quick ways to setup Product Displays in Drupal Commerce?

If you are adding product manually then you can use Auto Product Display module to set display of the product at the same time when you create product. But if you are using commerce feed along with feed then you will have to set two separate importer for each of them.


How do you 301 redirect links in Drupal via the .htaccess modredirect rules to keep spidered links?

Also have a look at the Redirect module. Managing redirects in the database might have some advantages over putting them in a .htaccess file.


Have you taken a look at this http://drupal.org/project/uc_donation... Ubercart can actually provide donation functionality. Let me know if this is what you were thinking.


Hide webform after the user's first submission

After creating your webform, go to the "Form Settings" under "Webform". In case you don't find it, here's the URL: node/Nid/webform/configure (I choose not to remind you of the Nid that you should change :)).

Here, you should see an option for "Per User Submission Limit"-
In your scenario, Limit each user to "1" submission(s) "ever".


How to interruput ajax request but keep for next possible uses?

I've solved it by:

        Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {

            if ($(this.element).hasClass(Drupal.settings.mymod.confirm_element_class)) {
                if (!confirm(Drupal.t('Please confirm your action'))) {
                    this.ajaxing = false;
                    return false;
                }
            }

            return true;
        }