How to use drupal_mail() to send emails with custom template

If you are trying to send the mails via your custom module then you can follow the below mentioned guide.
Say, I had one Module called "Commerce Canvas(commerce_canvas)"
 1. First Alter the Drupal's mail function to support links and add other encoding types

/**
 * Implements hook_mail_alter()
 * @param string $message
 */
function commerce_canvas_mail_alter(&$message) {
    $headers = array(
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=iso-8859-1; format=flowed',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer' => 'Drupal',
    );
    foreach ($headers as $key => $value) {
        $message['headers'][$key] = $value;
    }
}

Then next, hook the HOOK_mail in your module as

/**
 * Implements hook_mail()
 * @param string $key
 * @param string $message
 * @param unknown_type $params
 */
function commerce_canvas_mail($key, &$message, $params) {

    //Language Selection
    $options = array(
        'langcode' => $message['language']->language,
    );
    switch($key) {
        case "user_payment_notification" :
            $message['subject'] = isset($params['subject']) ? $params['subject'] : $message['subject'] = t('Payment recieved @site-name', array('@site-name' => variable_get('site_name', 'Express Canvas')), $options);
            $message['body'][] = isset($params['body']) ? $params['body'] : NULL;
            if (isset($params['headers']) && is_array($params['headers'])) {
                $message['headers'] += $params['headers'];
            }
            break;
    }
}

Then you need to create a wrapper function to invoke the mail from your module.

function commerce_canvas_mail_send(array $values = array()) {
    $module = $values['module'];
    $key = $values['key'];
    $to = $values['to'];
    $from = $values['form'];
    $language = isset($values['lang']) ? $values['lang'] : language_default();
    $params = array(
        'subject' => $values['subject'],
        'body' => $values['body'],
    );
    if(array_key_exists('headers', $values)) {
        $params['headers'] = $values['headers']; //Assumed as an array
    }
    $send = TRUE;
    $mail = drupal_mail($module, $key, $to, $language, $params, $from, $send);
    if($mail['result']) {
        return TRUE;
    } else {
        $error_msg = 'Failed to send the email in commerce_canvas Module';
        watchdog('canvas-email', $error_msg, array(), WATCHDOG_ALERT);
        return FALSE;
    }
}

This function will send the email and as well as create debug messages if anything happens wrong.
But still you won't be able to send the HTML mail because you need to extend the Drupal 7's default DefaultMailSystem with your own. So need to do as following,

class CommerceCanvasMailSystem extends DefaultMailSystem {
    /**
     * Concatenate and wrap the e-mail body for plain-text mails.
     *
     * @param $message
     *   A message array, as described in hook_mail_alter().
     *
     * @return
     *   The formatted $message.
     */
    public function format(array $message) {
        $message['body'] = implode("\n\n", $message['body']);
        return $message;
    }

    /**
     * Send an e-mail message, using Drupal variables and default settings.
     *
     * @see http://php.net/manual/en/function.mail.php
        * @see drupal_mail()
     *
     * @param $message
     *   A message array, as described in hook_mail_alter().
     * @return
     *   TRUE if the mail was successfully accepted, otherwise FALSE.
     */
    public function mail(array $message) {
        $mimeheaders = array();
        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }
        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        return mail(
        $message['to'],
        mime_header_encode($message['subject']),
        // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
        // on Unix and CRLF on Windows. Drupal automatically guesses the
        // line-ending format appropriate for your system. If you need to
        // override this, adjust $conf['mail_line_endings'] in settings.php.
        preg_replace('@\r?\n@', $line_endings, $message['body']),
        // For headers, PHP's API suggests that we use CRLF normally,
        // but some MTAs incorrectly replace LF with CRLF. See #234403.
        join("\n", $mimeheaders)
        );
    }
}

Next you need to register a new theme function that will call your custom template file in your hook_theme().

/**
 * Implements hook_theme();
 */
function commerce_canvas_theme($existing, $type, $theme, $path) {
  if($type == 'module') {
    return array(
      'tracking_code_email' => array(
        'variables' => array(
          'image_path' => NULL,
          'user' => NULL,
          'page' => NULL,
        ),
        'template' => 'commerce-canvas-tracking-code',
        'path' => drupal_get_path('module', 'commerce_canvas').'/theme',
      ),

    );
  }
}

Last you need to call this theme function in time of sending the email as,

function a_custom_function($params) {

$email_text_user = theme('tracking_code_email', array(
                    'image_path' => $base_url . '/' . drupal_get_path('module', 'commerce_canvas') . '/images',
                    'user' => null,
                    'page' => array(
                        'greet_text' => t('Thank you for your order at Express Canvas. Your order is ready and has shipped. You may track your order using FedEx tracking with your tracking number: '.$order->field_tracking_number['und']['0']['value'].''),

                    ),
                ));
$sent_to_user = commerce_canvas_mail_send($email_values_user);

}

These are the full snippet to handle the HTML email correctly in Drupal 7 thus in the hook_theme you can give your custom template.


You have to go to the menu configuration and manually check "expanded" for each item that has children. This is really annoying since there used to be a checkbox right on the list of links so you could do it on a single page at once. Not anymore.


Drush sql-sync failing with Ubuntu 14.04

So it turns out I'd installed Drush 6 on the remote server, while my local version was Drush 7. Upgrading solved the problem.


Since you're attaching the #theme to an element, you need to user render element in your theme declaration in place of variables:

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'some_form' => array(
      'template' => 'some-form',
      'render element' => 'form'
    ),
  );
}

After you clear the caches your template should start being used for that form.

See hook_theme() for more information.

Just another thought, if your template file is as trivial as just wrapping the form in a tag you can use the #prefix and #suffix properties on the $form object instead of using a theme at all:

$form['#prefix'] = '
';
$form['#suffix'] = '
';


@Scorchio Thanks for that. I was successfully able to convert the layout from '1 of xx' to '1 2 3 4 5 6 x' by overriding views-slideshow-slide-counter.tpl.php and modifying the views_slideshow.js. My changes are below.

views-slideshow-slide-counter.tpl.php

<div id="views_slideshow_slide_counter_<?php print $variables['vss_id']; ?>" class="<?php print $classes; ?>">
<?php
    $slide_count = count($view->result);
    for($i=1;$i<=$slide_count;++$i)
        print ''.$i.' ';
 ?>

views_slideshow.js

Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' span').removeClass('active');
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num' + (options.slideNum + 1)).addClass('active');
};


Skipping form validation with a custom action button

To send a redirect response from a form use setRedirect() or setRedirectUrl():

  function cancel_submit(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl($url);
  }

And add '#limit_validation_errors' => array() to the cancel button as already mentioned in the question to prevent validation errors.


You can check out the file_create_url() function that creates a URL for your file.

So, based on the code in your question, it would look like:

// Generate or get the image uri.
$image_uri = file_default_scheme() . "://";
// Create the url from the uri.
$image_path = file_create_url($image_uri);


How to see recently inserted terms in the site?

You could add a field to the term which saves the current date when saved. Use the hook_taxonomy_term_insert() for this.

I think there is no other information on the term itself than the tid.


Promoted to frontpage teasers in a block

Use Views:

Create view of content
Create "Block" display
Use filters to only show ones with "promoted to frontpage" selected
In Format section set  Show: Content | Teaser
Put your block on the frontpage

That's all.


put the code into the template.php file?

It's fine to put code in template.php, but do not print or echo there. All print or echo code should be in template files (.tpl.php). If you need to prepare variables for output in a template file, alter a preprocess function (eg. THEMENAME_preprocess_page if you need them in page.tpl.php), add your variables to the $variables array (eg. $variables['greeting'] = 'Hello!'; and print those variables in the template file (print $greeting;).

So for this example it would be something like:

function THEMENAME_preprocess_node(&$variables) {
  $common = $variables['content']['body']['#object']->field_fenlei['zh-hans'];
  $term_links = '';
  foreach($common as $vocab){
    $term_links .= l($vocab['taxonomy_term']->name,$vocab['taxonomy_term']->uri['path']);
  }
  $variables['fenlei_term_links'] = $term_links;
}

Now you can access the output with the variable $fenlei_term_links in your node.tpl.php:

<?php print $fenlei_term_links; ?>

In general you might want to use something like http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links or http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_items


How to delete duplicate comments using sql?

For toying things on the backend in SQL. The best place to start would be to look to see how the API does something in Drupal. For this you want to look at comment_delete_multiple which you can call to delete mass comments. You will need to know the comment IDs of the comments that you want to delete.

This is where this gets complicated. You have to find the CIDs you need before you can start deleting. Your criteria for finding the comments is going to depend on what you want to do. If you just want to delete any and all comments that are dupes then you could run a query like this to find dupes and generate the CIDs you want to delete.

Once you ahve the CIDs, it is very easy.You write a delete statement against the comment table.  Using the Drupal API where it would iterate through the list of CIDs

$cids = array( , , , .....)
db_delete('comment')->condition('cid', $cids, 'IN')->execute();

With the amount of comments you are trying to delete doing this strictly in SQL is going to be hard because you will need to write a statement with a gigantic list in a LIKE clause.

In my humble opinion: when I have had to do massive data changes like this in Drupal I write a PHP CLI script to do it so I can handle the data. I've migrated a website that had 150k users, 2000 blogs, and 110k comments, I did it all with PHP CLI scripts.


You could use the routing system and create a custom route and output your json within the controller.

After that you can load the url in your ajax call.

module.routing.yml (path_to_module/):

  module.content:
  path: '/json-output'
  defaults:
    _controller: '\Drupal\module\Controller\ModuleController::content'

  requirements:
    _permission: 'access content'

ModuleController.php (path_to_module/src/Controller/):

<?php

namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class ModuleController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function content() {
    // Load your json content here.
    $json = module_get_json();

    $response = new Response();
    $response->setContent($json);
    $response->headers->set('Content-Type', 'application/json');
    return $response;

  }

}

Now you can load your json via /json-output. It is also possible to pass variables to the controller via the url.


Assign all permissions to a user programatically

You could use rules - when a user is created (could include certain contextual requirements) then all the roles are added.

or the less tidy way

You could get all the roles from the DB and then insert each into the user_roles table.

Something like:

$userID = 'ENTER UID';
$query = db_select('user_roles', 'r')->fields('r')->execute();

while($role = $query->fetchObject()){
    db_insert('user_roles')->fields(array('uid' => $userID, 'rid' => $role->rid))->execute();
}
drupal_static_reset('user_access');  /* Flush the caches */
drupal_static_reset('user_role_permissions');  /* Flush the caches */

The code is untested but should be a good foundation.

You can also do the same in Drupal by loading the user object and making the changes, but the above will do the same.


Prevent "AJAX HTTP request terminated" error on early form submit

This might help you.

Drupal.behaviors.merchant = {
  attach: function(context, settings) {
    jQuery('form.node-form')
      .ajaxStart( function() {
          jQuery(this).submit(function() {
            return false;
          });
        })
       .ajaxStop( function() {
          jQuery(this).unbind('submit');
          jQuery(this).submit(function() {
            return true;
          });
        });
  }
}


UPDATED:

If you are going to create new users using user_save() then follow the following syntax.

$user = array(
   'name' => $userdata['name'],
   'mail' => $userdata['mail'],
   'init' => $userdata['mail'],
   'pass' => user_password(8),
);

Now call the function user_save() and pass the user info as second arg.

$account = user_save(null, $user);
if($account){
     _user_mail_notify('register_admin_created', $account);
}

To update values for already saved user.

$account = user_load(array('uid' => $userdata['uid']));
$updates = array(
    'pass' => user_password(),
    'name' => 'new_name',
    'roles' => array(
        <rid> => '<role title>';
    ),
);

user_save($account, $updates);


give node author ability to position the image when uploading content

Of course it can! Was covered in docs and in even more docs and is supported by Wysiwyg, with helpful modules like Insert to make it even easier.


Programmatically update node image field (using URI of the image) and get URL in twig

You have to create a file for the image first before you can add it to the node.

use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg';

  // check first if the file exists for the uri
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',
  ];

  $node->save();


That extension's operations are transparent to the application, you only need to configure the host that the DB connection is setup with.

From a Drupal point of view, you just need to update the "host" entry for the relevant database in settings.php to match the name of your mysqlnd_ms application. From the looks of your config file that's myapp, so your database connection might look like this:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'foo',
  'username' => 'bar',
  'password' => 'baz',
  'host' => 'myapp',
  'prefix' => '',
);

If that doesn't work, check that the extension is installed, configured, and enabled.


If I understand it correctly, a shopping cart refresh causes the recalculation of your line item price(s). For documentation on this topic, see sell price calculation on drupalcommerce.org and the referenced Prezi presentation on that page.

Maybe you can adjust the price calculation, by adding pricing rules that react on the event 'Calculating the sell price of a product' and use the action 'Set the unit price to a specific amount'.

Otherwise, you could implement one of the hooks provided by commerce_product_pricing.api.php.


Is there an existing way to make blogs for nodes (not users)?

It is a little bit of a learning curve at first but you could use OG Groups for something like this. Make your organization node be a group and add an audience field to blog content type.


How to prevent 'drush up' from deleting non native inodes in a sub-theme folder?

If your sub-theme folder is inside the base theme folder, it will get wiped out when there is an update to the base theme, as drush will remove the contents of the theme folder and replace them with the new updated contents of the theme.

The solution is to move the sub-theme folder to be along-side the base theme folder, so it's a sibling, rather than a child.


You can use an argument on your view to apply the filter from the URL. If you set the "action to take if argument is not present" to display all values then your standard job page will continue to function as before.

In Drupal 7 arguments are called "contextual filters" and are hidden amongst the "advanced" view options.


Changing the output order of Nodewords meta tags in head

You can implement hook_nodewords_tags_alter which will alter the rendering of the tags. It accepts function MODULENAME_nodewords_tags_alter(&$output_tags, $tag_options) {}.

But why do you want to do this ? Any SEO insight you might share with us ?


What is the correct way to handle caching with custom modules?

In your page controller for /bookings, set a cache tag in the build array:

$build['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Or since it's a form:

$form['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Then when you submit the admin form that has the settings for the page, invalidate the tag:

Cache::invalidateTags(['booking_page_settings']);

You can also add to your cache tags the nodes that display on your booking page, such as 'node:123', or you can add 'node_list' to invalidate the caching when any node is updated.


Have you considered ThemeKey?

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on
  current path, taxonomy terms, language, node-type, and many, many
  other properties.


You can use the following code in a module, or a theme.

function mymodule_js_alter(&$javascript) {
  if (isset($javascript[$path])) {
    $javascript[$path]['data'] = 'absolute URL to the file';
    $javascript[$path]['type'] = external;
  }
}

Replace $path with the correct value. Normally $path is build from the path where the module is installed with drupal_get_path('module, $module) . '/' $filename.


Should modules be in source code management?

As Jaypan and leymannx say in the comments above, if you use Composer to manage dependencies, you can just include composer.json and composer.lock in your version control repository. Then you can use Composer to rebuild your project when you deploy. This has the advantage of keeping all third party code out of your repo.

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

The documentation linked above shows how to use Composer to install Drupal core, contrib modules, and even patches and libraries.

This approach is the emerging standard. But it has its pros and cons. Here are some Drupal and Composer "gotchas" to look out for:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows

If you don't use Composer, it's probably a good idea to keep core, contrib, patches and libraries in version control.


The requested page "/mywebsite/?q=admin%2Fcontent%2Fnode&render=overlay" could not be found

The url you have posted translates to

admin/content/node?render=overlay

This is how the overlay works, which displays a regular page, but adds a param to tell drupal it should be rendered as the overlay (no header, footer etc is rendered).

The problem could be that overlay is disabled, or that the url isn't encoded as it should.

If you use clean urls, you shouldn't see the ?q=...


Logging out user by modifying database directly?

You can delete the user's session in the sessions table.


Play Buttons of SoundManager2 are disabled in Ajax o JS

Add below script in Ajax call

<script>
soundManager.reboot();
</script>


How to transfer a panel variant from one site to another?

Yes, Panels and panel variants can be exported using the Features module. If you are using the panel variant as a part of page manager the option to export variant is shown in the features UI under page_manager_handlers.

Check the screenshot below to see how sample variants of the node view (node/%node) page can be exported via features:


This "Variable Translation" module should help you out: http://drupal.org/node/1113374


Hide errors from users but show to admin?

Preface: This answer was first posted as an answer to "How do I suppress a warning or error message for site users?".

Disable Messages module

You could use the Disable Messages module for this. Here is a quote from its project page:

  Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6, Drupal 7 or Drupal 8.

About using regular expressions

If you're using its 'regular expression' feature, you have to make sure that you use a regular expression that "catches" the error message you want to intercept, as explained also in the Community documentation.

Below "Tip: Keep it simple." on that page, there is a great sample, which looks like so:

  Be aware that something that appears very straightforward like:

Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]entity_form_field.inc).

  Has a lot more unseen characters in it than one might expect:

Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]entity_form_field.inc).

  So just wrap the meat of the grep with a simple "any character" regex: ".+" as in:

.+Notice.+Undefined index:.+ctools_entity_form_field_content_type_render.+entity_form_field.inc.+

So the "clue" to come up with a correct message, is to shrink the error message you want to catch, and putting ".+" characters where appropriate.

Talking about shrinking, note that the field_txt_student_id has been omitted in the regular expression also (to make it NOT depend on the field name).

Example

As another example, assume you want to catch this error message:

  PDOException: in dblog_watchdog() (line 160 of /home/dbuser/public_html/yoursitesname.com/modules/dblog/dblog.module).

In this case a possible regular expression should look something like so:

.+PDOException.+in dblog_watchdog().+(line 160 of.+/modules/dblog/dblog.module).+

Note how I intentionally did not include part of the path before /modules/dblog/dblog.module (so that it can be reused in another site where the very same error occurs ...).

Also note that you have to give it some thought to yes or no include the 160 part of it: if the module ever changes a bit so that in the error message it (eg) becomes line 161, your error will not be intercepted anymore. To avoid that, omit the 160 part of it, if that's what you prefer (personally I would rather first see the error coming back then, and then re-adapt my regular expression).

If your regular expression doesn't work at first (= the message still appears), then it might be because there is some typo in the regular expression. To pinpoint such typo, first try with a less restrictive regular expression, even if it was only to try with something like so (to catch ALL messages containing PDOException and dblog_watchdog):

.+PDOException.+dblog_watchdog.+

Or even like so (to catch ALL messages containing PDOException):

.+PDOException.+

These last 2 expressions would probably suppress way too much messages, so you'd want to narrow it down to that single one you're after.

Unstable alternative

There is also the Better Messages module as an alternative. However, for D7 (which is what this question is about), it only has an Alfa version.


selecting hierarchical select values during migration

Dunno why my last message has been deleted but well I founded the answer alone :
In order To make it work, you have to pass an array of values containing the terms tid values and their parent's tid.
You might have to use a callback that retrieve the parent tid from the children one.

I am migrating contents from drupal 6 to 7, not from a csv, but I've declared a static function containing the mapping between the old tids and the new ones like so :

public static $hierarchicalThemesToTheme1TidsMap = array(
  '1'     => array('tid' => '13', 'parent' => '0'),
  '1797'  => array('tid' => '14', 'parent' => '13'),
  '14993' => array('tid' => '15', 'parent' => '13'),
  '1801'  => array('tid' => '16', 'parent' => '13'),
  '59'    => array('tid' => '17', 'parent' => '13'),
  '1795'  => array('tid' => '18', 'parent' => '13'),
  '1796'  => array('tid' => '19', 'parent' => '13'),
  '1798'  => array('tid' => '24', 'parent' => '13'),
  '1799'  => array('tid' => '23', 'parent' => '13'),
  '1811'  => array('tid' => '42', 'parent' => '0'),
  '1812'  => array('tid' => '42', 'parent' => '0'),
  '1813'  => array('tid' => '42', 'parent' => '0'),
  '1800'  => array('tid' => '20', 'parent' => '42'),
  '1802'  => array('tid' => '21', 'parent' => '42'),
  '1803'  => array('tid' => '22', 'parent' => '42'),
  '1804'  => array('tid' => '18', 'parent' => '13'),
  '1805'  => array('tid' => '18', 'parent' => '13'),
  '62'    => array('tid' => '25', 'parent' => '0'),
  '1806'  => array('tid' => '26', 'parent' => '25'),
  '1807'  => array('tid' => '27', 'parent' => '25'),
  '64'    => array('tid' => '28', 'parent' => '25'),
  '1808'  => array('tid' => '29', 'parent' => '25'),
  '1809'  => array('tid' => '30', 'parent' => '25'),
  '61'    => array('tid' => '32', 'parent' => '0'),
  '1723'  => array('tid' => '33', 'parent' => '32'),
  '1724'  => array('tid' => '34', 'parent' => '32'),
  '1725'  => array('tid' => '35', 'parent' => '32'),
  '1726'  => array('tid' => '36', 'parent' => '32'),
  '1727'  => array('tid' => '37', 'parent' => '32'),
  '1728'  => array('tid' => '38', 'parent' => '32'),
  '1729'  => array('tid' => '39', 'parent' => '32'),
  '1730'  => array('tid' => '40', 'parent' => '32'),
  '1731'  => array('tid' => '41', 'parent' => '32'),
  '1810'  => array('tid' => '43', 'parent' => '13'),
  '4401'  => array('tid' => '44', 'parent' => '13'),
);

I had to do that because we didn't use migrate for the taxonomies. I guess there's a better way if you had use migrate to import your taxonomies.

Then I've declared a callback which use that static array to retrieve the tids and their parent tid :

public function getHierarchicalThemeByTids($tids) {
  $mapped_tids = array();

  foreach($tids as $tid) {
    $mapped_tid = FOMigration::getMappedId(self::$hierarchicalThemesToTheme1TidsMap, $tid, NULL);
    if($mapped_tid !== NULL) {
      $mapped_tids[] = $mapped_tid['tid'];
      if (!in_array($mapped_tid['parent'], $mapped_tids)) {
        $mapped_tids[] = $mapped_tid['parent'];
      }
    }
  }
  return $mapped_tids;
}

Finally I just tell migrate he has to use that callback to get the values :

$this->addFieldMapping('field_types', 'field_theme')->callbacks(array($this, 'getHierarchicalThemeByTids'));
$this->addFieldMapping('field_types:source_type')->defaultValue('tid');


How can I modify the arguments passed to a core hook?

Implement hook_module_implements_alter and replace taxonomy_field_formatter_view() to your function.


Programmatically set date fields in Drupal 7: Date, Date (ISO Format) and Date (Unix Timestamp)

Here is a code that treat site timezone right for me:

 $node->field_date[LANGUAGE_NONE][0] = array(
    'value' => format_date(strtotime('now'), 'custom', 'Y-m-d H:i:s', 'UTC'),
    'timezone' => 'UTC',
    'timezone_db' => 'UTC',
  );


You can use the #markup property to display arbitrary data.

The function signature for your drupal_get_form callbacks must be:

function mymodule_proc($form, $form_state) {}

Concerning the response object that you want to render, I would need more information in order to help you.


How to create Scald Atoms media library for each content type?

There are two Views that come with Scald:

scald_library - Which, for our purposes, is what controls the format of the menu in the editor.
scald_atoms - Which controls the format of the Scald Library at /admin/content/atoms.

Both are fully editable views.

For the admin page, clone the View and assign each one a unique filter for Atom:Type and give each View a unique path URL. Add these URLs to an admin menu somewhere to make them findable.

The editing menu is a little more complicated. Cloning and filtering the View is the same, but I believe using them would require adding new functionality to either the editor or Scald. Though people editing content can still filter by type in the Scald search pane.


The directory public://xmlsitemap was not found or is not writable by the server

I found the file_public_path value from the /admin/config/media/file-system page. It was set to sites/default/files, relative to the installation path.

I checked permissions and noticed some writting permissions were missing (the directory was already created). I sudo chmod a+w xmlsitemap/ and that solved the issue.


From the information given, it is impossible to give a full answer.  For instance: Are your site on a dedicated server, or on shared hosting?  What user and group "owns" the files in your Drupal installation?  What is the extension (like .php) of the unwanted files somebody places in the imagecache subfolders?  (Please edit your question and expand it with this information, it will be a great help in order to give a more precise answer.)

However, since most people use shared hosting, I'll assume that you're using that.  You can read about how to set up correct ownership and permissions for in a shared hosting environment in this article: What are the most appropriate users and permission levels for Drupal sites on shared hosting?

However, the permissions you cite, and in particular the fact that 750 "breaks the website" indicate that you must have gotten something (probably the ownership to the files in your Drupal installation) wrong.  750means rwxr-x--- while 755 means rwxr-xr-x.

In a shared environment, the web server will either:

Run as the owner of the site (i.e. you). In this case your files/ folder (upload directory) should have 700 (rwx-----).
Run as a member of the www group. In this case your files/ folder (upload directory) should have 770 (rwxrwx--).

Not under any circumstance do you want the last triplet (permissions for others) to be anything else than zero.

However, unfortunately, wrong file permissions is probably not the only reason your files/ directory has been compromised.  Both 755 and 750 only gives write permission to the owner of the files/ directory.  You haven't told us who that owner is, but its either you or the web server user.

If it is you, then your shell account has been compromised, so look for Trojans with the excecute bit set (and change your shell account password).  If it is the web server user, then you have a cross-scripting attack or a PHP-injection attack, and you need to find and fix that.


Organic Group activity with grouped results

I achieved this by creating two different views and two exposed filters:

Filters
 - Group id
 - Date filter
Views
 - View 1 with content base table
 - View 2 with comments base table

.Then I have used views aggregation to present results


How to get slick slider working well on multi-directional(RTL/LTR) site?

This is possible by implementing template_preprocess_slick

use Drupal\Component\Serialization\Json;

/**
* preprocess variables for slick.html.twig templates.
*/
function template_preprocess_slick(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage();
  if($language->getDirection() == 'rtl') {

    $settings = $variables['content_attributes']->offsetGet('data-slick');
    if(!empty($settings)) {
      $settings = Json::decode($settings->value());
      $settings['rtl'] = true;
      $settings = Json::encode($settings);
      $variables['content_attributes']->setAttribute('data-slick', $settings);
    }
  }
}


Count words of a body field using PHP views field

So, after a long research, I stumbled at this issue post. It seems that field data are not present in the result set of Views PHP, so instead of print $row->bodyI needed to use print $data->_field_data['nid']['entity']->body['nl'][0]['value'] to access the data.  This solved my problem.


When adding Custom Blocks the weight is changed for the rest of the blocks

If you have blocks that have the same weight, that may trigger a bug where your blocks get shifted. At least, this is something I have experienced with views filters in D7, and I found a bug report here regarding a similar weight issue in D8 with taxonomy terms: https://www.drupal.org/node/941266

Ensure you are able to see the numerical weights of the blocks, and make sure they all have distinct weights.


How to hide particular field for specific role?

You can use Field Permissions module.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.

  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


add a search field which search for values of specific field in a content type

You can create a separate Search Page using Views: Here is a tutorial (http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7)

Views:

  You like the default front page view, but you find you want to sort it differently.
  You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain type.
      You like the idea of the 'article' module, but it doesn't display articles the way you like.
      You want a way to display a block with the 5 most recent posts of some particular type.
      You want to provide unread forum posts.
      You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
  Month, YYYY (X) where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts for
  that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


How to alter a link of the language switcher?

To wrap this up, here is the complete solution to this problem.

function mytheme_preprocess_links__language_block(&$variables) {
  $internal_path = $variables['links']['ja']['link']['#url']->getInternalPath();

  // In this case 'node/30074' is the translated node that will normally go to
  if ($internal_path == 'node/30074') {

    // We need to create a new Url object with the node we need to redirect to
    $new_internal_path = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 30073], []);

    // ...and replace the original Url object
    $variables['links']['ja']['link']['#url'] = $new_internal_path;
  }
}

Thanks to Clive for pointing out the process for this problem.


Changing the initial value of an exposed view filter

For some reason a site I was adding a feature to had a years taxonomy vocabulary, with a number of terms, one for each year in a range. So I wanted to auto set the exposed filter to the current year, but to do so needed to set the filter value with the tid of the right term.

I implement hook_views_query_alter().

check if the view is the right name and if the view doesn't have any user selected input (this view only had one filter).

You have to alter the value for the filter's query value

You have to unset the exposed filter area markup and regenerate it.

 function mymodule_views_query_alter(&$view, &$query) {

      if($view->name == 'executive_committee' && empty($view->exposed_input)) {
        $current_year = date('Y');
        // find year term id
        $term_query = new EntityFieldQuery();
        $tids = $term_query->entityCondition('entity_type', 'taxonomy_term')
          ->propertyCondition('name', $current_year)
          ->propertyCondition('vid', 3)
          ->execute();

        if(!empty($tids['taxonomy_term'])) {
          $tids = array_keys($tids['taxonomy_term']);
          $current_year_tid = reset($tids);

          // set values to the views object and query objet
          $view->exposed_data['field_year_tid'] = $current_year_tid;
          unset($view->exposed_widgets);
          $view->exposed_raw_input['field_year_tid'] = $current_year_tid;
          $query->where[1]['conditions'][2]['value'] = $current_year_tid;
          // rebuild the exposed form
          $form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);
          $form['field_year_tid']['#value'] = $current_year_tid;
          $view->exposed_widgets = drupal_render($form);

        }

      }
    }


un-escaped _server variable in settings.php - bad idea right?

D7 ? No need to do this!

First, talking about what you are doing, if it's for a Drupal 7 site, you do not need to do this in the first place.
Read the sites/example.sites.php for multisite settings.

$_SERVER['HTTP_HOST'] is almost safe.

See this great answer about how much secure $_SERVER variables are.

There is no point of sanitizing it either.

From Drupal.org post Writing Secure code,

  Whether you are writing a PHP snippet or an entire module, it is
  important to keep your code secure. Use check functions on output to
  prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into
  HTML.

But you are not outputting anything or populating any variable so you do not need to sanitize any output here.


If the link in your View is something like that node/XXXX I think it not possible, or at least you should modify the node.tpl.php and add a condition inside to show only teaser or full content according the context (from jCarousel or not).

Another solution it's to create another view, that will display only the Tease and point your links (from the view jCarousel) to that view. This view need to show node (tease) and accept an argument (nid).


Prevent Anonymous users info to be displayed in my views

I think that if a user is showing up in your users table (and thus users view), they must have an account on your system, so they would, at a minimum, be an 'Authenticated' user.  But they probably have no other roles other than 'authenticated'.

So try the following to filter them out of your users view:

Add a filter to your users view

Select the 'User: Roles' filter and configure it as the screenshot below:

Let us know if this worked.

p.s. I'm assuming you have Drupal 7 here, since that's what the screenshots are showing -- Views under Drupal 7, but it really helps to tag your question with the version of Drupal you're running.


Create menu link for authenticated user programatically

Given that you are simply moving a link of an existing route in a drupal menu, you are probably better off using the more simple hook_menu_links_discovered_alter(). A custom link/route is probably a bit of overkill.

But, presuming you do want to go the way you are in your example, you would need to have both a my_module.routing.yml and my_module.links.menu.yml

In the menu links file you might have something like:

my_module.hello_admin_user:
  title: 'Hello Admin User'
  description: 'See a Hello Admin User Message'
  parent: system.admin_config_development
  route_name: my_module.hello_user
  weight: 100

and in the routing file you might have:

my_module.hello_user:
  path: '/hello-user'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::helloUser'
    _title_callback: 'Hello Admin User'
  requirements:
    _permission: 'access content'
    _role: 'authenticated'
  options:
    _admin_route: TRUE

You've got a bit of a mix going in your example. Note that route names and links names need to be unique across the drupal system. Using your module name as the start is a convention but not required.


Search API Views only displaying one result

Try to remove this from your url

&group=true&group.main=true&group.field=ss_field_source_url


Webform Import

  Allows delimited data files to be imported as submission (results)
  into webforms.

  This is useful for importing submissions from other systems in to
  Webform. Can also be used to Edit submissions via Export / Import as
  long as the CSV has the SID column filled.

Webform Share

  This is a helper module to prepopulate newly created webforms and to
  export / import webforms between sites.

I think Webform Share module definitely solve your issue.


You can download it from the "View all releases" link (near the bottom of the module's project page). That page contains a link to scrollable 6.x-1.x-dev.


You can do this very simple way using hook_form_FORM_ID_alter.

Paste following code in your themename.theme file and clear the cache

function YourThemeName_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
    $form['newline'] = array(
      '#type' => 'markup',
      '#markup' => t('
Enter your login information here!
'),
      '#weight' => -10,
    );
}

Image output:

Before:

After:

This way you do not need to worry about anything, it will only show in Login page.


Is block weight ignored when setting content in hook_block_list_alter()?

Symptoms: When the block is not loaded from cache, but from the database, the ordering works fine. When loading from cache, the weight is ignored.

Diagnosis: The block module uses SQL to order the blocks:

function _block_load_blocks() {
  global $theme_key;

  $query = db_select('block', 'b');
  $result = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute();

// ...

After that, it ignores the weight value, and relies on the order of php array keys (order in which foreach iterates) when rendering:

function _block_get_renderable_array($list = array()) {
  $weight = 0;
  $build = array();
  foreach ($list as $key => $block) {
    $build[$key] = $block->content;
    unset($block->content);

// ...

    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight, // HERE LIES THE MADNESS!
    );
    $build[$key]['#theme_wrappers'][] ='block';
  }
  $build['#sorted'] = TRUE;
  return $build;
}

Strategy: Either hack the blocks module (DON'T) or find a workaround. I looked through the block.module and found (using lots of dpm()) where the order of array keys are being reversed:

function _block_render_blocks($region_blocks) {

// ...

  foreach ($region_blocks as $key => $block) {
    // Render the block content if it has not been created already.
    if (!isset($block->content)) {
      // Erase the block from the static array - we'll put it back if it has
      // content.
      unset($region_blocks[$key]); // THIS IS WHY THE ORDER OF KEYS CHANGE

// ...

      if (isset($block->content) && $block->content) {

// ...

        $region_blocks["{$block->module}_{$block->delta}"] = $block; // THIS IS WHY THE ORDER OF KEYS CHANGE
      }
    }
  }

  return $region_blocks;
}

Workaround: Manually sort the render array in a hook_page_alter(&$page) implementation.

function mymodule_page_alter(&$page) {
  if (!empty($page['sidebar_first']['my_block_1'])) {
    $page['sidebar_first']['my_block_1']['#weight'] = -1; // move it to the top
    $page['sidebar_first']['#sorted'] = FALSE; // indicate that it still needs to be sorted before rendering
  }
}

I only have two blocks in sidebar_first, of which the bottom one is cached. So I only need to lift the other block ('my_block1') above the cached block. A more sophisticated approach will be to query the weights from the block table again.

I'm not sure whether I should consider this to be a bug in the block module. It is a shortcoming, but it's only exposed because of my custom caching hack.


Core update installs 8.6.0-beta1 instead of 8.5.6

Solution for me was start from 8.5.0, upgrade to 8.5.5 then run:

composer update drupal/core symfony/* --with-dependencies

I'm now on 8.6.0 ! :)


Drupal 8 settings.yml file doesn't reflect changes

yml files are just imported on module install time.

If you need runtime changes, during development, have a look at
https://www.drupal.org/project/config_devel


I have 3 suggestions:

Might just be a typo on your behalf but the tpl file should be ds-1col--node-article-cartoline.tpl.php rather than ds-1col--node-article-immagini.tpl.php
Could it be that because you've specified ds_1col it's being affected by display suite's naming convention, try using your theme name instead.
There is some sort of inheritance that can be hard to spot, for example to override node--article.tpl.php you need node.tpl.php present in your theme


Programmatically change import URL of reference node

Answering my own question, it's basically the same. The $source object is the node itself, so in my module I called a hook like this:

function MYMODULE_feeds_after_import(FeedsSource $source) {

    //Get the config
    $config = $source->getConfig();

    //Save the current URL
    $url = $config['FeedsHTTPFetcher']['source'];

    //Run a basic check
    if(strstr($url, 'since')){

        //Do some fancy stuff with it and create a new one

        $newurl = 'http://foo';

        //Save the new configuration in the source node
        $config['FeedsHTTPFetcher']['source'] = $newurl;
        $source->setConfig($config);
        $source->save();
    }

}


How can I disable the "Text format" pull-down for users that are creating or editing content?

The absolute easiest way would be to hide the selection using CSS.

I only say this because there's nothing "bad" that can happen if someone does use the plain text format.

Otherwise you're looking at assigning custom permissions and probably using hook_form_alter()  which just seems like it's more trouble than it's worth!

.filter-wrapper { display: none; }


How do I override a taxonomy/term/% list with a view?

All of these answers are great solutions, and thanks for taking the time to provide such infomative answers.  Ashlar, your response taught me a lot about how taxonomy works works as well as the relationship between views and taxonomy.

I found a solution that works great for my situation, and I will share that in case it may help you guys too.

As I explained above, the my problem was that my view, with no argument, supplied the results I wanted, but the default taxonomy view with an argument, which was not what I wanted.

To solve this, I installed the module Taxonomy Display http://drupal.org/project/taxonomy_display.  I then reconfigured each view to have Taxonomy Term ID as an argument.

Taxonomy display lets you associate a vocabulary with a particular view. Now, when I click on vehicles/trucks, which is an alias for taxonomy/term/3, the view takes over and this is actually rendered correctly maintaining the integrity of the field structure.

If anyone wants to know more details about the configuration please let me know.


How do I handle an incoming POST request in a module?

If posting to external URLs is allowed, and given that you are not familiar with Drupal, you can post that data to an external URL where you can write a script using the language / framework you are familiar with and process the data. Especially since you are only looking to process the data with R.

If you want to manage your processing within Drupal itself that is also doable. You will have to write a custom controller in your module, add the route in the module.routing.yml file and then handle the POST data in your controller.

Here are couple of places you can start

https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

How to get $_POST and $_GET parameters


The simple answer is that hook_user is for Drupal 6 and hook_user_insert is for Drupal 7.

Most (all?) of the API functions in Drupal 6 and earlier that accepted an $op parameter got split out into individual functions in Drupal 7.  This happened with hook_block, hook_nodeapi, and some others.

For Drupal 7, the full set of user hooks is described at user.api.php.


You can do that by implementing hook_node_presave in your custom module, by something like:

function MODULE_node_presave($node) {
  $recent_copy = array_shift(array_values((node_revision_list($node))));
  drupal_set_message('User id of the user who edited latest is '.var_export($recent_copy->uid, TRUE));
  drupal_set_message('Username of the user who edited latest is '.var_export($recent_copy->name, TRUE));
}

You can find a detailed solution see: Get the edited node details without enabling node revision in Drupal.


Drupal template files are not recognized

By default, the template file is expected to be in the same directory containing the module or the theme which defines the theme function. To use a different path, in the hook_theme() implementation you need to use the path property, which is defined as:

  path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

So, in your case the code should be similar to the following one, since you are using a theme.

function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('theme', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}

For a module, the code would not be much different.

function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('module', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}


Render a node field inside page.html.twig

After doing quite a bit more research, I was able to find enough pieces in other questions and on drupal.org to achieve what I wanted to do.

No pre-processing is needed for this answer, so no code needs to be added to your mytheme.theme file.
All of these variables are already accessible in page.html.twig by default.

To render a field's default value inside page.html.twig, you would typically use a Twig variable as in {{ node.field_some_name.value }}.

If you have an image field, and want to render the URL to the image stored in that field inside the page.html.twig template, you would use {{ file_url(node.field_some_image.entity.fileuri) }}.

Finally, if you want to render the title of a node inside the page.html.twig template, you would use {{ node.label }}.

I also learned how to use some Twig conditionals for my particular issue, but that is beyond the scope of this question/answer.


Only Show Nodes From Child Terms (-1 excluding parent)

You could add an Node Nid as argument and check "Exclude the argument"

Select "Provide default argument" and select "Taxonomy Term ID from URL"

And then check "Load default argument from term page"

Thank should work for you.

Let me know if that helps.


Your host cannot reach smtp.gmail.com on port 465. It sounds like a network connectivity problem, not a Drupal problem. Run the command nc -zv smtp.gmail.com 465 to confirm.

You may need to talk your hosting provider if they have restrictions in place. My guess, if they are blocking it, is they are blocking SMTP access to GMail to prevent spam.


How to override markup in my .theme file?

I am afraid there is no way to fix this markup in theme file. In case you simply need to change spelling I suggest using string overrides as it is described in settings.php file.

$settings['locale_custom_strings_en'][''] = [
  'Search results' => 'New text',
];


How to restore a site from a backup done with Backup and Migrate module using Drush

Yes, you can restore your backup with Drush.

Here are Backup and Migrate commands for Drush explained: http://www.only10types.com/2011/03/drush-backup-and-migrate-command.html

I think drush bam-restore command is what you are looking for.

  bam-restore Restore the site's database with Backup and Migrate.

  Examples: drush bam-restore db manual
  "LCC-31.03.2011-14.01.59.mysql.gz" - restore the default database
  using the given dump file, which can be found in the destination
  called "manual"

  Arguments: source - Required. The id of the source (usually a
  database) to restore the backup to. Use 'drush bam-sources' to get a
  list of sources. Defaults to 'db' destination - Required. The id of
  destination to send the backup file to. Use 'drush bam-destinations'
  to get a list of destinations. Defaults to 'manual' backup id -
  Required. The id of a backup file restore. Use 'drush bam-backups' to
  get a list of available backup files.


How to display IMCE file browser in overlay or popup window?

Using the Media module instead of IMCE provides a powerful popup media asset browser that integrates with WYSIWYG.


Trying to change a radio value during form validate

Did a little more digging. It seems when Drupal (re)builds a form, it sets the element values based on the actual form input ($form_state['input']) and not the form values ($form_state['values']). See _form_builder_handle_input_element. So form_set_value does changes the form value, but it does not update the form input and, therefore, does not get processed how you want it to in this case. While I don't know if this is the "proper" way to do this, but in your form function, you can try throwing in something like:

if (!empty($form_state['values']['myelement']) {
  $form_state['input']['myelement'] = $form_state['values']['myelement'];
}

I tried this with a textfield element, and the value I set using form_set_value was displayed in the textfield when the form was rendered.


How to make a rule select all users of a role?

It appears to me that there is a straight forward solution to have your rule process all those users of a certain role (as in your question): you could an approach to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users that you want to be processed (= those users of a certain role).
add a loop to perform a Rules Action, probably similar to the rule you already have in place, for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Displaying URL taxonomy term as page title

Taxonomy Title is the only module that let's you control that title individually for every term. (You can also override the title generally by using a view or a pannel.) An additional "Taxonomy Term Page - heading" field wil appear on the taxonomy term edit form, allowing administrators to configure a specific heading for each term page.

  The taxonomy title module also provides tokens which can be used in
  conjunction with the Page title and Meta tags modules.

  This module was designed to update the heading tag at the top of the
  taxonomy term page. The contents of this H1 (or sometimes H2) tag are
  extremely important for SEO (Search Engine Optimization). People interested in SEO may prefer to add more user-friendly, keyword-rich,
  and descriptive words to this heading element.


List members visable in any organic group

Go to OG Members > EDIT > CONTEXTUAL FILTERS > PROVIDE DEFAULT VALUES > CURRENT OG GROUP FROM CONTEXT ....i assumed u have the OG MEMBERS which is a default view created after installation of the latest module.


one possible answer is to add views php module add php code in for titles and then for body.


How to get a fixed picture in the field without affect by responsive effect?

Tables are by definition "responsive" (quotes intended), meaning they will give more space to the more "filled" cell. You need to tell the browser to reserve a certain amount of space for the cell with the following css:

.views-field-uc-product-image {
  min-width: 110px;
  max-width: 110px;
}

The extra 10 pixels are to account for the padding around the image. The max-width: 110px is added to ensure the cell will also not take more space then needed.


In Drupal Commerce products are entities, not nodes. If you're looking for a product's SKU to be automatically set to the created product's id, there's the Commerce AutoSKU module which allows you to use tokens (e.g. [product:product-id]) to automatically create SKUs.

One caveat from the project however:

  If you decide to use the [product:product-id] token, you should be
  aware that this will cause any new products to be saved twice. This
  shouldn't be an issue for most people, but if you have rules in place
  for when a product is saved, you may not want to use this token.


Are you really sure you need a relationship handler for this?

In general the default relationship handler is already quite flexible because it uses the default join class which is really powerful.

There are some use cases for relationship handlers, for example the relation module, but this module does some vodoo stuff.

So back to the problem. It might be enought if you define 'relationship' with the right field and base field.

PS: There is a big reason why there is no documentation about api=3 because the difference to api=2 isn't big at all.

Here is an example how to define a relationship.

  $data['node_revision']['vid'] = array(
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'base' => 'node',
      'base field' => 'nid',
      'title' => t('Content'),
      'label' => t('Get the actual content from a content revision.'),
    ),
  );


In Drupal 8, you first need to define assets in a library in your theme or module: https://www.drupal.org/developing/api/8/assets

and then you can attach that library to your form like this:

$form['#attached']['library'][] = 'mymodule/mylibrary';


How to view blocks with Text Overlay on hover?

Your question appears to be a variation of Create a simple Text over Image Overlay on Hover with Drupal 7 and Views. If you also install/enable the Link module, the node title shown over the image can be a hyperlink to the node also.

Especially this part in it seems to be what you're looking for (be it with some minor variations):

  Create a view 'Overlay'. Create a page which shows content of type 'overlay-image'. It shows an unformatted list of fields. Save and edit. On the edit page, add the fields 'Content: Image' and 'Content: Link' to the fields and exclude them from display.  For the last field add 'Global: custom text'. In the text field, write:

[field_image][field_link]

Curious to hear if this somehow will help ...


How do I set up the Crumbs trail For Commerce Kickstart Checkout?

You will have more luck with Crumbs 7.x-2.*.

See also

Use Crumbs 7.x-2.*, or tell people how to upgrade. (Kickstart queue)
Commerce Kickstart Checkout Use Case (Crumbs queue)


How to apply single theme to all webform in drupal 7

Easiest way would be using a module like Display Suite to change the page layout of your webforms on it's 'Manage Display' settings. Using a two column layout, you can arrange the content on the left side and webform on the right (webform being all fields you create on the webform part of the node).

If you don't want to use a module just for that, another option would be rewriting the webform node template yourself. For that, copy your theme's node.tpl.php and rename it as node--webform.tpl.php. Note that you would have to print out the correct variables on the markup yourself.


Easy steps for adding the imported content on one single page for display

You can use Views module to do it. Follow these steps, to set a page listing all articles--

Download views & keep it in sites/all/modules folder.
Enable Views & Views UI from your module list.
Under Structure click View & Add a new View.
Select Content under show & Article of type.
Give a name to it & check Create a page.
Save & continue.
Give a path to the created view page.
Now you can access your path like $basth_url/(your given path).

Thats it.


How to use wysiwyg text editor (text_format) in a system configuration form

$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
];

And if you want to limit the wysiwyg editor to only the one format, add #allowed_formats as in:

$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
  '#allowed_formats' => [
    $config->get('distance_selling_terms.format') => 'Description of format'
  ],
];


where does $data come from in hook_tokens?

The $data is whatever is originally passed to the token_replace function by the process that's doing the token replacement.

The var itself is:

  An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

It's essentially just an array that's used to pass extra context to the token replacement, and it can contain anything at all.

For example if you were writing a module that introduced a custom entity type, you could use this feature to pass an instance of that type in to be used in your own tokens.

In your specific case, it's presumably the Webform module that prepares that data array, so that would be where to look if something's missing. Or it could be a submodule if that's what you've used to provide the payment fields themselves.


I don't think you'll find that particular condition out of the box. Conditions for rules are pretty easy to write though, check Commerce Conditions for some easy to follow examples.


How to make the Edit User Profile to have all tabs in one page?

The One page profile module should do this if you're using the core Profile module.


Where are admin/config/user-interface/archive setting stored

Generally, configurations in administrative pages are saved into variable table.

The path admin/config/user-interface/archive is not a Drupal core path. It must have been provided by a module. If you want to get a definitive answer, you should provide more information.


How can I enable the Front Page on minimal profile?

I got it. So, to document the solution:

Enable Views and Views UI modules
Either set the Front Page to the now-available frontpage for the traditional recent posts page

Another way (which was more suited to my intents) is to create a new content type (e.g. Static Page), create a new node of that type and set the site frontpage to that. This is useful when you are developing a theme with a custom frontpage template featuring several regions to be filled with different views.


This is not really related to Drupal since you are not using the Drupal Memcache module API.

But based on your example. Here is my test code.

  // Creating an object of Memcache
  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  // Adding a key.
  $cacheKey = 'mobile';
  // Delete old cache.
  $cache ->delete($cacheKey);
  // Create a temp json data.
  $jsonData = "{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";
  // Set the cache.
  $cache ->set($cacheKey, serialize($jsonData));
  // Fetch the cache.
  $Records = $cache->get($cacheKey);

  // Dump the cache.
  echo '<pre>';
  print_r($Records);
  echo '</pre>';

and here is the result

s:881:"{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";

with $Records = unserialize($cache->get($cacheKey)); here is the result.

{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }

The only reason why you are not able to see the result is because of this.

print_r(Records);

which is it should be

print_r($Records);

Record is a variable and therefore it must have a dollar sign before it.

Test your connection to Memcache

  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  $stats = @$cache->getExtendedStats();
  $available = (bool) $stats["localhost:11211"];
  var_dump($available);

If the result is true then you are connected to Memcache if false then you are not connected.

UPDATE 1:

I tested with your json.

  $arr = array(
    "nid" => "213",
    "public_url" => "http:\/\/www.mywebsite.com",
    "HTMLStr" => "layout and user interface.\ r\ n\ t http: \ /\/mywebsite.com<\/a><\/p>\r\n",
  );
  $jsonData = json_encode($arr, JSON_HEX_QUOT | JSON_HEX_APOS);

and here is the result

s:157:"{"nid":"213","public_url":"http:\\\/\\\/www.mywebsite.com","HTMLStr":"layout and user interface.\\ r\\ n\\ t http: \\ \/\\\/mywebsite.com<\\\/a><\\\/p>\r\n"}";


Send Mail After Checking Date Field Value

Yes you could do this through rules granted the product expiration date is a field.

Create a new rule to run on cron maintenance tasks
Condition--> has field name
Pick your field name
Action--> execute custom PHP.

I don't know what your level of PHP experience is so I'll hold off on putting any code down, but the next step would be to write a short snippet of PHP that takes the sites current datetime and checks the values of your chosen field for values that are 7 days away from expiration (rules should give you tokens for both items).

Then in that same custom PHP area use rules_action_mail() to send the email out with the results (for reference: https://drupal.org/node/322834).

You could also do this with a SQL query in the PHP area: http://www.barnettech.com/content/dbquery-drupal-creating-sql-queries-drupal-way . Just run through your field in the database and check for the values you need, then return the results in the mail message.

If I were to do something like this, I would implement hook_cron() in a custom module: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_cron/7 vs. using Rules since it would require less steps.

Edit: As requested:

See here to make a Drupal 7 module: https://drupal.org/node/1074360

Using hook_cron would go something like:

function mymodule_cron(){
 myfunctions();
}

function myfunctions(){
//do cool stuff
}

As far as what would go into "myfunctions", it would probably be a query on the database, returning those results, then sending those results in an email with mail(). That would be it.


Add this rewrite rule in your .htaccess file:

RewriteEngine On
RewriteRule ^/subfolder/(.*)$ http://www.example.com/$1 [L,R=301]

Change subfolder and www.example.com.

Also, you can try with this:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule !^subfolder/ /subfolder%{REQUEST_URI}  [L]

Again change you domain and subfolder name.


Advice for reference the same image for several nodes?

In my case the easiest was to do the following steps:

In content/media add the picture.
In your content type create a field type File. Save your content type.
When you add your new content, in your new field, use select media and choose the file that just upload it.

Note: If you delete the new content and there is no other content that reference that picture or file, the file will be deleted and you need to upload it again.

I created my content by using web services. So, I needed to do this programatically. The only I needed was the fid.

In my case I need to use services to create the content type, after testing you need the following and to tell if it should be displayed or not. This is the code in case anyone feels it is useful.

$node->field_file_name_field ['und'][0]['fid']='fid number';
$node->field_file_name_field['und'][0]['display']='1';

If you feel there is a better way or another way to do this. It be great to hear it.


user deletion : user_cancel_reassign not working when user has more than 10 associated contents

user_cancel() is run in a batch. This means that either it's called in a form, or batch_process() needs to be called after it. For example, this is the code used from UserController::confirmCancel().
$edit = [
  'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
];
user_cancel($edit, $user->id(), $account_data['cancel_method']);

// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually and should redirect to the front page
// after completion.
return batch_process('<front>');

It's not necessary to delete the account, as that is already done from _user_cancel(), the batch operation callback used from user_cancel().
case 'user_cancel_reassign':
case 'user_cancel_delete':
  // Send account canceled notification if option was checked.
  if (!empty($edit['user_cancel_notify'])) {
    _user_mail_notify('status_canceled', $account);
  }
  $account->delete();
  // …

It's also probable that hook_preprocess_page() is the wrong place to call user_cancel() as it would be called when the page is being rendered, while the batch operations require to redirect users. See batch_process(), which contains the following code.
if (($function = $batch['redirect_callback']) && function_exists($function)) {
  $function($batch_url->toString(), [
    'query' => $query_options,
  ]);
}
else {
  return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
}


How to migrate from DotnetNuke to Drupal?

There is a very good module to assist migration from other CMSs to Drupal called the Migrate module.

  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, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

Link : Documentation.


How to increase book weight range for a same-level chapters

I was surprised to hear that the weight range numbers are limited, I expected to get a number input field (so I could enter any number value) but instead, the weight choice widget is a select options type, and for the Book module weights it really is limited to values between -15 and 15, and it still is in Drupal 8!
This is an important accessibility issue, but it doesn't seem so easy to fix once you dig into it. This was on the radar for a long time: Reordering fails with more than 31 book pages in a book that turned to Add a scalable weight select element which circled back to Improve #weight select element behavior based on the number of items and finally in D8 Books: Better Sorting. Maybe you can test that patch and help get it implemented in D8? There is an Accessibility Group you can join and advocate for better weights handling without javascript.
In the meantime, there is a number of modules you can use to reorder book pages a different way.
Book helper seems to be the best to try out first.
There's also a comparison page: Comparison of Node/Entity Ordering Modules


How do I wrap two render array elements in a div?

You can also use the #container form element, and code similar to the following one:

$wrapper = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('class-name'),
  ),
);

$wrapper['twitter-icon'] => array(
  '#type' => 'markup',
  '#markup' => '

'
);

$wrapper['twitter-link'] => array(
  '#type' => 'markup',
  '#markup' => l(t('follow us on Twitter'), 'https://twitter.com/#!/zujava'),
);

The #container element wraps its children elements with a
 tag, whose CSS class is the one passed in the #attributes property.

You could even use a container for the "twitter-icon" element, but that doesn't give you any pro, except in the case you could possibly add an element to that, as with the following code:

$wrapper = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('class-name'),
  ),
);

$wrapper['twitter-icon'] => array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('twitter-icon'),
  ),
);

if ($condition) {
  $wrapper['twitter-icon']['twitter-icon-text'] => array(
    '#type' => 'markup',
    '#markup' => t('Icon text'),
  );
}

$wrapper['twitter-link'] => array(
  '#type' => 'markup',
  '#markup' => l(t('follow us on Twitter'), 'https://twitter.com/#!/zujava'),
);


Passing data from outer preprocess to inner template

Done this a couple times, but really got the caching better last time so that it works perfectly... I've put in some fairly verbose comments, but if anything is unclear just shout.

/**
 * Implements HOOK_preprocess_paragraph().
 */
function HOOK_preprocess_paragraph(array &$vars) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $vars['paragraph'];
  // Change 'content_reference' to be your paragraph bundle's machine name.
  if ($paragraph->bundle() === 'content_reference') {
    // Instead of 10 set that to be the max number of references in the field.
    foreach (range(0, 10) as $i) {
      // Change all references to 'field_content_reference' to use your field's
      // machine name.
      if (!isset($vars["content"]["field_content_reference"][$i])) {
        break;
      }
      /** @var \Drupal\node\Entity\Node $node */
      $node = $vars["content"]["field_content_reference"][$i]["#node"];

      // Example change to the Node.
      $node->field_parent_paragraph = $paragraph;
      $changed = TRUE;

      if (isset($changed)) {
        // If we've changed the node, give a new cache id.
        // THIS IS IMPORTANT!
        $vars["content"]["field_content_reference"][$i]['#cache']['tags'][] = "paragraph:{$paragraph->id()}";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = "paragraph";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = $paragraph->id();
      }
    }
  }
}

Follow that up with something like:

/**
 * Implements HOOK_preprocess_node().
 */
function HOOK_preprocess_node(array &$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $vars['node'];
  if (isset($node->field_parent_paragraph)) {
    $paragraph = $node->field_parent_paragraph;
    $vars['content']['#attributes']['class'][] = $paragraph->field_settings_1->value;
  }
}


How to login by single role if user have multiple roles?

Create a custom module
Create a custom form where Admin can whitelist users for certain roles .. Form should have  username and roles as a list or checkboxes.
Store these settings in database - uid - roles
When a user logs in redirect user to a form where he can select user roles from above list
On Form Submit, Update user programatically and assign role to the user he selected, remove other roles that user has if any


Using D7 OG I want to force (auto) join - any ideas?

I'm going to assume that you are using the 7.x-1.x branch of Organic groups. I believe there are some major changes in the 2.x branch - so this solution may/may not work with that.

// Assuming your group is of the entity type "node"
// and the name of your bundle is "group". A node bundle
// is the unique name of the content type which is a group
// type as well.
// Say $follower is the follower user entity and
//     $followee is the followee user entity
$opts = array(
  ':uid' => $follower->uid
  ':type' => 'group'
);
$gnid = db_query('SELECT nid FROM {node} WHERE type=:type AND uid=:uid', $opts)->fetchField();
if ($gnid) {
  $group = og_get_group('node', $gnid);
  og_group($group->gid, array(
    'entity type' => 'user',
    'entity' => $followee,
    'state' => OG_STATE_ACTIVE
  ));
}
else {
  watchdog('my_mod', 'Follower (uid=!uid) does not have a member group', array(':uid' => $follower->uid), WATCHDOG_ERROR);
}

Still, own (group manager) and is admin of are two different things, at least in OG parlance. Because a user may have the "administrator user" role in many groups. If you mean is admin of, the lookup of the node table above may have to be changed by doing a join with {og} and {og_users_roles}.


Is it possible to record user agent information on node creation?

I would probably use a combination of hook_node_insert and watchdog (to keep UA info off of nodes and because it is really a logging exercise).

Example (this is totally untested and off the top of my head):

function MYMODULE_node_insert($node){
  if ($node->type == 'MY_NODE_TYPE') {
    // Check for the empty value however you want here.
    // e.g. Field API, EntityMetaDataWrapper, or whatever
    if (!isset($node->field_MY_IMAGE_FIELD[$node->language][0])) {
      $user_agent = $_SERVER['HTTP_USER_AGENT'];
      $account = $_GLOBALS['user'];
      $message = t('Empty image field created by !uid using !user_agent',
        array('!uid' => $account->uid, '!user_agent' => $user_agent));
      watchdog('MYMODULE', $message, WATCHDOG_NORMAL);
    }
  }
}


How do I use $form_state['storage']['my_key']?

The example in the documentation link seemed to cause confusion.  Simply set your values in an associative array and use set/get storage.

$vals = [
  'name' => 'bob',
  'age' => 50
];

// save the data.
$form_state->setStorage($vals);

// retrieve the data
$vals = $form_state->getStorage();
$str = $vals['name'] . ' is ' . $vals['age'] . ' years old.';

https://www.cyberdev.co/how-to-store-temp-form-state-data


Did you add the disqusapi library to /sites/all/libraries (or a similar location)? This happened to my site. Our Disqus comment block stopped loading on existing nodes, and I could not turn on Disqus comments for new nodes.

Then I noticed the message in the Disqus config (/admin/config/services/disqus) that I needed to have the Libraries module installed and api files.

Once I added those files, the Disqus block loaded again.


Calendar View of Events shows 1st of month in header

Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date_views/theme/theme.inc and go find line 165.

Change these two lines:

$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

To these two lines:

$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.


Adding multiple HTML pages as nodes as part of workflow

Tahnoon,
This is a very unusual task you are trying to perform. Typically we use Drupal to generate new content and manage how that content is displayed. As you have experienced, there are a couple mechanisms in place to import data from databases, spreadsheets, CSVs etc, but not an easy way to import existing HTML files from a specific directory.

What you are trying to do CAN be done but it will take a certain amount of PHP coding [not a whole lot] to write a custom module that would do this.

Since your request is not a common case, you will not find a tutorial for it that exactly meets your needs. Rather, you will have to learn PHP and Drupal Module development techniques and write code to find that directory, parse through each file in it, extract out all of the markup between  and  and place it in the body field, change the filter to FULL HTML, take the file name and use it for the TITLE.

I can't possibly use StackExchange to teach you all of this, so I'll just get you started.
1] get friendly with http://api.drupal.org this is where we store all of the documentation on the Drupal API
2] specifically look up the hook_menu implementation and create a page where your custom code will fire [for this purpose you're going to hardcode the directory rather than build a user-interface that asks for it.]
3] study up on the family of Drupal file functions. I don't think you'll need any generic PHP file functions, but it could happen.
4] download and install and enable the Examples for Developers module  There is one example in there that is FILE related and it saved me A LOT of work last month.
5] You also need to look at the Google results on how to programmatically create nodes http://goo.gl/A3hUP4 there are a few ways to do this.

Those 5 steps should get you where you want to be. Since you're somewhat new to PHP and Drupal this may take a long time, but it will be a tremendously great opportunity to learn!

If you can afford it, you may want to pay someone to build this OR to help you build it so that you learn in the process.

I hope you find this helpful! :-)


How can I alter the form to add a new validation handler?

The form ID for an entity is a string that is usually returned from EntityForm::getFormId(), if the class used for the form doesn't override that method.
This means that, by default, the form ID follows the <entity>_<bundle>_<operation>_form schema, where the <operation> part is omitted, when operation is default.
Since the Media module doesn't have a class that overrides EntityForm::getFormId(), the correct ID for the form that creates a new Media entity whose bundle is permissions_json is media_permissions_json_add. This means that a module whose machine name is gp_mcs can alter that form by implementing hook_form_FORM_ID_alter() with a function named gp_mcs_form_media_permissions_json_add_alter. (Note that the form ID is between form and alter.)


How to change the 'Name' label on term add/edit pages programmatically?

If you mean you want to change the title of the form element, then it is basically the same as it was in 7.x.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'taxonomy_MYVOCABULARY_form') {
    $form['foo']['#title'] = t('New Title');
  }
}

Adding in what 4k4 said... field widgets behave differently than general form items:

$form['name']['widget'][0]['value']['#title'] = 'New Title';


Run below query on your database and see last column in the result table.

SHOW TABLE STATUS

See Screenshot below for example.


How to use different domains for multilingual sites and keep users logged in?

A cookie can only be read from the same domain that set it. This is a fundamental security feature in browsers to prevent other sites from potentially stealing login sessions, and there is nothing simple you can do about it.

With that said, the comment in the settings.php file seems to contradict my statement, and I'm honestly not really sure how to intrepret that. Perhaps it's only meant to be relevant to sub-domains, which are allowed to share cookies, but if so the comment should probably be re-phrased.

There are a number of ways to work around this, where the easiest is to use language prefix sub-domains instead of separate domains.

Baring that, I believe the "best" one is to use a Single sign-on system. There's a comparision of different SSO modules here. This could be a Drupal based solution, which is the way that is most likely to "nicely" integrate with your current Drupal sites, but that's not really necessary.

The Bakery module which is used by *.drupal.org itself is relevant to mention, as well as this related DA answer How drupal.org single sign on works

More info about cross-domain cookies in a Stack overflow question.


Add jQuery to exposed filter form on drupal 7

Do like this:

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'FORM-ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/js/SCRIPT.js' => array(
        'type' => 'file',
        'group' => JS_LIBRARY, // or JS_DEFAULT, JS_THEME.. read this -  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
      ),
    );
  }
}


How can I translate this domain model into the desired front page

Your best bet is probably Views. It can be set up to do exactly what you want. There are hundreds if not thousands of tutorials on how to use it.


I understand that this is an old question / thread, but just want to post something that worked for me for future reference. Your mileage may vary.

Take a backup of the 'node_field_data' table.
Search and delete 'orphaned' rows on node_field_data by comparing against the nids on the 'node' table.


How can I find out what's denying permission to access a path?

Users should always be able to edit their own profile. The access callback used for "user/%user_category/edit" is user_edit_access(), which contains the following code:

return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;

When the currently logged-in user tries to edit his/her account, the function returns TRUE, which means s/he has access to the edit form.

There could be a third-party module that altesr the access callback for that menu item, and which is using code that doesn't allow the currently logged-in user to edit his/her own account, or that doesn't consider such a case.


What I would is to use another field (assuming that the chapter names are unique) to identify which chapter it is a part of and do a secondary grouping with the field in views.


Trigger views exposed filter on custom select box

I managed to achieve that result I had thought of. Adding same filter in hidden display and just assign new values to it when the fake select box changed; then trigger the apply button.
I had little problems with 'all' value because I was parsing the selected values before reassign them.


how to detect current language to show the other(s) in the menu

Use the global variable $language

https://api.drupal.org/api/drupal/developer%21globals.php/global/language/7


Let users assign particular roles to other users

I hope Role Delegation module solves your problem !

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role


I've definitely run into problems with this before and it's pretty annoying..

One possible way out of it is to create an extra role with the required permission and in rules, add it, force save user, do stuff, remove role.


Highlight autocomplete suggestions Drupal 7

Try Autocomplete Deluxe Module. May b this help you


Just a regular space seems to be working for me.  Add the following to the end of your search URL: "&solrsort=ds_created desc".

Just to be sure though, you can always go to the following reports page, to make sure the ds_created field has been indexed.  You can see all the fields apachesolr has in its index there: /admin/reports/apachesolr

Let me know if that helps!

============== EDIT ===================

Another option I've used is to create a small module that modifies my solr query and/or solr results... I actually set my default sorting in that module.  Here's a snippet of my code:

function YOURMODULE_apachesolr_query_alter(&$query) {
  //Set the sort default options.  These are different options.  Just choose one!
  $query->setSolrsort('sort_label', 'asc');  // by title
  $query->setSolrsort('ds_created', 'desc');  // by created date
  $query->setSolrsort('score', 'desc');     // by best match
}

:-)  Hope that helps, since the above wasn't quite what you needed...


$_GET['keys'] should give you the term value.


Do views filter plugins not apply to base field definitions?

Looks like this is a known major issue. Here's the main "parent" issue where most of the work is going down: https://www.drupal.org/node/2337515

I think, by default, there is some basic views integration for all entities, but it's not that robust.

As a workaround, I was able to implement hook_views_data_alter to tell views to use the 'datetime' filter plugin instead of the default 'string' plugin it had.

function MY_MODULE_views_data_alter(array &$data) {
  $data['my_entity_type']['start_date']['filter']['id'] = 'datetime';
}


Make Backup & Migrate backups smaller in size

Backup & Migrate module by default backs up all the data that is in your database. That includes cache_%, watchdog, and other tables data that is not essential for a backup. By excluding data that lives in those tables from your backup (Advanced Backup settings) you can save a great deal of MB.
Read more about tables recommended for exclusion here -Backup and Migrate exclusion recommendations?.


Within bootstrap theme, print radio item with label and input as siblings instead of parent -> child

At first I was going to say hook_form_alter, but when I started digging into the Bootstrap theme I found they've created their own plugin system. I would checkout this page, you might be able to get to the render array by creating a Bootstrap theme plugin: https://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8


Restrict vocabulary on entity_autocomplete form field targeting taxonomy terms

The vocabulary is the taxonomy term's bundle, so you just have to add a target_bundles array to the #selection_settings entry. In my case the desired vocabulary ID is 'category'.

$form['p_cat_ac'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Product Category'),
    '#target_type' => 'taxonomy_term',
    '#selection_settings' => [
        'include_anonymous' => FALSE,
        'target_bundles' => array('category'),
    ],
);


How to display or hide a Views field based on it's length?

In the views conditional field you are comparing the string value to the value 70, not the length of the string.

And the $row variable in views is very limited.

For the field that you want to do a length comparison on, if it is a PHP field already, then before you do the print statement set the following:

<?php
$data->custom_len_70 = strlen($output);
?>

$output is whatever you are going to print as the value of the field, so your naming is obviously different.

Then create another PHP field after that one, exclude it from display, and set its output code to:

<?php print $data->custom_len_70;?>

You have now created a hidden field which has the value of the length of the field you require.

Now you can use the Views Conditional field to do a comparison.


{{ drupal_view('view1', 'block_2') }} renders only when cache is cleared

The answer to the issue is to prevent that block to be cached. So first find the "block--bar.html.twig" and substitute in "add-block-id-name".

 /**
     * Implements hook_preprocess_HOOK() for block.html.twig.
     */
    function YOUR_TEMPLATE_NAME_preprocess_block(&$vars) {
      if($vars['derivative_plugin_id'] == 'add-block-id-name') {
        //-- This stops the block being cache in drupal 8
        $vars['#cache']['max-age'] = 0;

      }


It sounds like with the 'Forward to' configuration for your domain, it may be iframed instead of the domain pointing directly to your server.  When you type a direct url, the path isn't passed on to your actual site so it only serves the homepage, and when you click on links it only changes the url of the inner frame so the address bar doesn't update.  You can check if the page is actually in an iframe by viewing the source of the page.

For setting up the DNS, you should be creating an 'A' record to point the hostname directly to your IP address.


How to compare custom product bundles in Drupal Commerce

For comparing drupal commerce products check out this module: https://drupal.org/project/commerce_product_comparison

There is also a module available which allows you to create product bundles using products of your choosing: https://drupal.org/project/commerce_product_bundle


I would like to offer an alternative. I  have always had issues with putting my analytics into the analytics module.  I have experienced what you have experienced, plus I question why this code has to go into a module? The fewer modules you have the faster your site performs.

I always get the code from Google and then hard code it into the theme files. In drupal 7, this would go into your html.tpl.php just before the  tag, just as google instructs.  That is called for every single page, so no pages will ever go without it. Plus, it makes your code lighter and one less module to worry about. It has always been the best solution for me.

note: if you are using d6 it would have to go into each page.tpl.php template or its derivative if you have more than that one.  Hope that helps.


How to add content programmatically to a field collection that it's in an entity (build with eck)

The problem here is that entity_load returns an array, not the single entity. So you should do something like this :

$entities = entity_load('formulario',array($id));
$entity = end($entities);

and then the rest of your code ...


Make the order available in checkout pane callback when viewing

You might need to use an order pane instead.


Get Webform submission count using custom module

Okay. I figured it out.

There is a function webform_get_submission_count in the webmodule includes file that does. Just added these lines and got it my count. Sweet and simple.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$mysubmission_count = webform_get_submission_count($node->nid, $user->uid);