How to split up the renderd page in a tpl file?

$page is the rendered content from page.tpl.php - you can't alter it in the HTML template without resorting to nasty string manipulation.

Fortunately your desired output lends itself nicely to being handled in the page template anyway. You won't automatically have the same template name suggestions available, although a theme/module might already make them available in your installation. If not, you can add it yourself:

function MYTHEME_preprocess_page(&$vars) {
  // This condition may need to change depending on your exact needs
  if (arg(0) == 'events' && !arg(1)) {
    $vars['theme_hook_suggestions'][] = 'page__events';
  }
}

Then in page--events.tpl.php you'll have access to the individual elements of the $page array, and you can render them as needed.


Drupal views custom template array issue

Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

<?php print $fields['field_images']->content; ?>

<?php print $fields['title']->content; ?>

<?php print $fields['title_1']->content; ?>

<?php print $fields['another_field']->content; ?>


It is possible to use node as multi step form with help of  page break field  Module . Enabled it and make it as one of the field where want in the node


is using non English words for paths recommended?

I use transliteration module in combination with pathauto module to transliterate any characters in my node title beyond ASCII 128 and automatically create friendly urls for each of my nodes.

This combination works really well! :)

Whether it is actually necessary or advantageous to remove unicode characters from your site's URLs is a subject on which I'm sure there would be many different opinions.

The Russian Wikipedia doesn't transliterate, but if you need to send your site's url's in an email, then things can quickly get out of hand and look ugly: http://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0

I have no experience if unicode characters in URLs affect SEO.


Manually Send Ajax request to a PHP file

For most functionality that you require with drupal, there is typically a module that already does what you are after or close to it.

I would recommend either:

using the module http://drupal.org/project/ajax_register
or looking at the code for the above module and make one that suits your exact needs

Hope this helps


Shipping county value showing as a number

The issue here is common to countries whose administrative areas don't render with abbreviations, which is the case in other countries like the U.S. and Canada where States and Provinces are abbreviated when printed (e.g. SC, NC, TN, etc.). Many of those countries use simple numeric codes or nonsensical alphanumeric codes as an administrative designation but should have the full names of the areas printed for display.

In the Address Field module, we introduced a configuration option for such countries' address formats called render_administrative_area_value that must be set to TRUE to do so. I've opened an issue for Estonia that will also ensure we've done this for the other countries we know about:

https://www.drupal.org/project/addressfield/issues/2983142

I'll have a patch up there shortly. : )


I highly suggest that you do not use the minimal install in Drupal, and go with the standard install.

It is way more efficient to use the standard install and then remove the modules that you do not want, than to use the minimal install and install a bunch of stuff.


How to modify term reference field in Drupal 7 custom content type?

Try the Taxonomy Term Reference Tree Widget.

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

Sounds like it would be perfect for your needs, but if not it's fully themable and already has the jQuery functionality built in so would be a very good place to start.


How to display title of a webform in twig template Drupal 8

Here is what I came up with

function THEMENAME_preprocess_webform(&$vars){
  $wfid = $vars["element"]["#webform_id"];
  $wf = \Drupal\webform\Entity\Webform::load($wfid);
  $vars["title"] = $wf->label();
}

Then in your theme's webform.html.twig you can use {{title}}


You can use the entity_clone module, which allows you to clone entities.

You can also clone blocks


This way should be bulletproof:

use Drupal\Core\Link;
use Drupal\Core\Render\Markup;

$url = $node->get('field_url')->getValue();
$imageUri = $node->get('field_image')->entity->getFileUri();
$image = [
  '#theme' => 'image_style',
  '#style_name' => 'medium',
  '#uri' => $imageUri,
  '#width' => 200,
  '#height' => 100
];
$rendered = render($image)
$linkMarkup = Markup::create($rendered);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();
render($link)


How do I replace a string when using hook_node_view()?

According to the doc, the first parameter should be $node, rather than &$node.
The replacement code should look something like this:
$node->content['body'][0]['#markup'] = str_replace($old, $new, $subject); so you missed [0] in your code, when in doubt, do a dsm($node) and check the variable you want.
Complete code:

function test_node_view($node, $view_mode, $langcode){
    if (drupal_is_front_page()) { // check if necessary
    $string = "new";
    $node->content['body'][0]['#markup'] = str_replace('old', $string, $node->content['body'][0]['#markup']);
    }
    //dsm($node);
}


It is possible to do that, but you definitely shouldn't do it.

The "random characters" are there for security purposes. Without them, it would be easier to reset passwords of other users, including the super administrator (uid: 1) for example. The hashes in URL are also longer in order to prevent collisions and make it harder for others to guess.

Password reset URLs are time-sensitive and expire after 24 hours (by default) if not used. Here is the breakdown of the password reset URL:

User ID of the member who is trying to reset the password.
Timestamp of when the password reset has been requested.
Hashed password. This is the element that is checked against the token stored in the database, and verifies that the link is valid. It's a unique hash that is built using the timestamp of when the password reset request has been made, account login information, hashed password and user ID. By doing so, the system makes it almost impossible to generate this information on your own, meaning that only your website is authorized to issue those URLs. And those URLs are issued only if you know the username or email address of an existing account.  See the source of user_pass_rehash() to understand this better if you want.

All of this was made so your users and your site would be more secure.

If you want to fully understand how this process works, open the /modules/user/user.pages.inc file, and check specifically the user_pass_reset() function. That function is responsible for validating the request, and allowing the users to reset their password.

Hope this makes sense; I wrote it pretty fast but it should cover the main points.


Do I have to unistall the disabled modules?

Disabled modules do not get executed so they should not affect performance but they may have variables and database tables that still exist. If you are not planning on using those modules again it is highly recommended to use the uninstall process at admin/build/modules/uninstall in D6 or admin/modules/uninstall in D7.


Reference to another database as a prefix

You have the format wrong for two databases you need something like this:

$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'db2' => array(
    'default' => array(
      'database' => 'd7_parent',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You can then use db_set_active('db2'); to change the connection and begin querying the second database.


Preprocess Node function not being called

You need check your page url. Hook_preprocess_node only run with page is node (example node/1...) or page have content is node (example page views have entity is node). If you done, you need clear cache.


How to render translated node body in two languages?

I found a solution: call field_attach_view with the required language.

/**
 * Implements hook_preprocess_node().
 */
function MYMODULE_preprocess_node(&$vars) {
  if ($GLOBALS['language']->language == 'ru') {
    $original_langcode = 'en';
    $content_original = field_attach_view('node', $vars['node'], $vars['view_mode'], $original_langcode);

    // need to check if languages match, it may be a language fallback
    if ($content_original['body']['#language'] == $original_langcode) {
      $vars['content']['body_original'] = $content_original['body']
    }
  }
}


How to list nodes that share one or more of the same entity references as the current node

You could get the blog posts related to projects refernced by the campaign displayed
through:

1- create a view  to get project id for projects have relation with that campaign.

2- create a new view listing blog posts that have relationships with projects taking project id as a contexctual filter.

3- create a .tpl file displaying the output of the view that gets projects from theme information

In that file embed blog posts view using views_embed_view() function giving the projects ids as a parameter for the view but you will need to

Configure views to accept multiple parameters you should set this option: View → Advanced → Your Contextual Filter → More → Allow Multiple Values

you will loop through fields to extract and form the ids array and pass it as the code sample below

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

By that you will be able to get blog posts from another separated view


Migrate user-data from a non-drupal site

Take a look at the Migrate module.  From the project page:

  The migrate module provides a flexible framework for migrating content
  into Drupal from other sources (e.g., when converting a web site from
  another CMS to Drupal). Out-of-the-box, support for creating core
  Drupal objects such as nodes, users, and comments is included - it can
  easily be extended for migrating other kinds of content. Content is
  imported and rolled back using Drush commands.


Use Rules to create new content and fill the corresponding node_reference field

I found how to fix my own problem

$node->field_YOURFIELD[LANGUAGE_NONE][0]['uid']=$userid;
$node->field_YOURFIELD[LANGUAGE_NONE][0]['nid']=$nid;


My view's 'more' link needs to go to a page with exposed filters already selected

I believe you want to use Contextual Filters (or, the functionality formerly known as Arguments").

Expand the "advanced" fieldset on the right side of your View's admin panel.

If, for example, I select "Content:Type" as a contextual filter, and my main page output of the view has a path of "/testview" then I can go to "/testview/Page" and see all content of type "Page". Same with my other content types, which happen to be "Story", "Product", and "Slide". You can do this with features besides content type. It sounds like using taxonomy terms would meet your needs.


Unless you created your site using composer create-project drupal-composer/drupal-project, Drupal core is not actually a dependency of your project; instead your composer.json file likely contains the line "name": "drupal/drupal". Effectively, your root composer file is the Drupal core package.

In this case you can only upgrade by manually downloading the new release.

See also: Why does "composer update drupal/drupal" not work?

Edit:

If you want to convert an existing D8 site to the composer-based workflow, the following steps should get you most of the way.

In a different location, use composer create-project drupal-composer/drupal-project:8.x-dev <my-new-site> to create the new project. (Confirm the removal of the existing git history, and if you are using version control, use git init; git add .; git commit to initialize the new repository.)
Look at the contrib modules installed in your current site's modules/ folder, go into the new project, and use composer require drupal/module1 drupal/module2 [...] to install them. (Any custom modules should be copied into the folder ./web/modules/custom/ in the new project.)
Copy the contents of your sites/ folder into the ./web/sites/ folder of the new project.
After backing up your database, go into your new project folder, and use vendor/bin/drush updatedb or vendor/bin/drupal upex to update your database with Drush or Drupal Console (both are installed by default).

At this point, your new project should be ready to serve the site; change your webserver configuration or symlinks to point at <my-new-site>/web (the web subdirectory, not the project folder itself).


Get default image directory with styles large?

I'm not sure this will get you exactly what you want, but the 'default' path is just public://, so.

$url = image_style_url('large', 'public://');

will return

http://yoursite.com/sites/default/files/styles/large/public

I think it's more likely you're looking for a specific path, e.g.

$url = image_style_url('large', 'public://field/image');

which returns

http://yoursite.com/sites/default/files/styles/large/public/field/image


I assume your view is using a block display and you don't want the block to display at all if there is only 1 result.

In my opinion you are hooking in too late in the process to hide the view there. It is possible to hide it in the theme layer but I don't think it is the optimal approach.

There are a number of ways you can do it but here are a couple of ways using a hook in a custom module, not in a theme. (This is not an exhaustive list of options that you have.)

Option 1

Hook into the view execution process and tell the process that execution has failed, so it will not render the view.

For example:

use Drupal\views\ViewExecutable;

function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // If there is only 1 result set the failure condition so that
  // execution will not continue and the view will not display.
  if ($view->id() == 'VIEW_NAME') {
    if (count($view->result) == 1) {
      $view->build_info['fail'] = TRUE;
    }
  }
}

Option 2

Configure your view to have 'Hide block if the view output is empty' = Yes
Hook into the view execution process and clear the results when you don't want it to display.

For example:

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute().
 */
function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // Clear the results if there is only 1 result.
  // The view will then hide as it is configured to hide the
  // block if empty.
  if ($view->id() == 'VIEW_NAME') {
    if (count($view->result) == 1) {
      $view->result = array();
    }
  }
}

Note: Depending on how you decide to hide the view, if your views block is the only block in your region then be aware of this outstanding bug, which may cause your region to still display even though your block doesn't: https://www.drupal.org/project/drupal/issues/953034


Upload a file to Drupal server from an outside URL

Here is a solution I've used recently for a Facebook module. Set the image path to $path variable (ie. http://graph.facebook.com/username/picture). Then do the following to store it via Drupal's managed file system:

$image = file_get_contents($path); // this is a PHP function to get a string representation of the image file

$destination = 'public://path/to/store/this/image/name.jpg'; // a stream wrapper path where you want this image to reside on your file system including the desired filename

$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);

if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
   $file->status = 1;
   $file = file_save($file);
}


All of those instructions only apply if you actually want to have a multi-site installation and e.g. different installations on different ports. Something that most people recommend to not do as it results in maintenance issues sooner or later.

If you just want to have one installation, use sites/default/settings.php and you're good to go.


Essentially there are 2 things needed to create your own hook(s).

  Create your own function that calls module_invoke_all('WHAT_YOU_WANT_YOUR_HOOK_TO_BE_CALLED');
  Create your new module and a function called YOURMODULE_WHAT_YOU_WANT_YOUR_HOOK_TO_BE_CALLED()

  That is ALL it actually takes to implement your own hooks in a Drupal module. The great thing here is the flexibility that it provides for you to do anything, AND allow other developers to easily extend your work. The major consideration I can see here is naming your hook. You should obviously try to choose something unique to your module, that a
  core or another contributed module wont be using.


How to wrap a custom content page with HTML tags?

Could you put an  tag inside the pane, and then with CSS give it a width: 100% and height: 100%, effectively filling the mini-pane?

To be specific, your html inside the pane would look like:

This Is A Link

And your CSS would look like:

a.mini-pane-link {
    display:block;
    width: 100%;
    height: 100%;
}

(You might want/need to put a few extra selectors in front of the a.mini-pane-link)


drush dl drupal-8

Since there are no stable releases of Drupal 8, you must use the --all option to see the tagged alpha releases:

drush dl drupal-8 --select --all

This also works.

drush dl drupal --default-major=8 --select --all

Both of these are now working in the current version of Drush, without the --all flag:

drush dl drupal-8 --select
drush dl --default-major=8 --select

Note that the Drush pm-* commands only work with one major version of Drupal at a time, and that version currently defaults to Drupal 7. Therefore, drush dl drupal only shows the various Drupal 7 releases available, and does not include any versions of Drupal 8. This much has not changed.

drush dl drupal-8 now works fine with the Drupal 8.0.0-rc1 release.


Another reason why an update hook would not run is a mismatch between the update hook name and the major release number of the module (see .info file).

For example: the update hook mymodule_update_7001 does not run if the module version is 7.x.1.0. In such case you must rename the hook to mymodule_update_7101.

See the hook_update API documentation


How to recover content/configuration from a hacked site

I have never used this module, but it might be worth researching and using on a COPY of your site - Drupalgeddon module.

The first step to recovering from a hacked site is to do an audit of the activity that has taken place. If you have HTTP server logs (apache access logs, etc) you can review the various attack vectors (e.g. POST /node/add, POST /node/3/edit) to identify areas that were compromised. Based on this activity you can formulate a time window when the attacks occurred and search for content edits within that (e.g. checking the "changed" date on the node table). I do know Drupalgeddon does modify records in the users table, so definitely check that.

Either way I think a full audit of the entire database and file-system (pretty sure Drupalgeddon does write to your docroot; hope you have version control to see changes?).


What can not be done by the Panels module without using the Panelizer module?

To answer your question, as in the 'title' of your question, consider reviewing the article about Creating Specialized Layouts with Panelizer. Here is part of what is written in it, and which I think are key features of Panelizer that you can't do with only the Panels module:

  Many users of Panels have taken advantage of the Panel Nodes sub-module to create customized layouts for nodes. Panelizer does that and takes things a giant step further; by integrating with Drupal 7's entity system, it can create custom layouts for any entity item.

  Panelizer was initially created to allow for one node to be displayed differently than any other node on the system. This allows content creators to be just about as creative with the look and feel of each unique piece of content as they would like.

Some more suggestions about tutorials that you may want to checkout:

Manage Drupal Content Layout with Panelizer.
Architecting Landing pages using Panelizer.

Regarding the Edit-In-Place (IPE, or In-Place-Editor), refer to what's mentioned also in Working with Panelizer combining panels and node displays, i.e.:

  Panelizer fully supports the IPE (In Place Editor) meaning that panelized nodes can enable the alternative directly editable panel.

The question about "Enabled Panels In-Place Editor module but cant see the edit icon" may contain other interesting information about IPE, with topics related to:

Clearing the cache.
Renderer mode.
Permissions.


How to remove user role using hook_user_update

The errors in your code are two:

vdb_hook_user_update() is not the correct name for an implementation of hook_user_update()
vdb_hook_user_update() is being used as form submission handler

As consequence of the second point is that you are declaring the function with the wrong arguments, since a form submission handler gets two arguments: $form and &$form_state.

As Clive pointed out, you should use hook_user_presave(), which is invoked before the user account is saved in the database. Remove the code adding the form submission handler, and implement hook_user_presave() using code similar to the following one.

function vd_user_presave(&$edit, $account, $category) {
  if (!empty($account->uid) && ($key = array_search('Hybridauth', $account->roles)) !== FALSE) {
    unset($account->roles[$key]);
  }
}


How to get translated field_storage_config

How is this possible and how can I programmatically set the
  translations for my field(s)?

You can load language overrides with ConfigurableLanguageManager::getLanguageConfigOverride, set values and save:

\Drupal::languageManager()->getLanguageConfigOverride('fr', 'field.storage.node.field_example')
  ->set($key, $value)
  ->save();


There are many ways to migrate a local site to a server. Here are a few of the most common.

SFTP/FTP is one way, you can "manually" move all the files up to the
server and use PHPMyAdmin to import the database. Many hosts will
also have automatic Drupal installs, in which case you can use that,
only upload your theme, files, and modules, and then import database. If you upload via FTP you will need to update settings.php to include the servers SQL log/pass as well as domain url
Set up a git repo which you can pull/push to from your local machine
and the server is likely a better solution if you plan on making
changes. This allows you to more easily manage the files and is a
"safer" solution. Set settings.php to .gitignore
There are also managed solutions such as Acquia Dev Desktop which
will allow you to push/pull files, code, and database simultaneously
using a UI.


Filter a view with content from two different content types

Are you creating two separate filters?  For example in your filter list, does it say:

Content: Type (= MensBlog)
Content: Type (= WomensBlog)

This essentially becomes an AND filter, which means it's looking for a content type that is both MensBlog AND WomensBlog.
You could instead change this to have the data in one filter.  Remove one of the filters and click to edit the other one.  On this screen, make sure the "Is one of" radio box is selected under Operator and then select MensBlog and WomensBlog.  This filter will be an or filter, rather


Trying to create user programmatically, running into issues

Drupal's anonymous and authenticated roles don't get saved in the users_roles table and you don't need to add the role yourself, all users are by default authenticated. Try editing your user in the backend, you'll see that it has authenticated checked off.
The code you list above where you send the roles array in the $edit will work fine with any other role.


How do I completely disable user profiles and the dedicated login page in Drupal 7?

Yes, you can change built in menu / page callbacks with hook_menu_alter

For example, alter user_menu

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Go to front page when visiting /user and /user/login
  $items['user']['page callback'] = 'drupal_goto';
}


How to check how many times a user has logged in?

I don't think drupal keeps that data as standard. You might want to look at User Stats Module which does it for you.

  Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
  1. days registered;
  2. join date;
  3. days since last login;
  4. days since last post;
  5. post count;
  6. login count;
  7. user online/offline;
  8. IP address;


Know if node is in view, edit, delete, etc. in page.tpl

Here's how to check against all paths related to nodes:

Node view:

arg(0) == 'node' && arg(1) && is_numeric(arg(1)) && !arg(2)

Node edit:

arg(0) == 'node' && arg(1) && arg(2) == 'edit'

Node delete:

arg(0) == 'node' && arg(1) && arg(2) == 'delete'

Node add "landing" page from where you choose which content type you want to create:

current_path() == 'node/add'

Node add page for a specific content type:

current_path() == 'node/add/YOUR_CONTENT_TYPE'

All node add pages:

arg(0) == 'node' && arg(1) == 'add' && arg(2)


How to Inject entity object in EntityForm

Declare the entity form in the route via _entity_form instead of _form:

First add a form handler to the entity type:

mymodule.module

/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['menu']
    ->setFormClass('poweredit', 'Drupal\mymodule\MyMenuForm');
}

Then add the form handler to the route:

mymodule.routing.yml

entity.menu.power_edit_form:
  path: '/admin/structure/menu/manage/power_edit/{menu}'
  defaults:
    _entity_form: 'menu.poweredit'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _entity_access: 'menu.update'

Now Drupal upcasts the route parameter to an entity and adds it to the form object when it is instantiated.

This is similar to content entities, only that config entities have no form modes. See How to utilize custom form modes to edit a user entity?


Correct way to display a custom field in a custom content type page template

Ok, figured this out. I copied node.tpl.php to my templates directory in my theme, and then duplicated that with the name of of custom content type:

node--lesson.tpl.php

I was then able to display my custom field with this:

<?php
   echo render($content['field_lesson_objective']);
?>


Errors occured while trying to retrieve tweets

If you haven't enabled Database Logging yet, go ahead and do that on the modules page. Then you should see  errors reporting under admin/reports/dblog.

Twitter recently dropped their version 1 support, which is what Twitter Pull runs off of. Now you must use the Twitter and oAuth modules to deal with v1.1. Look at this sandbox for a solution. It branched off from Twitter Pull as an alternative to deal with oAuth tokens.

Updated: Better way to do it

There's recently a new module that came out that makes it a whole lot easier to embed tweets using the embedded widgets. Try Twitter Block instead, and you'll get up and running a lot faster.


DynamicRoutesAlter.php

Problem #1 - preg_replace() without pattern

$url = preg_replace('_', '-', $key);

The $url will be always NULL, because you are using preg_replace() without regexp, use instead str_replace() or write appropriate regexp pattern: '/_/'.

Solution #1

$url = preg_replace('/_/', '-', $key);

Solution #2

$url = str_replace('_', '-', $key);

Problem #2 - wrong variable mixing

$collection->add('custom_module.dynamic_routes'.{$key}, $route);

You are wrong with mixing variable and string. You want to concatenate it with the curly syntax. This is also incorrect.

Solution #1

$collection->add("custom_module.dynamic_routes.{$key}", $route);

Solution #2

$collection->add('custom_module.dynamic_routes' . $key, $route);

After you fix those problems, your code will work.

I'm also not sure about 'type' => $key,, why is that here? There is nothing about type route param.

P.s. as you mentioned itself, better use slugs.

UPD - all files

Check your files for mistakes.

custom_module.info.yml

name: Custom module
type: module
description: For https://drupal.stackexchange.com/questions/281728
package: Custom
core: 8.x

custom_module.routing.yml

custom_module.dynamic_routes:
  path: '/custom-module/dynamic-routes'
  defaults:
    _title: 'Dynamic Routes'
    _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'
  requirements:
    _permission: 'access content'

custom_module.services.yml

services:
  custom_module.dynamic_routes:
    class: Drupal\custom_module\Routing\DynamicRoutesAlter
    tags:
      - { name: event_subscriber }

src/Controller/DynamicRoutesController.php

<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Returns responses for Custom module routes.
 */
class DynamicRoutesController extends ControllerBase {

  /**
   * Builds response for dynamic routes.
   */
  public function productType() {

    $build['results'] = [
      '#markup' => $this->t('Controller to get Products List.'),
    ];

    return $build;
  }

}

src/Routing/DynamicRoutesAlter.php

<?php

namespace Drupal\custom_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * DynamicRoutesAlter Class.
 */
class DynamicRoutesAlter extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];

    foreach ($products as $key => $value) {

      $url = preg_replace('/_/', '-', $key);

      $route = new Route(
      // The url path to match.
        '/custom-module/dynamic-routes/' . $url,
        // The defaults (see the custom_module.dynamic_routes for structure)
        [
          '_title' => $value,
          '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',
          'type' => $key,
        ],
        // The requirements.
        [
          '_permission' => 'create ' . $value,
        ]
      );

      // Add our route to the collection with a unique key.
      $collection->add('custom_module.dynamic_routes' . $key, $route);

    }
  }

}


Migration of multi-value pictures to user fields

Something is really odd about your code $this->destination is a MigrateDestinationFile yet $this->map is trying to track a MigrateDestinationNode .... I've never done anything that way.

I would do the following:

Import Users from Wordpress to Drupal.
Use your CSV file of legacy UIDs and picture files to run an update of the (newly) created Drupal users and insert the images as needed.

I'm doing this now as we speak on a Document content type of which there are 120k entries, but only 4k have movie files associated with them so I feel a node revision is a better use the time to import stuff.

This is an example from some work in progress and will not run as-is but it should be a concrete example:

class PrezDocumentMediaMigration extends PrezMigration {

  public function __construct($arguments) {
    parent::__construct($arguments);

    $document_fields = array(
      // ... fields ...
    );
    $this->description = 'Update created Documents with audio and video from legacy DB. There are only ~5k of entries.';

    $query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->fields('p', $document_fields)
      ->condition('av', 0, '<>');
    // Additional pseudo fields to move data from legacy derived data to drupal.
    $query->addExpression('NULL', 'local_video');
    $query->addExpression('NULL', 'remote_video');
    $query->addExpression('NULL', 'local_audio');
    $query->addExpression('NULL', 'remote_audio');

    $options = array('track_changes' => 1);

    $count_query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->condition('av', 0, '<>');
    $count_query->addExpression('COUNT(pid)', 'cnt');

    // We are updating existing content in Drupal.
    $this->systemOfRecord = Migration::DESTINATION;

    $this->source = new MigrateSourceSQL($query, $document_fields, $count_query, $options);
    $this->destination = new MigrateDestinationNode('documents');
    $this->map = new MigrateSQLMap($this->machineName,
                                   array(
                                     'pid' => array(
                                       'type'     => 'int',
                                       'unsigned' => FALSE,
                                       'not null' => TRUE,
                                       'description' => 'Unique content reference legacy document',
                                       'alias' => 'doc',
                                     )
                                   ),
                                   MigrateDestinationNode::getKeySchema()
    );

    // Migration mappings, the documentation for these mappings can be seen at:
    // https://www.drupal.org/node/1133448

    $migrator_user = user_load_by_name('PrezMigrator');

    // Some default values for sanity.
    $this->addFieldMapping('uid')
      ->defaultValue($migrator_user->uid);
    $this->addFieldMapping('revision')
      ->defaultValue(1);
    $this->addFieldMapping('log')
      ->defaultValue('inserted related media from legacy DB on ' . date("l jS of F g:i A.", time()));
    $this->addFieldMapping('promote')->defaultValue(0);
    $this->addFieldMapping('sticky')->defaultValue(0);
    $this->addFieldMapping('revision_uid')->defaultValue($migrator_user->uid);

    // What legacy content are we talking about ?
    // also we want this legacy ID to actually lookup through 2 source migrations.
    $this->addFieldMapping('nid', 'id')->sourceMigration(array('PrezDietNonPresidents','PrezDietPresidents'));

    // Map media files these are multiple value fields. They can accept a PHP array of values.
    $this->addFieldMapping('field_docs_media_videos_local', 'local_video');
    $this->addFieldMapping('field_docs_media_videos_remote', 'remote_video');
    $this->addFieldMapping('field_docs_media_audo_local', 'local_audio');
    $this->addFieldMapping('field_docs_media_audio_remote', 'remote_audio');

    // Each of the above media fields will need the following additional subfields
    // Only 1 is provided as an example to keep this example shorter:
    $this->addFieldMapping('field_docs_media_videos_local:file_class')
      ->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_docs_media_videos_local:language')
      ->defaultValue(LANGUAGE_NONE);
    $this->addFieldMapping('field_docs_media_videos_local:preserve_files')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:file_replace')
      ->defaultValue(FILE_EXISTS_REPLACE);
    $this->addFieldMapping('field_docs_media_videos_local:source_dir')
      ->defaultValue('/var/www/2015/presidency/drupal7-project/build/legacy/htdocs/www/media/');
    $this->addFieldMapping('field_docs_media_videos_local:urlencode')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:alt')->defaultValue('');
    $this->addFieldMapping('field_docs_media_videos_local:title')
      ->defaultValue('');

    // List fields not be migrated to destination.
    $this->addUnmigratedDestinations(
      array(
        // ... massive list of fields.
      ));

  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $youtube_format = 3;
    $quicktime_format = 2;
    $audio_format = 1;

    switch ($row->av) {
      case $youtube_format:
        $row->remote_video = $this-> find_remote_video($row->medialink);
        break;
      case $quicktime_format:
        $row->local_video = $this->find_local_video($row->medialink);
        break;
      case $audio_format:
        $row->local_audio = $this->find_local_audio($row->av, $row->medialink);
      default:
        break;
    }
    return TRUE;
  }

  // http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex
  protected function find_remote_video($link) {
      $separator = '***';
    $text = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20130823)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube         # or youtube.com or
          (?:-nocookie)?  # youtube-nocookie.com
          \.com           # followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\s-]       # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w-]{11})      # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w-]|$)     # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w.-]*    # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w.-]*        # Consume any URL (query) remainder.
        ~ix',
                         '//www.youtube.com/embed/$1' . $separator,
                         $link);
    return explode($separator, $text);
  }

  // other "find" media methods that return filesystem paths and stuff depending on where the media
  // existed in the legacy system.
}


Drupal 6 to Drupal 7 migration redirect not working

I had a slightly different use case - changing aliases for users from /source/user-name to /author/user-name and creating redirects from the old alias the new one - but the steps are still the same.

First, I implemented a complete() method in my migrate class. This is called after the new entity (node, user, etc) has been created:

  /**
   * Implementation of MigrateDestinationEntity::complete() method.
   *
   * @param $entity
   * @param $row
   */
  function complete($account, $row) {
    // Create redirect from old Source alias that uses /source/
    // to new user profile alias.

    if (!redirect_load_by_source($row->dst)) {
      // First, get the alias for the user profile. We have to generate it separately
      // here because pathauto_create_alias() has already been run by the time the code
      // gets here, and we don't have access to that path.
      $new_alias = pathauto_create_alias('user', 'return', 'user/' . $account->uid, array('user' => $account));

      // Next, create the $redirect object and save it.
      $redirect = new stdClass();

      redirect_object_prepare(
        $redirect,
        array(
          'source' => $row->dst,
          'source_options' => array(),
          'redirect' => $new_alias,
          'redirect_options' => array(),
          'language' => LANGUAGE_NONE,
        )
      );
      redirect_save($redirect);
    }
  }

And then, to handle rollbacks (during development), I created a new class that overrides DrupalDestinationUser and implements a custom prepareRollback method:

class CNSUserDestination extends DrupalDestinationUser {
  // Add prepareRollback() method to this class.
  public function prepareRollback($uids) {
    parent::prepareRollback($uids);
    // Load all of the entities, since we need them for pathauto_create_alias().
    $users = entity_load('user', $uids);

    // Load pathauto.inc file.
    module_load_include('inc', 'pathauto', 'pathauto');

    foreach ($users as $uid => $user) {
      $redirects[] = pathauto_create_alias('user', 'return', 'user/' . $user->uid, array('user' => $user));
    }

    // Delete redirects for user profiles.
    db_delete('redirect')
      ->condition('redirect', $redirects)
      ->execute();
  }
}

It worked like a charm.


I think you can do this using hook_field_display_alter, however, I would personally prefer to create a custom formatter for the used field type. With the main advantage that you can save settings for the field formatter.

See the answers of How do I write an additional field formatter for an existing field for basic steps on how to create your own field formatter.


How to keep password form populated ever if the validation fails on registration

The password form field is always cleared out when re-submitting the form after a validation handler reports an error.
There isn't a workaround to that, as the password form field is not using the "#default_value" property that usually other fields would use to pre-populate the fields with a value that is then edited from users. If you use the "#value" (supposing that would have any effect for the password form field) then that value would override the value entered from the users.


How to set transactional email api key for external app in drupal like mandrill

Assuming you're using the Mandrill module, the API key can be configured at this path:

/admin/config/services/mandrill


I am creating my own shortcut bar but can't manage the user access

Since you're defining a permission you can make use of the user_access() function to check that the user is allowed to access the shortcut menu. You can actually then use the #access key on your render array to denote whether or not it should be shown:

function shortcat_toolbar_pre_render() {
  $links = shortcat_renderables();

  $links['#attached'] = array('css' => array(drupal_get_path('module', 'shortcat') . '/shortcat.css'));
  $links['#prefix'] = '
';
  $links['#suffix'] = '
';

  $links['#access'] = user_access('administer shortcat');

  return $links;
}

That code will deny access for anyone who doesn't have the administer shortcat permission. All you need to do is make sure the permission is ticked for the editor role in the admin permissions page.

It's worth bearing in mind that user_access() wil always return TRUE if you are logged in as the super user (ID:1). If you need this to be different then the easiest way would be to check that the user physically has the editor role assigned to their account:

global $user;
if (!in_array('edit', $user->roles)) {
  $links['#access'] = FALSE;
}

Hope that helps.


How to keep URL parameters on subsequent pages after a form is submitted?

If you're able, and willing, to review/rework the current implementation you have for your webform submissions and the related "Thank you" page, you should consider getting the Rules module involved, e.g. to have the Rules module react to Rules event "After submitting a webform".
By doing so, you could then also use the Rules URL Argument module, which you can use to make the value of the URL argument available as new variable to Rules. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


In Drupal 6, if you know the taxonomy term ID, you can get the vocabulary ID by using the following code:

$term = taxonomy_get_term($tid);
$vid = $term->vid;

If you have a node ID, then you can use the following code to get the vocabulary ID of all the taxonomy terms associated with the node using the following code:

$node = node_load($nid);
$vids = array();

if (!empty($node->taxonomy)) {
  foreach ($node->taxonomy as $tid => $term) {
    $vids[] = $term->vid;
  }
}

In Drupal 7, the code would be the following:

$term = taxonomy_term_load($tid);
$vid = $term->vid;

In Drupal 7, the node property $node->taxonomy doesn't exist anymore. Instead, there is $node->field_<vocabulary_name>, which is an array with two different structures.

tags

other taxonomy terms

Using field_get_items(), you would get the taxonomy terms in the language they would be displayed, or in the language whose code is passed as argument to the function.

$items = field_get_items('node', $node, $field_name);

$node contains the node object, and $field_name the name of the taxonomy term field.

$items contains a simplified array, compared to the array contained in $node->field_<vocabulary_name>.


Correct way to render fields from Entities?

The equivalent to the sample code you posted from the article, but for an entity type other than node would be:

$entities = entity_load('ENTITY_TYPE_NAME', array($YOUR_ENTITY_ID));
$entity = $entities[$YOUR_ENTITY_ID];
$field = field_get_items('ENTITY_TYPE_NAME', $entity, 'field_name');
$output = field_view_value('ENTITY_TYPE_NAME', $entity, 'field_name', $field[$delta]);

If you're doing this in a template, your entity's fields should have already been retrieved by the entity module's template_preprocess_entity() function and made available under the $content variable, so you shouldn't have to do all these steps in an overridden entity template.


Drush sql-sync: Access denied; you need the SUPER privilege for this operation

The user defined in settings.php on one or both sides of the sync lacks the SUPER privilege on the database.

Log in as the mysql root user and do

GRANT SUPER ON [db_name] TO '[username]'@'localhost' IDENTIFIED BY '[password]';

If you are security-conscious (as you should be), it's worth taking the following into account:

  Do not grant the PROCESS or SUPER privilege to nonadministrative users. The output of mysqladmin processlist and SHOW PROCESSLIST shows the text of any statements currently being executed, so any user who is permitted to see the server process list might be able to see statements issued by other users such as UPDATE user SET password=PASSWORD('not_secure').


How is webform node type is defined in webform module?

The initial webform content type is created during install as an entity of type node. The code can be found in the webform_install() function:

$webform_type = array(
  'type' => 'webform',
  'name' => st('Webform'),
  'base' => 'node_content',
  'description' => st('Create a new form or questionnaire accessible to users. Submission results and statistics are recorded and accessible to privileged users.'),
  'custom' => TRUE,
  'modified' => TRUE,
  'locked' => FALSE,
);
$webform_type = node_type_set_defaults($webform_type);
node_type_save($webform_type);
if (variable_get('webform_install_add_body_field', FALSE)) {
  node_add_body_field($webform_type);
}

Additionally it might be worth noting, that you can turn any content type into a webform by checking the appropriate setting on the content types main configuration page. You can think of webform as an add-on extension to other content types. To find out which content types are "webform enabled" you should use the provided API functions. In webform-7.x-4.0-beta for example that would be webform_node_types().


You are checking for user access within the form builder function. Make sure that control is going to the actual form by adding a dpm. It is better to check permissions at the menu definition level unless you have a better reason not to do so.

Next try $form['#submit']='cheo_whiteboard_admin_form_submit';

This makes sure that cheo_whiteboard_admin_form_submit is the only form handler function and hence easier for you to debug.


The reason it was breaking is because you’re doing drupal_add_js outside of any function or listener hook.

You need to add it to the appropriate build, alter or preprocess hook that suits your needs.


You can try Views Sexy Throbber, not exactly that you need, but is still cool...


Why not programatically created nodes in the simpletests?

Here is what the Drupal documentation says on it's simpletest page.

  Testing methodology
  Drupal testing focuses on functional testing
  instead of unit testing. What this means is that the tests are written
  in such a way that they test the interface as a whole instead of
  testing individual functions or finite pieces of code. Drupal focuses
  on functional testing because it is more effective for the way Drupal
  is written. Functional testing ends up being just as effective if not
  more effective than unit testing and especially so due to the code
  style used in Drupal. The testing framework is geared towards this
  type of testing and the documentation focuses on writing functional
  tests.

Drupal tests are almost always functional tests and not unit tests. As quoted above, Drupal was coded in such a way (e.g. hooks system, forms api, etc) that Unit tests generally don't make sense.


Can I add a template preprocessor that's more specific than an existing hook?

For the Views module, if you want to know its template file suggestions:

Open edit for your view
Click on 'Theme information'
Use whichever template name that meets requirements
Go back to your view and, at the bottom of 'Theme information', click 'Rescan template files'
Your template file should be highlighted in this list


You want to use prepareRollback() because at that point the thing that you are rolling back has not been removed yet.

public function prepareRollback($entity_id) {
  parent::prepareRollback();
  // Code to execute before an entity has been rolled back
}

Take a look at this guide for more info.


I think this is a syntax issue. Try using

jQuery(function($) {
    //Your Code
});


How to open all external links in a new tab

Links can be generated in a number of ways, which makes it hard to change consistently. For a single implementation that you want to reach most parts, you should swap the link_generator service with your own subclass. This should catch all menu items and links in general, but wont touch custom markup from wysiwyg. Here you would need to create a custom filter.

The ::generate($text, Url $url) method is what is used to actually create the create the HTML. What you want to do, it to add the _blank target attribute if the url is external.

The code for the link generator subclass, could look like this:

class MyLinkGenerator extends LinkGenerator {
  public function generate($text, Url $url) {
    if ($url->isExternal()) {
      $attributes = $url->getOption('attributes');
      $attributes['target'] = '_blank';
      $url->setOption('attributes', $attributes);
    }
    return parent::generate($text, $url);
  }
}

I wont go into how to change the class of a service, there is plenty of examples for this here and elsewhere.


The not to good solution was, deleted all the index of apache solr and tried with the fresh indexing and all of sudden all thing work well.


How to add Google Maps data overlay to Openlayers map?

If you find OpenLayers for Drupal too daunting you could have a look at https://www.drupal.org/project/leaflet. It's easier to configure and more lightweight.

As for OpenLayers:

Create a view that provides an OpenLayers Data Overlay Display.
Then you may want to checkout: "admin/structure/openlayers/layers" and configure a Google Maps layer.
Then create a map over here "admin/structure/openlayers/maps". Make sure you enable your Google Maps layer as base and your Views Data Overlay as the Overlay for this map.
If you want to "show" the map also with Views create a new display (not an overlay) and use the OpenLayers Map formatter. You can then select your OL map created in step 3.


Drupal 8 lets you add 'DropButtons' to your View, which looks really good in UI.

add a 'Custom text' field for each action you want to provide - use 'exclude from display' and 'output as custom link'
add a 'dropbutton' field and select your custom links to be shown in it
profit


Configure inline images upload path per content type

Not directly. The only approach that I could think of right now is that you create a text format for each node type and then use a module like Allowed Formats or Better Formats to limit the allowed formats of each node type to that.

Maybe you can also alter the settings at runtime with some custom code based on the page that you're on right now, but I'm not sure.


You can construct your hierarchy using the core module taxonomy.  Go to admin/structure/taxonomy, create your vocabulary and add your terms. The form that lists your terms precedes the name with a graphic arrow widget (points in four directions.  Selecting that widget and dragging can reposition the terms in parent child relationships, and your done!  The Taxonomy Manager module can help you add large quantities of terms to a vocabulary very quickly as well.


In your view, under your field configuration, at "select bulk operation" section under the action there should be a "Skip confirmation step" option; uncheck it and you're ready to go


How to create a Drupal database on the server if you only have access via an FTP client

You need to ask your server admin to create a database and a user for that database to be able to install drupal. You don't need phpmyadmin but you do need a database/user.


Why doesn't my text filter strip out the tags I don't want?

Okay, I've found my own answer. The problem was with my understanding of how text filters work. Text is saved into the database with no changes, and filters are only applied when the text is output.

When using Entity Metadata Wrappers, as I am, when you get $wrapper->body->value(), it gives you an array with several elements. One is the "value", which is the raw, unfiltered text. Another is the "safe_value", which has had filters applied.

So in my case I needed to use the "safe_value" when displaying the text. Makes sense once you understand it!


There exists good documentation in Project Page of Views PHP module and Documentation under Read Documentation link in project page..

How to Use Views PHP in views filter
How to Use Views PHP as Views Output Field..

Some existing answers and tutorials which can explain better you can find below..

How can I insert PHP code in Views?

http://eureka.ykyuen.info/2012/03/10/drupal-7-add-php-field-to-view/


Iterate through user custom fields in twig

You should never try to display field values by going that deep into structured field properties data within your Twig templates.

Consider using according field displays, or hook_preprocess_HOOK() to preprocess your template variables, e.g. by providing a simple array of preprocessed item data the template can iterate over (an abstract example to put into your mytheme.theme file; where you have to replace mytheme with the name of your theme and themehook with the template's theme registry hook - usually the template name with underscores instead of dashes):

/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_themehook(&$variables) {
  // This will be the new list variable to attach to the
  // template.
  $users_list = [];

  // Get the entity object from existing theme variables.
  // This example assumes you have a node entity in
  // your variables array already.
  $entity = $variables['#node'];

  // Load all referenced users from a field named
  // 'field_users_entityreference'.
  $users = $entity->get('field_users_entityreference')->referencedEntities();

  // Iterate through all users found.
  if (!empty($users)) {
    foreach($users as $user) {
      $item = [
        // Add whichever properties you'd like
        // to show within your template.
        'email' => $user->getEmail(),
      ];
      $users_list[] = $item;
    }
  }

  // Attach the new variable to the template.
  $variables['users_list'] = $users_list;
}

In your Twig template you can now access the users list by accessing the new users_list variable:

{% if users_list %}
  {% for item in users_list %}
    {{ item.email }}
  {% endfor %}
{% endif %}

EDIT:

According to the template name you provided, you are trying to alter how the entity reference field itself is displayed. Generally you have the following choices:

(1) Using field display: Add an according display to the user entity and change the field display to rendered Entity using this display. You can do so by

Go to "Admin / Structure / Display modes / View modes".
Find the User entity (should be somewhere at the bottom) and add a new user view mode.
Then go to "Admin / Configuration / People / Account settings / Manage display".
Choose the newly created view mode and add all fields you want to show.
Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
At the field in question change the Format to rendered entity and choose your newly created display mode by clicking the cogwheel at the very right of the row.

This approach usually fits your needs if you don't want to digg too deep into programming. Unfortunately you'd like to show the email address. This field is usually not available in user displays (privacy reasons; re-consider if you really want to show it). If you like to add that field to a regular user view, you'd have to additionally implement hook_ENTITY_TYPE_view().

(2) Alter the additional template variables within a preprocessing hook:

Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
At the field in question change the Format to Entity ID.
Implement a preprocessing hook as described above.
Fetch the item IDs from the existing variables and load the user entities.
Attach your information to the variables and use it within your template:

$users = \Drupal\user\Entity\User::loadMultiple($variables['items']);


How to get $form_id based on $form_state for custom form rule?

I think the easiest way was to pass $form ArrayObject which has $form_id present. So:

'form' => array('type' => 'form', 'label' => t('Form')),

needed to be added next to $form_state parameter in hook_rules_action_info and the final function looks like:

/**
 * Action: Submit the form.
 *
 * @param ArrayObject $form
 *   A reference to the form array of the form for which the event
 *   was triggered.
 * @param ArrayObject $form_state
 *   A reference to the form state array of the form for which the
 *   event was triggered.
 */
function rules_forms_action_submit($form, $form_state) {
  $form_id = $form['form_id']['#value'];
  $form_state = (array)$form_state;
  drupal_form_submit($form_id, $form_state);
}

For submitting entity form, check: How to programatically submit an entityform?


Cloned node entity reference field stay in sync with parent node

1) You could use a hidden field of the same type with the same information. This way, the information relating the parent to child can be reverted, regardless of the changes or overrides. Use Rules to populate the duplicate field. Create a "Revert" button on the node and again use Rules, or as a form submit to react to copy the information from the hidden field to the visible one.

2) Use Rules to adjust any child nodes when the parent is saved/updated. This would act on both the hidden and visible field, with a condition on the visible (not to change if it has been overridden).

You could also write a module to do this, but I think it can be done with just Rules.


Best Practice of Extending Another's Theme?

This is partly up to developer preference and specific use case but generally, if it is a custom theme, as in this case, you would add templates and modify css/template.php/etc. in the custom theme you already have.

If it is a theme from drupal.org or some other theme source, where updates for that theme may come in future, then it is best to create a sub theme of that theme (which you can do even if that theme is already a sub theme of another theme).


You have to install Drush through composer because it provides all the depencies which are required for drush. apt-get is basically supported by the Linux and Debian.

So use this link to install using composer :
https://github.com/drush-ops/drush


Is drupal safe against brute force login attacks?

As you can see in the code, the function user_login_final_validate register a flood event. That means if a same IP try to connect a user/login password many times we will be "banned" for a while.

This is one of the protections that Drupal offers. Another one, and I think if its happens to your web site you will notice it very fast, it's the CSRF token that Drupal generate for each form.

This means that the attacker bot should generate the form, then get the token and associate it with the submit form. That is very time consuming and will likely discourage the attacker. But first, you will see your server starting get hotter.


Creating individual fields from a multi-column Field API widget

Here is the solution.

/**
*  Implements hook_field_views_data_alter
*
* @param mixed $result
* @param mixed $field
*/
function addressfield_field_views_data_alter (&$result, $field) {
  if (array_key_exists('field_data_field_address', $result)) {
    $result['field_data_field_address']['field_address_country'] += array(
      'title' => t('Country'),
      'help' => t('The Country name of the field'),
      'field' => array(
        'handler' => 'addressfield_views_handler_field_country',
        'click sortable' => TRUE,
      ),
    );
  }
}

Or if you want to not use a real field in the table such as field_address_country but to instead alias a field you can add a field and table attribute to the field array like this.

function addressfield_field_views_data_alter (&$result, $field) {
  if ($field['type'] == 'addressfield')) {
      $result['field_data_field_address']['country'] = array(
        'title' => t('Country'),
        'group' => 'Bad Ass',
        'help' => t('The Country name of the field'),
        'field' => array(
          'field' => 'field_address_country',
          'table' => 'field_data_field_address',
          'handler' => 'views_handler_field',
          'click sortable' => TRUE,
        ),
      );
   }
}


link field template syntax / display link field as an image / devel dpm (D7)

I dont really understand what the problem is, If you are already outputting the link URL, and you want to display that as an image, surely you can just wrap it in an img tag?

<?php $path = $items[0]['#file']->uri; ?>

<img src="<?php print file_create_url($path); ?>" />

OR, with an mp3 file like in your example...

<?php $path = $items[0]['#file']->uri; ?>
<audio controls>
  <source src="<?php print file_create_url($path); ?>" type="audio/mpeg">
</audio>


drupal_render($form) not rendering a form

Try:

<?php print render(drupal_get_form('simple_nameform')); ?>


How can I log in as any given user with Drush?

You can log in to any Drupal site if you have access to the command line and Drush, knowing either the username

$ drush uli username --no-browser

OR the user ID.

$ drush uli --uid 123 --no-browser

This will return you an URL that you can copy paste into your browser address bar and login as that user. You can leave out the --no-browser option when you want the command to directly launch the browser.


Here in drupalsixlandia, I wanted to have this on a different page and did something along the lines of this to get it to work:

global $user;

module_load_include('inc','node','node.pages');
$type = 'TYPEOFNODE';
$node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type, 'language' => '');

return drupal_get_form($type .'_node_form', $node);

so perhaps D7 needs a similar $node argument as well.

ADDITION:  a quick look suggests D7 wants $node to be an object, not an array and does it by just doing:

$node = (object) array('uid' => $user->uid, ...

You might be able to grab its code directly and use it.  Looking back, I don't know why I just didn't grab this from node.pages.inc directly myself:

/**
 * Returns a node submission form.
 */
function node_add($type) {
  global $user;

  $types = node_type_get_types();
  $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => $type, 'language' => LANGUAGE_NONE);
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

  return $output;
}

Ah...here's why.  I didn't like the title, and I doubt you want that if you are stuffing this in a block :)


Inline Entity Form - How to Theme the referenced form edit screen with a tpl.php file?

I found the following answer here: http://site-machines.ru/blog/temizaciya-inline-entity-form-v-drupal

===========================

When using Inline entityform time to time it is necessary to make it more beautiful, more than matching the concept of the site. There are several ways to implement this, segodyan I will talk about one of the - the use of theming template.

As   Inline entityform is the usual form, so it has a minima must be some hook_alter. See the documentation that is the way to be in the module - inline_entity_form.api.php. The documentation found the right hook - hook_inline_entity_form_entity_form_alter.

At the entrance is just fed our inline form.

The next step is adding theming function

/ **
  * hook_inline_entity_form_entity_form_alter
  * /
 function sm_inline_entity_form_entity_form_alter (& $ entity_form, & $ form_state) {
   // Added theme function
   $ Entity_form [ '# theme'] [] = 'inline_entity_form_entity_form_'.  $ Entity_form [ '# bundle'];
   dpm ($ entity_form);
 }
I almost forgot to say the magic is done in our template.php form.

I told him what happened, what we've done in the previous paragraph? We've added a feature to our temizaitsii inline form, not just for one but for all. devel dpm () function module will help us to examine the insides of our Inline form

The next step in our magic, it template.php create hook_theme and declare it a template for our inline form

/ **
  * Implements hook_theme ().
  * /
 function sm_theme ($ existing, $ type, $ theme, $ path) {
   $ Items [ 'inline_entity_form_entity_form_shoes'] = array (
     'Render element' => 'form',
     'Template' => 'inline-entity-form-entity-form-shoes',
     // This will set to module / theme path by default:
     'Path' => drupal_get_path ( 'theme', 'sm').  '/ Templates / inline_form',
   );
   return $ items;
 }
Just be sure to create our template file and we put him on the scullery indicated in the 'path' hook_theme.

Then I inserted the following code template

<-! Start inline-entity-form-entity-form-shoes.tpl.php ->

<-! @ See sm_theme adn template.php ->

Then we look at what we will give dpm (), continue using drupal_render output fields in the required manner


How to turn multi-value image field into a UL

You could certainly do it with a preprocess function...or you could install the Fences module and do it through the UI:

  Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.


You can see region--menu.tpl.php which is rendering main menu..

<div<?php print $attributes; ?>>   <div<?php print $content_attributes; ?>>
    <?php if ($main_menu || $secondary_menu): ?>

        <?php print theme('links__system_main_menu', array('prefix' => '
', 'links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix', 'main-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('element-invisible')))); ?>

        <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix', 'secondary-menu')), 'heading' => array('text' => t('Secondary menu'),'level' => 'h2','class' => array('element-invisible')))); ?>

    <?php endif; ?>
    <?php print $content; ?>


Bootstrap theme - add or remove classes in $navbar_classes

function YOURTHEME_preprocess_page(&$vars) {
      //add news class
      $vars['navbar_classes_array'][] = 'new-class';
      //remove class
      unset($vars['navbar_classes_array'][0]);
      // you need change value 0 to value you want remove class
      // Default
      // 0  'navbar', 1 => 'container', 2 => 'navbar-default'

}

You can do it with

Override file page.tpl.php. You can copy file page.tpl.php in bootstrap/theme/system/page.tpl.php to new your subtheme and edit it. It is right way.
Or you can use function hook_preprocess_page(). You can write code in file template.php of your subtheme. That way you don't need change file page.tpl.php


What has always worked for me when I build custom REST resource plugins for 8 is making the request and payload for the request in HAL+JSON format after activating the format for the endpoint. The return data has always come back as just JSON. Since many times I've already built content entities which have their own GET, POST, PATCH, DELETE operations, I generally build the custom REST resource plugins for custom operations which I create. I've only tested overriding the default core operations a few times and then I had to disable the core's REST endpoint on a specific operation to allow my endpoint to take priority. ie. My POST operation is used rather than the core's. I'm currently using the Beta14 version of 8.


If logged in, My Account/Log Out are missing, how can i fix?

The user login block doesn't include "My Account" and "Log Out" links.

user_block_view > user_login_block

However, you can add the "User menu" to that region instead

Admin > Structure > Blocks > "User Menu"

It contains "My Account" and "Log Out" links.


Seems to work properly if I do not use the default feed importer. Instead I created my own feed importer, I think with the exact same settings, and now it imports full html!


How field values are stored in the database

Different field types can have different data columns in the database. Most modules have a 'value' column. Others, like reference fields, have a 'target_id' column instead. The Date module can create a 'value1' and 'value2' column (for start date / end date).

You can't assume that it is always 'value'.

The 'target_id' value refers to the ID of the entity being referenced. So, if the field is referencing nodes, target_id is holding a node id value. If the field was referencing users, the value stored is the user id.


I can't log in after removing the user login left bar

Simply go to http://yoursite/user or if you don't have clean url enabled http://yoursite/?q=user


Migrating stories from Drupal 5 to Drupal 6

I would personally follow the steps described below:

1) Transfer my Drupal 5 site in a test machine (possibly a local VMWare Development Machine).

2) Convert the Drupal 5 site to Drupal 6 using the guide that you can find here.

3) Use a Node Export/Import module to transfer the nodes from the local site to the new/from-scratch-built website. (e.g. Node Export module)

Note: If you do not know how to transfer your live site to your local machine the steps that I usually follow are:

a) Download the live site's files locally

b) Export the live database through PHPmyAdmin and save it locally

c) Import the database in my local MySQL server

d) Most of the times the links don't work properly in the local machine. The most common reason for this is that the local server does not have the capability for clean URLs so I add this to the httpd.conf:

<Directory /var/www/yourDirName>
   RewriteEngine on
   RewriteBase /yourDirName
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

and restart the apache server (notice that you will have to replace the "yourDirName" part with whatever your dir name actually is)


The only place node_cron_last is set is in _node_index_node(), which is run when indexing a node for search results.
Its purpose, per the comments:

Save the changed time of the most recent indexed node, for the search results half-life calculation.

cron_last is simply used to

Record cron time.

per drupal_cron_run()
Given that REQUEST_TIME is used for all values (cron variables + node changed date) in the same request, you might well expect those two variables to contain the same value.


MongoDB is not a full replacement for MySQL, you still need it. You can only move certain pluggable systems to MongoDB, like sessions, watchdog and in Drupal 7 also the field storage.


Robots can find urls by following links either on-site or offsite.

You could use a link scanner as suggested by Clive, or look in google analytics to see where referrals are coming from to see if you have a lot of inbound links.

Alternatively, if a robot has figured out (or guessed) that your site is Drupal based then it's a pretty simple matter to start trying ?q=node/1, ?q=node/2, etc... and see what you don't get a 404 from.

I'd say a likely reason that the robot is using "?q=blah" instead of just "blah" is because the former will always work whereas the latter requires you to have clean URLs configured.

As well as robots.txt there are free services like Cloud Flare http://www.cloudflare.com/ that attempt to filter known-malicious bots for you before they can access your server.

You could also add rel="nofollow" to links on you're site that you're suspicious might be generating the traffic, which tells crawlers to not follow that link. Be careful with this as it also stops search engines, meaning it can harm your SEO if used unwisely.


Add content type machine name to an attribute in the body tag?

template_preprocess_html should be the right function to start with.

So your code should look like the following:

function mytheme_preprocess_html(&$variables) {
  if ($node = menu_get_object()) {
    $variables['attributes_array']['data-init'][] = drupal_html_class('node-type-' . $node->type);
  }
}

Make sure to replace mytheme with your custom theme and clear Drupal cache.


How do I change the transport for remote drush alias calls

It seems that you currently can't change the transport / replace SSH. However, most of the work can be fixed be writing wrapper scripts. Read https://github.com/drush-ops/drush/issues/2367


Variable created in hook_preprocess_node is not available to template

The variables added from hook_preprocess_node() are only available in node.tpl.php, or any other node template that Drupal will pick up because any suggestion contained in $variables['theme_hook_suggestions'] (Drupal 7), or $variables['template_files'] (Drupal 6).

To add a variable used by a region template file, you need to use a different preprocess function: hook_preprocess_region(), or hook_preprocess(). The latter is a generic preprocess function; the second parameter passed to that preprocess function tells it which theme hook is going to be preprocessed.

This means that, by default, the region preprocess function doesn't have access to $variables['node']; if you want to access the node object associated with the page being viewed, if there is one, you need to use similar code used in template_preprocess_page() and add the following line to your preprocess function:

if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

The function returns FALSE if the page is not associated with a node; this could happen, for example, if the user is visiting example.com/user/1.


How to make node delete confirmation inline?

you can put this in your node--node-type.tpl.php file:

$item = menu_get_item("node/$nid/delete");
if ($item['access']) {
    include_once(drupal_get_path('module', 'node') . '/node.pages.inc');
    $page_title = drupal_get_title();
    $delete_form = drupal_get_form('node_delete_confirm', $node);
    print render($delete_form);
    drupal_set_title($page_title, PASS_THROUGH);
}

also you can remove Cancel link from $delete_form


The "standard" way of creating multiple sites with some interaction between them using Drupal is to use the Domain Access module rather than multisites.

However, there is great write-up about using interacting multisites at Drupal Redesign: Domain Access vs. Multisite.

The gist of it is that you set up a multi-site as you normally do. Then you create a custom module to take care of interaction and sharing data between the sites.

Drupal can handle multiple databases, but you can avoid the complexity of managing multiple databases by using a single database and use a database table prefix to avoid namespace collisions.  If you already have created the databases as separate databases, you need to use hook_update_N (or SQL operations outside of Drupal) to refactor the schemas.


drupal_goto ignored in custom form submit handler

I had a problem like this and I used this as a workaround to get the page to redirect:

$url = url("node/$nid");
header("Location:$url");
drupal_set_message(t('Message to be displayed in the next page'));
drupal_exit();


Why, while developing a module, do I get an error for not specifying a handler when one exists?

Drupal 8 made the decision to be fast by default and use the APC Classloader if it is available.  It is faster, but it doesn't necessarily catch changes as you make them.  To not have to restart your web server during development, you can set your local environment to not try to use a better-for-production class loader.

For instance, in local.settings.php add:

$settings['class_loader_auto_detect'] = FALSE;

As documented in settings.php:

  If the APC extension is not detected, either because APC is missing or
  because auto-detection has been disabled, auto-loading falls back to
  Composer's ClassLoader, which is good for development as it does not
  break when code is moved in the file system.

In the issue where this change was made, Berdir warned that it would stymie developers.  More background information at what to do when developing a Drupal 8 module and a class file just isn't being loaded even though it is definitely there.


How can I have a block show only on the /user page, but only for users with specific role?

On the configure block page, at the bottom in the vertical tab menu, click on the roles tab, and select which user role you want it to display for.


Rules: how to programmatically set the bundle of an entity?

Actually, if you need to do something that's like an additional 'condition-then-action' within your rule's Action section, what you need is a Rules component!

You've loaded some entities in your action (perhaps in a loop) and now you need to apply a condition and action to those entities.  Here's the basic recipe for using components in your action section:

Go to /admin/config/workflow/rules/components to create a new rule component to run for each of the items in your loop (or for a single item you've gotten in your rule action). Click the 'Add new component' link at the top of the page
Select 'Rule' from the drop-down options, since this will be a component that contains both a condition and an action
Name the rule, and in the 'Variables' section, we have to let it know we're going to pass it a parameter to work with. In your case, this will be the entity you want to check.
Once you've named your components and named the parameter you'll pass it, the next screen looks very much like a regular rule.  Just set up the condition (make sure the entity is of type whatever) and the action (use the appropriate fields of that entity to do something).
Finally, save your component and call it in your original rule's action section (within the loop if you have one), passing it the entity to work with

Sorry that this is rather text-y.  I actually just recently answered a question about using rules components with commerce items in another question and included screenshots there, so see if you can use that as a reference too: https://stackoverflow.com/questions/17797285/drupal-commerce-order-object-extra-data/17843597#17843597

Let us know if rule components solve your issue!


Update.php with errors in multisite (WAMP)

probably an inconsistant module state. try to disable the migrate module in the database.

UPDATE system SET status='0' WHERE name='migrate';

for more details see here: How to manually uninstall a module?


How do I change store based on location?

Configuring the stores is one thing, determining which one is used for any given page request is another. One store is configured to be your default, and absent any other code, that store will always be used for the current page request, influencing visible products, pricing, carts, etc. If you want to make the current store something other than the default, you have to write a store resolver.
An example module you can reference is the Commerce Store Domain module, which resolves the current store based on the current domain. You can do something similar using the GeoIP module. I'm not aware of any existing contrib that integrates that as of yet.


Drupal 8 Custom Composite Entity Select Field

I think you just need to change...

'#type' => 'entity_select',

...to...

'#type' => 'webform_entity_select',

In the Webform YAML source editor we are hiding the 'webform_*' prefixes, within custom code they have to included.

@see https://cgit.drupalcode.org/webform/tree/src/Element/WebformEntitySelect.php


I would recommend using the FooTable Views plugin. I've used it before and it's quite helpful when dealing with responsiveness and smaller content areas.


Installation showing only SQLite as database option

You won't be able to convert an existing site as far as I know; you'll need to build a new site and migrate the content over to it. It might be easier to just start a new site from scratch and export/import the data manually, depending on how far you've got.

Before you do that, you need to enable MySQL in PHP. If you only see SQLite as a DB option, it means you haven't installed the PDO MySQL extension. Consult your web server's documentation for instructions on how to do that.

Once you have, MySQL will appear as an option for installation.


If your node is 12, your internal path is node/12 when the alias is 'inventory'. In that case arg(0) gives you 'node' and arg(1) gives you '12'.

In the case of dynamic URLs like inventory/ABCD, I assume that the internal path is 'inventory/ABCD' (so that inventory/ABCD does not have anything to do with node 12). Then arg(0) gives you 'inventory' and arg(1) gives you 'ABCD'.


How to add multiple products to cart at the same time with attributes

I suggest writing a custom hook_submit() who will add all the items of your views to the shopping cart.

Something like that should do the job.

 global $user;

 $results = views_get_view_result('view_name', 'block_1');

 foreach($results as $item) {
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);
 }

Good luck.

Cheers


Views different image styles depending on URL

Create different ImageStyles, If the image field of the content type is field_image then you can use this code:

        $variables['theme_hook_suggestions'][]='THE_THEME_HOOK_SUGGESTION';
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $photo_field = $wrapper->field_image->value();
        $url = arg(1); // you can distinguish the address by arg(0),arg(1), ...
        if ($url == "URL1") {
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE1',
                        'path' => $photo_field['uri'],
                    )
                );
        } else if ($url == "URL2"){
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE2',
                        'path' => $photo_field['uri'],
                    )
                );
        }

Make sure to put such code hook_preprocess_node, and also this code is run when the correspondent content type is loaded. then in the THEME_HOOK page of the content type use $image variable to display the image.


Drupal site moved from development to live - IE won't load stylesheets anymore

I would start by checking two things:

Is there a difference in settings for caching and/or CSS aggregation on live vs. dev?
Have you tried clearing the cache via the button in the UI? Doing it from drush does not clear the CSS caches, and it also has some other behavior that's different from the UI button way.


I used this on www.grupposportivo.be in a bootstrap nav bar

<?php global $user; if ($user->uid != 0)
                { print '
' .t('').
                    'uid). '">' .$user->name. '

'; print '

                    ' .t('Logout'). '

'; } else { print '

                    ' .t('Login'). '

'; print '

                    ' .t(''). '

'; } ?>


How do I correctly setup caching for my custom API routing?

This is all you need to set up caching for a response:

  $response = CacheableJsonResponse::create($output);
  return $response;

If you use a response that implements the CacheableResponseInterface it will be cached indefinitely.

Cache tags

When you add a list of taxonomy terms you have to add these tags:

  $list_tags = $this->entityTypeManager()->getDefinition('taxonomy_term')->getListCacheTags();
  $cache_metadata->addCacheTags($list_tags);

  foreach ($terms as $term) {
    $cache_metadata->addCacheableDependency($term);
  }

This will invalidated the cache entry when the terms are modified in the database.

Cache contexts

When you use a query parameter add this context:

  $lang = $request->query->get('lang', 'en');
  $cache_metadata->addCacheContexts(['url.query_args:lang']);

This will vary the cache by the query arguments.

Cacheable metadata in a response

To put all this together create at the beginning of the controller an empty CacheableMetadata object:

  $cache_metadata = new CacheableMetadata();

While building the content collect the cache metadata for all dependencies you use as described in the two examples before and then add the metadata to the response at the end of the controller:

$response->addCacheableDependency($cache_metadata);


Difference between field widget price textfield and price with currency?

The simple explanation is that:

Price textfield only allows the user to enter a price, where the currency code is selected in the field setting, where as Price with currency allows the user to select both price and currency and you can setup a default currency in the field setting.


The best way (the Drupal way) is to build on top of available Drupal features, rather than creating a custom solution that may do the narrow task at hand, but bypasses a lot of the built-in structure that carries a lot of value when using Drupal.

Views module is used to build the page you linked to, and Views is also the best module to use to list the geo-data to be displayed on a map.

Each node from that table has Longitude and Latitude coordinates (visible when you visit a node page, not directly in the table). These coordinates fields can be used to feed a Views map display.

You'll need to install a module that provides a special Views Format that renders a map. Then add that Display type to the same Views where the page you linked is built. Adjust the fields (override) to provide for the map display.

Are your Longitude/Latitude fields from Geolocation Field? Check under Structure > Content types > SAR Saves > Manage fields. Also check under Extend which geo-modules you have available.

With Geolocation Field you already have everything you need, you just need to configure a new map display in Views configuration, no coding required ;)


Drupal 7 cache page for anonymous users causes issues when loading different css files based on browser version

Serving up different content based on request headers isn't the best idea in general, especially if you aren't sending back a Vary header.

The best workaround is to use markup rather than server side logic.  When you do this, Drupal will cache things properly.

For IE, this means either using HTML conditionals and/or Paul Irish's method and/or JS "cleanup".

Pre-IE9 support for media queries has a few popular solutions, including the the Respond library.

For Drupal, I would recommend using a HTML5-aware base theme like Omega, which wraps all of this up in a nice package.


"Allowed memory size" errors on common tasks

Edit your sites/default/settings.php file, and change the line to set the memory limit:

ini_set('memory_limit', '100M');

or increase memory_limit in your php.ini file.


The best way to do so is by configuring the multilingual parameter of your node type as "Enabled, with field translation".

The steps :

enable the module i18n_fields
edit your node type
go to publishing options tab
set Multilingual support => "Enabled, with field translation"

This way, there will be only one node for all the translation of your node (e.g.: node/534) and only the translatable fields will change between language.

You need to then define which fields you want to translate :

in the content type, go to manage fields tab
choose the field and edit
check the box "Field translation" at the bottom


Changing the text displayed in an Entity Reference Autocomplete

You need to implement your own selection plugin for this.

I thought I've already answered a similar question but can't find it anymore.

Assuming the target is a node, extend from \Drupal\node\Plugin\EntityReferenceSelection\NodeSelection, otherwise from its parent or appropriate other child class and override \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::getReferenceableEntities().

Make that available under its own plugin id (not default:something, just something) and select it in the entity reference field settings.


Call a php function on text selection in text area

If you want to do something when text is selected, take a look at the .select() jQuery event.  Then you can enable/disable the button however you like.

Example from the jQuery page:

<!DOCTYPE html>

    Click and drag the mouse to select text in the inputs.

  <input type="text" value="Some text" />
  <input type="text" value="to test on" />


Yes, but it's under development.  It's called statuses.


Can't attach #ajax to altered form displayed in block

drupal_get_form will return a builded form/ rendered form. i.e Your form has been already prepared based on the specification done in the form callback, like its finalized.

So making changes to the return values of drupal_get_form wont work.

If you want to alter any of the form then you should use any of the following hook

hook_form_alter
hook_form_FORM_ID_alter


When to use custom nodes? How to display custom fields?

Best suggestion, don't start doing custom template overrides. With site building tools like Display Suite, you no longer have to continue writing custom node templates. By using Display Suite, you can set a view mode you defined to a two-column template, and then set the fields you'd like into each region.

You can see in the example below how easy it is to achieve something like this without having to build custom templates. Of course if you need to do anything extra, you can always customize on top of that.


Since you're not initiating the hook, you'll have to find another way. Maybe call a hook in the hook you're implementing?

If you would've been initiating the hook, you could've just passed on more parameters and used func_get_args to get the parameters, ie:

function sum ($a, $b) {
  $sum = 0;
  foreach (func_get_args() as $arg) {
    $sum += $arg;
  }
}

and call it with

sum(1, 2, 3, 4)


How to import translated strings having dynamic variables?

There are two way to achieve this

Add string in a your .po file like follows

msgid "Hi @firstname, please follow @sitelink or mail me at @email"
msgstr "Hola @firstname, por favor, siga @sitelink o envía un email al @email"

and import that .po file by going

  Administration » Configuration » Regional and language » Translate interface » Import

 If you want to change individual translated strings go to

  Home » Administration » Configuration » Regional and language »
  Translate interface » Translate

You can find list of strings there each having edit link beside. So you change the individuals like follows.

Hope this helps someone.


Drupal (or perhaps Apache) delivers wrong page

"The apache server is setup with some reverse proxy..." then you have to provide the correct response headers in an event subscribers, see How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)? how to set response headers.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

And uninstall the module Internal Page Cache, because this built in reverse proxy doesn't respect Cache-Control headers and you don't need it, because you already cache outside of Drupal, see PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF


How do I display a Taxonomy Term Description to a view in D7?

You will have to add a relationship to include the term data for the content(?) you are listing – then the term description will be available as regular View fields.

You can check out Learn Views with NodeOne, part 11: Relationships for a quick video on managing relationships.

Good luck!


URL path settings not supporting more than one level

That's strange. If you edit the URL alias manually, it shouldn't be automatically changed unless you bulk delete and update your URL aliases in Pathauto.

Have you checked your Pathauto pattern settings (/admin/config/search/path/patterns) to see if there is something overriding your changes?

You said that you inherited the site. Are there any URL/path-related modules that your predecessor has enabled?


Drupal 8 Installation Is Just Plain HTML

Wow. I just solved the problem. I didn't realize that by default on a Minimal installation that the Stark theme, which is simply a plain HTML theme, was enabled by default. I switched the theme and now it works fine.


As shown in this SO answer:

How to sort on different columns in the same view?

the views SQL object uses ->addField instead of ->addExpression. This code ended up working for me:

  public function query() {
    $this->ensureMyTable();
    $has_custom_sort_id = $this->detectCustomSorting();
    if($has_custom_sort_id !== FALSE){
      $id_to_top = $has_custom_sort_id;
      $this->query->addField(NULL,
        "nid = ".$id_to_top, 'is_match');
      array_unshift($this->query->orderby,['field' => 'is_match', 'direction' => 'DESC']);
    }
  }

The array_unshift just moves the is_match sort before the draggableviews sort which is also on this View. For some reason, re-arranging them in the View UI caused the draggableviews sort to drop off. Hope this helps someone in the future.


Rules module not enabling via Drush in drupal 7

You'll need the i18n module to install rules_i18n

drush dl i18n
drush en i18n_string
drush en rules*

Alternatively, enable the rules submodules individually, excluding rules_i18n


How to programmatically set the front page?

You can use variable_set() for that.

variable_set('site_frontpage', $value);


How can i send a mail to specific user when workflow state is changed or changed to particular state?

This can be achieved with the help of Rules module.

  The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
  Example use cases

  Build flexible content publishing workflows changes
      Send customized mails to notify your users about important
      Create custom redirections, system messages, breadcrumbs, ...
      Build an eCommerce store using Drupal Commerce

  And many more...

Check Tutorial: editorial workflow with rules, which has good documentation on the how to's.


You will need to check the ImageField array to see what needs to be changed but for D6 but it   should be something like the below:

$node = node_load($nid);
$node->field_photo[0]['value'] = NULL;
node_save($node);

Just change the field name to what you are using and change the $nid to the node id #.


Using Drush how can you see the last user that logged in?

drush sqlq "SELECT name FROM users ORDER BY login DESC LIMIT 10"

Tweak LIMIT to change the number returned.