Which is more performant: entity_metadata_wrapper or field_get_items?

The short answer: field_get_items() is more performant than entity_metadata_wrapper().

Check out the code for these functions:

field_get_items()
entity_metadata_wrapper()

Both require that you pass along the entity, which has already been loaded from the database. For example:

$node = node_load(123);
$items = field_get_items('node', $node, 'field_my_field_name');
print $items[0]['value'];

or, as you've already suggested:

$wrapper = entity_metadata_wrapper('node', $node);
$field = $wrapper->field_my_field_name->value();
print $field['safe_value'];

Both of these instances kind of bother me because of the silly logic in trying to get a value that's already available to you, but they are certainly useful in lots of cases.

You could just do print $node->field_my_field_name[LANGUAGE_NONE][0]['value']; but that would throw PHP notice errors if the field doesn't have a value, since you're trying to access arrays that may not exist (i.e. [LANGUAGE_NONE][0]['value']). I find myself doing this quite often lately:

if ($field = field_get_items('node', $node, 'field_my_field_name')) {
  print $field[0]['value'];
}

which is a lot cleaner than doing:

if (isset($node->field_my_field_name[LANGUAGE_NONE]) && isset($node->field_my_field_name[LANGUAGE_NONE][0])) {
  print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];
}

If you look at the code for field_get_items()) you'll see that it's doing nothing more then ensuring that the field's array has data in the curent language and then returns it. So, the overhead of running such a tiny function is negligible, but if you are really concerned with performance you can just do your own check if the data exists and then print it.

Edit: Since field_get_items() runs field_language() there would actually be a bigger performance hit than just checking the language, so, if you already know that $entity->language exists, you could just write your own super-performant function:

function my_super_performant_field_value_getter($entity, $field_name) {
  return isset($entity->{$field_name}[{$entity->language}]) ? $entity->{$field_name}[{$entity->language}] : FALSE;
}


How to hide custom fields on the menu item form?

hook_entity_base_field_info will add fields to the entire entity. If you want to hide the fields in specific forms, you will have to use a form alter to hide the fields. The following code might be what you are looking for.

/**
 * Implement hook_form_FORM_ID_alter();
 */
function modulename_form_menu_link_content_menu_link_content_form_alter(&$form, FormStateInterface $form_state) {
  $name = $form_state->getFormObject()->getEntity()->getMenuName();
  if ($name !== 'my-menu') {
    $form['show_mobile']['#access'] = FALSE;
    $form['svg_icon']['#access'] = FALSE;
  }
}

Change my-menu with the menu machine name of the only menu that you want the fields to appear on.


Drush command not found after Drush completely installed

Once you have installed Drush, you need to ensure that you ~/vendor/bin directory is in your $PATH, as explained in the installation instructions (Note: this link no longer works)

Add export PATH="$HOME/.composer/vendor/bin:$PATH" to your ~/.bash_profile or ~/.bashrc, and then run source ~/.bash_profile (or ~/.bashrc).

I would recommend against installing Drush 9 via composer require at this time. Sticking with Drush 8 is probably best; if you want to use Drush 9, use a simpler installation method, such downloading the .phar, or clone the repository and run composer install in the directory Drush was cloned to.


Ran into exactly the same issue, here is my solution. In my case for field 'first' I have a select list of contact types in field 'second' it is a plain text field. For one of the source fields I am converting a taxonomy term to a plain text so there is a service injected to do a lookup up from the source database. The migration config looks like this for the fields I want to convert:

  field_phoned:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_office
      source: field_phoned
  field_mobile_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_mobile
      source: field_mobile_number
  field_skype_contact:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: skype
      source: field_skype_contact
  field_whatsapp_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: whatsapp
      source: field_whatsapp_number
  field_location_taxonomy:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: location
      source: field_location_taxonomy

The process plugin 'add_contact_info_field':

<?php

namespace Drupal\custom_migrate_tools\Plugin\migrate\process;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\custom_migrate_tools\TermLookupInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'AddParagraphBody' migrate process plugin.
 *
 * @MigrateProcessPlugin(
 *  id = "add_contact_info_field"
 * )
 */
class AddContactInfoField extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Lookup source term service.
   *
   * @var \Drupal\custom_migrate_tools\TermLookupInterface
   */
  protected $termLookup;

  /**
   * The migration.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * TaxonomyLookup constructor.
   *
   * @param array $configuration
   * @param $pluginId
   * @param $pluginDefinition
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   * @param \Drupal\custom_migrate_tools\TermLookupInterface $termLookup
   */
  public function __construct(array $configuration,
                              $pluginId, $pluginDefinition,
                              MigrationInterface $migration,
                              TermLookupInterface $termLookup) {
    parent::__construct($configuration, $pluginId, $pluginDefinition);
    $this->migration = $migration;
    $this->termLookup = $termLookup;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $pluginId,
      $pluginDefinition,
      $migration,
      $container->get('custom_migrate_tools.term_lookup')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $contact_info = [];
    if ($label = $this->configuration['target_label']) {
      $contact_info[0]['first'] = $label;
    }
    else {
      $contact_info[0]['first'] = $label;
    }

    if ($destination_property == 'field_location_taxonomy') {
      $contact_info[0]['second'] = $this->termLookup->getTermName($value['target_id'])->name;
    }
    else {
      $contact_info[0]['second'] = $value['value'];
    }

    if ($targetField = $this->configuration['target_field']) {
      if ($field_contact_info = $row->getDestinationProperty($targetField)) {
        array_push($field_contact_info, reset($contact_info));
      }
      else {
        $field_contact_info = $contact_info;
      }
      $row->setDestinationProperty($targetField, $field_contact_info);
    }
    return $value;
  }

}


One way can be to get role id from role name than use role, since we fetch the rid dynamically so there is no chance of conflict. An example will go like

// Helper function to get user role by username.
function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);
}

// Role ID for Member role
$member_rid =  get_role_by_name("Member");

// Use Rid now
$roles = array(
$member_rid => 'Member');


In many respects the Paragraphs module appears to be a fork of Field Collection. Functionally, the difference between the modules lies in how their respective field widgets operate. The Field Collection widget allows users to embed multiple instances of a single field collection bundle in a node, while Paragraphs allows users to select a different bundle for each instance they embed using the Paragraphs widget. Both of these methods are extremely valuable and I now find myself combining field collections and paragraphs on the same node.

Read more in the issue about "Merge with Paragraphs module?".


how to create a apply button in view table result ?

1) On the left side of the Views admin screen, click the "Add" button next to Fields to add a new field

2) Search for "custom field" and select Custom Field

3) For Create a Label, enter: Apply for Job

4) For Text, enter:

Apply for Job

(class="button" is what makes the link look like a button)

5) Replace /link/to/destination above with the location of where they can apply for the job. If you need to use replacements in the URL like the node ID number, add the NID field to the view, and replace the URL with something like /node/[nid]/apply

View attached screenshot for what it should look like.


template_preprocess_forum_topic_list() initializes the variable with the value returned from _theme_table_cell().

global $forum_topic_list_header;

// Create the tablesorting header.
$ts = tablesort_init($forum_topic_list_header);
$header = '';
foreach ($forum_topic_list_header as $cell) {
  $cell = tablesort_header($cell, $forum_topic_list_header, $ts);
  $header .= _theme_table_cell($cell, TRUE);
}
$variables['header'] = $header;

function _theme_table_cell($cell, $header = FALSE) {
  $attributes = '';

  if (is_array($cell)) {
    $data = isset($cell['data']) ? $cell['data'] : '';
    $header |= isset($cell['header']);
    unset($cell['data']);
    unset($cell['header']);
    $attributes = drupal_attributes($cell);
  }
  else {
    $data = $cell;
  }

  if ($header) {
    $output = "$data	";
  }
  else {
    $output = "$data	";
  }

  return $output;
}

The variable $variables['header'] in template_preprocess_forum_topic_list() is the same variable that in forum-topic-list.tpl.php is accessed as $header.


Drupal 7 Weform 4 attach file message stays even though correct size file is updated

Have you checked PHP's own maximum upload file size?

Default in php.ini is usually this:

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

You can check your own site's setting at your sites /admin/reports/status/php


Using reverse proxy prevent login flooding

I had to edit the $conf['reverse_proxy_addresses'] = array('a.b.c.d', ...); part, and put in the address of reverse proxy address (127.0.0.1).


On account creation, the message is not displayed

A workaround would be to manually create message in hook_user_insert, with code like:

function mymodule_user_insert(&$edit, $account, $category) {
  drupal_set_message(t('Account created, wait for approval.'), 'status');
}

Alternative place is hook_entity_insert:

function mymodule_entity_insert($entity, $type) {
  if ($type == 'user') {
    drupal_set_message(t('Account created, wait for approval.'), 'status');
  }
}

Problem is - it is possible that the same error will hide this one too. Benefit: it's easier to experiment with small custom hook, than to debug core.


How do I force a 403/410 error code for specific users and content?

drupal_goto Can help you

drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

Parameters

$path:
A Drupal path or a full URL.

$query:
A URL-encoded query string to append to the link, or an array of query
key/value-pairs without any URL-encoding. Passed to url().

$fragment:
A destination fragment identifier (named anchor).

$http_response_code:
Valid values for an actual "goto" as per RFC 2616 section 10.3 are:

301 Moved Permanently (the recommended value for most redirects)
302 Found (default in Drupal and PHP, sometimes used for spamming search
engines)
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect (alternative to "503 Site Down for Maintenance")

Note: Other values are defined by RFC 2616, but are rarely used and poorly
supported.


Appending markup to privatemsg message body

(I haven't used privatemsg) ... but sure it's doable because of a new feature in D7:

  Instead of attachments, private messages are fieldable and any number
  and combination of fields can be added to them.

So what you do is code up a custom module that defines a custom "sent_by_sitename" field that is a text field_type. Then in your presave hook you would just do:

$message->sent_by_sitename = 'some_sitename_in_your_multisite_install';

Then you could alter your message display to show this new field with a custom formatter that adds the markup and leading "This message sent by " markup.

I dont have the code to do this offhand (its probably about 30 lines). Here is a similar request of adding custom fields to the default user object in drupal -- your request is different regarding privatemsg but you probably will still use some of the same functions: add-properties-to-an-entity-hook-schema-alter

So in short:

Define your custom field in your custom module, eg hook_field_info()
on module_enable() and module_disable() attach your field to the message entity, eg field_create_field() and field_create_instance()
alter your existing privatemsg API call to set this new field value instead of raw HTML.
alter your privatemsg message display to show your new field with its associated field_formatter to be at the bottom of the message display.


Language information in Session for anonymous users

For Drupal 7 it's normal, there's no session created automatically for anonymous users, we created a new module that stores and detects the language inside a cookie, see locale_cookie, the benefit of a cookie is that your session table stays small.


Contextual links for custom blocks: Add "Edit block content"

The missing "edit" link was a bug in early Drupal 8 betas, and has been fixed as of beta5:
https://www.drupal.org/node/2284917


Advertisement view sorted by Nodequeue relationship

I figured it out.
You need to tell the view to have a relation from Advertisement to Node (Ad: Aid). Do this by going to Relationships and adding a relationship based upon "Ad: Aid". You'll then see under Fields all of the Node fields such as Title and Body available. Then add another relationship "(Node) Nodequeue: Queue".


fetching records from webform_submitted_data table through following source code but showing error

Try below code,

You can retrieve node webform all submissions using  webform_get_submissions which accepts an array of filters.. As per the error you mentioned in the question seems like below code is causing problem

echo $val = $submission->data[15][0];

I would suggest printing the information that you got before you try to fetch the data so that you know you are correclty accessing the array results.. print_r will assist you to see the results..

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 159));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '
';print_r($row);print '
';
        print '
';print_r($data);print '
';
    }
}

Extract the information you want from $row and $data ...


Just tested this on a fresh install of 8.0.6 and I think I see what is going on.

I saved a block using the Full HTML format with the following content:

&nbsp;

And had it display in my sidebar region. Everything worked fine, there are two links in this block, that can only really be seen if you inspect the html.

However, when going to edit the block again, with the default as-installed text format settings, ckeditor will wrap my first link with a P tag, and completely remove the second link.

So, you have a few options.

Enter an &nbsp; character inside your empty tag.
Disable the ckeditor for your format and just use the plain-text editor, with the Full HTML (or a custom filter of your creation) filter.

Ckeditor is doing the fixing of your html, so getting rid of it will solve your problem.


Make a separate list of selected content

You can use Nodequeues to accomplish this really effectively.


How can I add extra data to a file field?

You can't by default, but check out the File Entity module.

  This module extends the core file entity, making it a full fledged
  entity, allowing for fields, display formatters, and more.

This allows you to add fields (such as a height/width field) to files in the same way that you add fields any other fieldable entity (nodes, terms etc...).


How to get the managed_file progress bar working in a custom theme?

Found, I think: My theme was based on Bootstrap 2, and I was getting bit by a problem of Drupal and Bootstrap disagreeing on what sort of thing the "Upload" button should be:

https://drupal.org/node/2155419

Since I'm still on Bootstrap 2 (I think) I wasn't having the problem with the input fields being out of order, but I did need to deal with the behavior assignments.  In addition to the fix outlined in the cited page, I also needed to run the assignments on page load / document ready to get things properly assigned.


The select element is built in Weight::processWeight():

  /**
   * Expands a weight element into a select element.
   */
  public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#is_weight'] = TRUE;

    $element_info_manager = \Drupal::service('element_info');
    // If the number of options is small enough, use a select field.
    $max_elements = \Drupal::config('system.site')->get('weight_select_max');
    if ($element['#delta'] <= $max_elements) {
      $element['#type'] = 'select';
      $weights = [];
      for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
        $weights[$n] = $n;
      }
      $element['#options'] = $weights;
      $element += $element_info_manager->getInfo('select');
    }
    // Otherwise, use a text field.
    else {
      $element['#type'] = 'number';
      // Use a field big enough to fit most weights.
      $element['#size'] = 10;
      $element += $element_info_manager->getInfo('number');
    }

    return $element;
  }

Which is only called in form building, not in normal rendering.


Expand sub-menus on hover in a menu block

You can use this module Nice Menus. Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)

  Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.


Use functions: uc_file_user_downloads function and theme function

If it is drupal 6 in order to print the  table you can simply do print uc_file_user_downloads($account); ,this function will internally call the theme function theme_uc_file_user_downloads

What you are trying in your code is combination of both.So in drupal 6 try witih the following code.

global $user;
print uc_file_user_downloads($user);

In drupal 7 the function uc_file_user_downloads($account); returns array unlike html in drupal 6. So try the following with drupal 7

module_load_include('inc', 'uc_file', 'uc_file.pages');
global $user;
$table = uc_file_user_downloads($user);
print drupal_render($table['downloads']);


With Omega, how to inline branding zone with header zone

You would just use 1 of the zones, not both. Either move the header regions to the branding zone, or move the branding zone to the header region.
Think of it as zones being vertical and regions being horizontal, if you want some regions inline, they should be in the same zone.


Intrigued by your question, I found the same issue with trying to use a date field to store a time as the date field stores a Unix Timestamp.

A Drupal 7 project called timefield allows you to store a time which has no relation to a date, even has duration, and display configuration. I have not used it in a live environment, but looks like a solution for you.


Limit user (not role) publication of content to specific menu subtree

Drupal's menu module is pretty good thing, but written with simple cases in mind.

Solution without using menu system:

Create a taxonomy tree representing the part of menu that gets repeated for each user
On node creation, omit menu altogether, let user choose taxonomy term from a tree instead
Use Views to render it all as one big tree, theming it so it would look like a menu

Added benefit is that you can easily move elements from user to user, allow users to change their names etc and it just works, no need to edit same thing in 2 places. And you can rename "menu element" once, in taxonomy, instead of "once per user".


The -auto-orient operator is part of the ImageMagick image processing toolkit, to select the correct orientation of an image based on its EXIF data. Have a look at How to detect shot angle of photo ... for a more complete explanation.

The ImageMagick module integrates this function in Drupal, but they are still having an issue with autorotation. A recent patch is available there.

Your best bet is to try it out and see if it corrects your problem.


I think your general premise is sound. I'd be tempted to use hook_user_insert() instead, which is called after the user has been created, rather than before, since:

Your module can't actually fail to create a group or insert a new one.
hook_user_presave is really for modules that want to serialize (simple) data to be stored in the users table itself, which isn't what you're doing.

The necessary hooks in OG7 are all there for checking and creating groups and inserting users.


Entity Reference

  Provides a field type that can reference arbitrary entities:

To your course content type add new field of entity ref type and refer videos content type.
Add second field to your course ct and refer instructions content type.

When you create new course you will be able to select instructions and videos

Tutorial (simple)

Youtube tutorial


How can I AND two OR statements with the #states feature of Drupal 7?

I found out that this can be done this way:

$form['non_phd_student'] = array(
    '#type' => 'item',
    // This #states rule says that the "non_phd_student" item should only
    // be shown if the "student_type" form element is set to "Undergraduate" or "graduate".
    '#states' => array(
      'visible' => array(
        array(
          array(':input[name="student_type"]' => array('value' => 'undergraduate')),
          array(':input[name="student_type"]' => array('value' => 'graduate')),
        )

      ),
    ),
);
$form['non_phd_student']['thanks'] = array(
  '#type' => 'item',
  '#description' => t('Thanks for providing your graduate status and your country');
  '#states' => array(
  //Because this has ['non_phd_student']
  //The or in $form['non_phd_student'] is ANDed into the or of this statement.
  // Action to take: Make visible.
  'visible' => array(
    array(
      array(':input[name="school_country"]' => array('value' => t('Other'))),
      array(':input[name="school_country"]' => array('value' => 'UK')),
    )
  ),
),
);

There is another answer that takes more work. We can do this because AND statements can be inside the OR statements. Also, because of Propositional Logic we can get the same results this way:

'visible' => array(
  array(
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '10'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '10'),

    ),
  ),

),


What all is required to completely uninstall Webform?

Like I said you need to uninstall it from /modules UI and then delete its folder from /site/all/modules.

If you take a look at webform module source code, in webform.install under function webform_uninstall() you will find this code:

foreach (node_type_get_names() as $type => $name) {
    variable_del('webform_node_' . $type);
}

as you can see it deletes every node which has webform type. for more details of what is going to be deleted after uninstalling the module, check the  function webform_install() and function webform_uninstall() functions in the mentioned file.


I assume you have already added the image and event description, etc. as fields for the event content type.
For custom content types, normally you control the display using the Manage Display link from Structure -> Content Types -> Edit.
You can rearrange the fields how you want in the UI, and you can also use a Twig theme template to customize the specific HTML.  Core also provides the Layout Builder module to make something more complex.
It's also possible to use Views to overwrite the default content page, but it is usually easier to use Twig templates and/or Layout Builder.  If you do want to use Views, take a look at the core Taxonomy Term display to see how Views can be used to override a path for a custom content type.


Like I also wrote in How can you render fields from an entity reference in node templates? [Drupal 8], content is a render array that contains data prepared for displaying.

If you want to check or compare something, use the values instead, which are available on the node object.

{% if node.field_example.value %}.

Note that the property depends on the field type. If it's a reference field, you need to use target_id instead. The referenced question links to a entity field API cheat sheet that lists common field types and their properties.


Can I run drush command from composer with custom script

I was able to do this. Here is a simple example:

First, create a file called import.sh and place it in the scripts folder.

#!/bin/bash

# Exit immediately on errors, and echo commands as they are executed.
set -ex

# Run coniguration import.
cd web
echo "Running coniguration import (config split imoprt)"
drush config-split-import -y

# Clear Cache.
drush cr

Second update composer.json by adding the script to the scripts folder.

"scripts": {
  "import": [
    "./scripts/import.sh"
  ]
},

Now you can run composer import


Most efficient way to change CSS between pages

I think the usual method of adding per-page CSS is in your template.php file using HOOK_preprocess_page(). A couple of examples:

alphorn_preprocess_page(&vars) {
  // Add CSS based on path (beware if you change your path structure!)
  // But as a bonus, this will add the CSS for any path under "/colour/red"
  if (strpos($_SERVER['REQUEST_URI'], 'colour/red') !== false) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
  }

  // Add CSS based on NID, with an out because this hook may be called on non-node pages
  // or pages that otherwise don't return anything useful for menu_get_object().
  @$node = menu_get_object();
  $red_nodes = array(1, 2, 3, 5, 8, 13);
  if(isset($node) && in_array($node->nid, $red_nodes)) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
    // If your stylesheet is really simple you could always inline it.
    drupal_add_css('body { background-color: #FF0000; }', 'inline');
  }

  // Then you need to plug your added CSS into your variables or nothing will happen.
  $vars['styles'] = drupal_get_css();
}


Do I have to activate a parent theme when I activate its sub theme?

No it doesn't. As long as the base theme is present, that's OK.
As an example, if you test the Sky theme on Simplytest.me and go to the admin/appearance page, you'll see that Sky is enabled, but the base theme (AdaptiveTheme) is not.


How to create a URL with $_GET values by writing my own custom module?

If I understood your question correctly, you are mixing the URL arguments and query string.

You can have as many query string arguments as you want and you do not have to define them upfront. Drupal will not limit you. An example of query string is page?arg1=123&arg2=456, just like what views module does for filters. This is what you need for your $_GET form.

What you define in the hook_menu are URL arguments - for example one/two/three. You can get them by using the arg() function, so arg(0) in the example above would return one, arg(1) would return two etc.

UPDATE

  So is the URL arguments in hook_menu not needed (i.e. page arguments)?

Yes, you don't need it in this case. You will solve everything by using query string (~question mark in the URL).

  Does 'page?arg1=123&arg2=456' not count as an argument, or is that just one big argument (i.e. arg(0))?

That is only one argument. arg(0) would return just page. arg1 and arg2 are query string parameters.

Think of page argument as a part of the base URL for the page.
Query string is what goes after the question mark.

You should use filter_input() instead of simple $_GET as it is much more secure.

See also drupal_get_query_parameters().


How do you deal with multiple locations?

I've been using GMap + Location to accomplish this.  The site I've been working on involves Apartment Communities spread out all over the place.  I created a content type for apt_community which accepts location data (I only allowed an exact address but you can let the user pick a location on a map).  Then I have a view that puts all the points on a map which I attach to a page.

Check this DrupalTherapy screencast on GMap + Location (http://www.drupaltherapy.com/gmap) and this other screencast Drupal Aficionado did on using GMap and Views (http://blip.tv/drupal-aficionado/gmap-location-and-views-1773822).


How to format a date submission value of a webform?

I finally found a answer myself.
Instead of changing the date format tokens you can set the date format globally for webforms under admin/config/content/webform.


Delete unused tables from the drupal database

You can safely remove them yes. You can use drush to delete these tables: run drush eval 'field_delete_field("yourfield")' and run cron afterwards with drush cron.


Add upload/processing status bar/throbber

Change from file to manager_file and use property #progress_indicator (by default is already set so you won't have to add it).
https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#managed_file


System pager isn't showing for logged in users

Finally figured out the problem with some help from a friend. It was being caused by a conflicting pager in a custom made View that rendered the current user's picture in a block on every page. It's only set to display when the user is logged in, hence why the problem was non-existent for anonymous users.

Changing the pager settings for the view from "Full, display 10 items" to "Display all items" has fixed the problem (presumably since there's only a maximum of 1 user picture to output in the View, Views dictated that there was only 1 page and that interfered with the other pager).

I suppose another solution, although not necessary in this case, would be to change the View's Pager ID.

In hindsight the solution is pretty obvious, because I have known about the Pager ID setting for a long time, and even knew what it did - but hopefully this will come in useful for anyone else with a complex site layout running into the same problem. :)


There is another solution to implement hook_preprocess_node to modify the comments links.

You can follow the answers in the Modifying teaser node comment links


How to remove the ADD USER in the “admin users area” in Drupal 7

That link is available to users with the "Administer users" permission enabled. You can disable that permission for all roles other than a role you create, and then give your account that role (or users you want to delegate this to), which would result in only you (or a limited number of people) with access to that link.  Hope that helps!


Show Colorbox or other Modal Window on page load

I figured it out, it's pretty easy. See below:

function popupmessage_init(){
    $colorbox_js = 'jQuery(document).ready(function(){ jQuery.colorbox({html: "
Your Message Here
"}); });';
    drupal_add_js($colorbox_js, 'inline');
}


How to create a Content pane view of nodes with common taxonomy terms (creating relared contents))

Found it, I should have select Multiple terms from node in Relationships to create Contexts not the Term from node


How to remove the 'Reply' link in comments?

If you wanted to remove all links, you could do it in a template file like this:

hide($content['links']);
print render($content);

But I don't know how to hide just the comment reply link this way. Based on a short article here, it looks like you can unset the reply link with a preprocess function in template.php like this:

function themename_preprocess_comment(&$variables) {
  unset($variables['content']['links']['comment']['#links']['comment-reply']);
}


Drupal removes "write" permission from settings.php, so to edit it, you need to give this permission back.

SSH

chmod u+w sites/default/settings.php

FTP, SFTP and alike

Use your cilent, and just tick appropriate checkbox. Like this:


How to move comments section out of its parent div

Depending on which container you want to escape, you need to use either node.html.twig (recommended) or page.html.twig (harder, unlike node you can't use {{ content.field_comment }} in page).

If you are using node.html.twig (or somehting like node--BUNDLENAME.html.twig) and you manually render {{ content.field_comment }}, then you can avoid double-rendering of comments by rendering the "normal" content using the without filter {{ content|without('field_comment') }}


Can I strip my form of some classes and DIVs?

There are 2 Drupal theme functions which you need to override in your theme's template.php

You can paste this code in your theme's template.php and change "themename" to the name of your theme (Drupal 7 code):

It shouldn't affect any ajax form functions if you have a custom theme, however if you are using a contributed theme you should check the javascript files to see if there are any functions using the classes / selectors you have stripped out.

Override theme_form() to remove the div

function themename_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
}
element_set_attributes($element, array('method', 'id'));
if (empty($element['#attributes']['accept-charset'])) {
 $element['#attributes']['accept-charset'] = "UTF-8";
}
return '' . $element['#children'] . '';
}
Override theme_form_element() function to strip out the classes

function themename_form_element($variables) {
  $element = &$variables['element'];
  $element += array(
    '#title_display' => 'before',
  );
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Remove line below if you don't want a custom class
  $attributes['class'] = array('your-custom-class');

// Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '' . "\n";
  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }

$prefix = isset($element['#field_prefix']) ? '' .   $element['#field_prefix'] . ' ' : '';

$suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';

switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

case 'after':
  $output .= ' ' . $prefix . $element['#children'] . $suffix;
  $output .= ' ' . theme('form_element_label', $variables) . "\n";
  break;

case 'none':
case 'attribute':
  // Output no label and no required marker, only the children.
  $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  break;

}

if (!empty($element['#description'])) {
    $output .= '' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}


hook_menu() items created in a custom module don't retain the active-trail of the parent tab

OK...so this basically ended up being more of an Open Atrium issue than anything else.  Due to the fact that Open Atrium relies heavily on Features and Context, the style sheet was setup to deal with the classes added by those modules.  Drupal's implementation of active-trail and active classes was working fine, however the theme's 'active' styles weren't setup to work without the classes added by the Context module.

I could either a) add a Context for the menu item added via my module (which is the route I took), or I could have (b) modified the CSS for the theme by adding a custom stylesheet.

Thanks for all the help guys, but I am embarrassed to say that in the end, it was just a bit of a theme problem from the Open Atrium install.


How to get values of selected options in Form api?

Since the form submission handler has access to the $form variable, you just use the following code.

$foldername = $form['select_list']['#options'][$form_state['values']['select_list']];

To make it clear with an example: $form['select_list']['#options'] is an array like array( 1 => 'first folder', 2 => 'second folder'), and $form_state['values']['select_list'] is a value between 1 and 2.


In drupal 7 views, can views data be cached for logged in authenticated users?

You click on the Caching link (here shown in the lower portion of the right column) and click Time-based (or whatever other cache()ing you have implemented on your system).

Then you can tell Views how long you want the cache()ing to be on the next menu presented:


Unable to use user fields from the global variable $user

The global $user variable doesn't contain all the values you would find from a user object loaded from the database; in particular, it doesn't contain any field associated with the user entity. If you need a full-loaded user object for the currently logged-in user, you should use the following code.

$account = user_uid_optional_load();
// Use $account to access the user fields.

If need to load a full-loaded user object knowing its user ID, then you should use the following code.

$account = user_load($1);
// Use $account to access the user fields.

Also in this case, you could use user_uid_optional_load(); since it only passes the given user ID to user_load(), you can directly use user_load() and use user_uid_optional_load() when you don't have always a user ID, and need the user object for the currently logged-in user in that case.


I had the same issue with some older Google tags plugins that did not work with jquery 3.0.  You basically have to use the D8 library override methods in your theme to do this.

This actually goes into the theme info.yml file.  You need to have the other version of jquery defined in your library.yml file as well.  Here's some excerpts from my theme files.

my_theme.info.yml

libraries-override:
  #downgrade jquery / force jquery into header
  core/jquery: my_theme/jquery

The core/jquery was found by searching thru the core to find the jquery library definition.

my_theme.libraries.yml

jquery:
  header: true
  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 }

Note: The header: true loads jquery in the header and not the footer.  Helps a bit with embedded jQuery code that complains that jquery does not exist.  I have a local copy of jquery in the js directory of my theme as well.

This technique can override any CSS or javascript included by any module or core.


How to create and set a new menu block in some content region, programmatically

You save the menu using menu_save:

$menu = array(
  'menu_name' => '',
  'title' => '',
  'description' => '',
);
menu_save($menu);

I'm not sure if there is an api function to activate a block, but it can be done, by inserting  a row in the blocks table. You need to know the module, delta, theme and region. For menus, the menu module will create one with the delta being the menu_name.

So with the above you could do something like this:

$menu_block = array(
  'module' => 'menu',
  'delta' => $menu['menu_name'],
  'theme' => '', // Either get the active theme or you can do it for all themes
  'region' => 'content', // Where you want to place it, theme dependant
  'status' => 1,
);

So while you can do it, you probably want to make this theme specific, or do this in an install profile, where you know which theme should be the active one etc.


in admin/config/services/disqus set the location to block

then in admin/structure/block put the "Disqus comment" block below the "Main page content"

Now, edit the Disqus comment block, scroll all the way down, under Visibility Settings, click on roles and check mark premium and administrator.

Edit:

Unfortunately, you can't remove the comment box. Disqus used to offer a way to do it, but now they don't.

The only workaround, would be to create a block that is displayed for anonymous users and non premium authenticated users only.

Then inside that block put css to hide the comment box behind/underneath the article body.

For Example:

<style>
 #disqus_thread { z-index: 1; position: relative; top: -180px;}
 .article-body { z-index: 2; position: relative; background: white;}
</style>

Unfortunately, with this tactic you would lose the comment count and the sort option. Although, you could display the comment count using the views module.


They are stored in the {cache_container} table of the database. The services themselves are declared in [MODULENAME].services.yml.


I would guess the problem is that drupal_valid_path() is expecting a system path, and you're passing it an alias.

Fortunately there's a function to determine the system path from the alias, drupal_lookup_path(). I would have thought a simple change to your code like this would make it work:

$target_path = drupal_lookup_path('some/path');
if(drupal_valid_path($target_path, FALSE) === FALSE){
  // create 'some/path'
}


This is what I ended up using, it could probably be optimized a bit but it works.

<?php
if ($node = menu_get_object()) {
  // Get the nid
  $currentNode = $node->nid;
}
if (in_array("Gold Member", $user->roles)) {
    echo '

Free Courses for Gold Members

';

    echo '
';
        $role_type = 'Gold Member';// Texas Member
        $getRole = db_query("SELECT rid FROM role WHERE name = '%s'",$role_type);
        while ($roleid = db_fetch_object ($getRole)) {
          $roleids[] = $roleid;
        }
        //Get the ID of the role type we are using from the array
        foreach($roleids as $roleId){
            $role_id = $roleId->rid;
        }

        $node_type = "page";
        $result = db_query("SELECT * FROM node WHERE type = '%s'", $node_type);
        $nids = array();
        while ($obj = db_fetch_object ($result)) {
          $nids[] = $obj;
        }

        $idsToInclude = array();
        foreach ($nids as $pageId) {
            $page_id = $pageId->nid;
            $realm = 'content_access_rid';// content access
            $grant_view = 1; // Has view
            $result = db_query("SELECT * FROM node_access WHERE nid != '%d' and nid = '%d' and gid = '%d' and realm = '%s' and grant_view = '%d'",$currentNode, $page_id, $role_id, $realm, $grant_view);

            while ($obj = db_fetch_object ($result)) {
              $idsToInclude[] = $obj;
            }
        }

        //var_dump($user->uid);
        //var_dump($nids);

        foreach($idsToInclude as $id){
            $courses = $id->nid;
            $nodeid = node_load($courses );
            if(node_access('view', $nodeid, $user)){
                echo '
'.$nodeid->title.'
';
            }
        }
    echo '
';
}

?>


Display content type in a tab of user profile

It sounds to me like you are trying to re-create what is essentially a combination of Profile2 and Field Permissions

Profile 2

  Designed to be the successor of the core profile module, which is
  deprecated for Drupal 7. In contrast to the deprecated module this
  module provides a new, fieldable 'profile' entity - leverage the power
  of fields!

Field Permissions

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


How to add View Translated Version button in Views?

You can add filter 'Translation Language' in view which can be exposed for user to select the language.


How do you make a Image View of a specific page?

In the block's options there's a paginator setion that lets you include a "more" link, so it isn't exactly what I wanted, but I just put the page's link there, and it does work so I think I'll just leave it there.


access callback admin permission is not working

Your latest edit clears up where the problem is likely to be:

  The above code is being called via

$users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

You're probably under the impression that the active user session from the calling site will somehow be passed through to and become valid for the API site? That won't happen, even if it's the same site - you're making a completely new request which doesn't share anything with the request you're making it from.

If you're building a secured API, you need to provide an authentication method that integrates with Drupal's login system, while still handling tokens etc for the API communication itself. That can be a fair amount of work, so people tend to use existing solutions like the Services module.

That module has an authentication layer for the core Drupal user login built in, and provides hooks for you to register your own resources. It will probably take less time to build your API using Services than building and testing your own authentication, so it's worth a look.


If I understand correctly, you need to create Views page where you add exposed filter on the content types.

This is how you create an exposed filter
https://www.youtube.com/watch?v=2Yk6rre3vi8

If that is unclear for you, I will make a screenshot.

Regards,

Oleg


Replacing a certain character pattern in a textfield when saving an entity

So, hook_field_presave, according to the documentation, "Defines custom presave behavior for this module's field types." So unless your defining a field type in your module, this is the wrong hook to use.

Instead, your gonna want to use hook_field_attach_presave. $entity_type will contain the type of entity the save is being called from (node, user, etc). $entity is the full entity object, which you can just go ahead and edit.

For example, a very basic function like so:

function replace_multiplication_symbol_field_attach_presave($entity_type, $entity){
  if(!empty($entity->field_field_technical_description['und'][0]['value'])){
  $entity->field_field_technical_description['und'][0]['value'] = "test";
  }
}

would, whenever an enity is save, check for the field field_field_technical_description and switch it's value to "test," if it's value was not null.


There is no built-in option to hide term ID from entity_autocomple form element. Its behavior is simple, if there is a term that match then shows (TID).


System module's system_cron() clears expirable entries from cache tables. An expirable cache entry is one that is beyond its "can expire" date, or it's an entry that was initially saved with the CACHE_TEMPORARY flag.

Assuming you're using the default database cache, you can see which entries are expirable by looking in a cache table.  The "expire" column contains the timestamp at which an entry becomes expirable. If the value is "-1", it's CACHE_TEMPORARY and always expirable.

As far as Drupal's default database page cache goes, the "expire" column won't tell you much, since the minimum cache lifetime is not applied to the expire value. Instead, Drupal keeps track of the last time the entire cache was flushed, and will not flush the page cache again until at least "minimum cache lifetime" seconds have passed.


You can use the context overlay module to achieve this, this way you can easily configure what pages should be opened in an overlay.

You'll need to install:

Context (https://www.drupal.org/project/context)
Context Overlay (https://www.drupal.org/project/context_overlay)


Altering (adding) field value when is unknown

For nodes, like for every content entity, you can use code similar to the  following one to check if a Field API field(*) exists.

if ($node->hasField('field_version')) {
  // The node has that field; access it with $node->hasField('field_version').
}

A more generic code that would work for either Field API fields or non-field properties would be similar to the following one.

if (isset($node->field_version)) {
  // The node has that field/property; access it with $node->field_version.
}

* I am using the terminology used in a comment for code in ContentEntityBase::__isset().

// "Official" Field API fields are always set. For non-field properties,
// check the internal values.
return $this->hasField($name) ? TRUE : isset($this->values[$name]);


Theming a node edit Form - Move Author Information to another positon

You can use the Display Suite module.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (Drupal 7 only) is available for even more drag and drop fun!


If sld.tld/subdomainroot/Y works, that suggests that you have set $base_url in your settings.php to include subdomainroot.  If that's the case, subdomain.sld.tld/Y certainly won't work because drupal will be using the above.  Now, if this is the case, and you change the above to subdomain.sld.tld, you still may have issues with cookies being set to the old domain until they are cleared.


How to validate if node is ubercart product?

I think the most solid way to test would be to check that the node's type is one that the uc_product module considers to be a product node type. You can do that by using the uc_product_types() function:

$node_types = array_keys(uc_product_types());
if (in_array($node->type, $node_types)) {
  // The node is a product
}


Rendering arbitrary field values without a parent entity in Drupal 8

Yeah, you can't get around having an entity object, but it doesn't matter what it is, the only place where it's needed in the following code is FormatterBase::view(), to set #entity_type, which will later be used for the class name.

<?php

use Drupal\Core\Field\FieldDefinition;
use Drupal\node\Entity\Node;

// Load the node, you can also create a temporary object or have your own
// dummy object that implements EntityInterface. (Might need ContentEntityInterface, not sure).
$node = Node::load(1);

// Create the field definition, some might need more settings, it currently
// doesn't load in the field type defaults. https://drupal.org/node/2116341
// Field name is only set to avoid broken CSS classes.
$definition = FieldDefinition::create('entity_reference')
  ->setName('whatever')
  ->setSetting('target_type', 'node');

/* @var \Drupal\Core\Field\FieldItemListInterface $items $items */
// Create a field item list object, 1 is the value, array('target_id' => 1)
// would work too, or multiple values. 1 is passed down from the list to the
// field item, which knows that an integer is the ID.
$items = \Drupal::typedDataManager()->create($definition, 1, $definition->getName(), $node);

/* @var \Drupal\Core\Field\FormatterInterface $formatter */
// Create the formatter plugin. Will use the default formatter for that field
// type if none is passed.
$formatter = \Drupal::service('plugin.manager.field.formatter')->getInstance(array(
  'field_definition' => $definition,
  'view_mode' => 'default',
  'configuration' => array(
    'label' => 'hidden',
    'type' => 'entityreference_label',
    'settings' => array('link' => TRUE),
  )
));

// Prepare, expects an array of items, keyed by parent entity ID, not sure if
// actually used, just array($items) worked too.
$formatter->prepareView(array($node->id() => $items));
print \Drupal::service('renderer')->renderRoot($formatter->view($items));

Yes, finding this out is not trivial, but I disagree with you that the 7.x code is relatively easy, it's just that you know the 7.x field API and internal magic callbacks very well. The main difference is that instead of building arbitrary array structures and passing them around, you need to find the right object/class/service and call methods on there. Once you found them, it's not that hard, FormatterPluginManager::getInstance() for example documents very well what it expects.


Commerce Feeds - Taxonomy term processor Issue

Tom, I found your question today while fighting the same problem in the standard Feeds module.  In the Processor > Mapping setup, do you have fields set as unique targets in the "target configuration" column?

In my system, I found that even though I had tried to set the imported column to be a 'unique target', that setting had not been saved. After going through the process of setting unique targets, updating the column map, and saving again, the duplication problem has now been solved in my system.


What's the best way to allow a user to save variables/options

Yes, instead of content entities you can use config entities. But for only a few configuration options this is too much effort. In this case you can use the Simple Configuration API, either by creating your own form
https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms
or by adding form values to existing admin forms in a form alter hook.
See for example how the core dblog module adds an option to /admin/config/development/logging when it is enabled:
/**
 * Implements hook_form_FORM_ID_alter() for system_logging_settings().
 */
function dblog_form_system_logging_settings_alter(&$form, FormStateInterface $form_state) {
  $row_limits = [100, 1000, 10000, 100000, 1000000];
  $form['dblog_row_limit'] = [
    '#type' => 'select',
    '#title' => t('Database log messages to keep'),
    '#default_value' => \Drupal::configFactory()->getEditable('dblog.settings')->get('row_limit'),
    '#options' => [0 => t('All')] + array_combine($row_limits, $row_limits),
    '#description' => t('The maximum number of messages to keep in the database log. Requires a cron maintenance task.', [':cron' => Url::fromRoute('system.status')->toString()]),
  ];

  $form['#submit'][] = 'dblog_logging_settings_submit';
}

/**
 * Form submission handler for system_logging_settings().
 *
 * @see dblog_form_system_logging_settings_alter()
 */
function dblog_logging_settings_submit($form, FormStateInterface $form_state) {
  \Drupal::configFactory()->getEditable('dblog.settings')->set('row_limit', $form_state->getValue('dblog_row_limit'))->save();
}


What is the correct token for a multi value field?

Since the rules module gives you access to the $node object (if triggered on 'after saving content'). I managed to use it like this $node->field_myField['und'][0]['value']. Where 0 is the delta and und (probably) the language.

Since this looks like a multidimensional array I assume one could use a foreach on $node->field_myField['und'], but I did not test this.


You could use the 'not often used' description field already available on each link? Then just add it into the menu links yourself on the front end by overriding the menu_link theme function.

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $description = '' . $element['#localized_options']['#original_link']['description'] . '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'] . $description, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}


How to add additional query parameters to a views page url?

You can load different displays by using the views_get_view_result() function.

$grid_view = views_get_view_result('YOURVIEWNAME', 'grid');
$grid = $grid_view[0];

More documentation is found here and here


Password request redirect to another page

You can add your own submit handler to the form :

function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_reset') {
    $form['#submit'][] = 'CUSTOM_form_submit';
  }
}

function CUSTOM_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'request-access';
}


One approach can be using content access module.So basically while creating content type you will get option to share content type with user role you want to.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Other approach does not require any module, and will be simple and out of the box.

Create a content type, lets say editor_guide.
While creating the content type opt to keep the nodes unpublished.
Now create nodes,which can be single node(copying the complete guide to one node),multiple node(dividing the guide content into chunks as separate nodes),you can also keep the guide as file field on node.
Create a view of display type page with path say editor-guide.
In views you will get option to set permission for the page, set the permission for editor, in the views filter remember to change status for content for unpublished.
Now in you nav-bar menu block add a menu item, link it to editor-guide(or whatever).

This link will be automatically visible to editor role only.


How do I programmatically install and enable a module?

There's just one step, using module_enable():

$modules = array('module1', 'module2'); // Array of module names
$enable_dependencies = TRUE; // Whether or not to enable dependant modules

module_enable($modules, $enable_dependencies);


What is the difference between "Path redirect" and "Global Redirect"

Global Redirect searches for an alias of the current URL and does a 301 redirects to it if found. This prevents content from being displayed on multiple urls when the path module is enabled. Displaying duplicate content at multiple url's can cause a loss of search engine site ranking.

Path Redirect allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status. This is important if you want to change your url scheme for some reason and you don't want to break all exisiting links (search engines, user's bookmarks etc.)


More information about content in Link field autocomplete dropdown?

The autocompletion matches are provided by EntityAutocompleteMatcher::getMatches. The format is hardcoded as $key = "$label ($entity_id)". Label and entity id come from selection manager, which packages entity id and label pairs in an array keyed by entity bundle, so that could be used as a source for adding content type into the results. You'll need to override system.entity_autocomplete route's controller to get to your own matcher.

The same controller is used for rendering the selection dropdown though it does not display the entity ids, only labels (in web/core/misc/autocomplete.js). Overriding that is another thing you'll need to do.


Drupal nested ajax call not working correctly

Correct one, just copy and paste it:

function agl_jira_new_test_form($form, &$form_state) {
  $form['#tree'] = TRUE;
  $form['select'] = array(
    '#title' => 'select',
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('man', 'woman')),
    '#required' => TRUE,
    '#default_value' => isset($form_state['values']['select']) ? $form_state['values']['select'] : 'man',
    '#ajax' => array(
      'callback' => 'agl_jira_select_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  $form['test']['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#tree' => TRUE,
  );
  if (isset($form_state['values']['select']) && $form_state['values']['select'] == 'man') {
    $form['test']['names_fieldset']['text'] = array(
      '#title' => t('name'),
      '#type' => 'textfield',
    );
    $form['test']['names_fieldset']['attachment'] = array(
      '#title' => t('File'),
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
      '#tree' => TRUE,
    );
    if (!isset($form_state['num_names'])) {
      $form_state['num_names'] = 1;
    }
    for ($i = 0; $i < $form_state['num_names']; $i++) {
      $form['test']['names_fieldset']['attachment'][$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Name'),
      );
    }
    $form['test']['names_fieldset']['add_name'] = array(
      '#type' => 'submit',
      '#value' => t('Add one more'),
      '#submit' => array('agl_jira_example_add_more_add_one'),
      '#ajax' => array(
        'callback' => 'agl_jira_example_add_more_callback',
        'wrapper' => 'agl-jira-file-attach-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

function agl_jira_select_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  return $form['test']['names_fieldset'];
}

function agl_jira_example_add_more_callback($form, &$form_state) {
  return $form['test']['names_fieldset']['attachment'];
}

function agl_jira_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function agl_jira_new_test_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

removed $form['test']['names_fieldset'] = array(
    '#markup' => '

',
  );, added reference to the form_state in agl_jira_example_add_more_callback..


Entity Reference create problem with REST server using Services

I found the solution!
The required data structure depends on the input widget, since Services uses the form submit handlers (which may be a major design flaw).
For "Autocomplete/Tagging" the label (id) thingy is necessary. But if you switch to checkboxes it reads "field_reference": { 1:1, 2:2,  ... ,nid:nid} and for select box "field_reference": [1,2,3 ... nid].

The REST-API depends on the widgets the frontend uses ... but at least it works. I guess its upside is that REST-posts are validated just as normal form inputs are. I'll also have a look at the approach implemented http://drupal.org/project/restws


It's quite hard to understand exactly what you mean but I think an answer I wrote before might help since VBO doesn't really do what you want it to.

How to bulk delete selected content/nodes?

Follow the link if that "one page" functionality is what you need. It's limited but it works.


Google Analytics custom dimension for anonymous/authenticated users

There currently isn't a role token that provides only a anonymous/authenticated role. The only way to do this (without removing all roles) is to create your own custom token to use with GA.


Does Organic Groups Views allows post to group relationships?

it's possible, see the screenshot: (open image in new window to see full size) . Add the 2 relationships as "required" to only show nodes belonging to groups.
The naming conventions of the group objects is very confusing to me, it helped me to look at the "og" and "og_membership" tables in the DB and then check the SQL that views builds for you.


How to set a form field sizes based upon the screen size responsively?

Yes: you can use any CSS media query you want in your theme or module's CSS and affect form elements. You'll want to use a web inspector (like the built-in ones in Chrome and Safari, or Firebug for Firefox) to identify what selectors you want to target.

If, for example, you wanted to make the text fields on the node submission form responsive, you'd target the .node-form selector in your CSS file:

@media screen and (max-device-width: 480px) {
  .node-form .form-text {
    width: 200px;
  }
}

To attach your own CSS for your module's forms (or for any form), you'll want to modify the #attached property in your form:

$css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
$form['#attached']['css'][$css_path] = array('media' => 'screen');

Where mymodule is replaced with the short name of your module. The #attached property is an array of CSS files: if you don't need to modify any options, you can just do:

$form['#attached']['css'][] = $css_path;

Otherwise, you'd set the key to $css_path and the value to an array that mimics the $options array for drupal_add_css().

If you wanted to modify existing forms, you'd do the same thing but in a form alter function. For example, if you wanted to add your custom CSS to the node submission form, you'd do:

function mymodule_form_node_form_alter(&$form, $form_state) {
  $css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
  $form['#attached']['css'][$css_path] = array('media' => 'screen');
}


How to allow users change theme for specific pages

You hook_custom_theme()

function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'Your Path') {
    return 'Your theme name here';
  }
}

Note: Clear cache and have a check

Or You can use Drupal module: ThemeKey

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


Ok... found my answer.

There are two ways you could do this. One way, is in the themename.theme file:

function mytheme_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] == 'motivation_card' && $variables['element']['#field_name'] == 'field_link') {
    foreach ($variables['items'] as $index => $item) {
      $variables['items'][$index]['content']['url'] = $item['content']['#url']->toString();
    }
  }
}

Another (preferable) way that I used is to use the render_var twig function.

{{ render_var(item.content['#url']) }}


So when you use drupal_add_js to add settings during an ajax callback, this indeed merges the results. On the server side this is done in ajax_render (called from ajax_deliver or equivalent) which adds an ajax_command_settings command, instructing it to merge the results.

On the client side the merging is done by calling jQuery.extend, which causes the behaviour you have seen, and cannot be changed.

There is no work around if you want your results to be inserted into Drupal.settings. However you can pass your settings to your behaviour directly without using Drupal.settings. For this you would add a call to ajax_command_settings yourself. It would be something like this:

function mymodule_ajax_callback() {
  $commands = array();
  // ...
  $commands[] = ajax_command_settings(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  ajax_deliver(array(
    '#type' => 'ajax',
    '#commands' => $commands
  ));
}

Note that if your callback is called fom the Form API's #ajax['callback'] then it runs ajax_deliver on the value returned by the callback, so you shouldn't call it yourself.

On your script on the client side, your settings will be available as the second parameter of your behaviour attach method:

Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    // Here settings contains your settings
  }
};

(edit: sorry, previous answer was very wrong)


how we can upload file on media browser type field programmatically

i change my code and its working for me now.

$temp_attachpath = MYFILEPATH;
$attachpath = drupal_realpath($temp_attachpath);
if(file_exists($attachpath)){

    $file = (object) array(
        'uid' => 1,
        'uri' => $attachpath,
        'filemime' => file_get_mimetype($attachpath),
        'status' => 1,
    );

    $file = file_save_data(file_get_contents($attachpath), 'public://'.basename($attachpath));
    $file->filename  = basename($attachpath);
    $file->display = 1;
    $file->description = "";
    $new_node->field_upload_file[$new_node->language][0] = (array)$file;
}else{
    $new_node->field_upload_file[$new_node->language][0] = '';
}
node_submit($new_node);
node_save($new_node);


Creating a ticket system with core only. How to modify fields on full_content view without reloading?

Another approach would be to use a form mode instead of a view mode. Put there the fields you want to make writable and add the read-only information in a form alter hook (or separate view block if you want a UI only solution).

To use the form mode you need a module like Form Mode Control or some custom code,  see this good tutorial https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8.

While quickedit is a single purpose solution for in-place editing of web content, you can now that you have a real form do all kind of tricks to get the behavior you want, for example implement autosave: https://www.urbaninsight.com/2016/08/21/how-implement-ajax-autosave-drupal-8-forms


You can use the path (url alias) module for the create path. Since that's a single url, you can create a single path alias to change that.

It's a bit harder for your custom entities. You would have to create a custom module and integrate with path auto module to be able to create path aliases for the view urls of your custom entities. It's a lot of code, you can see how the path auto module does it for the node module. But be warned, it's not easy as there are many parts.

The gist of it is that you need to make some tokens available for the path system you are going to make, like the entity label and such. Then you need to create a function that can create an alias when given an entity. This is, however, a bit harder since you need to use the path auto API functions for this.


Problem to display name from current logged

I guess the problem is the block is cached for every user. You have to tell Drupal that it should be cached depending on the current logged in user. To do this you have to make use of Cache Tags.

In your case, you have to tell Drupal that the cache of that block should be invalidated when the current logged in user changes. That's because a Cache Context (the user) has changed.

How to do it? You are returning a Render Array, a structure that tells Drupal how to render certain data. In the render array you can set the cache contexts that affect this render array (if the context changes then the cached data changes). In the specific page that talks about the Cacheability of Render Arrays you can see an example of a render array that is cached for each user:

$build = [
  '#markup' => t('Hi, %name, welcome back to @site!', [
    '%name' => $current_user->getUsername(),
    '@site' => $config->get('name'),
  ]),
  '#cache' => [
    'contexts' => [
      // The "current user" is used above, which depends on the request,
      // so we tell Drupal to vary by the 'user' cache context.
      'user',
    ],
  ],
];

So, I guess that you should add the #cache key to your render array, probably in your theme function, but it may work in the build function (long time since I don't do theming, so I'm not sure).

The code to add is:

'#cache' => [
  'contexts' => ['user']
]


How to Wrap the text in Source View of CKeditor

I found the solution to this:
This is a Firefox browser issue only (FF version >= 36). This behavior is not affected in other major browsers (Safari, IE and Chrome).
Here is the fix. Add the following code to you theme's CSS file:

.cke_source {
    white-space: pre-wrap !important;
}

Basically, you are overwriting the 'white-space' property of the "cke_source" selector in the "editor_gecko.css" file  of the CKEditor module. This file is located at: \sites\all\libraries\ckeditor\skins\moono\editor_gecko.css

References:

https://stackoverflow.com/questions/29038262/source-code-not-wrapping-in-ckeditor-on-firefox

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

http://dev.ckeditor.com/ticket/13031


The weight you set here would be overridden by the weight values you set via Mange Fields.

However...

You can get around this by changing the weight in pre_render.

E.g.

function mymod_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymod_form_alter_weight';
}

function mymod_form_alter_weight($elements) {
  $elements['account']['#weight'] = 100;

  return $elements;
}


How to prevent fake drupalcommerce orders

Your problem is due to robots, in particular spam robots (spambots). I've monitored these pests closely on my site for some time, and found that spambots (such as XRumer) will click on anything that's clickable.  I doubt that you need to be concerned about spammers of the human kind.

There is nothing wrong with the suggestions from Strae, but don't expect spambots such as  Xrumer to respect tags such as rel="nofollow".  (Nice robots such as googlebot do, so if your fake orders are from nice robots only, this will fix it.).

In my experience, the single most successful measure to filter out spambots is to add effective CAPTCHA to the site.  If the user is not logged in yet, the CAPTCHA must be present in the order submit form.  If a new user register, the CAPTCHA must be present in the registration form.  (You don't need to use CAPTCHAs in the order submit form for logged in users). If you set up a CAPTCHA, don't bother with "math challenge", "leave this field blank" and "ReCAPTCHA" - XRumer knows how to solve those.

On my site, the Captcha Riddler is by far the most successful robot guard.  Even blatantly obvious "riddles", such as: "What is Justin Bieber's  first name?" stops the spambots.

PS: If your site is big enough, your "riddles" and their answers will probably be added to the knowledge base of XRumer and other spambots. But if you run a small site you will probably be able to fly under the radar for a long time with "riddles" you create yourself (and you just watch the logs and retire and replace any "riddle" that is cracked by a spambot).


Printer Module: Show link base on Content Type

Edit the content type and go to Printer, email and PDF version and choose to display or not.


Add class to a views field depending on image's being vertical or horizontal

The answer could be approached from various angles. Simpler perhaps would be to target the template_preprocess_image itself, and add a div wrapper around it with the class, or just add the class on the img tag. I chose to do it via template_preprocess_field.

function THEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_IMAGE_NAME') {
    foreach($vars['items'] as $key => $item){
      if (_add_image_proportions_class($item)) {
        if ($item['#item']['width'] > $item['#item']['height']) {
          $vars['classes_array'][] = 'landscape';
        }
        else if ($item['#item']['width'] < $item['#item']['height']) {
          $vars['classes_array'][] = 'portrait';
        }
        else {
          $vars['classes_array'][] = 'square';
        }
      }
    }
  }
}

function _add_image_proportions_class($item) {
  return $item['#image_style'] == 'medium';
}

_add_image_proportions_class() is just a function you implement to test whether you want to add the class or not. In my example, I targeted the image style that is applied to the image. You could for instance create a specific image style that is used only for that view, and target it specifically. Or you could test the path you are on, etc.


How to place facet block in views page header? (not regions)

Firstly, I would recommend that you consider placing the facet block right above the view instead of performing a surgery on views :D

That said, here's what I think might work:

Solution 1: Views Header

Views allows you to attach rendered blocks in the views header.
In the views UI, click the Add button in the Header configuration.
Then choose Rendered Entity - Block and choose the facets block you want to display

Solution 2: Attachment Before

Write a hook_views_post_build()
In this hook, render the facet block as the attachment_before of the view.

See this answer about rendering blocks programmatically

You might face some difficulties with views caching, etc, but you can fine-tune the views build to alter the caching rules.
If you don't like the idea of Attachment Before, you can also consider adding a header item with a custom token like @facet:foo@ and then replace this custom token with a rendered facet block in hook_views_pre_render()

I hope this helps!


Access item url in views-view-fields.tpl.php

If I understood it right, you can simply add a new field in Views which holds the URL to the item. And then in the template file you can print this field as you described in you question.


How can I change the order of the list of countries provided by the Countries module?

It's a shame Sumeet didn't continue his answer, as he got so close, but here is the alter hook:

function HOOK_countries_alter(&$countries) {
  $US = $countries['US'];
  unset($countries['US']);
  array_unshift($countries, $US);
}

It copies US, removes it from the list, and attaches the copy back to the top.

You don't say in what context you use the module. I verified that it does what it should on a country-field.


Start page count from 1 with views pager

To change it just on the UI, you can adapt the number in template_preprocess_pager in your theme's .theme file.
Something like:
function template_preprocess_pager(&$variables) {
  foreach ($variables['items']['pages'] as $key => $value) {
    $variables['items']['pages'][$key]['text'] = $key +1;
  }
}

To change the query params, you could use hook_url_inbound_alter and hook_url_outbound_alter to manipulate the queryparams, but this was D7.
In D8 you would need to go in this direction to manipulate them: How do I implement the equivalent of hook_url_inbound_alter()?


How do I implement an image categorization system using Entity Browser and File Entity?

For the tagging part, forget about entity browser, that (currently) doesn't know about the context of where it is invoked and to what those files will eventually be added.

Instead, what you want to hook into is hook_node_presave(). Go through the referenced files in all your fields that you want to support (could be all image fields or a configurable list), check the image referenced there. If the image doesn't have a category yet, set it based on the field that you're currently looking. Or maybe always ensure it is categorized based on the current field. Whatever you want.

For views, that's currently not possible yet, for the same reason. Entity browser doesn't receive the context yet. There are some related issues like https://www.drupal.org/node/2656196 and https://www.drupal.org/node/2366335. Note that there are many ways to embed an entity browser and you don't always have a field, for example  with entity_embed.


How can I export node data the same way you do webform data?

Use the Views data export module.

This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:

CSV
Microsoft XLS (or really simple HTML understood by Excel)
Microsoft DOC
Basic TXT
XML


Create a list and count of users per role

I'm going to assume Part A is the easy part, but just to be thorough:

Create a new view based on the Users table
Add the User: Name field (if it isn't already there)
Limit the results to 10
Sort by descending

As for Part B, let's begin by dissecting why Aggregation will not work right out of the box with Views 3.

The only reasonable base table that we could use to count user roles is the Users table, right? After all, Views gives us a User: Roles field right away. So, we turn on Aggregation on two copies of the User: Roles field (the first to group the results, and the second to COUNT the results). However, if you take a look at the SQL, the query is:

SELECT users.uid AS uid, COUNT(users_roles.rid) AS users_roles_rid
FROM {users} users
LEFT JOIN {users_roles} users_roles ON users.uid = users_roles.uid
GROUP BY uid

So, the query will:

SELECT a uid and then COUNT the roles that particular uid possesses
Perform a LEFT JOIN by comparing two uids from the users table and the users_roles table (not very helpful)

It turns out that the COUNT does its job correctly by counting up the roles each user has... but it is not what we need. Since we chose User as the base table, the COUNT is only counting the number of roles. What we actually need is to COUNT how many users belong to each role. The users_roles table will provide us the necessary information.

Here is the SQL we're after:

SELECT role.name, COUNT(users_roles.uid) AS users_per_role
FROM users_roles AS users_roles
INNER JOIN role AS role ON role.rid = users_roles.rid
GROUP BY role.name

The above query will give you a list of all of the roles in your site along with a count. Since users_roles is not an available base table out of the box, we cannot construct this query via Views without some PHP customization.

There are a few options to get the required results:

Use the Views API to describe users_roles to Views. This requires a bit of PHP heavy lifting. Check out this answer for more information. The Data module may be of use as well.
Cheat and run the above query through db_query and stick the results in $view->attachment_after.

Here is an example of the latter, using hook_views_pre_render in a custom module (be sure to clear caches first to get this hook to work):

function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'my-view-name':
      $results = db_query('
        SELECT role.name, COUNT(users_roles.uid) AS users_per_role
        FROM users_roles AS users_roles
        INNER JOIN role AS role ON role.rid = users_roles.rid
        GROUP BY role.name
      ')->fetchAll();

      foreach($results as $result) {
        $rows[] = array($result->name, $result->users_per_role);
      }

      $view->attachment_after = theme('table',
        array(
          'header' => array('Role', 'Number of Users'),
          'rows' => $rows,
        )
      );
      break;
  }
}

Lastly, keep in mind that a user may have multiple roles. So, it would be incorrect to sum up all of the "Users Per Role" values and say that the result is your total number of users.


If you want to get the parent of the menu link use getParent():

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
if ($link = reset($links)) {
  if ($parent = $link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}


You need to debug the rule!

This is not a direct answer but can help you find the problem. And it is too long to post as a comment. You should follow these steps regardless of other similar rules working (a teeny tiny difference can be causing the rule to fail).

Required tools

Install the devel module. but NOT on production site, only on your development site. It will add an extra action to rules debug a value under devel section.

Is the rule actually triggered?

Method 1:
Add a simple action, display a message and enter a simple text. Do the required actions actually needed to fire the rule (buy a sample product). Is the message displayed or not?
Drawback: If the message is not displayed, you wont actually know if the action is not triggered OR there is some error in rule definition, preventing the rule engine from executing it.

Method 2: Go to admin/config/workflow/rules/settings On your site, there is a checkbox to enable rules debugging. It's something like dpm() but for rules only with helpful information. Whenever a rule is triggered, all the thing happening (or failing) will show up in the debugging area. If something has failed it will be printed in red so you can easily find it.
Drawback: Can get annoying going through the rule stacktrace :|

If it's not firing:
There should be something wrong with the event/conditions you have set, Or a fatal error in the rule action definition. If the later find it with method 2 above.

Are the data you are using not null and valid?

Temporarily remove the condition commerce-order:commerce-line-items:0:type. Since you are working on development site this should not be a problem. In the actions (Important: In the beginning, as the first action) add the action debug a value. the value to debug would be "commerce-order:commerce-line-items:0:type. Go and buy the sample product, the rule should fire, and devel's debug a value would print the type. Check if it is set and is what you want it to be.
Do the same for commerce-order:commerce-line-items:0:commerce-product:creator:mail.
Do the same for "language" : [ "commerce-order:state" ] --> However this sounds fishy! why would you set the language as the state?!! You should read the language from user entity (the creator).

Have fun debugging rules!


How do I remove the Previous and Next links?

On the MANAGE DISPLAY of the content type that has this image edit the formatter for the colorbox image. There set the Gallery (image grouping) > No Gallery.


Programatically remove field content from all nodes where content equals 'string'?

The video_embed_field module adds a simple field based on whatever you named it.  So if your field is named "field_youtube_embed_test", you'd get a field on your content type that is a standard drupal field, with a table "node__field_youtube_embed_test" and a revision table "node_revision__field_youtube_embed_test".  You can run a query to delete all entries based on bundle as that is one of the columns on both tables.  So you can run a query for each.

DELETE from node__field_youtube_embed_test where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

DELETE from node_revision__field_video_embed where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

Or if you want to delete everything from those tables, you just use the truncate command:

TRUNCATE node__field_youtube_embed_test;

TRUNCATE node_revision__field_video_embed;

Using a query works for simple fields such as textfields, booleans, etc, but it doesn't work for more complex structures such as field collections or paragraphs.  For those, you would probably want to iterate through them programmatically and unset the value and then save the node.


How do I create a view from the user interface, and get the code to create it programmatically?

That is a feature that the Views module already has. In Drupal 7, you need to follow these steps:

In the page listing all the views defined in a site, select the "Export" operation

In the next page, the Views module will show you the code that defines the view.

This is only the code that defines the views.

Another way, is the following one; in this case, you get the complete code to use to write a module.

Enable the Bulk Export module that is listed under the modules that are part of the Chaos Tools Suite module
On admin/structure/bulk-export, select the view(s) you want to export in a module, and enter the name of the module

After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view

In Drupal 6, you need to follow these steps:

Enable the View Exporter module that is part of the Views module (I am referring to version 6.x-3.0.)
On admin/build/views/tools/export, select the view(s) you want to export in a module, and enter the name of the module

After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view


How to output every second grouping in views?

This seems like a good use-case for a theme override.

If you click the "advanced" section in the view and click "Theme Information" at the bottom, you'll get a list of theme names. Click on "Style output" and copy the code, and paste it into a file in your theme folder with the most specific name possible (at the end of the list starting with "views-view-unformatted.tpl.php").

Not sure if there's a more elegant way to get a row count (it doesn't seem to be an available tpl variable) but you can DIY like so:

  <?php function count_this_view() {
    static $count = 0;
    return $count++;
  }?>

Then wrap your tpl in a conditional like

  <php if (count_this_view() % 2) :?>


Answer by Paul worked (thanks):

alias drush='"/Applications/Dev Desktop/drush/drush"'

Needed inner double quotes to allow for space in Dev Desktop.


How woud you plan a sector directory with Drupal?

Reference entity http://drupal.org/project/entityreference will let you make all the relations you need.

Also, instead of use node I will create my own entities (http://www.istos.it/blog/drupal/drupal-entities-part-1-moving-beyond-nodes) and all the connections with views.

And remember that taxonomies also are Entities, so you can create a Vocabulary that it's "Sector", and every Sector add all the fields you need.

It'll harder but it'll improve the performance.

Oskar


3-column fixed width Zen-based layout + SASS; giving exact width to columns

This is really more a math question than anything, but here goes.  Given that you're using a fixed width column layout, we have to start and find how many columns we need to achieve the proportions you posted. The least number of columns possible to achieve 220px | 480px | 220px is 46 with each column equating to 20px (920px / 46 = 20px). With 46 columns, the sidebars are 11 columns each and the main content is 24 columns.

The rest is just plugging in the numbers into the zen grids functions.  See http://vpaste.net/VDwL1 for my example.

After defining the number of columns with $zen-column-count, you need to plug in the numbers so that each sidebar spans the correct number of columns while starting at the correct column with zen-grid-item($column-span, $column-position). The Zen starter sub-theme comes with three layouts to account for 1 (left) sidebar + main content, main content + 1 (right) sidebar, and 2 sidebars + main content. Here is how it looks with our new, 46 column system:

/**
 * The layout when there is only one sidebar, the left one.
 */
.sidebar-first {
  /* Span 35 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(35, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }
}

/**
 * The layout when there is only one sidebar, the right one.
 */
.sidebar-second {
  /* Span 35 columns, starting in 1st column from left. */
  #content {
    @include zen-grid-item(35, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}

/**
 * The layout when there are two sidebars.
 */
.two-sidebars {
  /* Span 24 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(24, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}


Overriding theme_item_list() not working

You don't need to implement hook_theme() if you just want to override an existing theme function.

I've just tried this code in my template.php file:

function MYTHEME_item_list(&$variables) {
  // my custom stuff done to theme_item_list
  return 'test';
}

And all calls to theme('item_list') now return the string 'test', and nothing else.

You'll need to clear Drupal's caches once you've implemented the function, that might also be an issue.


There is no simple solution, and therefore I'm not sure this question is good for the Drupal Stack Exchange. It's going to be a matter of custom JavaScript or AJAX Form API code, and it will be dependent on how you're using Address Field and what sort of form you're integrating it into.

Based on the comments below, though, I'd add that there's nothing particularly challenging about this. If both sets of form elements are on the same page, it's a simple matter to use JavaScript (especially with jQuery) to copy the data from one form field to the next. There just isn't a simple property to toggle within the form API code itself.


To use TVI with individual vocabularies instead of all vocabularies, first make sure it is not globally overriding your vocabulary term pages. Go to Admin > Configuration > User Interface > TVI Settings (admin/config/user-interface/tvi) and uncheck the Use view override checkbox.

Then edit each vocabulary to apply the TVI view override individually. Admin > Structure > Taxonomy > edit vocabulary. In your case, you would edit your Article vocabulary and make sure the Use view override checkbox is unchecked.

Then edit the two vocabularies you do wish to override with the appropriate view. The fields for selecting the view appear once you check the Use view override box:


Is there a way to track or record users entered taxonomy?

You may want to take a look at the Community Tags project.  We have used it on a few sites.  From the project page:

  The Module has three main features:
  1. Stores who tagged what and when.
  2. Allows for this information to be exposed with views.
  3. Adds an easy AJAX interface for tagging nodes without going to node/edit.


How to set permissions for cron for other roles (not administrators)

The permission to run cron in Drupal 7 is Administer site configuration.

Warning: Give to trusted roles only; this permission has security implications.

It can debated whether it is a good idea to give permission to the editor role, as opposed to running cron automatically every five minutes.

However, in my use case cron does some heavy lifting every time it runs, so running it every five minutes would make my site very slow, creating a bad UX. I've scheduled it to just run cron automatically once per day (at 3 am). I use Notify to distribute newsletters, and it in turn relies on cron, so I permit trusted editors who use the site for sending out newsletters hit cron manually if there is some urgency about getting a newsletter distributed.

The path to the Drupal cron UI is admin/config/system/cron. It is probably a good idea to add this path to some menu the editor has access to make it easy to find.


Adding a radio buttons in views exposed filters for published and unpublished drupal 7

This can be achieved using Better Exposed Filters module. If you need to do this programmaticaly then you may need to look at the code of this module. You need to implement the hook_theme as done in better_exposed_filters.module and implement the code to display as radio button as done in better_exposed_filters.theme(Function: theme_select_as_radios)

I would suggest using the module directly if that is an option.


where are menu item configurations stored?

Menu is a Entity, like a Node (sure, with some differences). There is a config and content, config you can export and import through UI, but not with content, this you will find only in DB.

Maybe you can find some modules to import/export content, but its not available at default install of Drupal 8.


After finding out all the possible options for implementing mathematical equations, and considering the requirement to create PDF, I got to the conclusion that the only way to do this is using a CKeditor plugin.

There is the fmath plugin, and I found a useful link: Configuration steps.

As JavaScript is loaded after page load, it was very difficult to generate PDF on the fly.


May I suggest an alternative approach of using the Themekey module. It was built to solve the exact issue you are facing:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server

The important thing to note about Themekey, is that the module works well with the external caching as well. Do check out its documentation for more.


Why is the "Recent log entries" report missing?

Check to make sure you have the module "Database logging" turned on.

THis is sometimes turned off for performance reasons.


I would like to split up the fields in the 'create new content' screen into sections

You can use the Field Group module to group fields together.

You can use the Field Permissions module to only allow access to certain fields based on users roles.


Manually trigger AJAX from custom JavaScript

It turns out that it's actually much easier than I thought, by using a custom jQuery event, in my case I called in postcodeValid:

'#ajax' => [
  'callback' => [$this, 'checkPostcode'],
  'event' => 'postcodeValid',
  'wrapper' => 'postcode-container',
],

I changed the JavaScript function I already had to:

$('#edit-postcode').bind('input', function() {
  var trigger = $(this);
  $(this).val(function(_, v) {
    if (isValidPostcode(v)) {
      trigger.triggerHandler('postcodeValid');
    }
    return v.replace(/\s+/g, '').toUpperCase();
  });
});

The isValidPostcode function is a simple test against my postcode regex, thanks to Delay ajax call on textfield to allow for typing I was able to discover this.