Is it proper to perform a db_update on an entity table?

The thing to look out for is invalidating the correct caches and making sure the correct hooks are called if needed.

When updating entities directly you will need to flush the appropriate caches so the next time the entity is loaded it does not grab the old data from the cache.
entity_load()
 -> DrupalDefaultEntityController::load() {uses a static cache by default}
 --> DrupalDefaultEntityController::attachLoad()
 ---> field_attach_load() {uses the cache_field cache bin}.

Once you have that taken care of you will then need to address any 3rd party modules that use hook_entity_load() or hook_TYPE_load() (hook_node_load()). Odds are you won't have to do anything in here but it is best to double check.

Once loading has been addressed you will need to address the hooks that get ran on insert/update to make sure nothing else is done in a different place that you may not know about. hook_entity_update(), hook_entity_insert(), field_attach_presave(), hook_entity_presave(), hook_TYPE_presave() (hook_node_presave()), etc... You can follow the trail of hooks in node_save() as an example. Once again odds are nothing crazy is going to happen in here, but it is best to double check.

In regards to getting ID's entity_load_unchanged() might be what you are looking for.

Most people will tell you it is not "proper" to update fields in the database directly via SQL queries. This is because 3rd party modules might do something with that data or react to it in different ways; also be aware of modules added after you've done this workaround. In reality you can directly update the database as long as you know the risks and how the code works; most people do not and thus using the API is the best answer.

Now for the interesting part. My guess is you're looking to work around the entity api due to speed issues. There are some ways to fix this. Using a background worker to do the updates is my recommendation. register_shutdown_function() when used in combindation with HTTPRL's threading can help. I don't have a good how-to yet but here is a really quick explanation:

httprl_qcinp - Queue Callback to run In a New Process. This takes arguments similar to call_user_func_array(). I'll use a node as a example.

<?php
hook_node_save($node) {
  // Preform update at the end of this request.
  register_shutdown_function('my_shutdown_function', $node);
}

my_shutdown_function($node) {
  // Load other entity that needs to be updated.
  $alt_node = entity_load_unchanged('node', $node->some_field_reference_nid);
  // Update object
  $alt_node->my_field = 'updated info';

  // Queue background node_save.
  // node_save($alt_node);
  httprl_qcinp('node_save', array($alt_node), FALSE);
  // Run it.
  httprl_send_request();
}
?>

At this point you might not even need HTTPRL; register_shutdown_function might do what you need.

EDIT: Also noted that this is a handy guide for just updating a single field http://timonweb.com/how-insert-and-update-only-specific-fields-your-entity-drupal-7


How to change the page of a view block display programmatically

This is how you can get a view programmatically:

  $view = views_get_view('view_name');
  $view->set_display('view_block_name');
  $view->set_arguments(array($argument_goes_here));
  $view->pre_execute();
  $view->execute();
  print $view->render();

The views object has many functions which can be viewed here.

You can set current page for the pager with $view->set_current_page($page);


The code you are trying doesn't work because syntaxhighlighter_prepare_callback() and html_pre_filter_prepare_callback() are not hooks: They are simply callback functions defined in the implementation of hook_filter_info() done from those modules.

In fact, the code used by check_markup() to invoke the input format filters is the following one.

  // Get a complete list of filters, ordered properly.
  $filters = filter_list_format($format->format);
  $filter_info = filter_get_filters();

  // Give filters the chance to escape HTML-like data such as code or formulas.
  foreach ($filters as $name => $filter) {
    if ($filter->status && isset($filter_info [$name]['prepare callback']) && function_exists($filter_info [$name]['prepare callback'])) {
      $function = $filter_info [$name]['prepare callback'];
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
    }
  }

  // Perform filtering.
  foreach ($filters as $name => $filter) {
    if ($filter->status && isset($filter_info [$name]['process callback']) && function_exists($filter_info [$name]['process callback'])) {
      $function = $filter_info [$name]['process callback'];
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
    }
  }

No hook is invoked, or you would see a call to module_invoke() or similar function.

If you are looking at a way to programmatically re-order filters used by input formats, the only way I can see is altering the cache where Drupal stores the information about the input filters. See filter_list_format(), which is the function that returns an ordered list of filters used by an input format.
More easily, this can be accomplished from the user interface, since on admin/config/content/formats you order the input filter for each input format.


Removing a field from the new content form

Three good options:

Display Suite has a feature to hide fields from the form
You can use hook_form_node_form_alter to remove the field

Edit: per Clive's suggestion, set ['#access'] = FALSE instead of unset($form['field_zip_file'])

Create a new module, (create MY_MODULE.info, MY_MODULE.module), and add this to MY_MODULE.module:

<?php

  function MY_MODULE_form_node_form_alter (&$form, &$form_state, $form_id) {
    if ($form['#node']->type == 'my_content_type') {
      if ($form['nid']['#value'] == '') {
        $form['field_zip_file']['#access'] = FALSE;
      }
    }
  }

Use CSS to make it disappear:

Add this to your theme's CSS file:

body.page-node-add #edit-field-zip-file {
  display: none;
}


Drupal doesn't have a lot to help with this, it's really a general PHP task.

If you're determined to use the API for it, just load the file data in any way you like (fopen, file_get_contents, etc), and use Json::decode() to turn it into an array.


You can get the complete (main) menu tree with this in your THEME_preprocess_page

  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $vars['main_menu_expanded'] = menu_tree_output($main_menu_tree);

Then you can pass that to a theme function in your page template:

<?php print theme('links__system_main_menu', array(
  'links' => $main_menu_expanded,
  'attributes' => array(
    'id' => 'main-menu',
    'class' => array('nav', 'navbar-nav'),
  ),
)); ?>

I've been using the function below to create a Bootstrap ready dropdown menu - you can clearly see how the submenus are themed by checking the $link['#below'] part of the array.

    /**
     * Implements hook_links__system_main_menu().
     *
     * @param array $vars
     * @return string
     *  Themed HTML for bootstrap 3 ready main menu.
     */
    function YOURTHEME_links__system_main_menu($vars) {
      // Get the active trail
      $menu_active_trail = menu_get_active_trail();
      // Initialise our custom trail.
      $active_trail = array();

      // Get current path
      $dest = drupal_get_destination();
      if (is_string($dest['destination'])) {
        $paths = explode('/', $dest['destination']);
        // Loop through and add all active paths
        foreach ($paths as $path) {
          // Read previous element added to active trail (using array values
          // preserves original array).
          $safe = array_values($active_trail);
          $previous = array_pop($safe);
          if ($previous) {
            $active_trail[] = $previous . '/' . $path;
          }
          // Or this is the first one
          else {
            $active_trail[] = $path;
          }
        }
      }

      // UL classes
      $class = implode($vars['attributes']['class'], ' ');
      $html = '
';

      // Iterate links to build menu.
      foreach ($vars['links'] as $key => $link) {

        // Check this is a link not a property.
        if (is_numeric($key)) {
          $sub_menu = '';
          $li_class = array();
          $a_class = array();

          // Check if link is in active trail and add class.
          if (in_array($link['#original_link']['link_path'], $active_trail)) {
            $li_class[] = 'active-trail';
          }
          if ($link['#original_link']['link_path'] == end($active_trail)) {
            $li_class[] = 'active';
          }
          // Check if last element in list and see if LI contains actual link
          $link['#attributes']['class'][] = strtolower(str_replace(array('& ', ' '), array('', '-'), $link['#title']));
          $link_title = $link['#title'];

          if (isset($link['#localized_options']['attributes'])) {
            $link['#attributes'] = array_merge($link['#localized_options']['attributes'], $link['#attributes']);
          }

          // Check if we have a submenu.
          if (!empty($link['#below'])) {
            // Check if lvl 1, if higher do other stuff
            if ($link['#original_link']['depth'] < 2) {
              $li_class[] = 'dropdown';
              $link_title .= '';
              $link['#attributes']['class'][] = 'dropdown-toggle';
              $link['#attributes']['data-toggle'] = 'dropdown';
            } else {
              $li_class[] = 'dropdown-submenu';
              $link_title .= '';
            }
            // Theme submenu
            $sub_menu = theme('links__system_main_menu', array('links' => $link['#below'], 'attributes' => array('class' => array('dropdown-menu'))));
          }
          // Build classes string
          $classes = '';
          if (!empty($li_class)) {
            $classes = ' class="' . implode($li_class, ' ') . '"';
          }
          $html .= '
' . l($link_title, $link['#href'], array('html' => 'true', 'attributes' => $link['#attributes'])) . $sub_menu . '
';
        }
      }
      $html .= '
';
      return $html;
    }


How to add template suggestion for user--VIEW-MODE--ROLE.html.twig

All you need to do is to get the current user object, get its roles, and then add the suggestion like in the following snippet. The current user also already is available in the $variables.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {

  // Define the view mode.
  $mode = $variables['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;

  // Get current user.
  $current_user = $variables['elements']['#user'];

  // Get current user's roles.
  $roles = $current_user->getRoles();

  // Add suggestion per role.
  foreach ($roles as $role) {
    $suggestions[] = 'user__' . $mode . '__' . $role;
  }
}

This will give you:

<!-- FILE NAME SUGGESTIONS:
   * user--full--administrator.html.twig
   * user--full--authenticated.html.twig
   * user--full.html.twig
   x user.html.twig
-->


But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

There seems to be a major misunderstanding here.

Compilation of SASS is invoked by you, it's not an automatic action that a server will just take upon itself to perform. Your remote VPS will not be set up to try to auto-compile SASS into CSS unless you, or someone else with access to the server, has set it up like that. The very fact that you've had to setup and install ruby on the remote serve should hopefully make that obvious.

Having that stuff on your production server is wrong anyway, you should prepare your distribution locally (read: compile SASS, minify/uglify js, etc), and sync that. That way you can never have any problems.

Your comment below the question is correct: if you don't want to compile SASS, then simply don't run bundle exec guard, compass compile, or whatever other method you're using to instigate the compilation.

If you haven't told any process to watch/compile your SASS files, then no process will be able to do so. The power is yours.


From where drupal get the template? if i don't have one

The variables for which you get those errors are the variables that Drupal uses to output the default regions a Drupal 7 theme should have, which are the following one.

regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

The template.php file is not a template file; it's the file containing functions template files use.

When your theme doesn't define a template file, Drupal uses the one defined from the module implementing the theme function. For example, the Node module defines theme_node(); if your theme doesn't have the template file used by that theme function (node.tpl.php), Drupal will use the template file that is in modules/node/node.tpl.php.


how to get all options values of simple hierarchical select in drupal $form?

In Drupal 7 you can use field_info_field(), while in Drupal 6 you can use content_field_instance_read(), which is defined in the CCK module.

You can also use list_allowed_values().

$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);


How can I prevent Drupal from stripping/sanitizing anchor tag

Just for sanity's sake...from a 'Drupal' point of view, your code works fine. For example (without the loop),

$emailAddress = 'test@test.com';
$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

//Snippet of render array being used to create the table
$rows = array();
$rows[] = array(
    array('data' => $entry['Email']),
);

print theme('table', array('rows' => $rows));

Produces:

      test@test.com

You may have a custom implementation of theme_table() somewhere which sanitises the incoming cell data, but it's not being caused by Drupal core.

Or, it might simply be that you're trying to re-use $entry when it doesn't make sense to.

$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

...

foreach ($tableEntries as $entry) {

Are you sure you meant to overwrite the outer $entry array with the one in the foreach?


The way to invalid the Cache in a Block is with
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

This comes from BlockBase


how to use user_save with custom column?

Manually adding extra columns in tables will rarely work for Drupal as there are dependencies and references that have to be honoured.

The correct way would be something along the lines of this case.


Check this:

How to add a tab to a Views page:
On the View that you want as the default tab: In the Views ‘page settings’, set the Menu Type as ‘Default Menu Tab’ then click the little setting ‘gear’ and set the ‘parent menu item’ to ‘normal menu item’.  Set the path as “/something/tab1″; for example, “/postlist/allposts”
On the View that you want as your second (or 3rd, etc) tab, set the Menu Item Type as ‘Menu tab’.  Set the path as “/something/tab2″ for example, “/postlist/newposts”
The key to making the tabs show on the View page is the path setting!  All of the pages must have the same parent-path – in the examples above this is “/postlist”.  If the parent-paths are not the same, you will never get that damn tab to show up in the View.

For more check the original post


When I going to Disable Twig template cache , Fatal error

The least hassle way is to install Drupal Console

Then run the command drupal site:mode dev (turns off caching and turns on twig debug)

Once you're done, run drupal site:mode prod (turns off twig debug, turns caching back on).


Send email to different email depending on taxonomy term

I don't know how you did it in D7, but hook_mail_alter is my preferred solution. And in hook_form_contact_site_form_alter i would add taxonomy term reference field to the contact form.

  This still works in D8

Code would look like this in your custom module:

/**
 * Implements hook_mail_alter().
 */
function YOUR_MODULE_mail_alter(&$message) {

  if ($message['id'] == 'contact_page_mail') {

    $tid = $message['params']['your_form_field'];
    if (!empty($tid) && $tid > 0) {
      // $tid to determine the address ?!
      $message['to'] = 'your@emai.l';
    }
  }

}


Taxonomy term AND (,) operator does not work

I am not the best with deciphering exported settings, but I think you should remove that Contextual Filter and use "Content: Has taxonomy term ID" instead.  Make sure you tick "Allow multiple values" under the More section.  That will result in a chain of AND clauses in the WHERE for the view (well, it does in one that I just looked at).


I was doing the wrong practices with Drupal Theme, in CSS whenever I have to use the url() to declare the path, I was using url('sites/all/themes/mytheme/images/bg.png') which is considered as Bad Practice, so I changed that to url(../images/bg.png) and same for Images inside misc folder as url('../../../../misc/configure.png') from CSS and everything is working as expected.

To tell long story in short, don't use absolute url from the root in CSS but use relative paths.


Fetch view results from mymodule_preprocess_page hook

The easiest way would be to execute the View again in the page preprocess hook.

If you want to avoid executing the View twice the task is getting a bit more tricky. This is because in D8 page elements are not necessarily rendered downstream in the order you expect. The element could have been cached in a previous request or in case the element doesn't qualify for caching it could have automatically been placeholdered and the page has been built without it, postponing the rendering until the cached page is finally delivered.

In Drupal 8 elements often need to send information upstream despite being cached or placeholdered, like cache tags or libraries. The mechanism for this is bubbleable metadata. You can use this for other things, too. See for example  Add an attribute to $variables from a Controller

In case of the views results you can try this:

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render($view) {
  if (isset($view) && ($view->id() == 'my_view')) {
    $view->element['#attached']['placeholders']['

']['#markup'] =
      '
' . $view->total_rows . '
';
  }
}

Place the empty div container somewhere on the page, for example in the body field of a custom block or directly in page.html.twig:

AJAX

When you enable AJAX the code above only works for the first page load. To update the results when the View gets refreshed via AJAX add your own command in a response event subscriber.

Getting the executed View then is straightforward, Views AJAX implementation keeps it in the response, so that you can use it when altering the response, see ViewAjaxResponse::getView.

/src/EventSubscriber/ViewAjaxResponseSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Response subscriber to handle View AJAX responses.
 */
class ViewAjaxResponseSubscriber implements EventSubscriberInterface {

  /**
   * Adds an AJAX command to ViewAjaxResponse.
   */
  public function onResponse(FilterResponseEvent $event) {
    $response = $event->getResponse();
    if ($response instanceof ViewAjaxResponse) {
      $view = $response->getView();
      if (isset($view) && ($view->id() == 'my_view')) {
        $response->addCommand(new HtmlCommand('#my-view-results', $view->total_rows));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }

}

mymodule.services.yml

services:
  mymodule.view_ajax_response_subscriber:
    class: Drupal\mymodule\EventSubscriber\ViewAjaxResponseSubscriber
    tags:
      - { name: event_subscriber }


Add all the fields to view automatically in csv export

This might be a really stupid suggestion but why dont you just edit the view and add all the registration fields manually. The view will have empty cells for fields thats not a part of the registration type at a specific row, but thats something you'll get anyways.

Another way to go is to skip views alltogether and export data with a module of your own using the entity api. You aparently are writing a module to override view fields above so you have already started down that road (so to speak)


Which payment gateway are you planning to use? If it is Paypal, then there is this system called Adaptive payment which helps you split payments.


How can I make web scraping of a field more difficult?

You can try to do something like this:

Your Placeholder


How to convert existing taxonomy terms (to ucwords) with Termcase module?

Not a perfect solution but this is the way I used to solve the problem while converting terms to ucwords:

If all the letters of terms are lowercase then applying ucwords is working correctly.

Go to the vocabulary page you wanted to convert terms (admin/structure/taxonomy/VOCABULARY_NAME).
Select the "Convert all characters to lowercase" option.
Enable the "Convert the existing terms in this vocabulary immediately."
Save and then it will updates (converts) all the terms to lowercase.
Then select the "Convert the first character of each word to uppercase" option.
Save and then it will updates (converts) all the terms to ucwords.

Done.

original -> step 1-4 -> step 5-6

my first term -> my first term -> My First Term
MY SECOND TERM -> my second term -> My Second Term
My Third Term -> my third term -> My Third Term
mY FourTH TErm -> my fourth term -> My Fourth Term

It works correctly.

(If you directly apply "Convert the first character of each word to uppercase" option to these terms above, the results would become:

original -> ucwords

my first term -> My First Term
MY SECOND TERM -> MY SECOND TERM
My Third Term -> My Third Term
mY FourTH TErm -> MY FourTH TErm

Doesn't work correctly if the words has uppercase letters. So do as I mentioned above (steps 1-6).


template to add a h2 tag around a field group title

The way I dealt with this was to change the wrapper in the Manage Display section from a fieldset to a div. Then, options for the label element could be changed from inside the UI.


How to define an optional argument to Route callback

The docs you link to say:

  Finally, if any static arguments should be passed to the controller, provide those in the defaults array as well. Name them to match the arguments of your controller method. See below.

Emphasis mine.

So your code should be:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
      _permission: 'access content'

See also Required and Optional Placeholders in the Symfony routing docs.


How can I copy theme configuration when copying a site?

Theme settings are stored in the database. However, Drupal 8 has configuration management. You can export the configuration to yml files. Theme configuration is included.

You can download the yml files at /admin/config/development/configuration/full/export

Or you can export it to the configuration folder by
$ drush config-export sync


Take a look at the Views PDF module.  It will allow you to add a "PDF" display to the views you choose.  From the project page:

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.


The Zen theme uses many different CSS files. You need to create a subtheme for Zen and then you are supposed to choose which layout you want. Fixed or Liquid.

Within the subtheme there are many CSS files. Depending on your choice of Fixed or Liquid you have to edit that css file...

layout-liquid.css
or
layout-fixed.css

Within that file you can change the parameters you are trying to override. As long as you don't have css files aggregated in the performance settings you do not need to clear the caches, otherwise you do.

To create a Zen subtheme you need to follow a tutorial:
http://drupal.org/documentation/theme/zen

I recommend going through that completely and reading and learning as much about Zen as possible. One thing to know is that you never want to alter the core files of Zen, you only want to override them in your own subtheme.

Lastly, adding your own custom CSS file can be useful, but for this situation it would not be recommended because there are already CSS declarations for your use. I use a custom Zen subtheme for this site: https://www.fdanconia.com/ - I love the Zen theme structure and once you learn where everything is and how to override everything is a great theme to use.


It's because Devel uses the Database::getLog() static method to get a list of the queries that have run for the page.

That method can only be run for a single connection at a time, and Devel specifically requests logs for the 'default' database connection (see devel_shutdown_real()):

$queries = (devel_query_enabled() ? Database::getLog('devel', 'default') : NULL);

In short you've got 2 options that I can think of:

Edit the devel module file directly, forcing it to loop through all available connections and combine the query logs (obviously hacking contrib modules is not recommended though)
Implement your own logic in a custom module and have a second set of query logs appear at the bottom of your page. The devel_shutdown() function and devel_shutdown_real() should give you all the code you need to get started if you go down this route.


This shouldn't work as @Alex said, because you are not using Drupal's Form API. You should implement hook_form($node, &$form_state), to create a form.

Sample code which creates a form with a single text field:

function MODULE_form() {
  $form = array();
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Field description goes here...'),
    '#required' => TRUE,
  );
  return $form;
}


How to show content type with only related taxonomy item?

Download and install Views Module and enable the Taxonomy term view.


The drupal 7 Metatags module has built-in Facebook opengraph support as an add-on module. If your specific metatag is not covered, the Meta tags module allows you to add it manualy.

Although not recommended, if you need custom code for specific pages, you may use the theme's preprocess hook. For example, here is the one I wrote on the preprocess-page.inc file on the preprocess directory of my Omega sub-theme (for other themes, you may need to write the code in a hook_preprocess_page function on template.php):

<?
  // Add og:title and og:description for the front page
  if($vars['is_front'] == TRUE){
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        "property" => "og:title",
        "content" => t("Druvision - Drupal News"),
      ),
    );
    drupal_add_html_head($element,'og_title');

    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        "property" => "og:description",
        "content" => t("Druvision is a team of web solution experts focused on enterprise systems, open source development, responsive design and Drupal project management."),
      ),
    );
    drupal_add_html_head($element,'og_description');
  }

  // Add og:image
  global $base_url;
  $img =  $base_url.base_path() . drupal_get_path('theme', 'MYTHEME') . "/logo.png";
  if($vars['is_front'] != TRUE){
    if(isset($vars['node']->field_image['und'][0]['uri'])){
      $img = file_create_url($vars['node']->field_image['und'][0]['uri']);
    }
  }
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      "property" => "og:image",
      "content" => $img,
    ),
  );
  drupal_add_html_head($element,'facebook_share_image');
?>

Note: The question is old, but I've found it in search so other people are looking for it, so I answer it for the completeness of this thread.


In the Views filters, there are 2 default filters for taxonomy. You want to use Content: Has taxonomy terms (with depth), then select the vocabulary and depth of the terms to include.


How to use fixed width in AT Panels everywhere (site template)?

Found the answer: look at default site template, copy-paste the css of the sample variant and set the page-wrapper.


This is actually easier than it looks! :)

Use the one submit callback and in it use a switch or if statement to execute different actions depdending on what step you're on.

function my_form_submit($form, &$form_state) {
  if (!isset($form_state['storage']['step'])) {
    $form_state['storage']['step'] = 'step-two';
    $form_state['rebuild'] = TRUE;
  }
  else if ($form_state['storage']['step'] === 'step-two') {
    // do something awesome for step-two
  }
}

UPDATED

The following is working code I have running in Drupal 6:

  // multistep form
  if (!isset($form_state['storage']['page']) || $form_state['storage']['page'] < 4) {
    $form_state['rebuild'] = TRUE;
    $page = $form_state['storage']['page'];
    $form_state['storage'][$page]['values'] = $form_state['values'];
    $form_state['storage']['page']++;
  }
  // process submit
  else {
    // grab submitted values for each step from storage array
  }

It runs in the only submit handler of a multistep form.

I realize this is Drupal 6 but its close enough, can you try this?


Workbench Moderation: Published data overriding draft data on draft view

It was a two-part solution.
There was a bug that needed patch #16 from here:
https://www.drupal.org/project/workbench_moderation/issues/2021903

I also needed to add vid to node_load:
    When I combined the
    $vids = $node->vid;
    $node = node_load( $nid, $vids );
    with patch #16 from:
    https://www.drupal.org/project/workbench_moderation/issues/2021903 it solves the issue.


Enforce URL rules when posting content types

You want to use the PathAuto module.  This lets you create default patterns on a per content type basis that can use information from fields on the node to create a URL.


The node object does not store the "publication date", install this module to create that field http://drupal.org/project/publication_date
Some details from the module's project page:

The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.
The "Published on" date can be used in any templates, or views. Publication date also incudes integration with the Display Suite module and has entity wrapper support, so it can integrate with modules like Rules that use the Entity API module.
The "Published on" date can be edited through the node edit form, allowing a custom published date to be set. If a custom date is set prior to publication, it will be respected when the node is published. The publication date is also retained when a node is unpublished and then republished.


Why Can't I Call Drupal Function From .inc File?

I think your module must have weight higher than the taxonomy module so that I can call any functions that are defined in taxonomy.

You can make sure your module is the heaviest one in order to run last by implementing hook_install().
You would create a file yourmodule.install in your module folder which may contain the following code:

/**
 * Implementation of hook_install()
 */
function yourmodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'yourmodule')
        ->execute();
}

/**
 * Implementation of hook_uninstall()
 */
function yourmodule_uninstall(){
    db_delete('system')
        ->condition('name', 'yourmodule')
        ->execute();
}


How can I have "Table view" as the default result instead of "Submissions“

You may need to do this in a custom module. In your custom module, implement hook_menu_alter:

/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
   // Node webform results.
  $items['node/%webform_menu/webform-results'] = array(
    'title' => 'Results',
     // the page callback here is what will display the table.
    'page callback' => 'webform_results_table',
    'page arguments' => array(1, '50'),
    'access callback' => 'webform_results_access',
    'access arguments' => array(1),
    'file' => 'includes/webform.report.inc',
    // Change the weight to change the order
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,

  );
}

Once you added that to your custom module. Make sure the module is enabled, and clear all caches.


Turn on Twig debugging by:

Copy sites/example.settings.local.php and rename to sites/default/settings.local.php

Go to sites/default/settings.php and uncomment the code below the comment relating to "Local development override configuration" and save the file.

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

Open sites/development.services.yml in a text editor and add the following to the bottom of the file and then save the file

  parameters:
    twig.config:
      debug: true
      auto_reload: true
      cache: false

Note: use two spaces for each indent. Twig can be fussy with this.

The debugging will be visible as html comments in the source code. Use Chrome or other developer tools to inspect.

If you want to inspect the data structure of variables in a speciifc template, install Devel module and enable Devel and Devel Kint and then add this in your template:

# to dump everything
{{ kint() }}

# to dump a variable
{{ kint(page) }}

# to dump lower down in the data structure
{{ kint(page.content) }}


I managed to get around this by using the drupal_get_path_alias function in the end, so my resulting code was:

function THEME_links__system_MENU_NAME($variables) {
  $html = '<select name="" id="dropdown-menu">';
  $html .= '<option class="" value="home">Select Item</option>';
  foreach ($variables['links'] as $link) {
    $html .= '<option class="" value="'. drupal_get_path_alias($link['href']) .'">'. $link['title'] .'</option>';
  }
  $html .= '</select>';

  return $html;
}

Dissapointed I didn't think to search for such a function in the first place!


You can use Entity Reference Prepopulate.

  Allow prepopulating any Entity reference field via URL

In your booking-request set up an entity reference field pointing to user entities. Then, create a link in the listing node to booking-request node add form with the right parameter to prepopulate that entity reference field.

See README in the module:

  In order to pre-populate an entity reference field you have to supply
  the parameter in the URL.

  The structure is node/add/article?[field_ref]=[id]

  Where [field_ref] is the name of the entity reference field and [id]
  is the id of the entity being referenced.

  Examples: node/add/article?field_foo=1 node/add/page?field_bar=1,2,3


How to display the translated value of a boolean field when viewing a translated page?

Try what's mentioned in Comment #1 of issue # 1762488, i.e:

  ... visit 'Manage Display' and switch from "Default" to "Default translated".


Exclude fields from a node-add form (but keep them on the node-edit form) by excluding (to save load time) not hiding? Drupal 7

Okay I got it to work. On new nodes there is no NID on existing nodes there is. This code works.

function custom_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'custom_node_form') {
    if (empty($form['nid']['#value'])) {
    unset($form['field_remove_this_field_name']);
    }

}

Unfortunately I still have a slow load time and I suspect that even though I'm unsetting the form fields that involve entity references (and therefore views queries to populate selection lists) that the queries are still getting run.

It's only really slow on the first form load after clearing caches. The second form load is much faster.

If anyone has any ideas to speed up the initial form load, I'd love to hear them.

It may be that I need to create a custom form from scratch using module code and only load the essential fields.


Unique Value validation rule does not show the indicated message

You wouldn't believe this but it was the theme. We had forgotten to include the markup that contains the flash messages sent by core to the user so basically it any flash message (including the validation errors) wouldn't show up.

The reason why other validation errors showed up was the Client-side Validation module that causes some certain form of validation violations to be detected in the client and displays them via it's own device.


You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.


New to Drupal 7 and I was wondering if this is possible to do?

Yes, it is possible. You can port an external web application, and can make it automatically compatible with your div specific properties. I suggest you to use jQuery to get external web application.

To add jquery in drupal 7, you need to install JS injector module. Enable the module and you can add jquery at admin -> config -> development -> js-injector. In the JS code section, the syntax is as follows:

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

   =====your jQuery code goes here ==========

}
};
})(jQuery);

For porting an external web application, let us assume you have a link/button in a specific div section and when you click on that link/button, I'm going to display that website in a target div section.

HTML should look like this:

    Click here to port an external website.

And the jquery to port web application:

$('#sourceDiv a').on('click',function(){
    var url = $(this).attr('href');
                                     //returns the targetDiv's height and width
    var height = $('#targetDiv').height();
    var width = $('#targetDiv').width();
                                    //replaces the div with porting the website.
    $('#targetDiv').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
    return false;
   });


Using path aliases how to identify node IDs from database and based on these IDs how to publish them?

You can use drupal_get_normal_path() to get the node/id-paths for each of them.

Then you can use the following code to publish them.

// Load the node object.
$node = node_load($nid);
// Set the status property to 1.
$node->status = 1;
// Re-save the node.
node_save($node);


Have a Rules condition that will take the current time minus last comment posted time

Overall goal:  If a node has not been commented on in an in a given time frame, send an email.

Here is a bare bones solution. On paper this should work.

Basically, we use sticky as the tell tell sign if a new comment has been added (if it's not sticky, no one has commented). Once the e-mail gets sent, we set node to unsticky.

1) Create a rule after saving new comment.

Add Action: Under Node, Make Content Sticky >> comment:node

  Then it's very similar to my answer to your question Rules Conditions
  being evaluated after schedule time
  elapsed?

  Create a New Component

  1) Add Compotent of Rule.

  2) For Data Type: select Node. Name, Label and Machine name use
  whatever you want.

  3) Add condition of Content is of type

  For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of test you put test
  Select your content type

4) Download and Install Conditional Rules Module

Then for action, click on Add IF >> DATA COMPARISON >> test:sticky >> False

Then in IF: Data Comparison row click Add Action >> Send Mail

Then in Conditional row (1st row white) you will now see an Else button, click on it.

Then in Else click on Add Action >> Make Content Unsticky >> test

  Now Create a new Rule

  1) For action use after content is created

  2) Leave the condition empty (no need for condition here)

  3) for Action add the scheduled component evaluation and select the
  component you just created.

  use node as your data selector


Ajax %-wildcard URL giving 404 error when setting a parameter

If the form is part of a standard Drupal form, you can use Drupal's built in AJAX system. There is a detailed explanation here: Ajax Forms in Drupal 7. Basically it should look like this.

function hook_some_form($form, &$form_state) {
  // Create a frop down
  $form['some_select'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'some_ajax_callback', // This is the php function to be called
      'wrapper' => 'some_wrapper', // The javascript #id to put content in.
      'method' => 'replace', // Content placement option
    ),
  );

  // Result contents container
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );
}

And for the PHP callback

function some_ajax_callback($form, $form_state) {
  // Fetch the value AJAX gave us.
  $value = $form_state['values']['some_select'];

  // Recreate the wrapper as we overwrite the old one.
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );

  // Append the value of the drop down to it.
  $form['some_wrapper']['value'] = array(
    '#type' => 'item',
    '#markup' => check_plain($value);
  );
  // Return everything to Javascript.
  return $form['some_wrapper']
}

This allows you to pass form values to PHP for processing.


I think one way to achieve that is by altering '<front>' route with a RouteSubscriber service.

  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    arguments: ['@config.factory']
    tags:
      - { name: event_subscriber }

Then in your RouteSubscriber.php class :

/**
 * Event subscriber.
 */

namespace Drupal\mymodule\Routing;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscribe to KernelEvents::REQUEST events and redirect if user is press.
 */
class RouteSubscriber extends RouteSubscriberBase  {

    protected $configFactory;

    /**
     * RouteSubscriber constructor.
     * @param ConfigFactoryInterface $config_factory
     */
    public function __construct(ConfigFactoryInterface $config_factory) {
        $this->configFactory = $config_factory;
    }

    /**
     * {@inheritdoc}
     */
    public function alterRoutes(RouteCollection $collection) {
        if ($route_front = $collection->get('<front>')) {
            $route_front->setOption('no_cache', TRUE);
        }
    }
}


Add js file in .info theme file. And set it to load first

You can add the scope (header/footer) where to load the JS and also add a weight.

Example options:

$options = array('type' => 'file', 'scope' => 'header', 'weight' => 5));

Play around with these to get the file loaded on the right position that suits your needs. For more detailed information check the documentation.


No, this is not possible.

You would need to hack core in order to do it (twig_render_template), which might be ok for your local development.

The code in interest is this part:

if ($twig_service->isDebug()) {
  $output['debug_prefix'] .= "\n\n<!-- THEME DEBUG -->";
  ...
}

You could add a condition, like this:

 if ($twig_service->isDebug() && $template_file != 'awesome-template-file') {

I'm not sure what $template_file looks like, but I'm sure you could use it to make a condition to make the template file in question be skipped debug. This actually requires that the field uses it's own template file though.


hook_nodeapi() is great on nodes, but what can I use on non-node pages?

You have three options:

hook_init() This hook is not run on cached pages - though CSS or JS added this way will be present on a cached page.
hook_boot() Only use this hook if your code must run even for cached page views.
hook_exit() This hook is run at the end of each page request. It is often used for page logging and printing out debugging information. Only use this hook if your code must run even for cached page views.

Performancewise, you will want to avoid hook_boot() and hook_exit(), since they will run regardless of caching. Having one module that implements those hooks brings the familiar warning on the performance page, "The following enabled modules are incompatible with aggressive mode caching and will not function properly: …"

If all you need to do, is add some Javascript, static HTML, or CSS, hook_init() is the best option: the JavaScript and CSS you add will be added to the cache and be present.

If, however, you need to run actual PHP that is not needed for the rest of the request, e.g. to write a record in a database, or log a line to some file, then hook_exit() is the best option: it will only be called after the page is already served.

If you need to run some setup: e.g. establish a connection with a service, perform access-check and such, then hook_exit() is the best option.


Invalid datetime format for a field never submitted?

It may be possible your field_yapim_yili_value field has a default value and that default value is invalid for datetime format.


Change default format for date field on user register form

You can implement template_preprocess_field() and alter the markup of the date field.

function MY_THEME_preprocess_field(&$vars) {
  if ($vars['field_name'] === 'field_custom_date_field') {
    $date_format = 'short'; // You need to provide the machine name of the format you want.
    $timestamp = strtotime($vars['element']['#items']->value);
    $markup = \Drupal::service('date.formatter')->format($timestamp, $date_format);
    $vars['items'][0]['content']['#text'] = $markup;
  }
}


How to set mysql port for Drupal and Drush

For the port configuration in settings.php you can do by following(in example i used MYSQL in 33066) and the value of port is integer not string:

//D6 DB config
$db_url = 'mysqli://mysqluser:mysqlpassword@dbhost:33066/yourdb';

//D7 DB config
$databases = array('default' => array('default' => array(
  'driver' => 'mysql',
  'database' => 'yourdb',
  'username' => 'mysqluser',
  'password' => 'mysqlpassword',
  'host' => 'dbhost',
  'port' => 33066 )));


3 columns with main content in front page

Panels module would help you in this regard. In Panels you can place nodes, views blocks, general blocks. All these things can be themed independently.

Panels are themselves nodes and blocks(mini panels).


How to get the file ID using managed_file on custom form?

I think you need to save the file :
public function submitForm(array &$form, FormStateInterface $form_state) {
  $event_image = $form_state->getValue('event_image');
  if ($event_image) {
    $file = File::load(reset($event_image));
    $file->setPermanent();
    $file->save();
    drupal_set_message('Filename: ' . $file->getFilename());
  }
}


If it's a core/contrib theme, just download the original and replace the modified version with it.

If it's a custom theme, just restore from whatever backup you have available (or from Trash or your OS's equivalent feature).

If you're wondering if Drupal somehow keeps track of file system changes and might be able to help you restore deleted files - it doesn't (I've yet to come across a framework that would do this).


How do i do some search feature like this

This is related to the issue on D7 Faceted Search module here.

Using specialized search systems (Solr, Sphinx, Xapian, or others) is the way to go.

You can get results with Solr, the Apache Solr Search Integration module, and customizations.


Users' list view based on current logged in user taxonomy field value

Suppose your taxonomy field is labelled User Tag and has a machine name field_user_tag.

Create a view that lists users
Add a contextual filter for User:
User tag (field_user_tag)
Under WHEN THE FILTER VALUE IS NOT IN
THE URL Select 'Provide a Default Value' and then Select 'PHP
Code'
Insert the following snippet:

global $user;
$term= user_load($user->uid)->field_user_tag;
return $term['und'][0]['tid'];

The PHP code grabs the current user. In this context the current user object doesn't have any additional fields loaded. So we need the user_load function to get those. The we need to extract the taxonomy id from the relevant array.

This approach works, but may not be the best or most efficient.


Limit the reviews on "Product" content type

The error is that you use die; the hook should simply return to the calling function. If you use die, you are avoiding that the code calling the validation handler is called back, which means the code that checks if there are any validation errors, and shows them to the users is never executed.

If you look at the code used by a Drupal validation handler, such as user_pass_validate(), you will notice it doesn't use die, which is never used from any form validation handler.

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}


Setup existing drupal 6 site on local server

Steps to setup a Drupal Site :

Place your Drupal 6 directory in your htdocs directory of xampp folder. All files and design folder should be at same place where they are on live version of site.
Open your settings.php, change the database credentials according to your local server.
Restore your database using phpmyadmin.
May be some image would not be shown up on site so you need to setup a domain in apache's vhost file.


How to delete Ghost Menu Link in Main Menu?

I think the easiest way is to manually delete this item from the table menu_links search for value user/%/notifications/subscription in link_path column. Delete that row and clear your cache.


Drupal loaded only the needed strings on every page which we are included.
Those strings are added in javascript itself.

I think this is fixed by across the script files before they are actually added to the page.

So, you should be able to translate that string into the translate interface.

For more help, You can see this link,

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

Hope it will be helpful.


How to create a rule that unpublishes comments that contain links?

Look at honeypot and hidden capchta before getting too many rules involved.


How to email the webform content to current page author email "Token [current-page:node:author:mail] is not working any more"

After almost 4 weeks driving us crazy , we have finally found where is the problem. Thing is we were looking in the wrong direction.

Overwrite http://s000.tinyupload.com/?file_id=06809135818916665525 after updating Token to 1.6. Just extract it on sites/all/modules/token. We don't know why yet. We have completely checked all the change logs, git commits and everything in Webform and finally decided to look in another direction.

You can update the Webform module as suggested by the module maintainers.

So, to have it back working, do the following:

Upgrade to Token 7.x -1.6 http://ftp.drupal.org/files/projects/token-7.x-1.6.tar.gz
Extract the file http://s000.tinyupload.com/?file_id=06809135818916665525
Clear the cache

The token will be back.

We have obtained all the feedback from this post https://www.drupal.org/node/919760 and the patch applied is https://www.drupal.org/files/issues/token-current_page_object_token-9197.


How do I load specific page template for /store-locator

There are many possible ways to solve this problem.  My suggestion, however, would be to use the Page Manager Existing Pages module.  This module will let you easily override the callback at that URL and place the content for the page in any region of your Panels layout.

If you want to do it the same way as you've been doing it for other pages, then there will already be template suggestions automatically provided for you, derived from the path.  So if the path to the item is sitename/store-locator then the template suggestions that will already be automatically created for you are page__sitename and page__sitename__store_locator.  You need only to create those tpls.

That said, I'd still generally recommend the PM Existing Pages module for this type of functionality.


How to programmatically get the Title for a Local Menu Task?

I figured out how to finally get the title.

I was using dpm(menu_get_item()); which listed an array, but I had no idea how to access it. I just had to turn it into a variable to hold that data, then I could access it!

$db_site = menu_get_item();
$db_site = $db_site['title'];


How do I send http authorization header in GET request in drupal?

You can add basic authorization to url to access http basic protected address.

  // http auth
  $remote_url = 'http://uname:pw1234@example.com/service/node';


Had similar outcome but issue was purely that the User record was still set to Blocked rather than Active.


How can I include ratings in the site, with reference stored in the node table?

You can use Fivestar module for this.

  The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7.

You configure which content type should have the Fivestar module enabled; you can also set the permissions for the users who can vote etc. You will have multiple option to show the vote result on the configuration page of module.

I have used it in 3-4 e-commerce websites and it works simply great.


How to prevent non-English characters from turning into jumbled words?

This is a bit of a guess, but it sounds like some part of the process isn't UTF-8 clean.  If Drupal is displaying everything properly, then it sounds like the database actually is UTF-8.  This leaves phpMyAdmin.

I would log into phpMyAdmin with Firefox.  Right-click, and do View Page Info.  Make sure the encoding say UTF-8.

Then install the Live HTTP Headers plugin.  Download a backup and restore one with the plugin running.  Make sure the Content-Encoding is always UTF-8.

If any of them aren't, then you have some server-specific configuration to fix.

Personally, I think phpMyAdmin is a terrible tool and a security risk.  I use the legacy MySQL Administration Tool for most of my server work and a fair number of backup tasks.  You can also try the Backup and Migrate module for taking and restoring backups.  You can also use the sql-* and/or bam-* commands in drush.


Commerce product programatically with price

Prices are stocked as integer in database.

Try replacing 1.00 by 100 in your price array :

$values = array (
        'price' => 100 ,
        'currency_code' => commerce_default_currency() ,
    );

Cf : http://drupal.org/node/1124416


Enabling HTML in MENU_LOCAL_TASK titles (primary tabs)

The key is this if construct: if (!empty($variables['element']['#active'])) with regard to getting the titles of the inactive tabs to respond. My solution was to customize: theme_menu_local_task. Perhaps there is a better solution?

/**
 * Alter theme_menu_local_task.
 */
function my_theme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      if (arg(0) != 'my-page') { // ** ADDED **
        $link['title'] = check_plain($link['title']);
      } // ** ADDED **
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  if (arg(0) == 'my-page') { // ** ADDED **
    $link['localized_options']['html'] = TRUE; // ** ADDED **
  } // ** ADDED **

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";
}


How to include "File upload" field in the webform composite element?

Depends on the destination folder. This webform FAQ might help you.

Edit: Webform Composite Elements do not support File elements yet. Reference on drupal here

Follow these issues (active as of 6/20/2017) to find release updates-
https://www.drupal.org/node/2883734
, https://www.drupal.org/node/2884624


Setting anonymous user timezone on page load

drupal_get_user_timezone() is the main function that retrieves the user's zone (based on a configured user setting, site setting, or PHP's date_default_timezone_get() depending on site/user settings).

This function's implementation is based off of retrieving configuration settings and native PHP function. There's no way to override that short of
trying to redefine to this function (if you don't mind a solution that is a bit of hack).

An alternative to that would provide some wrapper function in a custom module. For example:

function mymodule_get_timezone() {
  // @TODO: At timezone lookup retrieval based on IP/Whatever
}

function mymodule_get_user_timezone() {
  // Or \Drupal::currentUser()->isAnonymous() in D8
  return user_is_anonymous() ? mymodule_get_timezone() : drupal_get_user_timezone();
}

Then reference mymodule_get_user_timezone() wherever you need to insert your own discovered timezone.


How to fix combination Dutch domain - English uri

My favourite way of dealing with 404 like that is to use module like Search 404:

  Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL, e.g. if a user goes to http://example.com/does/not/exist, this module will do a search for "does not exist" and shows the result of the search instead of the 404 page. This should help retain visitors coming in from old URLs linked from other sites or from search indices.

That way user will see a link to an article on a proper domain, if he will enter bad URL.

To prevent creation of "interesting" links it's worth to use Global Redirect - with it even if you will have temporary misconfiguration, users and bots (including Google bot) will get redirected to content's main URL, and that's what will get indexed.

Last but not least, be sure to always set canonical URL for your content, if you care how it looks in search results.

I'm afraid you will never know what misconfiguration caused this in the first place, unless it still occurs. Things to check would be:

Canonical URL - are you sure it does not direct everyone to one single domain?
Web Archive - maybe they have a snapshot from time when your site was actually displaying something under these URLs. If so, you could use backups to unpack a copy on a dev machine, and examine configuration that made this.


Converting a Views SQL query with INNER JOIN to an EntityQuery

You can try hook_query_TAG_alter
Sample code
$query = $this->getEntityQuery('taxonomy_term')
  ->condition($entity_type->getKey('bundle'), 'MY_VOCABULARY')->addTag('join_flaging');

/**
 * Implements hook_query_TAG_alter().
 */
function MYMODULE_query_join_flagging_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->addJoin("INNER","flagging","flg","taxonomy_term_field_data.tid = flg.entity_id AND (flg.flag_id='MY_FLAG' AND flg.uid='MY_UID')");
}


How do I override/theme Views REST Export display field?

Here's one option:

Add a new relationship in the view for the field (field_feature_image in your case)

Add new field for "File: URI" using this new relationship

Use the File URI formatter, and also enable the "Display the file download URI" option

This method may not be ideal for fields with multiple values. I am still working out the best method to do that using the core tools in Drupal 8.


Content field list(text) : using correctly ?

I tried this too and it didn't work.  https://stackoverflow.com/questions/4248061/what-is-the-easiest-way-to-have-images-next-to-the-text-on-a-html-dropdown-combob you cannot put images in dropdown box in general (unless you use javascript).  I tried it as a 'Check boxes / radio buttons' widget and it did work.  Maybe that will be a good enough solution for you


Drupal 7 - Call the default/base template implementation

I have never tried this, but I suspect you can implement template_preprocess_node in your theme, use drupal_is_front_page, and if FALSE, remove the specific template from the $variables["theme_hook_suggestions"] array.


How to use Hierarchial Select Module for select field's of webform module?

Seems like webform doesn't support Hierarchical Select module...

You can use Webform Conditional module to create dependent fields...

Project page says

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.


How do I debug a the output errors on SimpleTest when I'm not sure where in the script the error occurred?

Part of why your test is failing is pretty easy to see.  Your code is relying on node 1 existing:

function insertMockData($data = array(), $submitted_datetime = REQUEST_TIME) {

        $node_web = node_load(1);
        $submission = (object) array(
        'nid' => $node_web->nid,
        //'uid' => $user->uid,
        'submitted' => $submitted_datetime,
        'remote_addr' => ip_address(),
        'is_draft' => FALSE,
        'data' => $data,
            'serial' => $this->serial_value++,
        );
  //lots of stuff omitted here...
}

The code assumes that there's a node in your DB for you to load.  Sadly, no :-)

When SimpleTest runs, it creates a whole empty DB that's just installed.  If you need a node, you have to create one, like this:

$settings = [
  'title' => 'My Test Content',
  'body'  => 'and what a body it is',
  'status' => 1,
  'type' => 'article',
];

$test_node = $this->drupalCreateNode($settings);
$this->assertNotNull($test_node, "Make sure our settings work");

See core/modules/simpletest/src/WebTestBase.php for some of the methods you can use to create nodes and users and other useful test data.  But in general: your test or the test's superclasses need to create everything you need either in setUp() or in your test itself.


Custom php code using the site header and footer

Yes, you'll generally solve this by writing a custom module. In your .module file you'll probably want, as a minimum:

An implementation of hook_permission to provide access control to your content
An implementation of hook_menu to define the routing to your page, in other words which URLs will cause your custom code to be invoked.
The actual callback which generates the content.

In the callback you can use whatever PHP code you want, though if you do use Drupal's APIs and established good practice you'll be less likely to create security weaknesses and your code will work better with other modules. That's likely to save you time in the long run.


How to obtain a token based on a entity_reference field?

You need the Entity Tokens module, part of the Entity project: http://drupal.org/project/entity. Once it's enabled you'll see the available recursive tokens in the tree.


How might I go about flagging a post or comment containing certain keywords?

Look at hook_node_xyz (d7) or hook_nodeapi (d6) to add code after node save or update.


Taxonomy term missing as type of data to store in new field for content type

Use the Content taxonomy module. It provides a CCK field type for referencing taxonomy terms.


Executing jQuery code during form submission

Try this

   $form['actions']['property_endlease'] = array(
            '#type' => 'submit',
            '#value' => t('End'),
            '#access' => TRUE,
            '#weight' => 15,
            '#attributes' => array("onclick" => "javascript:test();"),

        );

and create a custom js

function test()  {
//your code
}

Hope it will work


Inline Template with Render Array in #context

The issue not in the inline_template but the issue comes from {% trans %} if you place a render array variable into {% trans %}{% endtrans %} you will get the following error and it will not rendered:

  Warning: htmlspecialchars() expects parameter 1 to be string, array given in Drupal\Component\Utility\Html::escape()

So you have two options:

1) get the variable out of {% trans %}{% endtrans %} like the following:

    $my_subtemplate = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} my {{ foo }} here {% endtrans %}',
      '#context'  => [
        'foo' => 'bar'
      ],
    ];
    $my_string_with_embedded_themable = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} Print this string and this subtemplate: {% endtrans %} {{ my_subtemplate }} .',
      '#context'  => [
        'my_subtemplate' => $my_subtemplate,
      ],
    ];

2) Pre-render the renderable array variable to a string first.

    $my_subtemplate = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} my {{ foo }} here {% endtrans %}',
      '#context'  => [
        'foo' => 'bar'
      ],
    ];

    $renderer = \Drupal::service('renderer');
    $my_subtemplate = $renderer->renderRoot($my_subtemplate); // this fixes it

    $my_string_with_embedded_themable = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} Print this string and this subtemplate: {{ my_subtemplate }}.{% endtrans %}',
      '#context'  => [
        'my_subtemplate' => $my_subtemplate,
      ],
    ];


How to add a media type to drupal_add_css in custom module

drupal_add_css() is defined as:

drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE)

and in your example, you are doing:

drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'screen and          (max-width: 640px');

which appears to have two problems:

You are skipping the $type argument,
You aren't closing the max-width parenthetical.

I'd suggest trying:

drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'module', 'screen and (max-width: 640px)');

and seeing it that fixes things up.


views_query_alter Matching all values in IN clause

The following code should allow you to add the SQL code found in the accepted answer to the S.O. post you mentioned to the Views generated SQL code.

function YOUR_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'YOUR_VIEW_NAME' ) {
        $value_count = 0;

        // Collect the number of selected values in the exposed filter
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_listtext.field_data_field_listtext_value' ) {
                $value_count = sizeof($query->where[1]['conditions'][$key]['value']);
                break;
            }
        }

        // Add the having expression
        if( $value_count > 0 ){
          $query->add_having_expression(
            0,
            "count(distinct :field_name) = :value_count",
            array(
              ':field_name' => 'field_data_field_list_select.field_list_select_value',
              ':value_count' => $value_count
            )
          );
        }
    }
}

Good luck!


how to inspect the output array from PHPVideoToolkit::getFFmpegInfo()

Quickest way I can think of:

Install the Devel module.
Go to http://mysite.com/devel/php and run the following code:

$info = PHPVideoToolkit::getFFmpegInfo();
dpm($info);

When you run that code you should be presented with a nicely formatted array in the messages area that you can inspect.

If you get an error that PHPVideoToolkit does not exist then find out what file in your installation declares that class, and make sure it's included using either module_load_include() or PHP's include/require.


Custom Password validation on Drupal 7 form

Please check Password Policy module. It will satisfy all your above requirements (Uppercase, Lowercase, numeric and special characters).


How to add class to all forms automatically?

You can do something like this:

function MYMODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'MY_CLASS';
}


Theming site name in mayo over Flexslider slideshow header?

Ok I've sorted it.

Use the Module: Views variable field

Add the field to the View for the slideslow / flexslider.

Add the site_name variable to the field.

Rewrite as Link and type in

Rearrange the fields so that it is Site name then Slideshow then Caption

Save.

Rewrite the CSS to grab the site name div and place it where you want.

Remove some annoying div whitespace

Be happy!


Commerce Line Item Taxonomy Reference Filtered by Product Selection

You have two basic approaches you can use: either treat the stain color as a customization or treat it as a second attribute.  Which you pick depends on a little on your backend process needs and the experience you want to provide.

If you use a second attribute and have a product variation for each stain in each wood, Commerce's default add to cart form should provide the user experience you are describing. You might find it helpful to take a look at this tutorial.

If you want to treat stain as a customization you'll likely want a couple extra modules -- in particular Commerce Customizable Product.  Commerce Guys have a tutorial covering that scenario.


You can assign your admin menu to a block,  and have that block disabled on certain pages.


How to enable Text formats after disabling it in Drupal?

This looks like a bug in Drupal. Anyway the following method works.

Go to your Drupal database (I use phpMyAdmin)
Browse table called 'filter_format'
There You can see list of input formats.  In  'status' column  change
(update) status form 0 to 1. (Disabled status will have 0. So
change to 1 to enable)
Clear your cache. (configuration >> development >> performance)

That's it. Now  all 'Text formats' will be visible under that configuration page.

It works, I tested it :)


Do I need to use a block or form to implement login box, or can I just post to a 'login' url the user details?

You can print login block in the tpl file. No need to use username/password fields of HTML/CSS.

<?php print drupal_get_form('user_login_block'); ?>

For Registration :

<?php print drupal_get_form('user_register_form'); ?>


Strange error updating PHP code in a node

inarray() isn't a PHP function, you're probably looking for in_array() :)

The error you're getting is probably masking the internal Call to undefined function inarray() exception that would be thrown.

EDIT

You also have one too many closing parentheses at the moment, I'd recommend separating out your code to make it cleaner:

<?php

$has_required_role = in_array('approved user', $GLOBALS['user']->roles);
if (user_is_logged_in() && $has_required_role):
  // Do something
endif;

?>


Ajax callback does not replace the form but add a new field

You have to setup a wrapper on the field you want to update :

$form['responsible']['zipcode'] = array(
      '#type'               => 'textfield',
      '#title'              => t('Zipcode'),
      '#default_value'      => empty($account->Dossier->responsable->adresse->codePostal)
                                    ? Null
                                    : $account->Dossier->responsable->adresse->codePostal,
      '#required'           => True,
      '#maxlength'          => 5,
      '#ajax' => array(
        'callback' => 'ajax_get_cities_callback',
        'wrapper' => 'div_city_wrapper', // Changed here
        'method' => 'replace',
      ),
    );

    $form['responsible']['city'] = array(
      '#type'               => 'select',
      '#title'              => t('City'),
      '#options'            => array(),
      '#required'           => True,
      '#prefix'           => '
', // Added this
      '#suffix'           => '
', // Added this
    );

The callback function seems to be fine as it returns the wrapped form element ($form['responsible']['city'])


Drupal behaviour function not getting executed

Lol, it was a silly typo, Sorry. First it's behaviors not behaviours and then the namespace is jQuery not JQuery. Hard to find them on the IDE since it's valid javascript after all.


Change

$(".toggle-visible").click(function () {

for

$('.toggle-visible').unbind('click').bind('click', function() {


Enable modules across platforms using Features/Drush

Yes, this could be automated. I'd suggest the missing component is git or possibly another source control tool, so you can create commits that represent complete sets of configuration changes.

(I see you mention commit in your question so presumably you already use git).


Change homepage template, depending on admin setting

My version is:

Create needed fields (driver image and driver text) for node type
Add checkbox field to the frontpage node type ('Driver mode')
Use template_preprocess_node(&$variables) or hook_node_view() to make some changes if checkbox field is checked


First if you haven't enabled revisions for your content type, please enable like below:

admin/structure/types/manage/[your-content-type]

After that you need to create view to show revisions like below:

This will help you to achieve all information of event on node.

Thanks!


There is no intuitive way to do it, but I found a solution using hook_views_post_execute and hook_form_views_exposed_form_alter:

function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MY-VIEW-NAME') {
    // Regenerate the exposed form after execute the view query
    $exposed_form = $view->display_handler->get_plugin('exposed_form');
    $view->exposed_widgets = $exposed_form->render_exposed_form();
  }
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == 'MY-VIEW-NAME') {
    if ($view->total_rows == 0) {
      // Hide 'results per page' when the view has no results.
      $form['items_per_page']['#access'] = FALSE;
    }
  }
}


How to trigger email by comparing date value in node?

Hi You can add a filed in your content type like date_content_type .
a)chose filed type =date  in content type(admin/structure/types/manage/content_type/fields)

b)add a condition in Rule set
c) select condition= data comparison
d) click on continue button
e) select data selector set your custom date type field
f)then add your time() value and save it . now your date condition rule set will be execute
i hope it will help you
Thanks


Custom template for fields in user profiles

According to Drupal's theme hook suggestions for Drupal 7 the following suggested template names are available:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php

The content-type in this case is user (I guess it means entity type really), so to theme fields just for user profile pages, your template should be called:

field--user.tpl.php

I've just tested that on a dev site and it works perfectly.


Programmatically get a list of all fields?

You should use field_info_fields(), which returns an array containing information about all the defined fields. Its output is similar to the following one.


How I solved my issue with this structure.

I created a manager here my_module/scr/Pluging/myManager.php

Here I have a function with a entityQuery that return a list of nodes.

I created a block here my_module/scr/Pluging/Block/myBlock.php

Here in my build function a call my function in myManager.php and I pass the name of the theme, and a variable with my list of nodes

I updated my .module here my_module/my_module.module

In hook function my_module_theme()
I add my theme and varibles to be pass.

I created a twig here my_module/templates/block-related.html.twig

Here I just do a for to display all field of each node.

Then in my admin/stucture/block I added my block to display in Content section  in specific content type.


How to attach custom CSS to a Views output?

You will need hook_views_pre_render().

And here is an example:

/**
 * Implements hook_views_pre_render().
 */
function base_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'this_is_my_view_with_no_css' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'base/test';
  }
}


Putting modules in sites/samplesite/modules/mymodule is specifically for a multi-site setup.

Drupal won't just load all modules in all sites directories all the time, it will only load modules in the samplesite directory if you are hitting the samplesite domain (or you have an entry in the sites/sites.php file to tell Drupal which domains map to samplesite.

The other option from the page you link to is to make a directory in sites/all/modules that is a symlink to your custom module directory.
Then (assuming you're using Apache), make sure your server is configured to enable the FollowSymLinks option.

There are also a couple of other options:

Add a directory for your modules, eg. sites/all/modules/samplesite or whatever is logical to call it. Exclude that directory in your main .gitignore file. make that new directory a clone of your other modules repository. Alternatively you could not have the sub directory and have separate repositories for each module.
Using a similar directory structure as above, use git subtree to have a repository in a repository (or many individual module repositories if that is your requirement). This seems like a decent post to give you more information on git subtree: http://getlevelten.com/blog/tom-mccracken/smarter-drupal-projects-projects-management-git-subtree

Either method may be preferable depending on your situation however I would probably recommend the subtree method over the completely separate repositories. It would be easier to manage things like deployments, since with the subtree method the main repo still contains everything, even though the source repos are different.


Drupal 6 site updates are not been applied

Did you clear the cache?

Are you sure you are updating the right modules? Drush for example will place modules in sites/all/modules, but if your modules are placed in profiles/profile/modules Drupal might still be reading the old modules.
Drupal won't complain if you are having duplicates, only on enabling.

Can you confirm the modules are read? Check the database, are the module path correct? Is the info file of you modules showing the correct version?


facebook login redirect drupal for facebook module

Drupal for facebook module has a sub module called "FB Rules Integration"
Enable it.

Then create a new rule:
give it a name, something like "after connecting facebook account".

add an action: page redirect
then enter where do you want to redirect to, something like ""

Here is an export of the rule which you can just import.

{ "rules_after_connecting_facebook_account" : {
    "LABEL" : "after connecting facebook account",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "Drupal for Facebook" ],
    "ON" : [ "fb_user_connected", "fb_user_login" ],
    "DO" : [ { "redirect" : { "url" : "\u003Cfront\u003E" } } ]
  }
}


The problem you are noticing is caused from the fact that  us_register_form_submit() for Drupal is the form submission handler for the form returned from us_register_form() and, at the same time, you set us_register_form_submit() as AJAX callback.
That function will be called twice, when AJAX is enabled: first as AJAX callback; then, as form submission handler.

Just change the code as this. (See the /* changed this */ comment.)

  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'us_register_ajax_callback' /* changed this */,
      'wrapper' => 'form-register-wrapper',
      'effect' => 'fade',
    )
  );

AJAX callbacks are not for validating a form, and they will never get called to validate a form, except when you set as AJAX callback a function already used as form validation handler. The purpose of an AJAX callback is reacting when a JavaScript event happens for a form field, and updating the form without returning to the browser a full page.


Rules loop through list and create nodes with custom title

I've figured it out by myself.

Inside the loop when you create a node the pattern used for the title needs to be from the Replacement patterns for Current list item section and in my case, it was the [list-item:title] (the title of the current referenced entity in the loop).


How could I change webform submission tags to common html email tags?

I think you want HTML format template option to send an email with HTML format.

For this, you can use  htmlmail and mailsystem module and enable it and select "HTMLMailSystem" option at admin/config/system/mailsystem.

Now check step 3 at admin/config/system/htmlmail and select "Full HTML".

Now you can config you webform mail setting and select custom mail template and add your HTML tags and inline CSS in div.


I did a google search and found the Commerce Credits module; it sounds like what you're looking to do.

  Commerce Credits allows you to have users buy or win credits. The credits these users buy or win are fully configurable and can expire after some time. The process used for these credits is also fully configurable through Rules. It allows you to entirely define your own process for the payment and the use of these credits.


Use 'Contains' in better exposed filters?

If you use the field as textfield, then you will have options to filters department like above.


Modify output on a page created with the View module

If you want to access modify date and render data so you can use hook_views_pre_render(&$view) $view->result to access result nodes.

and you want to change query condition the you can use hook_views_query_alter(&$view, &$query)


How to show different Views for the same URL with contextual filters

This can be done via a zero-coding solution using Page Manager (CTools), Views Content Panes (CTools) and Panels.

Delete your current view as we want to re-use its path.
Install the three modules.
Create a view as follows:

Create a view of type content (nodes) that shows content of your product type. Add a relationship to the 'taxonomy terms on node' and set it to your 'catalog' vocabulary.

Add a contextual filter of 'Taxonomy term name.' It will automatically select the relationship of 'term'. Hide the view when the filter value is not available.

Now add two 'Content pane' displays to this view.

Content pane 1: This is the view that will show tablets only. Click on 'edit' next to argument input in 'Pane setting' column. Select 'from context', and for the required context, select Taxonomy term->name.

Just above 'argument input' is a setting for 'Category'. Set it to something meaningful, such as 'View Panes - Catalog'.

This first pane will show 'tablets', so add fields that you want on this pane, and change its display Name to Tablets.

Content pane 2: Duplicate pane 1 exactly. It will show all the other terms, so alter the fields and display name.

Add a custom page at admin/structure/pages/add

Set it's path to : catalog/%term

During the wizard setup it will ask you to define the arguments (%term in our case). Set it to term name and limit to vocabulary 'Catalog' so that it looks like this:

Basically what we have done is to tell page manager what the argument %term represents, namely a taxonomy term that belongs to vocabulary 'catalog'.

When selecting a panel layout select single column.

Eventually you will get to the screen where you can add content to the single panel. Add content, and select 'View Panes - Catalog' (remember we defined a meaningful name for the category of our view panes. This is it). This will further display two content panes. You select the content pane you added first, ie the one to show tablets.

Now we need to limit it to only show for terms of type tablet. Select selection rules for your variant, and 'Taxonomy Term.'

Set it up so that it looks like this:

Now update and save your page and you can test that for the path that has an argument of tablet, it will show the view.

Now you need to add a second variant to this panel. To do this you can clone the first variant.

And all that remains now is for you to change this second panel variant slightly.

First, you need to remove the selection rule. As this is a catch-all variant, we do not need a selection rule at all.

Second, you need to remove the view from the panel pane single-column content, and replace it with the second pane that you added.

Now update and save. Make sure that the two variants are in the order: top variant has a selection rule and shows first view pane, and the second variant does not have a selection rule and shows second view pane. Page Variants are selected from top to bottom, with the first variant that matches being used.


Primary admin actions block on view dissapears if change path

The LocalActionsBlock is a block plugin that displays menu action links for a given route based on the LocalActionManager::getActionsFromRoute method.

The route that corresponds to the path /admin/content has action links, but whichever route that corresponds to the path you are using does not have any action links defined.

Action links are defined in MODULENAME.links.action.yml file.

If the desired outcome is to have the local actions that correspond to /admin/content on a different path, then a module should be created that defines additional action links for those routes.


How to include exposed filter name in views data feed export CSV title?

%exposed itself combination of the number of exposed filters you have on your view. When you save file name only with %exposed.csv it should generate file name as per your request would be like "industry_relocation.csv".

So, %exposed will generate based on "FIELDIDENTIFIERNAME_VALUE-ANOTHERFIELD_VALUE".

To generate a custom file name you should use hook_views_pre_build() function. You can find examples here: https://www.drupal.org/project/views_data_export/issues/1288612


How can you filter out other languages Taxonomy Terms from an exposed filter?

It's a long time ago but I leave my comment here for anyone who came across this from Google.
If you have installed "i18nviews" module, then you need to enable Multilingual select (i18n_select) module as well and your list will be filtered out based on the selected language.


Using a node reference in Drupal 7, is there a way to tell what the parent node is?

Reading the text of your question, it looks like you don't necessarily need to know what the parent is but more where the visitor is coming from (and if it is a movie which one).

A possible solution, as you mentioned, would be to add some parameters to the URL.  A simpler option might be just a tiny bit 'o javascript.

Then use the referrer (previously browsed URL) and compare it against the list of movie URLs via JQuery.  If one matches, add a css class to style the link as an indicator.

Where

duck

duck

goose


First, I have to make a configuration in "transition" tab (in the same place where I have defined states for my workflow). After that I can choose it.


View showing related nodes before unrelated nodes

similarterms might fit your bill. If not, here is a comparison of 4 modules that show related content


How can I report to Drupal what is the translation in a language of a string passed to t()?

You could browse to the Translate interface page
(/admin/config/regional/translate/translate).
You could use a .po file and import it (en/admin/config/regional/translate/import).

You'll have to enable the Locale module for this (it's in core).
More information is available on Translating a site interface to different languages.


Drupal incorrectly reporting that permissions need to be set on settings.php

They keyline here is Protection disabled.

Which means you have to check your settings.php or setting.local.php for

$settings['skip_permissions_hardening'] = TRUE;

which must be

$settings['skip_permissions_hardening'] = FALSE;

instead.

If it's not there already, add it.

Flush cache, done.


How to redirect URL with language prefix to the same URL with no prefix (default language)

The below answer requires that at least part of your website is using Page Manager + Panels. In my opinion, they should anyway, but others will disagree.
Both of these modules are tools, as opposed to solutions, so this answer will require that you research and understand these two modules. Link to excellent video tutorial. At the time of writing, this requires the -dev version of Ctools.

At the time of writing, this Ctools patch must be applied for the following instructions to work.

Ensure that the page you want to redirect from, is managed by Page Manager. This page will have 2 variants.
Add a "HTTP response" variant, with a 301 response to cart. More details on this step in another question. It's important that this variant is the topmost one. You can reorder them afterwards, if need be.
On the HTTP variant, go to the "Context" tab on the left side, add a "Language" context, selecting "Current language".
Go to the "Selection rule", and add a "User:Language" == "English".
Add a second variant, this time a Panels variant.
In the second variant, add all the content that you wish to be part of the Japanse page.


The easiest way would be to create a content type called images, remove all the clutter and just add an image field. Since your images are now nodes, you can use any workflow module that you generally use. (Note you will have a overhead of one node for every image you upload)

If you don't want to follow the above approach then you can consider using rules and VBO module along with the the private folder options in image field settings.


Barrio theme not showing user menu drop-down

after investing a lot .. i found that barrio theme is only coming with impelemntation for the navigation menu not for the user account menu .
what i did is i just copy /templates/navigation/menu--main.html.twig and renamed it
menu--account.html.twig

and it works fine


You need to implement a custom module which defines a form and a path to this form.

In Drupal forms are implemented with the Form API. Please check this links for more information

http://drupal.org/node/751826
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

You can define the path by implementing hook_menu.


The 'date restrictions' module might be what you need https://www.drupal.org/project/date_restrictions


how to modify the confirmation email in Ubercart?

You'll want to override the file 'uc_order-customer.tpl.php' found in the ubercart module. The way you do this is:

You need to copy two files from sites/all/modules/ubercart/uc_order/templates
The files to copy are uc_order.tpl.php and uc_order-customer.tpl.php

Then just edit uc_order-customer.tpl.php to your liking.


Strange problem with enabling/disabling modules

My first thought was permissions, but I don't think that incorrect file permissions would result in the kind of problems you're seeing.

Have you checked that the server has all the same extensions installed for PHP? If you've still got access to the old server, put a phpinfo() page on both server and compare the extensions that are available to see if any are missing.


Add PayPal WPS payment payload information to Commerce admin e-mail

You can extract those array and add them data object. After adding them to the token replace function you can use that to create custom tokens which will help you to get the tokens.
That custom tokens can now be used to get the buyer's email address

// Write a code for porting data to token_replace()
$data = new val();
$data->mc_gross = variable_get('mc_gross', '');
$data->invoice = variable_get('invoice', '');
$data->protection_eligibility = variable_get('protection_eligibility', '');
$data->invoice = variable_get('payer_email', '');
token_replace(['payload']', (array) $data);

--------write this in  module_name.tokens.inc file------------------------------------------

 function hook_token_info() {
      $info = array();

      // Add any new tokens.
      $info['tokens']['payload']['mc_gross'] = t('Gross');
      $info['tokens']['payload']['invoice'] = t('Invoice');
      $info['tokens']['payload']['protection_eligibility'] = t('Protection Eligibility');
      $info['tokens']['payload']['payer_email'] = t('Email');
      // Return them.
      return $info;
    }

    function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
     $replacements = array();

    if ($type == 'payload') {
    foreach ($tokens as $name => $original) {
          switch ($name) {
            case 'mc_gross':
              $replacements[$original] = $data['mc_gross'] ;
              break;
            case 'invoice':
              $replacements[$original] = $data['invoice'];
              break;
            case 'protection_eligibility':
              $replacements[$original] =  $data['protection_eligibility'];
              break;
            case 'payer_email':
              $replacements[$original] = $data['payer_email'];
              break;
          }
        }
      }

      return $replacements;
    }


Insert block content into the $content variable to be indexed by search

You can use Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page.

Side effect of managing blocks' content like that is exactly what you want: they can be indexed in search, as they are, in fact, nodes.

If you have dynamically created blocks, you could try to use API provided by Bean module - it works the other way around, exposes blocks as entities, instead of entities as blocks. And if it will not work, well, at least you could use it as an example code for entity <-> block mapping.


I ended up doing node-based permissions instead of field-based. To set it up, I followed the instruction in the video I linked to originally. I simply created content types for SD and HD streams, and am granting access by user to those. I'm probably going to create a view that will go on my original node that displays if the user has the correct permissions.


You need to use image styles to get all the images the same size.

From the admin menu, Configuration > Media > Image styles.

Create a new image style, with a scale and crop attribute to the exact dimensions for your slideshow. Name it "slideshow-image".

Then go back to the slideshow settings on your views slideshow, and select "slideshow-image" as image style.

Now every image will be the same width and height, regardless of the dimensions you upload them in.


Stop registration form from sending mails

Google is your friend, a search for "drupal 7 user registration email settings" produced:

User: access and management settings

configure user registration, user email, and user picture settings on the Account settings page:

Administer > Configuration > People > Account settings) in Drupal 7, and (Administer > Settings > User) in previous versions.


How to add custom css files in a theme from drupal.org?

While you can add your own styles to the Zen theme, it would require that you hack the theme.

What you should do instead when using Zen, is to use it as a base theme, and create what's call a subtheme. That is a theme that will use the styles, templates etc from the Zen theme, but where you can custom overrides, alterations and additions without changing Zen itself.

There is a detailed handbook page where you can read about how this is done and what to be aware of.

Within the Zen theme there is also located a start kit for your subtheme that will help you to do most of what needs to be done, and documentation on what to do in the README file in the theme.