Entityform view block not displaying on page

I solved my own problem by changing the "When the filter value is NOT available" setting to "Provide default value: Content ID from URL" and using the 2nd path component (which is the Entityform submission ID):

This works for me. But I can imagine a scenario where the ID is obscured from the URL and this wouldn't work.


Try the css way

li.menu-mlid-600 > a {
    background-image: url('../images/my_icon.png');
    height: 150px;
    width: 200px;
    text-indent: -9999px;
    display: block;
}

But there are other ways. Google it. Here is another way:

How to use images for menu items in Drupal with a simple preprocessing function


Fatal error: Unsupported operand types in common.inc on line 2287 when registering new user

The problem is in the url() function and is because either the l() or url() functions are being called with a 'query' that is not an array.

Those functions expect the 'query' option to be an array and it is likely that something is passing a string into them.

Do you have any custom code in modules or themes that is calling l() or url()?

I see you have already seen the issue at http://drupal.org/node/1275048

To debug the problem, add this code to the line before the error line:

if (!is_array($options['query'])) {
  die(print_r(func_get_args()));
}

Then reload the page with the error and you will get a bunch of text on a white screen.
Post that text back here and/or that drupal.org issue.

After your latest information
There is a bug in logintoboggan that makes this break whenever you have a redirect url with a query string in it (that is the part with ?key1=value1&key2=value2).

I have made a patch to fix it in the issue mentioned above.


How do I get information about the payment method from the order object programmatically?

The Commerce Payment module adds the payment_method base field when it is enabled, see commerce_payment_entity_base_field_info https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment/commerce_payment.module#L28

You can access the payment method (and gateway) through

$order->get('payment_method')->first()->entity
$order->get('payment_gateway')->first()->entity

Example of when we get the payment method label for the order receipt email.

if (!$order->get('payment_method')->isEmpty()) {
  $variables['payment_method'] = [
    '#markup' => $order->get('payment_method')->first()->entity->label(),
  ];
}

From https://github.com/drupalcommerce/commerce/blob/77b25bf4889a940eed6652475c3952c36144efc0/modules/payment/commerce_payment.module#L122


Override html.tpl.php per node type does not work

you don't need different template for this.
you can set variable in preprocess function and print it.

function MYTHEME_preprocess_html (&$variables, $hook)
  $node = menu_get_object();
  $dont_cache = array('some_type');
  if (!empty($node->nid) && in_array($node->type, $dont_cache)) {//check if it is node and if it shouldnt be cached
    $variables['appcache'] = '';
  }
  else {
    $variables['appcache'] = 'manifest = x.appcache';//put your value here
  }
 }

and then print $appcache in you html.tpl.php


How Update item on the second page in WebForm wizard

When you are in the preview page, you're too late then.

You need to set this in your previous step in a validate function

function webform_certificadoemail_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {

   if ($form_state->get('current_page') == 'step_1') { // or whatever you called the first page
     $element['#element_validate'][] = 'webform_certificadoemail_set_valor';
  }

}

function webform_certificadoemail_set_valor($element, FormStateInterface $form_state) {
   $form_state->setValue('valor','This value is .......');
}


PHP evaluated in rule works locally but not on remote server

Please follow below steps to debug.

Enable Rules Debug settings.
Enable the rule you created.
Check the messages given by rules debug messages on rule activation conditions.

Still if you cannot able to find the solution, check the error logs.

You may need to change the format of collecting node values. Using "und" $node->field_project_skills['und']['0']['tid'] is not the right way. You can check below post that explains right way of reading node values.

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


How to add a CSS class to fields in Drupal 7?

You could use hook_preprocess_field() in which you can define additional classes for your fields.

Check these to get some idea:
http://atendesigngroup.com/blog/adding-css-classes-fields-drupal
https://gist.github.com/1184302


Most likely because the JS code you write in JSFiddle is automatically run when the document is ready; the same isn't true in a normal environment, you need to be explicit:

(function ($) {
  $(function() {
    $('div.applytoggle').click(function() {
      $('.applytoggle_title, .block-tellafriend').toggle();
    });
  });
})(jQuery);

But to be properly Drupal you should use behaviors:

(function ($) {
  Drupal.behaviors.myToggle = {
    attach: function(context, settings) {
      $('div.applytoggle', context).click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
      });
    }
  };
})(jQuery);


You are seeing a page containing just that string because the code you are using is printing the string, and then it exits. This means the theming system used by Drupal is not used to render the page, which will just contain the echoed text.

If you want to theme a page, the page callback needs to return HTML content, as in Drupal 6, or an array that contains the same elements used for the array passed to drupal_render().

As example of page callback, you can look at node_add_page():

function node_add_page() {
  $item = menu_get_item();
  $content = system_admin_menu_block($item);
  // Bypass the node/add listing if only one content type is available.
  if (count($content) == 1) {
    $item = array_shift($content);
    drupal_goto($item['href']);
  }
  return theme('node_add_list', array('content' => $content));
}

An example of page callback that returns an array is node_page_default(), which contains the following code:

function node_page_default() {
  $select = db_select('node', 'n')
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('promote', 1)
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->extend('PagerDefault')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access');

  $nids = $select->execute()->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build = node_view_multiple($nodes);

    // 'rss.xml' is a path, not a file, registered in node_menu().
    drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
    drupal_set_title('');
  }
  else {
    drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);

    $default_message = '
' . t('No front page content has been created yet.') . '
';

    $default_links = array();
    if (_node_add_access()) {
      $default_links[] = l(t('Add new content'), 'node/add');
    }
    if (!empty($default_links)) {
      $default_message .= theme('item_list', array('items' => $default_links));
    }

    $build['default_message'] = array(
      '#markup' => $default_message,
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }
  return $build;
}

You first task is then to incorporate the code there is in the /global_applications/news/home.php file into news_main(), and change it to either return HTML content, or an array as required by drupal_render(). The latter is preferred as it allows other modules to alter the output of the page callback.

Keep in mind that if you need to render a form, you should use the form API, which means that the page callback should be "drupal_get_form," in that case; the first argument passed in "page arguments" is the form ID for the form to render.


CKEditor is missing when editing a page, but works fine when creating a new page

The solution, in my situation, was two-fold.

Multiple CKEditor versions in different locations

First, the main reason was due to having multiple versions of CKEditor installed in different locations.

When you install the CKEditor module, you must also download the actual CKEditor code separately. It can be installed within the modules/ckeditor folder or in libraries. I had updated the module as well as the code, but the old version persisted in the libraries folder. Sometimes CKEditor would load, and other times it wouldn't. Likely it was due to one CKEditor library loading first.

Removing all duplicate references and clearing the cache worked. CKEditor loaded again on most of our sub-sites.

Buggy code on server causing a 500 error

The second problem was due to faulty php code on one of our subsites. For some reason, an unrelated page included other PHP and was somehow being called when CKEditor made the AJAX call to the server. The server responded with a 500 error, and the error logs shows that this unrelated page was somehow being called and failing.

I took out the reference to the buggy code, and CKEditor worked again for that page.

I still have no idea how that code was being called. It was a simple page with a single line of php, including a different file. Yet CKEditor failed to load on every page within the subsite, not just that page. I chalk it up to lacking enough understanding of Drupal internals.


Check if there's a content type published

Something like this?

hook_form_alter() {
  /* check that you're looking at the right form here.. */
    global $user;
    $type_to_check = 'House';

    $query = db_query("SELECT nid FROM node n JOIN users u ON n.uid = u.uid WHERE n.status = 1 AND u.uid = %d AND n.type = '%s'", $user->uid, $type_to_check);

    if(empty(db_result($query))) {
      /* kill the thing you don't want here */
    }
}


How do I get the current path of a block?

Yes, this is because of block caching. The block is built once for the first request and then will stay in the cache forever, until you clear the cache.

You have to set a cache context on the url path:

'#cache' => ['contexts' => ['url.path']],

Then the block will get a cached version for every path.


Upgrading Drupal from 6 to 7 results in double slash being present in image file paths

I migrated my website from an old domain to a new one and this issue came up. Apparently, you should define new paths for website media (e.g. images) here:

http://youwebsite.com/?q=admin/config/media/file-system

There are two paths that must be specified. In my case,

Private: sites/youwebsite.com/private

Public: sites/youwebsite.com/files


Drupal 7 Commerce Stock - Setup stock rules on purchase success for all line items?

Firstly, make sure there is a Line items loop(Data Selector -> commerce-order:commerce-line-items). Then While adding the action, please make sure it is added to the already added Line item Loop(you will find under the 'operations' tab) and NOT as a new 'Add action' at the bottom.


Look at the Bundle Copy module. It'll let you clone a content type.


How to know from variables tu use them in a custom code

May be I'm missing something: I don't understand why you want to programatically make the field required.

Required is not a feature of a field by itself, it is an option you can set on its instance once it's attached to a node, through the admin/structure/types/manage/yourContentType/fields/yourFieldName.


How do I remove gid from og_group_ref field's autocomplete?

Well, I changed the form field og_group_ref to a select box. This is enough to hide the group id number from users and has curbed confusion. Though I'd be happy to hear what others would do in this situation.


Add "- Please Select -" to a required CCK field

Use the key|label format for allowed values:

|-Please Select -
1|option1
2|option2
3|option3

By making the key for "-Please Select -" an empty string, the form can't be submitted with this value.


You could use this module:
https://www.drupal.org/project/bundle_copy

Create a field
Export the bundle/content type
Copy the field in the exported text, paste several times, changing stuff for each field that you want to change for each new field
Import the same bundle/content type


Accessing a block types content programatically

This is a cutdown version of the function to access the block entities.

function _access_content_block_fields_build_arr($bidArr, $fieldRequestArr)
{

    $return = array();
    $blockElements = array();
    $blocks = \Drupal\block_content\Entity\BlockContent::loadMultiple($bidArr);
    foreach ($blocks as $block) {
        foreach ($fieldRequestArr as $fieldRequest) {
            $blockResult = $block->get($fieldRequest)->getValue();
            $blockElements[$fieldRequest] = $blockResult[0];
        }
        $return[] = $blockElements;
    }

    return $return;
}

purencool.com/accessing-a-block-types-content-programatically is the entire function for image fields url as well


How can I add a new module to existing Examples Module?

Thank you so much on starting on this! Examples module have helped many developers overcome the Google fail!

And contributing to it is pretty easy. Personally, to add the module to the main module, I would follow the steps below:

Create a sandbox project with the name foo_example (foo being the nature of your module.
Check if the module satisfies the checklist : https://www.drupal.org/node/2209627
Create an issue in the issue queue with

Title : Add foo_example to the D8 repo.
Category : Plan
Version : 8.x-1.x-dev
Component : Other
Status : Needs Review

Inside the body give a description of what your module does, link it to the sandbox project.

Next, you wait for the reviews :) You might get it reviewed by your peers or friends/IRC so that some obvious issues are spotted on early. And the maintainers of the examples module should be able to review it. And you should also get credits for your work!


Hook or rules event to identify payment failure in Drupal commerce

There is no direct hook or event, but essential to payment transactions in Drupal Commerce is that they should be created for every attempted transaction, not just complete ones. This means when a payment fails, a payment transaction will still be created for your order. Thus you can hook into the payment transaction creation process (or use Rules on the related event) to look for failed transactions based on the transaction status.


Runtime Exception - no weight or dimension field after importing

A patch and code insert posted at comment 14 and 15 at
https://www.drupal.org/project/commerce_migrate/issues/3044987 partially solved this but for the text data field import still did not work to bring in the text


Lightest way to control a field's markup

Yes I think Display Suite is quite an overhead just to control field markup. You could obviously overwrite the templates manually, but for a quicker solution there's the excellent Fences module

Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

The difference in markup is huge. From

Foobar field:&nbsp;

Leaner markup means better front-end performance.

to

Foobar field

Leaner markup means better front-end performance.


Answer is in here: https://www.drupal.org/node/361832#comment-4204294

You'll need a cookie for the user saying what theme they are using. This is done in a hook_init() call.

  // If no cookie is set, set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    setcookie('custom_theme', $GLOBALS['theme'], REQUEST_TIME + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }

Then you'll need to modify the page cache cid ($_SERVER['REQUEST_URI']) in settings.php

// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so switchtheme can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

Code is from D6 but looking it over really quickly it should work for D7.


How to get list of templates for the active theme?

This is a working prototype, although I will be rewritting it a bit later.

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Form\ThemeTemplateForm.
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Theme\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Component\Utility\String;

/**
 * Form for editing template files for current theme.
 */
class ThemeTemplateForm extends FormBase {

  /**
   * The cache backend to use for the complete theme registry data.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The lock backend that should be used.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
   * The module handler to use to load modules.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme registry service.
   *
   * @var \Drupal\Core\Theme\Registry
   */
  protected $registry;

  /**
   * The template that is being edited/created.
   *
   * @var string
   */
  protected $template;

  /**
   * The front-end theme that we'll be editing templates for.
   *
   * @var string
   */
  protected $theme;

  /**
   * Creates ThemeTemplateForm object.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend interface to use for the complete theme registry data.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to use to load modules.
   */
  public function __construct(CacheBackendInterface $cache, LockBackendInterface $lock, ModuleHandlerInterface $module_handler) {
    $this->cache = $cache;
    $this->lock = $lock;
    $this->moduleHandler = $module_handler;
    $this->theme = $this->config('system.theme')->get('default');
    $this->registry = new Registry($this->cache, $this->lock, $this->moduleHandler, $this->theme);

    $template = $this->getRequest()->query->get('template');
    if (!empty($template) && $this->templateIsAllowed($template)) {
      // Always use machine name of the template
      $this->template = str_replace('-', '_', $template);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cache.default'),
      $container->get('lock'),
      $container->get('module_handler')
    );
  }

  /**
   * Returns path to selected theme.
   *
   * @return string
   *   Path relative to Drupal root.
   */
  public function themePath() {
    return drupal_get_path('theme', $this->theme);
  }

  /**
   * Returns the list of template files.
   */
  public function templateList() {
    $list = array_filter($this->registry->get(), function($info) {
      return isset($info['template']);
    });
    // Allow modules to alter the list
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    ksort($list);
    return $list;
  }

  /**
   * Returns list of overridden templates by the front-end theme.
   */
  public function overriddenTemplateList() {
    $list = array_filter($this->templateList(), function($info) {
      // The system will return templates that have preprocess functions
      // implemented by the theme so we need to remove them from the list
      // since they aren't really overridden.
      $theme_path = $this->themePath();
      return $info['theme path'] == $theme_path && (isset($info['path']) && stripos($info['path'], $theme_path) === 0);
    });
    return $list;
  }

  /**
   * See if provided template is allowed.
   *
   * @param string $template
   *   Template name.
   *
   * @return bool
   *   TRUE if template is allowed, FALSE otherwise.
   */
  public function templateIsAllowed($template) {
    $list = $this->templateList();
    $list[$template] = array();
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    // If no module removed the template the template is allowed
    return isset($list[$template]);
  }

  /**
   * Returns information if the provided template is overridden by the theme.
   *
   * @param string $template
   *   The template name.
   *
   * @return bool
   *   Returns TRUE if the template is overridden, FALSE otherwise.
   */
  public function templateIsOverridden($template) {
    $overridden = $this->overriddenTemplateList();
    return isset($overridden[$template]);
  }

  /**
   * Returns the template information.
   *
   * @param string $template
   *   The template name.
   *
   * @return array
   *   Returns the template information array. Empty array is returned
   *   when template was not found.
   */
  public function templateInfo($template) {
    $templates = $this->templateList();
    if (isset($templates[$template])) {
      return $templates[$template];
    } else {
      $base_hook = $this->registry->getBaseHook($template);
      return $base_hook ? $template[$base_hook] : array();
    }
  }

  /**
   * Returns the source path of the template file.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   Path to the source template file relative to Drupal root.
   */
  public function getTemplateSourcePath($template) {
    $info = $this->templateInfo($template);
    return $info['template'] . '.html.twig';
  }

  /**
   * Returns the path of the template in the theme.
   * If the template does not exist(is not overridden yet)
   * the 'templates' directory within the theme directory will
   * be used as destination for the new template. Otherwise
   * 'path' will be used since themes don't have to explicitly put
   * their templates into the 'templates'directory.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   The path to the template file within the theme directory
   *   relative to Drupal root.
   */
  public function getTemplateThemePath($template) {
    $info = $this->templateInfo($template);
    if (isset($info['path']) && stripos($info['path'], $this->themePath()) === 0) {
      return $info['path'] . '/' . str_replace('_', '-', $template) . '.html.twig';
    } else{
      return $this->themePath() . '/templates/' . str_replace('_', '-', $template) . '.html.twig';
    }
  }

  /**
   * See if provided path is allowed for writing/overriding
   * a template file.
   *
   * @param string $path
   *   Path to the template relative to Drupal root.
   *
   * @return bool
   *   TRUE if template can be created/overridden, FALSE otherwise.
   */
  public function pathIsAllowed($path) {
    // Access is allowed only to theme's directory AND this
    // always has to be located within the 'sites' directory.
    return stripos($path, $this->themePath()) === 0 && stripos($path, 'sites/') === 0;
  }

  /**
   * Returns content of requested template.
   * If the template is not implemented by the theme
   * the content of the original template will be returned.
   *
   * @param string $template
   *   Template name.
   * @return string|false
   *   Returns the code of the template or FALSE if template could not be loaded.
   */
  public function getTemplateCode($template) {
    $info = $this->templateInfo($template);
    if (empty($info)) {
      return FALSE;
    }
    $path = isset($info['path']) ? $info['path'] . '/' . $template : $info['template'];
    $path .= '.html.twig';
    return @file_get_contents('.' . base_path() . '/' . $path);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'theme_template_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    $templates = $this->templateList();
    $overridden = $this->overriddenTemplateList();

    if ($this->template) {
      $form['#title'] = $this->t('Template: @template', array('@template' => str_replace('_', '-', $this->template)));
    } else {
      $form['#title'] = $this->t('Create new template');
    }

    $form['left'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-left'
      )
    );

    $form['left']['edit'] = array(
      '#type' => 'textarea',
      '#rows' => 35,
      '#default_value' => $this->template ? $this->getTemplateCode($this->template) : NULL,
      '#required' => TRUE
    );

    $form['left']['name_wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Template name'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE
    );
    $form['left']['name_wrapper']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Template name'),
      '#required' => !$this->template,
      '#field_prefix' => $this->template ? String::checkPlain(str_replace('_', '-', $this->template)) . '--' : NULL
    );

    $form['left']['actions'] = array(
      '#type' => 'actions',
      'save' => array(
        '#type' => 'submit',
        '#name' => 'save',
        '#value' => $this->t('Save')
      ),
      'delete' => array(
        '#type' => 'submit',
        '#name' => 'delete',
        '#value' => $this->t('Delete'),
        '#access' => $this->template && $this->templateIsOverridden($this->template)
      )
    );

    $form['right'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-right'
      ),
      'templates' => array(
        '#theme' => 'item_list',
        '#items' => array()
      )
    );
    foreach ($overridden AS $template => $info) {
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        ),
        '#attributes' => array(
          'class' => array('overridden')
        )
      );
    }
    foreach ($templates AS $template => $info) {
      if (isset($form['right']['templates']['#items'][$template])) {
        continue;
      }
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        )
      );
    }

    if ($this->template && isset($form['right']['templates']['#items'][$this->template])) {
      $form['right']['templates']['#items'][$this->template]['#attributes']['class'][] = 'active';
    }

    $form['#attached'] = array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.themetemplateform.css.less'
      ),
      'library' => array(
        'mymodule/codemirror.twig'
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.themetemplateform.js'
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);
    if (!$this->templateIsAllowed($template)) {
      $this->setFormError('name', $form_state, $this->t("Template name is not allowed."));
    } elseif (!$this->pathIsAllowed($this->getTemplateThemePath($template))) {
      $this->setFormError('name', $form_state, $this->t("Template cannot be changed."));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);

    $tplpath = $this->getTemplateThemePath($template);

    switch ($form_state['triggering_element']['#name']) {
      case 'save':
        $write = @file_put_contents('.' . base_path() . $tplpath, $form_state['values']['edit']);
        if ($write === FALSE) {
          $this->setFormError('edit', $form_state, $this->t("Couldn't write data into file. Please try again or contact help desk."));
        } else {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template',
            'options' => array(
              'query' => array(
                'template' => str_replace('_', '-', $template)
              )
            )
          );
          mymodule_success_message();
        }
        break;

      case 'delete':
        $delete = @unlink('.' . base_path() . $tplpath);
        if ($delete) {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template'
          );
          mymodule_success_message();
        } else {
          $this->setFormError('edit', $form_state, $this->t("Couldn't delete template. File does not exist or is not accessible."));
        }
        break;
    }

    // Always rebuild cache
    Cache::invalidateTags(array('theme_registry' => TRUE));
  }

}


SQL injection and lot of database updates are visible

Install Security Review for maintaining security of your website. Or if you have custom modules, make sure form handling is done only via drupal forms.


Views Block's machine name is being "hashed" (?)

This is because the block module expects a 'delta' (block id) up to 32 characters long. But a view block display can have up to 65 characters: up to 32 characters from the view name and 32 characters from the display name and an hyphen '-' between them.

When the delta exceeds the 32 characters limit, Views will hash it through md5 — it is not a random string. You can safely use it for CSS and jQuery selectors.


I can't speak for Drupal 7/Views 3, but with Views 2 I used the Services module several times to expose content via Views, e.g. Services + SOAP Server + Views to make a bespoke Drupal-powered SOAP API. Perhaps that's not what you're after? SOAP Server would need porting anyway, but perhaps you could experiment with Views 3 and Services 3 and if it works ok with XML-RPC then consider helping port SOAP Server. It probably wouldn't take much work.


How to find non-existing terms based on the list?

If the list is in text file (list.txt), this can be achieved by grep comparision.

First, extract the list of terms from the database by drush:

$ drush sqlq "SELECT name FROM taxonomy_term_data -- WHERE vid = 1" > my_list.txt

Then compare the two lists:

$ grep -Fxv -f my_list.txt list.txt

This will print all the term names which doesn't exist in my_list.txt file.

This solution is based on: Is there a tool to get the lines in one file that are not in another?.


You can use hook_views_data to alter view data like Commerce discounted products. As suggested by Clive, here is the patch which is implementing related feature:

Allow Views to sort / filter based on pre-calculated prices

Other hooks to consider which can allow to alter the views data are:

hook_views_query_alter,
hook_views_pre_render.


getting around recursion when dumping a node?

You cannot get around this in the sense that kpr($variables) will always display this unless you hack the implementation of krumo (the library that kpr uses).

Use

kpr($variables['node'])

to display the node instead.

Also, the node page has a devel tab that does exactly this.


My answer concerns the structural and not the semantic difference between the two.

The table field_data_commerce_line_items corresponds to a standard drupal field. On the other hand commerce_line_item is a table that is managed by one of the modules in the commerce module family.

The table field_config_instance describes the relationships between drupal fields (which are actually tables such as field_data_commerce_line_items) and higher level entity types (i.e. node) and bundles (i.e. content type) that reference them.


Merge multiple block views to a single jump menu

Well... It was very simple. I just used a single block view with all the vocabularies and I just used "Group by" the field vocabulary name. This outputs the option values within optgroups for each vocabulary.


Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node?

In the CKEditor page you have to select Enable in CKEditor -> EDITOR APPEARANCE -> "Default editor state".

This you can find in admin/config/content/ckeditor/edit/<yourtextformat>

Or if you dont want to enable that by default, then you can click manually "Switch to to rich text editor" in /node/<nid>/edit


Click here:

Then set the column to sortable, set the default sort order, and set the column to the default sort column:

Save settings and done.


how to make term reference field choose term from a multi level taxonomy vocabulary

Try Simple Hierarchical Select, it is less buggy than the more complex one.


How do you add taxonomy with fields to page--node.tpl.php?

This can be done without any need to use php code and tpl.php files.  The capability to generate content based upon a taxonomy including images can be done by using the modules.  These modules are intended to define and implement a site's design and are well written and tested. Template files will handle the layout and appearance of your content, but are not necessary for the content you have described.  IF you are not familiar with Drupal, take a little time to learn more about what it can do before you make changes in the template files.  If you are familiar with Drupal, then it might be helpful to understand more regarding what you are trying to do.


$img_file = file_get_contents("Path/to/module/Images/image1.jpeg");
  $img_file = file_save_data($img_file, file_directory_path() .'/path2imagefield_folder/image1.jpeg', FILE_EXISTS_RENAME);
  $node->field_image_cache = array(
    array(
      'fid' => 'upload',
      'title' => basename($img_file),
      'filename' => basename($img_file),
      'filepath' => $img_file,
      'filesize' => filesize($img_file),
    ),
  );


choosing image style during content creation

The Formatter Field module looks like the right one. Here is a quote about it (from the module's project page):

... provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


Every time a page is rendered, the Tour module load all guided tours for this one. Those tours are added at the end of the DOM (with hook_page_bottom) with a css 'hidden' class. Then the Tour JS script (tour.js) handles those hidden elements by watching a triggering html element targeted by the id toolbar-tab-tour. If any tour is registered for the current page, that toolbar-tab-tourelement will also be hidden by tour.js.
I did this thing for showing a student role tour. I simply created a plugin block within my module:

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'StudentTourBlock' block.
 *
 * @Block(
 *  id = "student_tour_block",
 *  admin_label = @Translation("Student tour block"),
 * )
 */
class StudentTourBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    if (\Drupal::currentUser()->hasPermission('access tour') && !\Drupal::currentUser()->hasPermission('access toolbar')) {

      $build = [
        'tour_button' => [
          '#type' => 'html_tag',
          '#tag' => 'button',
          '#value' => ' ' . $this->t('Help'),
          '#attributes' => [
            'id' => 'toolbar-tab-tour',
            'class' => ['btn btn-success btn-xs hidden-sm hidden-xs']
          ],
          '#cache' => [
            'contexts' => [
              'user.permissions'
            ]
          ],
          '#attached' => [
            'library' => [
              'tour/tour',
            ],
          ],
        ]
      ];
      return $build;
    }
    else
      return [];
  }

}

Don't forget to attach the tour/tour library :)


Emoji works in a site but not in the other site on the same host

First I SUGGEST to take a look at https://www.drupal.org/project/utf8mb4_convert module

try to adding   'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci', configs to your settings.php file.

after adding it should be something like :

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
);

if it does not work for you, probably you need to change MySQL configs. use the following config in your MySQL configuration ( usually my.cnf or my.ini)

# Use UTF8MB4 as the character set
collation-server = utf8mb4_unicode_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4

another suggestion:

ALTER DATABASE dbname CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;') AS mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "dbname"
AND TABLE_TYPE="BASE TABLE"

FINAL STEP to make the warning go away and get a clean Status Report:

USE YOURDATABASENAME;INSERT INTO variable SET name='drupal_all_databases_are_utf8mb4', value='b:1;';

my.ini or my.cnf
add:

[mysqld]
innodb_large_prefix=true
innodb_file_format=barracuda
innodb_file_per_table=true

settings.php

  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',


How to create a view filter plugin to filter a column created by a view field plugin

After some digging I will answer myself to this question: it is not possible to create a filter on a non existent DB column.
How to solve this issue:
In my example, the values of this non existent column are calculated via the function return_1_2_or_3_depending_on_dyn_data_like_the_current_date($node).
We couldn't use this function to create the filter. Instead, for each value returned by the function (in my case 1,2 or 3), we have to write a query with the same logic used in the "dropped" function.
All the logic must reside in the query method of the filter plugin.
Here is an example:
1- Add the filter in hook_views_data_alter
function mymodule_views_data_alter(array &$data) {
  $data['node_field_data']['internal_status_filter'] = [
    'title' => t('Filter by Internal Status'),
    'filter' => [
      'title' => t('Filter by Internal Status'),
      'help' => t('Bla bla'),
      'id' => 'internal_status_filter',
    ],
  ];
}

2-Create the filter plugin (In my case, I have extended the inOperator Class)
/**
 * Filters the internal status of a node
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("internal_status_filter")
 */
class InternalStatus extends InOperator {

  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Available Status');
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  public function query() {
    $configuration = [
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'field'      => 'entity_id',
      'type'       => 'LEFT',
      'extra_operator'   => 'AND',
    ];
    if (
    $selected_status = $this->value[0];
    if ($this->operator == 'in') {
      $this->ensureMyTable();
      switch ($selected_status) {
        case (1):
          //Add a condition on another field
          $table_field='node__field_another_field';
          $configuration['table']=$table_field;
          $join = Views::pluginManager('join')->createInstance('standard', $configuration);
          $this->query->addRelationship($table_field, $join, 'node_field_data');
          $this->query->addWhere('AND', "${table_field}.field_simulation_is_past_value", 1, '=');
          //Add as many condition to get what you need
          break;
          ....
       }
     }
  }

  public function generateOptions() {
    return [
      1=>'Status 1',
      2=>'Status 2',
      3=>'Status 3',
    ];
  }

Make sure that your annotation at the top of the file @ViewsFilter("internal_status_filter") is the same id than the ones defined in hook_views_data_alter


Proper way to define weight / country wise shipping rates

Have you looked at these two modules?

Commerce Shipping Postal Code Weight
Commerce Shipping Weight Tariff


Boolean field inside node twig renders ok but does not work in if statement

In content is the render array of the field output. A boolean is probably a text in #markup. What text this is for 0/1 can be configured in the display mode. But don't try to find it there, better use for coding the node. There you get the values directly from the database.

{% if node.field_sample.value %}


How to remove "There is currently no content classified with this term." phrase?

Using mytheme_preprocess(&$variables, $hook) to override the $variables['page']['content']['system_main']['no_content'] variable.

function mytheme_preprocess(&$variables, $hook) {
  if(isset($variables['page']['content']['system_main']['no_content'])) {
    unset($variables['page']['content']['system_main']['no_content']);
  }
}


Your function isn't actually returning anything. So

'#markup' => print_payment_table()

will result in markup being empty. I've noticed in your function you have a lot of print statements. It would better to build a string variable in your table construction. Like:

$string = "
";
$string .= "
".$stuff"
";
$string .=
;

then at the end of the function, return $string.

EDIT: -----------------------
your functions should be seperated, not defined iside of each other.

So:

function table_builder($node){
//do stuff
   return $stuff;
}

function *my_mod*_node_view($node, $view_mode, $langcode){
   $node->'#markup' .= table_builder($node);
}


Ajax Function jquery Fails to send data Drupal 7

In function set_speaker_state() , the $ symbol doesn't recognized, you must put set_speaker_state() function into:

(function($, window, undefined){
 // here!
})(jQuery, window);


How do I create a directory in webform for uploaded files

First go to "Administer -> Site Configuration -> File System -> File System Path" configuration page. verify your file path and temp path given no error.

change permissions(writable) to files folder under "sites/default/files".


In my case, I actually didn't need server-side validation; I just needed validation to serve as a reminder to fill out an exposed field. Instead, I added field-level validation with required.

$(context).find('.field-name-field-stop-displaying-after').hide();
$(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
$(context).find("input[name='field_status[und]']").click(function() {
    var radioSelect = $(this).val();
    if (radioSelect == 0) {
        $(context).find('.field-name-field-stop-displaying-after').hide();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
    } else {
        $(context).find('.field-name-field-stop-displaying-after').show();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',true);
    }
});


Displaying a block only for nodes of a specific content type, how do I check the content type using PHP?

// Only show if $match is true
$match = FALSE;

// Which node types
$types = ['kYn'];

// Match current node type with array of types
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  $type = $node->type;
  $match |= in_array($type, $types);
}

return $match;

source : http://drupal.org/node/115419


You need to convert array to string to show it as link. May this works for you.

class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
$title = 'Custom Link';
$url = \Drupal\Core\Url::fromUri('http://www.test.com');
$link = \Drupal\Core\Link::fromTextAndUrl($title, $url)->toString();

      return $link;
    }


That code is overriding the fields structure. That fields have a specific structure and that code is changing it completely, so in submit the values are not recognized.

I recommend you use devel module and use dpm function to inspect the structure of that fields:

  dpm($form['field_cr_case_number']);
  dpm($form['field_cr_case_title']);

To make your form changes you must only add the #ajax property to your field:

$form['field_cr_case_number'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'case_records_database_ajax_callback',
  'event' => 'change',
  'method' => 'replace',
  'wrapper' => 'div-case-name-element-wrapper',
);

And to add the wrapper and #value to your second field do something like this:

$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#prefix'] = '
';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#suffix'] = '
';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#value'] = $cs_short_title;

In this question is also explained how to make the ajax callback.


Style block based on configuration setting

I'd probably just use the Block Class module and assign a classes like block-left and block-right.

  Block Class allows users to add classes to any block through the
  block's configuration interface. By adding a very short snippet of PHP
  to a theme's block.tpl.php file, classes can be added to the parent
  <div class="block ..."> element of a block. Hooray for more powerful
  block theming!


Building a view programmatically fails when filtering specific nids but not others

The argument to the $views->set_arguments() function should be an array containing the arguments, even if only one, so, try:

$view->set_arguments(array(35));

or

$view->set_arguments(array($nid));

instead of passing the value in directly.

As to why it was working before sometimes, I am betting it was working with nids 1 thru 9 only, because there, for example, if $nid='4', $nid[0]=='4' is also true, but if $nid='35', $nid[0]=='35' is false (it is '3') but I leave this to another discussion, but look up "php strings as arrays" if you want to delve into it further.  This Strings as Arrays Q&A gives a brief description/introduction.


You should use Autocomplete Delux module. After installing and enabling the module you can change your tag field widget in your form.
Autocomplete Delux:

This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy.


How do you turn off comments, by default, for a module defined content type?

These instructions will enable you to identify and set any variable you'd like in Drupal 7. Please feel free to ask for clarification.

I'd start by installing the Devel module so you can see the variable you need to set. This will allow you to inspect the array where this setting is defined.

Visit a node of the content type you're working with. You'll see a tab called "Devel". Follow it and you'll be able to see the array which defines a node of this content type. There should be a value called "Comment", and I believe it needs to be set to "1" to disable comments.

As a sidenote, the Features Overrides module does this by setting
$overrides["variable.comment_mycontenttype.value"] = '1';

But, since we're not using that module, we'll set it manually.

You should be able to define that variable inside your module code by using the variable_set() function.

That code can live inside hook_update_N(), which is executed when update.php is run. Simply add the code for your update hook inside your custom module and run update.php on your site.


You can "Tag" rules which is a nice feature to group / filter them.


How do customize the HTML output around a specific field using field.tpl

You need identify the field machine name. For example if you have a field called Name and have a machine name field_name the field tpl name should be field--field-name.tpl.php.

See this thread as well as it provides a comprehensive guide on how to override field template using hook_theme and preprocess function.

One of the most handy helper I used is $conf['theme_debug'] = TRUE; in settings.php. It will show a template suggestion in HTML source.


Where is the module registry stored outside the database?

Common causes:

External cache (Memcache, etc) that is not purged on rebuild
Your SQL import contains cache from prod (I tend to make sure backups make cache tables structure-only).
Your SQL is imported into a DB which contains tables, but does not drop some of them (such as cache). (I personally drop and create the DB before each import).
The module is still enabled/present in the system table (confirm in your SQL that the row in the system table is gone/disabled & uninstalled).
Something else on your site depends on it and is re-enabling it (eg master module, feature dependencies, etc (although dependencies usually block things from being disabled)).
Sometimes worth doing a drush cc drush after importing the SQL. When in doubt, clear caches ;)


If you care for SEO, consider using Metatag module:

  Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.

For Drupal 6 there is Nodewords module, that was inspiration for Metatag as far as I know.

To force https where you need it, use Secure Pages. You can check "Switch back to http pages when there are no matches" to make sure pages not required to use SSL will never actually use it - that way you save both server's CPU load (as encoding isn't free) and problems with duplicated content. It's pretty convenient, and a good first step, but it should not stop you from setting canonical, of course.


Updating all existing user's custom field

Found out why it was not working (Which also explains why none of my debugging was displaying.) I had to skip over the the user with UID of 0 and modify how I set the field value or else the user_save function would break the code (For anyone that is interested.)

/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    if($user->uid == 0)
    {
      continue;
    }

    $edit = array(
      'field_my_field' => array(
        'und' => array(
          0 => array(
            'value' => 'test'
            )
          )
        )
      );
    user_save($user, $edit);
  }
}


How do I use a jQuery version different from the default one used by core?

Add your custom jQuery library in your mytheme.libraries.yml:

jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

Then override the core jQuery library in your mytheme.info.yml:

libraries-override:
  # Replace an entire library.
  core/jquery: mytheme/jquery-custom


As far as I know you can empty the sessions table and all users will be logged out. There may be an issue though, depending on the modules that you have installed. For example, modules that implement hook_user_logout() will never get their actions fired, which could be an issue. Check to make sure none of your installed modules is implementing this hook.


Output the term title on page--custom.html.twig

Try with:

{% if node.field_work__services|length %}

        {% for item in node.field_work__services %}

{{ item.entity.label }}

        {% endfor %}

{% endif %}


Are there any other settings besides php.ini to allow file upload?

Please read through this documentation:
https://www.drupal.org/node/97193

Depending on your HTML form and server configuration if you have a 1MB filesize limit; uploaded files close to your maximum filesize may not successfully upload to a webserver because a file is sent as apart of a multi-part HTTP transmission.

You want to assure post_max_size is typicaly 2x or 3x larger than your upload_max_filesize. Brief discussion on this can be found here:
https://stackoverflow.com/a/15077229/1491507

Googling PHP maximum post size and file sizes should lead to similar documentation on php.net and other resources.


Selling per-node access without creating two entities

It really depends on how you want to display the content to your customers. For example, you could show a teaser of the content page via Views. Access to the full content page could be contingent on node access implemented via the Content Access module. You then just have to figure out how to display to the customer which articles they have full access to - for example, a "Purchased articles" View that shows all fully accessible articles using a node access filter.


Custom search_api query for categories block

The following code does what we need.

  /**
   * @return int[]
   */
  function getCountsByTid($indexName, $facetFieldName) {

    $options = [];
    $options['search_api_facets'][$facetFieldName] = [
      'field' => $facetFieldName,
      // No limit.
      'limit' => -1,
      'operator' => 'and',
      'min_count' => '1',
      'missing' => '0',
    ];

    $q = search_api_query($indexName, $options);
    $q->range(0, 0);
    $q->fields([]);

    // Skip hook_search_api_query_alter().
    $result = $q->getIndex()->server()->search($q);

    if (!isset($result['search_api_facets'][$facetFieldName])) {
      return [];
    }

    $countsByTid = [];
    foreach ($result['search_api_facets'][$facetFieldName] as $item) {
      // The tid comes in a weird format.
      $tid = (int)substr($item['filter'], 1, -1);
      $count = $item['count'];
      $countsByTid[$tid] = $count;
    }

    return $countsByTid;
  }

Normally, the $options['search_api_facets'] would be set in search_api_facetapi_search_api_query_alter(). However, this adds ALL facets, instead of just a specific facet. Also it limits the number of facet counts to 50. See #12132878: search_api_facetapi pollutes and slows all queries

Instead we set this option manually, and then skip the $q->execute() that would trigger hook_search_api_query_alter().

SearchApiService classes always add quotes around the search values, which seems quite pointless to me.

We could get the raw tids from $result['search_api_solr_response']->facet_counts->facet_fields->$propkey, with $propkey = 'im_' . str_replace(':', '$', $facetFieldName), but this only applies to search_api_solr.


Block feed importer to create a new term in taxonomy

I achieved it using Feeds Tamper. We can control the fields that we want to import.


Imageapi Optimize - enabled libraries exec

so what does the second one do?

It'll optimise the already-optimised image from the previous plugin as best as it can. Which won't be much.

  I suppose it should be radio buttons rather then checkboxes.

Perhaps; but that would remove the ability to have combinations of different kinds of plugins (not just file size optimisers) in the future, so it might be a bit short-sighted to say that.


How to show a user login form on a completely separate page?

Easiest way would be to remove all permissions from the anonymous user at /admin/people/permissions and then set the 403 page on /admin/config/system/site-information to /user.


How to access same name table fields in table join using db_fetch_object

You should name your fields in the SELECT, then you can use AS to rename them to something clearer:

SELECT fielda, fieldb, A.SNO AS thisone, B.SNO AS thatone, FROM... etc


How to find Image URI in Kint via .entity in the node tree

Every image in Drupal 8 is a file entity.

You can try in template_preprocess_node():

$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;


Is it possible to load a webform that is using a specific custom handler?

You can use the next code:
$webforms = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple();
  foreach ($webforms as $webform) {
    foreach ($webform->getHandlers() as $handler) {
      if ($handler->getPluginId() == 'your_custom_handler') {
        // do your logic.
        break;
      }
    }
  }


Keep entity object after getTitle() method in render() method in a custom controller

When I try to save the entity to my class as $this->entity It gets
lost when the Render() function gets called.

Use a service. Services are singletons and when the class resolver finds an existing service it loads the instance from the container and doesn't create a new class instance:
defaults:
  _controller: 'my_service:render'
  _title_callback: 'my_service:getTitle'

For good practice this is not really necessary in this case because entities are cached in memory automatically and loading an entity twice doesn't have a performance impact.
Good practice, though, would be to load the entity via route parameter upcasting:
foobar.view:
  path: '/foobar/{foobar_placeholder}'
  defaults:
    _controller: '\Drupal\foobar\Controller\Foobar::content'
    _title: 'Oh yeah foobar'
  options:
    parameters:
      foobar_placeholder:
        type: entity:foobar

Example from https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/parameter-upcasting-in-routes


One way -- possibly the easiest way -- is to create a page containing whatever you want to be displayed on the home page, then going to www.yoursite.com/?q=admin/config/system/site-information if you're using Drupal 7 (or www.yoursite.com/?q=admin/settings/site-information if you're using Drupal 6), and then changing Default front page from node to node/1 (assuming the page you created was normally located at www.example.com/node/1).


Extra fields in 'manage display' for content types

When using Display Suite, you have to first save the layout you're going to use, then the fields will appear.

Under the "Current Template" section, "None" is probably selected. For a default display, select the "One Column layout" and click save. These fields should then populate.


If you want the list of fields per content type (now bundles in Drupal 7), you should use field_info_instances().

//List all fields of bundle "your_content_type" using devel module
dsm(field_info_instances('node', 'your_content_type'));


There are a few ways.

If your context allows for Dependency injection, inject the entity_type.manager service and use it like so:

$node = $this->entityTypeManager->getStorage('node')->load($nid);

If not you can still use the entity_type.manager service:

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

If you prefer, you can use the Node class directly:

$node = \Drupal\node\Entity\Node::load($nid);


Remove wrapping div from field type radios (Drupal 7)

The div.form-radios is set by the theme wrapper of the radios. Use this code to prevent the theme wrapper from adding the additional div:

function no_name_form($form, &$form_submit) {
  $form['radios'] = array(
    '#type'    => 'radios',
    '#title'   =>'Question text',
    '#options' => array(
        '1' => t('yes'),
        '0' => t('no')
    ),
    '#theme'   => 'no_name_radios',
    '#theme_wrappers' => array(),
  );
  return $form;
}


Hugronaphor's comment helped me find a solution that worked for me... I'm just going to explain it clearly.

Browse to /admin/config/content/ckeditor
Edit the CKEditor GLOBAL Profile
Under the "Advanced Settings", change the "Path to CKEditor"

What you enter here will depend on whether you have downloaded and installed the full package (as described in my initial question) and where you have installed it, or whether you want to use the CDN.
The instructions given below the text box are quite clear, but much like anything, it's just knowing where to look !

Because I'd already installed the full package and installed it to "modules/ckeditor/ckeditor" it means instead of using the CDN, I entered "%m/ckeditor" which made it work perfectly.

If I'd installed the full package to "/sites/all/libraries/ckeditor" I would have entered "%l/ckeditor"

...and if I wanted to use the CDN version, I would have entered "//cdn.ckeditor.com/4.4.3/full-all"  Although, I assume this version number will possibly change in the future


How to sort a View according to contextual filters?

The Views Arguments Extras module (for Drupal 7) seems to do what you are looking for. According to the module page, it provides the following:

  Argument Order Sort

  a sort handler, that allows for the order of items to be based on
  their order in a multi-value argument

This particular component is ported to Drupal 8: Views Argument Order Sort:

  Using this module will give you a new sort type with a variety of
  options where you can choose what field to apply the argument values
  to for sorting.


How are contextual arguments specified explicitly in the URL?

Contextual filters always use AND operator between them. Unless you use a special module to change it Views Contextual Filters OR.

But there are conditions under which a Contextual filter will show all the results as if it hasn't been applied. This means that it could be seen as if the OR operator is applied.

Contextual filters have two major options in their configuration:

`When the filter value is NOT available`

and

`When the filter value IS available or a default is provided`

Under the former options there is always the Exceptions setting, where the default value is all (you can change it if you think it would be better for UX).

But this means that you can use that expression in the URL as a way to temporarily cancel that Contextual filter, so you can test the others if you have more than one.

field_1_value/all/all

or in your case to ignore the first and the second one:

all/all/field_3_value

To apply the first one only you can use:

field_1_value/all/all

but you could also use

field_1_value

if you have configured the last two Filters to use
Display all results for the specified field or
Provide default value.

There is also the setting Action to take if filter value does not validate under Specify validation criteria where you can choose the option Display all results for the specified field. So you can also use this in combination with other settings, if it makes sense in your specific case.

Setting up a Contextual filter isn't a trivial thing, there are different "paths" that can come out out of a single filter, and you'll get a different set of results.


Per the d.o. requirements page, D6's requirements are:

Web server: Apache, Nginx, or Microsoft IIS
Database: MySQL 4.1 or higher, PostgreSQL 7.1,
PHP: PHP 5.x only (5.2.5 or higher recommended). Warning: support for PHP 4.x has been dropped. Drupal core should work with PHP 5.3.x, but PHP 5.3.x and higher may produce errors or unexpected behavior especially for contributed modules and themes.


How do I add Custom fields to the Order Information Checkout page in Commerce 2?

I found the answer to this, it's not very obvious at the moment due to the lack of documentation but it's blinding simple when you know how.

Install the new profile module.
https://www.drupal.org/project/profile

Edit the page:

configuration > people > user profile

Here you can add commerce2 user pane or new fields.

For me I needed to make a new Content type form that the user could create and fill out as part of the checkout process, so I used the inline entity form.

Really you could use any field collections or paragraph's to add to the user fields as I notice there is a new patch to support field group and paragrahs.

I hope that helps someone else looking for this answer.


Views: how to override a linked "Content: Title" field's href programmatically?

Here is the solution:

Put the following code to your theme's template.php file, and substitute MYTHEME with your own theme's name (or you can even put it in your module's file, and substitute MYTHEME with your module's machine name):

<?php

/**
 * Implements template_preprocess_views_view_field()
 * @see http://api.drupal.org/api/views/theme!theme.inc/function/template_preprocess_views_view_field/7
 * Process a single field within a view.
 * This preprocess function isn't normally run, as a function is used by default, for performance. However, by creating a template, this preprocess should get picked up.
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  // @see http://drupal.org/node/939462#comment-4476264
  if (isset($vars['view']->name)) {
    $function = 'MYTHEME_preprocess_views_view_field__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
      $function($vars);
      // we can return to only use the specific preprocess function (it matters if there are more codes below in this function)...
      return;
    }
  }
}
// */

/**
 * Implements template_views_view_field__VIEW_MACHINE_NAME__DISPLAY_MACHINE_NAME()
 * @see template_views_view_field()
 * @see MYTHEME_views_view_field()
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field__block_of_articles__block(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  if (isset($vars['row']->nid, $vars['row']->node_title)) {
    $path    = drupal_get_path_alias('node/' . $vars['row']->nid);
    $options = array();
    if (isset($_GET['page'])) {
      $options['query'] = array(
        'page' => $_GET['page']
      );
    }

    $vars['output'] = l($vars['row']->node_title, $path, $options);
  }
}
// */

Don't forget to clear your cache!
This should only be done in cases when it's really needed: for example when an Article listing block (like this really simple one which you can import: http://pastebin.com/tmq0kZwT) is also displayed next to the article nodes, and we want the current pager position to be "remembered".


Is there an ready-made solution to mark edited form fields?

I've only seen Track Field Changes, but that doesn't give immediate visual feedback.

Edit: I know you asked for something that was already out in the wild, but the following might be useful.

I guess you could write something custom relatively easily though using jQuery's .change event.

Something like the following I guess (code will need checking but it should be pretty near).

JavaScript

(function ($) {
    Drupal.behaviors.formFieldTracker = {
      attach: function(){
        $(input).change(function(){
          $(this).addClass('field-edited');
        }));
      }
    }
})(jQuery)

Module

function MYMODULE_preprocess_page(&$vars) {
  // Only add the JavaScript on admin pages as defined by hook_admin_paths()
  if (path_is_admin(current_path())) {
    $path = drupal_get_path('module', 'MYMODULE');
    drupal_add_js($path . '/js/MYSCRIPT.js');
    $vars['scripts'] = drupal_get_js();
  }
}

Then you could add whatever CSS you fancy afterwards:

.field-edited:after {
  content: 'Edited';
  display: inline-block;
  color: #F00;
  font-style: italic;
}


Creating a duplicate button for multiple entry field collection field

I think you should be using the Replicate API for this purpose. The module provides an API to duplicate entity along with many hooks. It's targeted towards developers however there are several modules build on top of it.

With respect to your use case, there is an implementation for supporting field collections. I think it will be the closest solution for you what you.


Search results showing duplicate entries

You seem to have added a field (Field: Image). If there are nodes with multiple field items (multiple images), then they will show up multiple times. To avoid that, enable aggregation in the advanced settings. It might also be possible to configure the field to only list the first value, not exactly sure.


How to send POST request to https using \Drupal::httpClient()?

The error message should inform you what is going on. You are using a self-signed certificate locally. This probably won't be an issue on your production sites, but this is not really useful for local development.

Inspect the \Drupal::httpClient() static method you may discover that it uses the http_client_factory:fromOptions service. Use this directly allows you to pass options into Guzzle to allow requests to sites using self-signed certificates.

$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

Obviously this is not ideal. You should probably parameterize the URL that you are using instead of hard coding the URL. Then locally you can test without a self-signed cert or HTTPS. Or parameterize the options you pass into Guzzle so that verify => TRUE when you're on production. It is not recommended to set it to FALSE and this is a security risk.


See hook_menu for reference under using Wildcards but you need to tell your menu which page arguments are going to be passed into your function:

$items['committee'] = array(
        'title' => 'Committee Page',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/roster'] = array(
        'title' => 'Roster',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/charter'] = array(
        'title' => 'Charter',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

In this case array(1) would be the second positiong (as array(0) would be the first) if your wildcard resided in committee/charter/% it would be array(2).

I do not believe your items will be showing in the menu because there are wild cards, you would have to do that in your local tasks instead as the menu would not have any idea.


Change field options after form has been filled with data

I'm guessing the type is Long Text with Summary. If thats the case, can't you just go to admin/structure/types/manage/[your content type]/fields/[your field name] and uncheck Summary input.

Drupal will then automatically create a summary if it's required to, just as it would if you had chosen Long Text (without summary).


Use loadMultiple():

$storage = \Drupal::entityTypeManager()->getStorage('default_entity');
$config_entities = $storage->loadMultiple();
$list = [];
foreach ($config_entities as $id => $entity) {
  $list[$id] = $entity->label();
}


Bootstrap theme overrides "theme_list_item" function and removes div's "item-list" class

1) Default markup. To return default item list markup just do this:

function bootstrap_subtheme_item_list($variables) {
  return theme_item_list($variables);
}

2) But. Your issue is not caused by Bootstrap markup. Try this:

$form['header'] = array(
  '#markup' => $stages_list,
);

You are using fieldset incorrectly, learn Form API Reference.


How do I export/import all the relations created by Relation module?

Export/Import of entities is something that is not standardized and there are many methods of approaching the problem. This is also something Drupal 8 is attempting to solve.

Currently you want to look at Deploy and UUID Features are your best bet. Neither have stable D7 releases, but I played around with deploy and using the views plugin I was able to export entities.

The primary issues with content (entities vs configuration) is that content many times needs to be merged from one server to another so it ends up being a fairly complicated proposition.


How to use multiple text fields in widget "image" in content type

You can take a look on Image Field Caption module.

Adds an extra text area for captions on image fields.

Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

Media module also work for you.


You could examine the Profile Entity class here profile / src / Entity / ProfileInterface.php, showing you a list of public methods including its getter methods, eg.:
$profile->getCreatedTime();

Additionally and similar as with Entities in general, you can also call data via either $entity->get('field_name')->getValue() or $entity->field_name->getValue().
See more on that here: Get information from an entity/ Entity methods
So if you have a Profile Entity with a field machine name address, then you could get its data like:
$profile = \Drupal\profile\Entity\Profile::load(123);
$profile->get('address')->getValue();
$profile->address->getValue();


How to pass dynamic parameters through a local action button?

Local actions and local tasks are quite similar, so looking at the Customising local task behavior I've managed to pass in dynamic route parameters to my local actions by specifying the class parameter (MyClassName) in my_module.links.action.yml and overriding the LocalActionDefault::getRouteParameters() method in that class. Only one initial cache rebuild was required.

use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class MyClassName extends LocalActionDefault {

  public function getRouteParameters(RouteMatchInterface $route_match) {
    return array(
      'my_local_action_parameter' => $route_match->getParameter('existing_parameter_from_route')
    );
  }
}


One approach to version the API is to add a version number to the URL.
So, for example your Views REST display URL /rest/taxonomy-list would become /rest/v1/taxonomy-list or /rest/v2/taxonomy-list
You could duplicate the existing Views display to adjust the fields and new URL in a new REST display.
For custom REST API plugins, you can extend the existing RestResource and give it a new URL, e.g:
use Drupal\my_module\MyRestResource;

/**
 * Sample Rest Resource
 *
 * @RestResource(
 *   id = “my_rest_resource_v2”,
 *   label = @Translation(“My Rest Resource (v2)“),
 *   uri_paths = {
 *     "canonical" = "/api/rest/v2/endpoint”
 *   }
 * )
 */
class MyRestResourceV2 extends MyRestResource {

  // Extend and override functions here

}


Priority of execution of hooks in different modules

The system table has a 'weight' field. The hooks are executed in that order.

You can change during install with this code:

function your_module_name_install() {
  db_update('system')
    ->fields(array('weight' => your_preferred_weight))
    ->condition('name', '[your_module_name]', '=')
    ->execute();
}

Source: https://www.drupal.org/node/110238


You can use file_url_transform_relative():

/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by file_create_url().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @see file_create_url()
 */
function file_url_transform_relative($file_url) {


Custom module block programmatically assigning it to a specific role

This is how I did it.

function _<module-name>_check_user_access() {
  $roles = [
    'editor',
    'admin',
  ];

  $current_role = \Drupal::currentUser()->getRoles();
  foreach($roles as $role) {
    if($role == $current_role[1]) {
      return TRUE;
    }
  }

  return FALSE;
}

See my blog post for more information about it


You can create new file and call it as theme-settings.php and add the following to it or even add this to THEME_NAME.theme file.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;

function THEME_NAME_form_system_theme_settings_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  $form['THEME_NAME_settings']['social_icon']['social_url'] = array(
    '#type' => 'textfield',
    '#title' => t('Social Link'),
    '#default_value' => theme_get_setting('social_url', 'THEME_NAME'),
  );
}

Then you need to add the following to THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['social_url'] = theme_get_setting('social_url','THEME_NAME');
}

Then you can use it in the twig file.

To have a default value for the social url, you can include it in your  config/install/THEME.settings.yml

Hope it helps!


The following code exposes an API that returns the field and properties data of the user entity type.
It uses a recursive method and the nature of typed_data to achieve such goal.

The post and get methods are called because they are the lowercased versions of GET and POST.

The below code relies on Drupal 8.2 because GET requests are problematic in Drupal 8.1 See this issue

<?php

namespace Drupal\sandbox\Plugin\rest\resource;

use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceDefinitionInterface;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\Core\TypedData\Type\BooleanInterface;
use Drupal\Core\TypedData\Type\FloatInterface;
use Drupal\Core\TypedData\Type\IntegerInterface;
use Drupal\Core\TypedData\Type\StringInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Represents entities as resources.
 *
 * @see \Drupal\rest\Plugin\Deriver\EntityDeriver
 *
 * @RestResource(
 *   id = "user_type",
 *   label = @Translation("User type"),
 *   uri_paths = {
 *     "canonical" = "/user_type",
 *   }
 * )
 */
class UserTypeResource extends ResourceBase {

  /**
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $fieldManager;

  /**
   * UserTypeResource constructor.
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param array $serializer_formats
   * @param \Psr\Log\LoggerInterface $logger
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, \Psr\Log\LoggerInterface $logger, EntityFieldManagerInterface $field_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->fieldManager = $field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('entity_field.manager')
    );
  }

  public function post() {
    return $this->resolve();
  }

  public function get() {
    return $this->resolve();
  }

  protected function resolve() {
    $field_definitions = $this->fieldManager->getFieldDefinitions('user', 'user');

    $data = [
      'type' => 'Object',
      'fields' => [],
    ];

    foreach ($field_definitions as $field_name => $field_definition) {
      /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition */
      $storage_definition = $field_definition->getFieldStorageDefinition();
      $data['fields'][$field_name] = [
        'type' => 'Array',
        'element' => $this->transformFieldDefinition($storage_definition),
      ];
    }

    return new ModifiedResourceResponse($data);
  }

  protected function transformFieldDefinition(FieldStorageDefinitionInterface $storage_definition) {
    $fields = [];

    foreach ($storage_definition->getPropertyDefinitions() as $property_name => $property_definition) {
      $fields[$property_name] = $this->transformDataDefinition($property_definition);
    }

    return [
      'type' => 'Object',
      'fields' => $fields,
    ];
  }

  protected function transformDataDefinition(DataDefinitionInterface $definition) {
    if ($definition instanceof ComplexDataDefinitionInterface) {
      $fields = [];

      foreach ($definition->getPropertyDefinitions() as $property_name => $property_definition) {
        $fields[$property_name] = $this->transformDataDefinition($property_definition);
      }

      return [
        'type' => 'Object',
        'fields' => $fields,
      ];
    }
    elseif ($definition instanceof ListDataDefinitionInterface) {
      return [
        'type' => 'Array',
        'element' => $this->transformDataDefinition($definition->getItemDefinition()),
      ];
    }
    elseif ($definition instanceof DataReferenceDefinitionInterface) {
      return $this->transformDataDefinition($definition->getTargetDefinition());
    }
    else {
      $type = "Unknown ({$definition->getDataType()})";

      $class = new \ReflectionClass($definition->getClass());
      if ($class->isSubclassOf(PrimitiveInterface::class)) {

        if ($class->isSubclassOf(StringInterface::class)) {
          $type = 'String';
        }
        elseif ($class->isSubclassOf(IntegerInterface::class) || $class->isSubclassOf(FloatInterface::class)) {
          $type = 'Number';
        }
        elseif ($class->isSubclassOf(BooleanInterface::class)) {
          $type = 'Boolean';
        }
      }
      else {
        switch ($definition->getDataType()) {
          case 'language':
            $type = 'String';
            break;
        }
      }

      return [
        'type' => $type,
      ];
    }
  }

}

The definition of rest.resource.user_type configuration.

id: user_type
plugin_id: 'user_type'
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie
  POST:
    supported_formats:
      - json
    supported_auth:
      - cookie
dependencies: {}


Override site's registration restriction on accepting invite

This is a bit hacky, but it could be done with the following:

  my_website.com/admin/config/people/accounts

  Who can register accounts? - Visitors

  Install https://www.drupal.org/project/redirect and add redirect /user/register to a basic page which says something like "Sorry, to register you need an invite. Please contact us to receive an invite."

Invited people can now log in to site but there is no way for people to access the user register page, as that page will redirect.


I have next that work successfully:

  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn&#39;t be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }


You can add the file to a theme's or module's .info file using scripts[]:

scripts[] = js/my-script.js

The path should be relative to your module root.

See also Writing theme .info files and Writing module .info files.


How to add IE specific stylesheet in drupal 7 in drupal way

You don't hack Drupal core if you add that to your THEME's html.tpl.php but anyway you can try implementing hook_html_head_alter() in your theme's template.php


Which Rules event can I use to send a weekly mail to all users using Rules?

Below is a blue print of how I would resolve this challenge, without any custom code needed ...

Step 1: Enable the 'Rules Once per Day' module

Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

On top of that, also note what's mentioned on its project page, ie:

  The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

With that, you should be able to adapt any rule to perform its rules actions only once a week.

Step 2: Create your custom rule

As per your "mail to all users" requirement (for which you want to use the Rules module), just create some custom rule to do so. The most straight forward Rules Action to use for this, seems to be "Send an eMail to all users of a selected role", whereas role is just authenticated users.

If however you want more granularity in the set of users to be selected, you could use the Views Rules module instead. for more details on such approach, refer to the Plan b part of my answer to "What's wrong in my rule for sending e-mails using VBO?".


Version of Drupal is no longer supported [Using the latest 7.42 release]. After automatic update

You updated Drupal core outside of updating the entire distribution. You're seeing this message because of the Distribution Update module and having upgraded outside of the distribution.

On that note, CK 2.32 uses Drupal 7.41. I will roll CK 2.33 with 7.42


Using the Sites module with a multiligual site

You cannot use the PURL "path" method with i18n (Internationalization) because it conflicts with i18n outbound url rewrites - specifically the detection and maintaining of region and language using the path.

I'm not sure if PURL domain and query string methods will still work.

I too am looking at this because I have a project where we've used PURL to maintain a brand identifier with the commerce module, but we want to also use i18n in future. I've used i18n and Domain Access modules before, both separately and together and they play well. Domain Access though is not what you want.

My suggestion would be to treat your "set1" and "set2" like regions. The i18n module lets you specify a region and language that is detected from the path. This is so you can have things like

Germany with German (DE-de)
Germany with French (DE-fr)
Germany with English (DE-en)
United States with Spanish (US-es)
United States with English (US-en)
etc.

So, in these examples we have a country-code and then a language. The i18n module allows you to detect first the country code as a region and the language code for language and then customise the settings based on both.

I would suggest you use this method to specify custom languages where you have a "set1" for region and a standard language code for language, defaulting to English where no language is defined (ie. LANGUAGE_NONE).

I'm going to give this a go myself for my project. I'll let you know how I go.


Creating a custom login system by developing a new module

You don't need any other modules, to just show a form. Your code is not correct in some points, though, and that needs to be corrected.

A form validation handler doesn't return TRUE nor FALSE; it just calls form_set_error() in case the submitted data doesn't pass the validation.

A form submission handler doesn't validate the submitted data; that is the task of the form validation handlers. The purpose of the form submission handlers is to take the necessary actions (e.g. loading data from the database, saving data to the database), but they don't return anything.

You don't inject values entered from user directly in the query, as you do with db_query(). That is the perfect way of given a malicious user access to the user #1 access, for example, and without the user knowing the user #1 account.
Always use placeholders for input obtained from users, when you are using it in a query. See what user_login_authenticate_validate() does.

$account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();

The correct way to show a message to the user is using drupal_set_message(). In the specific case, showing a message with a logout link is not much helpful, since the users will not see it anymore after moving to a different page. In any case, you don't use echo() to print anything on a Drupal page from a form submission (or validation) handler.


Use template_preprocess_field in your template.php and add your variable there.

Then in your tpl.php you can easily access that variable and render that variable along with your markup.


What would be the Drupal way to have a preloader overlay divs untill they were finished loading?


Using the built in summary feature when using ONLY paragraphs module for text

Well, looks like it is time again to answer my own question!

So, since the Metatag Module I want to also use is based on tokens anyway, I have managed to implement this using my own module which in turn just defines an additional custom token which in turn returns my desired summary. Here is what my current custom_summary_token.module code looks like right now (still work in progress):

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\paragraphs\Entity\Paragraph;

function custom_summary_token_token_info(){
    $type = [
        'name' => t('Nodes'),
        'description' => t('Tokens related to individual nodes.'),
        'needs-data' => 'node'
    ];

    $node['custom_summary'] = array(
        'name' => t("Custom Summary"),
        'description' => t("Token for dynamically generating a node summary, depending on the content. Used for extracting text when not using standard body field, but only paragraphs."),
    );

    return [
        'types' => ['node' => $type],
        'tokens' => ['node' => $node],
    ];
}

function custom_summary_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata){

    if (!isset($data['node'])) { return; }

    $replacements = array();
    $node = $data['node'];

    if($type == 'node' && !empty($node)) {

        foreach ($tokens as $name => $original) {

            switch ($name) {

                case 'custom_summary':

                    if (!empty($node->body->value)) {

                        $text = strip_tags($node->body->value);

                    } else if ($node->field_summary && !empty($node->field_summary->getValue())) {

                        $text = $node->field_summary->getValue()[0]["value"];

                    } else if ($node->field_paragraph_test && !empty($node->field_paragraph_test->getValue())) {

                        foreach ($node->field_paragraph_test->getValue() as $key => $value) {
                            $paragraph = FALSE;
                            if (!empty($value['entity'])) {
                                $paragraph = $value['entity']; // Use that, we're probably previewing.
                            } elseif (!empty($value['target_id'])) {
                                $paragraph = Paragraph::load($value['target_id']);
                            }
                            if ($paragraph !== FALSE && $paragraph instanceof Paragraph && $paragraph->getType() === "text") {
                                $text = strip_tags($paragraph->get('field_text_body')->value);
                                break;
                            }
                        }

                    }

                    if (strlen($text) > 150) {
                        $text = substr($text, 0, 150)." ...";
                    }

                    $text = str_replace("&nbsp;", " ", $text); // filter out artefact when editing with chrome
                    $replacements[$original] = $text;
                    break;
            }
        }
    }

    return $replacements;

}

So what this does in that tokens hook is (after checking that we have the right token of course) first to look for an ordinary default body text which is not empty. Simply because then this also works for my other (in this case also simpler) content types. Then, the code looks for a custom field named field_summary. Turned out that some users actually want to create a custom summary, so yeah now they can do that as well. For those who don't (the majority ...), the code then looks for the first paragraph instance which is also a text block (and not empty). Last but not least, tags are stripped, and the whole thing is truncated to 150 chars, with some "..." appended for good measure.

Now, I can use this just like any token in my Metatag setup: [node:custom_summary], and - with a little help from the twig tweak module - also in any template:

{{ drupal_token('node:custom_summary', { node: node }) }}

Of course this implementation still might be too naive or there would be an even better way, also I am not sure how big the performance impact of such a solution is. But hey - at least this works!

What would you think?


drupal is welcoming other user after login


The specific function you are looking for in the database abstraction API is db_close() but you may be able to solve your problem through another route by increasing your max connections.

See this earlier thread on drupal.stackexchange for guidance on increasing max_connections. You might also be having a problem with slow / stalled queries that are trying up limited query slots, this thread offers advice on how to debug.


drupal_goto() not remove url path of 404 page

Hope this will help you,

In Drupal 7 , you can check whether the page is 404 page or not. If it is a 404 page then change the drupal_goto $path parameter.

drupal_get_http_header : Gets the HTTP response headers for the current page.

  $status = drupal_get_http_header("status");
  $path = ($status == '404 Not Found'){
    //change the path from example.com/nopage/searchyour/trips to example.com/searchyour/trips
    drupal_goto('/searchyour/trips', array('query' => $query));
  }else{
    drupal_goto('/searchyour/trips', array('query' => $query));
  }


Can you get any view to list content based on a field value?

Solution

Get the view, and the view alone to do what you want. You need a contextual filter on the field you want to match against. Test the view out in the views UI.
Add a content pane display, this requires the views content module to be enabled. In the pane settings, find argument inputs settings (Sorry, no UI in front of me, that setting could be something else). In here you can tell Views what type of data the View should expect for the contextual filter. Pick From context. You'll be presented with a looong list of available options, it's easy to get this wrong, be careful. Scroll down until you under Node find the field you are trying to match against. If you have multiple fields with the same label, there is no easy way to know which is which. Yes, it's crap, you will have to go trial-and-error until this gets fixed. Save the view.
Go into Panels. Ensure that the new view is visible under the View panes category, not just Views. Add the view, tell it which node to get data from, which is usually just one, save.

Troubleshooting

This setup is non-trivial for a lot of users. I find that the common most problem people hit is configuring the view to require a certain type of input. If you can't get this to work, there are two things to try.

The Panels process for identifying which Views are valid, seemingly can get stuck sometimes. Clear caches, and resave both the View and Page.
In the Views arguments configuration, set the argument to be optional. This is not really what you want, but if this causes the View to show up in the Panels UI, then we know the problem is that Panels does not have access to the information that the View says it wants, which at least narrows the problem down a lot.


How to redefine a message type for drupal_set_message?

The status is arbitrary, so:

drupal_set_message('A message', 'custom_status');

Will produce

A message

Notice the "custom_status" class, which you can target with CSS.


There are two ways you can do this:

The Upload File Replace module. A small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.
Specify an optional subdirectory within the field setting where files will be stored using a unique token in the file path settings. (e.g. [current-date:raw])