2 seperate feeds updating the same set of nodes (feeds module)

EDIT: there's a patch in this thread: https://www.drupal.org/node/1539224

I knocked something together that allows my second feed to update the nodes from my first feed. Not sure if this is the right way of doing things but it works. Here's what I did in case it helps someone else in future:

Created a custom processor that extends FeedsNodeProcessor
Copied across all of FeedsNodeProcessor's functions to the new class.
Overrided the existingEntityId function as follows (harvard_format is my secondary feed and pure_feed is my primary feed):

protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {

if($source->id == 'harvard_format') {

  $query = db_select('feeds_item')
    ->fields('feeds_item', array('entity_id'))
    ->condition('feed_nid', $source->feed_nid)
    ->condition('entity_type', $this->entityType())
    ->condition('id', 'pure_feed');

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'url':
        $entity_id = $query->condition('url', $value)->execute()->fetchField();
        break;
      case 'guid':
        $entity_id = $query->condition('guid', $value)->execute()->fetchField();
        break;
    }
    if (isset($entity_id)) {
      // Return with the content id found.
      return $entity_id;
    }
  }
  return 0;
}
elseif ($nid = parent::existingEntityId($source, $result)) {
  return $nid;
} else {

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'nid':
        $nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
        break;
      case 'title':
        $nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->config['content_type']))->fetchField();
        break;
      case 'feeds_source':
        if ($id = feeds_get_importer_id($this->config['content_type'])) {
          $nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
        }
        break;
    }
    if ($nid) {
      // Return with the first nid found.
      return $nid;
    }
  }
  return 0;
}

}

Copied across the the Process and newItemInfo functions from FeedsProcessor.
Overrided newItemInfo as follows:

protected function newItemInfo($entity, $feed_nid, $hash = '') {

$entity->feeds_item = new stdClass();
$entity->feeds_item->entity_id = 0;
$entity->feeds_item->entity_type = $this->entityType();
// Specify the feed id, otherwise pure_feed's entries in the feeds_item table will be changed to harvard_format
$entity->feeds_item->id = ($this->id == "harvard_format") ? "pure_feed" : $this->id;
$entity->feeds_item->feed_nid = $feed_nid;
$entity->feeds_item->imported = REQUEST_TIME;
$entity->feeds_item->hash = $hash;
$entity->feeds_item->url = '';
$entity->feeds_item->guid = '';

}


Is it possible to use different versions of same language with different prefixes?

Yes you can.

Go to the languages settings page (admin/config/regional/language) and click on the Add Language link.

There you can select a preexisting language, but below of that list is a Custom Language option.

Fill that form with your new language settings and there you have your new language.

To start, I'd suggest to export (admin/config/regional/translate/export) your main language and import it (admin/config/regional/translate/import) in your new language. It will give you a translated new language. Then, you can go to the translate interface and update the texts that must be different.


Add a Module Form to a front page region

Take a look at the Drupal block APIs. You need to use hook_block_info to define a block. Then use hook_block_view to return the rendered content of the block. You will still need to include the block, ether programmatically, or by using admin/structure/block.


Entity Field Query OR condition,between node title and a custom field

`
function hook_query_customproductstag_alter(QueryAlterableInterface $query) {
  $keys = $query->getMetaData('keys');
  $or = db_or()
    //->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE')
    //->propertyCondition('title','%'.$keys .'%', 'LIKE');
    ->condition('usage.field_usage_number_value', '%' . db_like($keys) . '%', 'LIKE')
    ->condition('node.title', '%' . db_like($keys) . '%', 'LIKE');

$query->condition($or);
}  `

fieldCondition didn't work because db_or is not a part of entity query.


How do I create a catalogue list that links through to my individual product nodes?

Now, I'm not using D7 yet, but Views has settings to turn fields within a node (your product nodes) into links to the originating node. Just go to your View that is your grid of products, check out the individual Fields you use, in their settings some of them (if not all of them) should have an option to turn the field into a link back to the original node.


How to filter an already rendered calendar view of a specific date with categories (taxonomy terms)?

If your "list of every event on that date" is generated by Views, you can add a Filter to Views based on Taxonomy Term.  This can then either be exposed to the user so they can pick Movie or Sport - or you can select which one you want explicitly for them.

See selection options below - you'd likely want "Taxonomy: Term" (and you'd be doing this in the Filter - not Contextual Filter).


Sort taxonomy terms alphabetically by default

I hijacked the code from /modules/taxonomy/taxonomy.admin.inc that runs when you click "Reset to alphabetical". I tweaked it a bit and you can place this code in a custom module and it will run every time you insert a taxonomy term.

/**
 * Implements hook_taxonomy_term_insert()
 */
function YOURMODULE_taxonomy_term_insert($term) {

  $vocabulary = taxonomy_vocabulary_load($term->vid);
  $tree = taxonomy_get_tree($vocabulary->vid);

  if($vocabulary->machine_name = 'MACHINE_NAME_YOU_WANT_TO_FORCE_ORDERING') {
    //Make sure the taxonomy doesn't have terms with two parents
    if ($vocabulary->hierarchy < 2 && count($tree) > 1) {
      $params = array(
        'values' => array(
          'vid' => $term->vid,
          'name' => $vocabulary->name,
          'machine_name' => $vocabulary->machine_name,
        ),
      );

      taxonomy_vocabulary_confirm_reset_alphabetical_submit(NULL, $params);
    }
  }
}

If you want it to apply to all vocabularies, you can remove the IF statement on line 7. Good luck!


Drupal search - 2 search pages using their own settings

First, I would consider to use Views along with exposed filters to create your special "search" pages. E.g. create a view which only lists blog entries and then add a filter for body text to it.

My next approach would be the Search API module along with the Search API Page module.

Last but not least, you always can write a module for that. ;) I would take a look at different search modules which already implement additional search pages.


How to remove all commerce coupon from database?

Since coupons are entities, you'll want to delete them using the entity functions. As an example, if I want to delete all disabled coupons, something like this should work:

$disabled_coupons = commerce_coupon_load_multiple(array(), array('status' => 0));
$disabled_coupon_ids = array_keys($disabled_coupons);
commerce_coupon_delete_multiple($disabled_coupon_ids);

If you need to batch them, you may want to try doing them in batches of 250-1000... not sure how many can be deleted successfully per batch. Then just let it run.


How can I get node url in rules for facebook auto post

Make sure when you use [node:url] in any code, it must be in "" so for example

$path = [node:url];

is wrong, it must be

$path = "[node:url]";

As another solution

When you Set a data value you can use Value textarea and php codes to generate the node url.

this is an example where I post a trimmed field_body and the node url to Facebook. If you need to post the node alias to Facebook, you can use

$nid = [node:nid];
$path = drupal_get_path_alias('node/$nid');

to get the alias then print it in the <?php segment.


How to use ctools modal to popup some fields of a node on node view?

I know that there is no codeWriting service here, but I can try to explain (with example) the process (not a universal way.. Will work only with the content the same type and same structure (suppose we have a content type with body, field_description and field_something)):

You need to customize (override) template of the content type:

example (node--MY_CONTENT_TYPE.tpl.php):

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php print render($content['body']); ?>

    <?php print ctools_modal_text_button(t('Click to see DescriptionField'), 'show-as-a-popup/' . $node->nid .'/field_description/nojs', t('DescriptionField'), 'ctools-modal-custom-modal-style'); ?>

    <?php print ctools_modal_text_button(t('Click to see SomethingField'), 'show-as-a-popup/' . $node->nid .'/field_something/nojs', t('SomethingField'), 'ctools-modal-custom-modal-style'); ?>

Create custom module
Create a function in my_module.module file which includes ctools' libraries and sends javascript settings:

example:

function _myModuleIncludesModal() {
  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();

    $customModalStyle = array(
      'custom-modal-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 800,
          'height' => 'auto',
          'addWidth' => 20,
          'addHeight' => 20,
          'contentRight' => 20,
          'contentBottom' => 20,
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.6,
          'background-color' => '#000000',
        ),
        'closeText' => 'Close',
        'loadingText' => 'Loading...',
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
      ),
    );

    drupal_add_js($customModalStyle, 'setting');
  }
}

Implement hook_menu() hook:

example:

function my_module_menu() {
  $items = array();

  $items['show-as-a-popup/%node/%/%ctools_js'] = array(
    'title' => 'Node Field',
    'page callback' => 'nodeFieldPopupCallback',
    'page arguments' => array(1, 2, 3),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Create a callback function:

example:

function nodeFieldCallback($node, $fieldType, $js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $output = $nodeWrapper->{$fieldType}->value();

  $return[] = ctools_modal_command_display(t('PoPUp'), $output);
  print ajax_render($return);
  drupal_exit();
}

Finally call our _myModuleIncludesModal() in "specific" node pages:

example (template.php):

function MY_THEME_preprocess_node(&$variables) {
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    _myModuleIncludesModal();
  }
}

Modal settings/options, templating and throbber templating can be found in ctools' help directory;
Don't forget to flush the cache;


Can I use a custom CCK Link field as URL for Ubercart Product Image

Digging into Ubercart, this is the theme function you are talking about:

/**
 * Formats a product's images.
 *
 * @ingroup themeable
 */
function theme_uc_product_image($images, $teaser = 0, $page = 0) {
  static $rel_count = 0;

  // Get the current product image widget.
  $image_widget = uc_product_get_image_widget();

  $first = array_shift($images);

  $output = '

';
  $output .= '';
  $output .= theme('imagecache', 'product', $first['filepath'], $first['data']['alt'], $first['data']['title']);
  $output .= '

';
  foreach ($images as $thumbnail) {
    // Node preview adds extra values to $images that aren't files.
    if (!is_array($thumbnail) || empty($thumbnail['filepath'])) {
      continue;
    }
    $output .= '';
    $output .= theme('imagecache', 'uc_thumbnail', $thumbnail['filepath'], $thumbnail['data']['alt'], $thumbnail['data']['title']);
    $output .= '';
  }
  $output .= '

';
  $rel_count++;

  return $output;
}

First off, I hope you didn't go in there and start hacking away, but rather copied the above to your theme's template.php file and renamed it YOURTHEME_uc_product_image() and made your modifications there :)  But, either way, from the declarations of this theme function, the only data you have to work are in the $images argument plus anything uberfunky returned by ub's image_widget.  You might want to throw in some debug code to see if anything in there is what you are looking for like this:

drupal_set_message('
' . print_r($images, TRUE) . '
');

at the start of your copied function.  Just remember to clear your caches/theme registry so drupal sees your function.


How can I hide search results until the user submits the exposed form?

You can change that under Advanced Views options (third column): Exposed form style:

After you choose Input required, you can adjust further options, including the text to display before any filters are active:

If you're using Better Exposed Filters module it has an option for it too:

  Input required
  Only display results after the user has selected a
  filter option.

It hasn't changed since D7, it works the same in D8 as it did in D7.


There are three different testing frameworks in Drupal 8.

1. Simpletest: Functional, Upgrade and Unit Tests

These should be located underneath src\Tests per the documentation linked in the Question comments. This corresponds to the namespace Drupal\my_module\Tests.

This is documented best at https://www.drupal.org/node/2166895.

2. PHPUnit: Unit Tests

Theoretically these could be anywhere with a phpunit.xml.dist file, but if you need to support running through Drupal's test runner (run-tests.sh) or drupal.org infrastructure then these must be placed in tests\src\Unit and the namespace corresponds to Drupal\Tests\my_module\Unit

3. Behat: Behavioral Tests

I think there is a movement to store behavioral tests in a directory parallel to tests\src\unit, but no official convention as Drupal core does not utilize Behat yet.


Theme a subscriber field in Simplenews issues

{{ simplenews_subscriber.field_lastname.value }}
In the header of this template:

Note that depending on the used caching strategy, the generated body
might be used for multiple subscribers. If you created personalized
newsletters and can't use tokens for that, make sure to disable
caching or write a custom caching strategy implemention.

To solve it I added in the sites/default/services.yml
services:
  simplenews.mail_cache: ~

  simplenews.mail_cache:
    class: Drupal\simplenews\Mail\MailCacheNone


I guess you are changing the id with '#attributes' => array('id' => 'foocats',),
And now the callback is not executed because the id is changed.

if you change your code it will work ( tested this in my own install )

$form['foocat']['subcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => $foocategory,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'edit_displayname_callback',
    'wrapper' => 'displayname',
  ),
  //'#attributes' => array('id' => 'foocats',),
  '#prefix' => '
',
  '#suffix' => '
',
  '#size' => 9,
);


Rewriting taxonomy term in exposed filter

The easiest way is to use hook_form_alter to alter the names displayed in the options.

An alternative and a bit more tricky way, is to create your own views_filter_handler for them term used in the view, and customize how the exposed filter form should look like. This is a good solution if you are creating many views and want a single place to do the alterations. See How do I add dropdowns in Filter Criteria in Views module? for more info.


Is inheritance between content types possible?

For Drupal 7 there's the Bundle Inherit module.


how can I debug theme.theme file in my theme using phpstorm?

Go to Preferences -> Editor -> File Types
Scroll down the Recognized File Types list until you find PHP; select it
In Registered Patterns add *.theme
Save

You can now set breakpoints in *.theme files.


Which Views hook do I use to alter the view results page before it loads?

The answer was to remove the views_get_view function as well as the set->display function. There was also no need to try to execute the exposed input. All that was needed is to simply set the default values for the variables I wanted in the views_pre_view hook, and then Views takes care of the rest as it finishes doing its thing. Here is the resulting, correctly working code:

function zipcode_filter_views_pre_view  ( &$view, &$display_id, &$args) {

    $view->display['default']->handler->options['title'] = "this is the new title";
    $view->exposed_input['distance']['postal_code'] = $_SESSION['zipcode_filter']['zip'];
    $view->exposed_input['distance']['search_distance'] = $_SESSION['zipcode_filter']['distance'];

}

Although, I don't understand why this works - Why do I not need to specify a display? Why did having the other parts of earlier code cause it to not work properly?


So, the solution is to add a new region into your theme.info.yml (say before_body)
Then the code you'd place into theme_name.theme be:

function theme_name_preprocess_html(&$vars) {
  /**
   * moves region before_body into before_body var inside basic html
   */
  if (isset($vars['page']['before_body'])) {
    $vars['before_body'] = $vars['page']['before_body'];
}
function theme_name_preprocess_region(&$vars){
  /**
   * Cleans before_body from standard html markup
   */
  if ($vars['region'] === 'before_body') {
    $vars['content'] = theme_name_clean_special_content($vars['content']);
  }
}
/**
 * Cleans content from basic markup
 * @param $content
 * @return \Drupal\Component\Render\MarkupInterface|string
 */
function theme_name_clean_special_content($content) {
  /** @var \Drupal\Core\Render\Markup $content */
  $content = preg_replace('~<\/?section.*?>|<h\d?.*?>.*<\/h\d?>|<\/?div.*?>~', '', $content);
  $content = preg_replace('/(?=<!-- (THEME DEBUG|BEGIN OUTPUT|THEME HOOK|FILE NAME SUGGESTIONS|END OUTPUT))([\s\S]*?)-->/i', '', $content);
  $content = preg_replace('/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))$/m', '', $content);
  return \Drupal\Core\Render\Markup::create(trim($content));
}

Just don't forget to add before_body variable into your basic html template.


Change the default value of the node reference via hook_alter_form

I can't think of any reason why your code would need to be in an after_build function, you would usually put it straight into the form alter hook. At the moment you've got the array keys the wrong way round. Without being able to see the structure of your form it's difficult to say exactly where the correct element is, but one of these should work:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  // Try this one
  $form['field_userid'][LANGUAGE_NONE][0]['#default_value'] = $user->uid;

  // Or this one
  $form['field_userid'][LANGUAGE_NONE][0]['uid']['#default_value'] = $user->uid;
}


How do I allow users to just click a marker on an OpenLayers map to go directly to the node?

Usually jumping to new page just by clicking object is not what users want, as they need to be sure first that the clicked object is correct one, this is why there is no built-in function and you do not see this much in the wild.

OpenLayers module has behaviours for this kind of actions. It seems that the core module does not have what you expect, and nobody has done it yet, so no easy configuration option :( Here is the guide how to create new behaviours from scratch. I would use Popup behavior as sample.


Unfortunately, sometimes answers on stackexchange are misleading.  It doesn't look like ANY classes within migrate_d2d extend MigrateDestinationEntity, that invokes a "prepare" hook.  So I think the question itself is misguided.

Looking in the migrate code, it looks like any class that extends abstract class MigrateDestinationEntity can call this process function see
/migrate/plugins/destinations/entity.inc,

on line 140:

// Then call any entity-specific handlers
migrate_handler_invoke_all($this->entityType, 'prepare', $entity, $source_row);

Rather than trying to find a place to call this from DrupalNodeMigration, which will never call this function, what you need to do is add a mapping for nid, and a mapping for "is_new".

In your class that extends the DrupalNodeMigration class, in the __contruct() function, just make sure to add a mapping for nid and is_new.

$this->addFieldMapping('nid', 'nid');
$this->addFieldMapping('is_new')->defaultValue(TRUE);

Otherwise, nid will be automatically assigned.


How can I upload an image for a specific image style?

Image styles are “derivatives” - they’re automatically derived from the original image you uploaded. A UI to manipulate those derivatives wouldn’t really make sense, the whole point is that they’re generated automatically.

If you can’t change the way you’re working, as in upload the 2x version as the original, and use a 0.5x image style for desktop, and the original upload for Retina, you could always replace the generated styled image files manually via sFTP or similar. But it would become a pain quite quickly.


Why is my view not displaying Solr index results?

The problem was i forgot to look at the php-error log/watchdog. There was a custom module which had some code which was causing a fatal error on all links being generated. Fixed that issue, all was working after.


Field image in attachment affect block settings

View module provides ability to override changes based on display. Please check steps below:

Go to Attachment display.
Click on Down arrow, next to Fields, and click on Rearrange. As per shown in screenshot.

Click on For drop down and select "This attachment (override)" and click on Apply button. check screenshot below:


Dealing with errors 403, 404 in Google Webmaster Tools

For Taxonomy terms you can use Disable Term Node Listings module (https://www.drupal.org/project/disable_term_node_listings)

There is also a great write up on drupal.org about similar issues: https://www.drupal.org/node/345620

In short use robots.txt to disallow paths like ones you specified above. This will prevent google from indexing those pages in first place.


Hook_menu() and its page callback: how to redirect users on a condition?

If you are altering a hook_menu item that an existing module defines, use hook_menu_alter. You will receive all menu items by reference, and you can alter the necessary menu items as necessary.

In a hook_menu() implementation, if you define example path, http://example.com/example, http://example.com/example/foo, http://example.com/example/foo/bar... and so on will have the same page callback and other properties. However, if you define http://example.com/example/foo/mine, that page will use the explicit definition of example/foo/mine. There is a negotiation with MENU_DEFAULT_LOCAL_TASK too.

PS: If you are trying to redirect comment pages to their node paths, try this module.


Best way to add a search function to user profiles

You could code up a form_alter() in a custom module that could put search in that admin page.  Or, you could just use www.yourhost.com/search/user to search user accounts.  And if you have advanced search and are using content profiles, you could also restrict your regular node search to that content type, eg type:profile terms to search for in those nodes.


The Webform module just extends Drupal's Form API. Most of the elements available to a webform can be used in custom-built forms. For example, you can use the WebformMultiple element in any FAPI form.

@see https://git.drupalcode.org/project/webform/blob/8.x-5.x/src/Element/WebformMultiple.php


Farbtastic color picker to change the background color of text field input?

Something like this?

/**
 * Show farbtastic colorpicker widget.
 */
(function ($) {
  Drupal.behaviors.my_color_picker = {
    attach: function(context) {

      $(".edit-my-color-picker", context).on("focus", function(event) {
        var edit_field = $(this);
        var picker = edit_field.closest('div').parent().find(".my-color-picker");

        // Hide all color pickers except this one.
        $(".my-color-picker").hide();
        $(picker).show();
        $.farbtastic(picker, function(color) {
          edit_field.val(color);
          // background color, may need to add # to color.
          $(edit_field).css("background-color", color);
        }).setColor(edit_field.value);
      });

    }
  }
})(jQuery);

Notice I added 'context' to the original selector and changed 'live' to 'on'. Live function is deprecated as of jquery 1.7.
I also changed it so the edit_field variable stores the jquery object.

Drupal does already have a couple of color fields, on of which is HERE


How to print an entity bundle field from one with multiple values

Try the following and load the actual entity to get its field values.

The code assumes you have drupals entityTypeManager injected via dependency injection. Otherwise use \Drupal::entityTypeManager() isntead of $this->entityTypeManager()

// Get the entity ids.
$entityIds = $this->entityTypeManager()->getStorage('school_objects')->getQuery()
  ->condition('type', 'homepage')
  // Add more conditions if you need.
  ->execute();
// I assume only one id is returned and reset the array. Otherwise go over
// each Id with a foreach() and do this in a loop.
$entityId = reset($entityIds);
$schoolObject = $this->entityTypeManager()->getStorage('school_objects')->load($entityId);
// Now get the values of your field. I assume the fields machine_name is 'field_hero_banners'. Adjust if needed.
$values = $schoolObject->get('field_hero_banners')->getValue()
// Loop over all values.
foreach ($values as $item) {
  $value = $item['value'];
}


What's the difference between globals $base_root and $base_url

$base_root is:

  The root URL of the host, excluding the path.

e.g. http://localhost

$base_url is:

  The base URL of the drupal installation.

again, e.g. http://localhost

The only situation I can think of where these would be different is if your Drupal installation is in a sub-folder of the web root. In that case $base_url would also contain the sub-folder in the path, e.g. http://localhost/drupal

The descriptions in the documentation are exactly the same for both across versions 6, 7 and 8.


How can we override view field template in drupal 8

There is a detailed answer in this Q: Overriding views-view-field.html.twig for specific fields.

You can simply use views-view-field--fieldname.html.twig. Of course, don't forget to clear your cache after creating the new template.


There's now a table component module for webform, take a look to it.


How to set body field display programmatically on node type install?

You can access and alter the view mode configuration via field_bundle_settings(), (which is basically a shortcut to variable_get and variable_set):

$bundle = 'my_node_type';
$bundle_settings = field_bundle_settings('node', $bundle);
$bundle_settings['view_modes']['teaser']['custom_settings'] = true;
field_bundle_settings('node', $bundle, $bundle_settings);


How to change the image size within a Drupal view

You can create an image style at admin interface and then use same style at your view settings.

Navigate to admin/config/media/image-styles and add new style. After that edit image field inside your view which will look like below image.

In image you can see Image style which you have created in earlier step. This way you can change the image sige at views.


Best practice for language key for "und" in hook_form_alter

Unfortunately, your self-answer is not so universal. Field language and node language are not the same things.
Field language is needed only if you are using Field Translation API (for example Entity translation). When you start using it, some fields are converted to translatable.

Translatable fields have language code, which really makes sense. But if the field is not translatable, the language code will always be (and for all content types, entities, etc) — LANGUAGE_NONE (best to use the constant LANGUAGE_NONE and not the string 'und').
So with your solution you can get a situation when a node is Russian, but a field of the node uses LANGUAGE_NONE.
Happily, fields are attached to the form with '#language' key, which always contains the correct language code.

$lang = $form['FIELDNAME']['#language'];
$form['FIELDNAME'][$lang][0]['value']['#value'] = $value;

If you have no access to attached form, Field Language API functions can be useful.


How to show categories and regarded node in drupal 7

Create taxonomy(first add vocabulary and then add terms) by going to
the below path:

  admin/structure/taxonomy

Configure your content type to add a field of type 'term reference':

  admin/structure/types/manage/article/fields

Add content and select your brand field.
Create a view by doing the following configurations shown in
attached image.


For reference, there was a backwards-compatibility break in CKEditor v4.6 - it removed some of its own paste-from-Word button's cleaning. See this discussion on the Drupal side: https://www.drupal.org/project/drupal/issues/2871539

Note comment #6 there offers another workaround - responding to the
afterPasteFromWord CKEditor event in some custom Javascript and filtering exactly as desired.


Drupal Commerce "product type" vs kickstart "variation type"

Product variations types within Drupal Commerce Kickstart are the same as product types referenced by vanilla Drupal Commerce.

I think the label changed within Kickstart so that it is a little less ambigious.


Cannot change checkboxes options in drupal form using AJAX callback

* Update using new code *

Form definition:

$form['tags']['ask_button'] = array(
  '#type' => 'button',
  '#value' => t('Next'),
  '#ajax' => array(
    'callback' => 'ajax_tag_callback',
    'wrapper' => 'replace_tagfield_div',
  ),
);
$form['tags']['values'] = array
(
  '#prefix' => '
',
  '#suffix' => '
',
);
if(isset($form_state['values']))
{
  $final = drupal_map_assoc(array(t('SAT'), t('ACT')));
  $form['tags']['values']['question_tags'] = array(
    '#title' => t("Tags"),
    '#type' => 'textfield',
    '#value' => $tag_names, // Note - you didn't show how this is created
  );
  $form['tags']['values']['table'] = array(
    '#type' => 'checkboxes',
    '#options' => $final,
  );
}
else
{
  $form['tags']['values']['question_tags'] = array(
    '#title' => t("Tags"),
    '#type' => 'textfield',
  );
  $form['tags']['values']['table'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  );
}

And your ajax callback will look like this:

function ajax_tag_callback($form, &$form_state) {
  return $form['tags']['values'];
}

* Original response *

Not enough information provided to say for sure what your problem is, but it's likely one of these:

Problem 1:

You are making changes to the form in the ajax callback. You cannot do this. Here is how the form API works.

1) Form is generated

2) Form is cached on server

3) Form is sent to user

4) User initiates some ajax

5) Values are sent to server

6) Form is rebuilt, with submitted values

7) New form is cached on server

8) Form is sent to ajax callback

9) Relevant values are returned from ajax callback

10) Drupal sends data to browser, and the new parts of the form are injected into the page

11) User submits form

12) Drupal checks submitted values to the cached form, to see if the received values match the cached form, giving an error if they don't. This is the major strength of the Form API.

Step 7 and 8 are the key points here - the form has already been cached before it is sent to the ajax callback. So any changes you make won't be part of the cache causing errors.

Problem 2

You don't have a #prefix set on $form['tags']. You have only set the suffix. You need to provide a wrapper with your #ajax definition (which you didn't show us), so maybe the wrapper you have provided does not exist.


Something I can't understand in Acquia Marina theme

The Acquia Marina theme is a sub-theme of Fusion core. $primary_links_tree is defined in the template file of that theme, in the fusion_core_preprocess_page(), which the preprocess function that is called before page.tpl.php is used to output a page. Starting from line 80, you find the following code:

$vars['primary_links_tree'] = '';
if ($vars['primary_links']) {
  if (theme_get_setting('primary_menu_dropdown') == 1) {
    // Check for menu internationalization
    if (module_exists('i18nmenu')) {
      $vars['primary_links_tree'] = i18nmenu_translated_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    else {
      $vars['primary_links_tree'] = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    $vars['primary_links_tree'] = preg_replace('/<ul class="menu/i', '<ul class="menu sf-menu', $vars['primary_links_tree'], 1);
  }
  // ...
}


change entityform value via function before save

OK I now see what the problem is. LANGUAGE_NONE should not have quotes around it. It's a constant. Been there, done that. :)


How to link a field to node title in view

You get %20 because the browser replaces/fixes/auto-corrects the empty space between your title with %20 as empty spaces are not allowed in URLs.

EX: If you try to go to drupal.org/Hello World, browser url changes/corrects it to drupal.org/Hello%20World.

Here is another possible option:

Add Path as a field, and checkmark exclude from display.

Make sure Content: Path is above Content: Cities, if not please re-arrange it.

Then in cities, for link path put [path]


Facets blocks populated with incorrect field data and strange behavior

When preparing the data for the Search Page, make sure that the fields you index are indexed as strings and not full text. This is what caused the problem.


Drupal 7 views 3 add custom filter handler for an existing field

To add a Drupal 7 views custom filter handler for an existing field, you should implement the following hooks.

//in yourmodule.module
/**
 * Implements hook_views_api().
 */
function yourmodule_views_api() {
  return array(
    'api' => 3,
  );
}

// in yourmodule.views.inc
/**
 * Implements hook_field_views_data_alter().
 */
function yourmodule_field_views_data_alter(&$result, $field, $module) {
  if($field['field_name'] == 'field_your_existing_field'){
    $name = $field['field_name'];
    foreach ($result as $table_name => $table_data) {
      if (isset($table_data[$field['field_name']]['field'])) {
        $result[$table_name][$field['field_name'] . '_value']['filter']['handler'] = 'your_custom_handler_in_separate_inc_file';
      }
    }
  }
}

//your custom handler class in separate file
class your_custom_handler_in_separate_inc_file extends existing_handler_class{
// your code goes here
}

//Don't forget to add your_custom_handler_in_separate_inc_file.inc file in your module's .info file like.

files[] = your_custom_handler_in_separate_inc_file.inc


You can try:

/**
 * Implements hook_services_resources
 */
function test_module_services_resources() {

  $resources = array();

  $resources['search_results'] = array(
    'index' => array(
    'callback' => 'test_module_search_service_results_index',
    'file' => array(
      'type' => 'inc',
      'module' => 'test_module',
      'name' => 'resources/search_results.resource'
    ),
    'access arguments' => array('access content'),
    'args' => array(),
    ),
  );

  return $resources;

}

Ensure the resource callback test_module_search_service_results_index is located in your module subfolder

test_module/resources/search_results.resource.inc

Then try hitting http://www.example.com/api/search_results (using your site services endpoint)


How can I write an if else statement in Twig based on commerce stock quantity?

This is very close - but it seems you are missing the actual stock level value from the object. Start by doing something like:
{{product.variation_field_stock_level.0|json_encode}}

Run it through a json cleaner to make it readable, like: JSON Cleaner
You will see this:
{"#type":"html_tag","#tag":"p","#value":0}

Now the conditional will be:
{% if product.variation_field_stock_level.0['#value'] > 0 %}
    {{ product.variation_price }}
{% else %}

Sold

{% endif %}


Trouble installing drupal-project with Composer

Despite not technically being a Drupal question, this gets asked a lot. The answer, for anyone coming across this using various local dev stacks - you need to inform your command line of where PHP ($PATH variable) is that you want to use. Otherwise it will default to what is installed on your machine, likely very out of date.


Displaying a weform in modal (might be called popup as well) it is a lot simpler than you thought
Lets assume your webform has URL /contact than you can create a link in the following manner
Contact US

Pressing that link will have your form open in a modal with error validation and messages inside the modal
NOTE:
At least in my case I had to also add the following hook_preprocess_page in the .theme file
function THEMENAME_preprocess_page(&$vars) {
    //custom logic of when to include the library
    // ....
    $vars['#attached']['library'][] =  'core/drupal.dialog.ajax';
}

Some people have reported that this is not needed but I assume some other module included this library for them ...


Which are the file_save_upload() validators?

You can see the validators in core at the end of this listing:

http://api.drupal.org/api/drupal/includes%21file.inc/group/file/7

the ones starting with file_validate_

Also there's an example of the array structure here: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_validate_picture/7


According to PHP manual

  A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

You can use below code instead

print ($is_mobile ? "TRUE" : "FALSE");


Installing the Media Module + WYSIWYG Module on Acquia Cloud

Short answer: turn off livedev in your Acquia Cloud dev environment.

Longer Answer: I was trying to drush my modules and do basic site building in their environment using the livedev option. But they don't let you run mkdir and scp live in their environment via CLI.

Their recommended workflow will have you add your modules/libraries locally, commit via git and then push up to their environment.


How to display only one Commerce product variation in Views?

Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.


How to give access to the files of node for individual users?

To do the access checking yourself you'll need to write a hook_file_download().

In broad strokes you'll need to get the actual file object (see this question for help with that), find the references with file_get_file_references(), and finally load them to check each reference (probably just one but it would be unwise to assume that's true) to see if the current user is given access to the file.


How do I programmatically get a styled version of an image via imagecache in D7?

theme_image_style. Imagecache is replaced by image style in Drupal 7.
Example:

print theme('image_style',array('style_name' => 'thumbnail', 'path' => 'path/to/image'));


how to delete the files uploaded in the file field?

I also crossed this issue.
I just did these following steps.

edit the node, and delete the file from the field (dont upload now) and save it.
then edit the node, now upload the file (with same name) and save it.

Its worked for me. without xxx_0 like that.

Thanks


After enabling utf8mb4 on 7.50, cannot enable update module

Hacking core, not a great answer.  This is just the best I have found so far.

In modules/update/update.install:

/**
 * Implements hook_schema().
 */
function update_schema() {
  $schema['cache_update'] = drupal_get_schema_unprocessed('system', 'cache');
  $schema['cache_update']['description'] = 'Cache table for the Update module to store information about available releases, fetched from central server.';
  return $schema;
}

So I went to modules/system/system.install:

  $schema['cache'] = array(
    'description' => 'Generic cache table for caching things not separated out into their own tables. Contributed modules may also use this to store cached items.',
    'fields' => array(
      'cid' => array(
        'description' => 'Primary Key: Unique cache ID.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'data' => array(
        'description' => 'A collection of data to cache.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
      'expire' => array(
        'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'created' => array(
        'description' => 'A Unix timestamp indicating when the cache entry was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'serialized' => array(
        'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
        'type' => 'int',
        'size' => 'small',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'expire' => array('expire'),
    ),
    'primary key' => array('cid'),
  );

And I changed the length of the varchar for the primary key from 255 to 191.  Now I can enable and disable the update module properly.


I had a look at this interesting module and I am afraid I didn't see a way to do this. I tried Views rewriting, to collect all email addresses from first and second email field into a third one. Standard Views presented the new dynamic field fine... But, this is not supported by the Views Send module. It seems like it would need the data available in the database, and not dynamically generated.

If you want to have that working in an easy way, you could try adding a Computed Field to your content-type. This computed field would then store all the emails from your first and second field. And this concatenated string would be available to Views Send.

Would that be a way out for you? If so, here is an 'draft' version for the code to put in the "Computed Code (PHP)" textarea:

$field_main = field_get_items($entity_type, $entity, "field_main");
$field_additionals = field_get_items($entity_type, $entity, "field_additional");

if(isset($field_main[0])) {
  $emails[] = trim($field_main[0]["value"]);
}

foreach($field_additionals as $field_additional) {
  if(trim($field_additional['value']) !== '') {
    $emails[] = trim($field_additional['value']);
  }
}

$entity_field[0]["value"] = implode(', ', $emails);

Voila! Your computed field is readily available in your Views and Views Send containing all the emails from both fields.


I had same issue , but i solved like this

$form['fieldset']['select-user'] = array(
   '#type' => 'select',
   '#title' => t('Select a user'),
   '#options' => select_user_dropdown_options(),
   '#description' => t('Select a user'),
   '#size' => 10,
   '#multiple' => TRUE,
   '#attributes' => array(
      'id' => 'edit-select-user',
      'style' => 'width:600px',
   )
);

Code:

Form:

Output in submit:


perform action if user is not logged in for 24 hours

It is sending every hour because cron is running every hour, and the user has not yet logged in to change the timestamp. There is no check to see if the email has been sent, or when it was sent.

You can either update the user's timestamp to $now, which will stop the email from being sent for the next 24 hr., or set a flag on the account to say that an email has been sent.


How to remove a Views row if field equals value?

I would use a views row template override for this. Do the following in a Development site first.

1) In the view, expand the Advanced options and click on the Theme: Information link. This displays all the available theme template suggestions.

2) Under the heading "Row style output" you will see all the possible template suggestions. Which one you override depends on your needs, but the last listed is the most specific so I would start there. Select it with your cursor and copy the file name.

3) Open this file in your code editor: sites/all/modules/views/theme/views-view-fields.tpl.php

4)Save it as the most-specific suggestion (the value you copied in step 2) and save it to your theme's template directory (e.g., sites/all/themes/yourtheme/templates or sites/all/themes/yourtheme/templates/views)

5) Now you can edit the template (the one we just saved to your theme). You can use a combination of html and PHP to achieve the exact markup and logic you want. Generally it's best practice to not code a lot of logic into your templates (use preprocess functions instead), but simple logic like checking if a field is present or has certain values is fine to include in the template.

There are many different ways to do this, but here is an example (change field_custom_boolean to the machine name of your custom global field ...

 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>
  <?php
  /* if custom field is present and set to 1 */
  if (isset($content['field_custom_boolean']) && $fields['field_custom_boolean'] == '1'): ?>
    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

6) Save file and flush all caches. Now when you check the view Advance:theme information settings, you should see your template override listed in boldtype. When you load your view it should only display rows for records where the custom global field is set to 1.

Good luck.

For more info on Views templates, see:

https://api.drupal.org/api/views/theme%21theme.inc/group/views_templates/7.x-3.x

https://www.drupal.org/docs/7/modules/views


Try Convert Excel Data Types in the corresponding column.

Excel 2010

Click the File tab, Click Excel Options, Click Advanced.
In the Editing Options, verify that the AllowEditing directly in cells check box is selected. Click OK.
Double-click the cell you want to format, and then press ENTER.
Click the error button next to the cell, and then click Convert to Number on the shortcut menu

How to convert text to numbers in Excel


How do I stop a stuck-and-running cron job (Elysia Cron on Pantheon)?

update elysia_cron set running = 0 where name = '[THE NAME IF YOUR CRON JOB]';

Actual sql query based on Mika A answer above


How to change calendar entry background based on taxonomy?

Look at the HTML source of your calendar display, and try to find:

Calendar entry stuff

The CSS class name might be something like "block block-calendar block-calendar-entry" but you just want the most specific one that works, and only shows on each calendar entry.

Use CSS transparent coloration of the individual entries:

/* Colors a calendar entry lighter */

div.block-calendar-entry {

background-color: rgba(255, 255, 255, 0.3)

}

The first three numbers give the RGB value, and the last one gives the opacity.

Since 255, 255, 255 (maximum red, green, and blue) would be white, an opacity of 0.3 (30%) will lighten any background color that bleeds through from the parent container.


Add all related content from entity reference with views

Click the "More" link in the contextual filter. That fieldset is collapsed by default but you'll find the option to make exclusions there. You may have to exclude the current node ID separately--not sure about that.


Can you set an image that is part of a custom content type as the background image in a view?

Set all of your field to hidden, then add a Global: Custom text field (not hidden). In that field you add all of your fields back via the replacement patterns, making sure to wrap them in divs (or appropriate tags) with appropriate classes, and that your image is contained in the outer div. something like this:

  [image]

[title]

Then apply CSS to get the overlay effect to your liking. Text Blocks Over Image


So the problem was that I have various pages in my module which are each separated in their respective files e.g. mymodule.module, mymodule.page2.inc, mymodule.page3.inc etc

The issue was that the form of the block was in mymodule.page2.inc so when the user navigated to page3 the methods of the form where not being loaded.

The solution was to copy all the form methods into mymodule.module since it is like the parent of all the pages, so then the methods were accessible from all the pages.


Develop a module that adds a new content type with custom fields

Although its possible to do programatically, your easiest bet would be to use features.

This is how you would do it:

Manually create your content type
Manually add fields
Create a new feature and export the content type (and its fields)
Done!

Now if you install this feature is a fresh Drupal installation that content type and fields will be automatically added.


How can I add a condition to the list of taxonomy a view is created from

The reason why you can't add a Filter based on a Taxonomy field is because you're building a Content type views and that information simply isn't available directly from content tables in the database. If you were using Taxonomy term views then you could add that filter directly.

But since you have an entity reference from your Content to the Taxonomy term, it is possible to add that extra information into Content Views, so you will be able to Filter your Content based on a Taxonomy term Field that is on the taxonomy term that your nodes are referencing.

With Relationships in Views you're allowing Views to reach into other database tables and use data from them, if they are somehow related to the entities the view is based on.

Here's how you do it in your case:

Add a Relationship to the field in your content that is referencing your relevant Taxonomy Taxonomy term referenced from field_mytermref

If you Require it, it will filter out only the nodes where that field isn't empty.
Add a Filter hide from public.

It will now be available in your Add Filter list because you added the Relationship in the above step, and that Relationship will be selected by default.

Adjust the Operator and Value so that it's not equal to Hide from public, or the other combination that it's equal to it being False.

Now your results will only show the nodes tagged with terms that are "public".
To adjust the Exposed filter the easiest is to use the Limit list to selected items option in its settings, and select only the terms you want to appear (Use the Ctrl key).


How to provide email notifications to admins for *all* comments?

I see that you've already found the Comment Notifications comparison page over at Drupal.org - but also that you say you have not found the module you're looking for there.

However, from the description of your requirements, it sounds like the Notify module is pretty close.

Since it uses a digest format and depends on cron, it will not give your site admins instant notifications of new content, but otherwise, it matches your description.  Most important, It will send out notifications about all new comments, all new nodes, or both.

Disclosure: I am a co-maintainer.


Not fully understanding the output you really want to achieve, but here's examples on how to count the results coming from the database

get count with db_select

OR

rowCount

Let me know if any of those work for you.


display link after finishing coutdown time

Have a look at the project page. It says

You can use jQuery Countdown in two different ways, one is using theme('jquery_countdown'), the other is using jquery_countdown_add().

In the following example, we display an alert box saying "You are done!" after counting down from 10...

<?php
  echo '
10 seconds!
';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>

You can use the above example to achieve your requirement.


Unable to run update.php or update modules from web interface

update.php does not update modules. It updates the database state if needed (after installing module updates, aka db-update).

Did you check the permissions of your /modules/contrib/* filesystem? When you update your modules with the admin UI, your webserver's user (apache or www-run...) needs to have write permission there.

Did you install your instance with composer? If so, do not use the admin UI.

Maybe, check the docs again: https://www.drupal.org/docs/user_guide/en/security-update-module.html


I'm not aware of a simple way to provide checkboxes of what fields you want to show for a node form.

You could probably use Conditional Fields to show 1 field type you create called desired_fields it simply has checkboxes for artist, publisher, performers, band, producer, as they check those boxes you could have a condition in Conditional Fields that Shows the field in the node form.

If you're comfortable coding you could probably have a custom form that gets the choices you want and then shows the form.

Both approaches will get complicated if you have required fields.


drush 8.1.9 on php 7 not giving any "drush status" in docroot folder

Drush usually does this when it cannot find a Drupal installation, which happens when it cannot find a settings.php. Did you go through the installation process yet? (visiting install.php on the browser or doing drush site-install)


How to resolve "Referenced error: Highcharts not defined" when using Easychart?

Easychart 7.x-3.7 recommends version 4.2.7 of the Highcharts library. This is also what you can see in this specific commit.

And the Easychart project page states "... v4.x of the Highcharts library".

So it appears that using Highcharts 5.0.3 is not yet supported, which probably also explains the folder problems you described in your own answer. I don't think that you're missing anything else (or some other "latest" module) that you're missing (as long as you stick to the recommended version of Highcharts you should be fine).

PS: Be aware that there is also the feature request about "make use of new Highcharts 5.0.0 methods" (for the Easychart plugin).


Getting WSOD for non-LDAP User with Domain and LDAP modules enabled

Of course, shortly after I post this, I am able to fix it by deleting and recreating the entry for the ldap server. Hope this helps someone else save lots of time (-:


I dont know whats OA2 friendly but Case Tracker, and Project Management are both D7 friendly.

From the project page of Case Tracker:

  Actually, the 7.x-1.x-dev version has the content types for Project
  and Cases working without problems. The Notifications, Actions and
  View integration that needs to be tested.

  The development is active and we're working toward a release. Check
  out the 7.x-1.x branch and post your patches!

From the project page for Project Management:

  Project management software, allowing you to manage:

  Organizations, Teams, People, Projects, Tasks, Tickets, Timetrackings,
  Notes, Invoices, and Expenses. Each of these features is managed as a
  separate module within the suite.


Create a View that Displays a group of Taxonomy Terms

If you want to group Assets just by the Campaign (taxonomy) image, you can easily set the Grouping feature under Format to the Image field.

You have to add the Relationship for the taxonomy field first, as you have found out, then you get all the information related to the referenced taxonomy term into the Views. Without that Relationship you only have the Taxonomy term ID available, as the Taxonomy reference field only stores that info.

When you add the Relationship you can add the Taxonomy image field (Campaign image). Each Asset will then show its associated campaign image in its row.

That's when you can use Group by field and set it to the Campaign image. This will split the Asset results into Campaign groups with the image field as the "group header". You will still see the image displayed in each row, which you probably don't want, so you edit the Campaign field setting in Views and choose Exclude from display. This way the image will only display in the "group header" and won't display next to each Asset result.

If you need to display more info about the Taxonomy (Campaign) in the "group header", for example the name, image, and the description, you can add all those fields to your Views, Exclude them from display, and set them all to group by.

But sometimes the styling that comes out of this strategy isn't good enough, the HTML can be a bit unexpected. You can solve that by using Custom text field after all the Taxonomy fields where you enter your own HTML with the taxonomy field values printed out through tokens. And Group only by the Custom text field.

I've written an article about this if you need more detail: Grouping by multiple Fields in Drupal Views


This isn't something I've tried myself, but if you create a form with a file element, you should be able to control the $_POST['id'] that Drupal looks for by manipulating the id of the file-element.

That way the file should get passed on to the forms submit function, and then you can do whatever you want with it's content and react accordingly afterwards.


Add a CSS class to a certain text field for node display

Another option would be to use Display Suite if you didn't want to use hooks in template.php.

This would allow you to add the class directly from the content type edit page, this would probably be a little easier to manage if you started adding more classes to other fields.

After downloading Display Suite, you would need to enable: Display Suite, Display Suite UI, Display Suite Extras.
Then go to /admin/structure/ds/list/extras and check Enable Field Templates
Go to your content types manage display page and use the "Select A Layout" dropdown, this will enable display suite for that view mode under that content type.
Arrange your fields as needed and click the gear button to the right of the field and select Field Template: Expert
Check "Field Item" or any of the wrappers and add a class and an element and you're done.

It may seem like a lot to do to complete your specific task but it will make your life much easier in the long run.  I haven't built a single site without display suite since I discovered it.


How to allow user of certain role to create user only of selected roles?

Try Role Delegation

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


I can see a few problems at first glance:

'access callback' => TRUE, will mean everyone gets access no matter what and make 'access arguments' redundant.

The default access callback is user_access, which would accept your access arguments of array('access content'). So to use that just omit the access callback line.

$items['achievementList/list'] = array( is a strange path.
Generally best to keep it all lower case but that's not a requirement.

'page arguments' => array(1), will be passing in the string "list" to your achievementList_generate_table() function, but there is no point passing in a parameter that never changes and you arent actually using it, so just array() is fine for those arguments.

For more information I recommend reading all of the documentation for hook_menu().

The real problem though would be that your callback function is not returning anything for some reason.

(as per Clive's comment) I'm going to assume you are using Drupal 7.
In which case your call to the theme() function is incorrect.

In drupal 7 all variables going into the theme function should be in an array, so your line should look like this:

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


The HTTP flag is being set by your browser as you're accessing Drupal over HTTP (and thus vulnerable to cookie hijacking). Drupal creates 2 different cookies (an unsecure HTTP one, and a secure HTTPS one) depending on what protocol it detects.

If you want only secure sessions, force HTTPS at the web server or application level (depending on your stack configuration).


Upgraded Drupal 7.37 to 7.38 using Drush and its not working. update needs a higher bootstrap level to run - Error

Make sure your Drush commands are issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site, is it?), and then retry your Drush comand ... Seems that is what is causing your problem ...

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...


using drupal 7 functions in external files

Make a copy of the index.php file and rename it to foo.php. index.php ships by default with Drupal 7 and can be found in the root of the Drupal source.

Remove the last call to menu_execute_active_handler() from the new file. This is the router that calls an appropriate page handler based on the query string. You wouldn't need this.

This leaves:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/* Stub */

As you can see, Drupal is now bootstrapped fully. This makes the API methods of Drupal core and all other enabled core and contributed modules available for use in this script from the fourth line.


Verify your configuration at admin/config/media/file-system on the multisites. "Public file system path" may be configured to sites/default/files.


how to add field programmatically in Drupal 7 with dynamic content value?

I'm not sure what you are trying to do. But if you are trying to add a new field programmatically, below is a code snippet that can get you started.

    $myField_name = "my_new_field_name";
    if(!field_info_field($myField_name)) // check if the field already exists.
    {
        $field = array(
            'field_name'    => $myField_name,
            'type'          => 'image',
        );
        field_create_field($field);

        $field_instance = array(
            'field_name'    => $myField_name,
            'entity_type'   => 'node',
            'bundle'        => 'CONTENT_TYPE_NAME',
            'label'         => t('Select an image'),
            'description'   => t(''),
            'widget'        => array(
                'type'      => 'image_image',
                'weight'    => 10,
            ),
            'formatter'     => array(
                'label'     => t('label'),
                'format'    => 'image'
            ),
            'settings'      => array(
                'file_directory'        => 'photos', // save inside "public://photos"
                'max_filesize'          => '4M',
                'preview_image_style'   => 'thumbnail',
                'title_field'           => TRUE,
                'alt_field'             => FALSE,
            )
        );
        field_create_instance($field_instance);
        drupal_set_message("Field created successfully!");
    }

Hope that works

Muhammad.


What is InstallerException and can it be thrown from a hook_install() implementation?

No, this is not for hook_install(), this exception is for errors during installation of a new drupal site:

install.core.inc:

function install_drupal($class_loader, $settings = []) {
  ...
  try {
    // Begin the page request. This adds information about the current state of
    // the Drupal installation to the passed-in array.
    install_begin_request($class_loader, $install_state);
    // Based on the installation state, run the remaining tasks for this page
    // request, and collect any output.
    $output = install_run_tasks($install_state);
  }
  catch (InstallerException $e) {
    ...
  }
}


You can accomplish this with the Rules module, and the Domain Rules module.

  Adding Rules module actions related to Domain Access module.
  Allowing automation of different actions needed to create/modify/delete domains.

  First version includes:

  rules_action_create_domain - create new domain using given arguments
  rules_action_delete_domain - delete existing domain
  rules_action_set_user_defaults_domain - set a given role access to a given domain
  rules_action_set_node_domain - set domain to a node
  rules_action_set_domain_theme - set a theme to a given domain


Which Rules Event can I use for automatic login from main site to sub site with same database after clicking on a link?

I'm pretty sure that the "... Content is viewed, but actually it doesn't get called at all ..." part of your question is not correct. And that this Rules Event does get called (if not you've found a major Rules bug ...), but that it is NOT the right Rules Event to use for your scenario. Read on for details (and a possible solution) ...

You should be able to get this to work, using the Rules module, using the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. Using Rules event " Content is viewed " is typically 'too late'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for more details on that. Adapt your rule to use this event, and (just for temporary unit testing) add a Rules Action (as the very first Rules Action) to "Show a message on a site", e.g to say 'Bingo, let the Rules party begin (we did find a Rules Event to continue building on)'.

Moreover, as per the http://[node:author].[site:url-brief]/ajax_callback.php?context=buyer-redirect&username=[account:name]&nid=[node:nid] URL that you mentioned, you can make the value of the URL arguments (= such as the value of the context argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

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

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

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

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

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

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


Separate home page per domain in multilingual setup (i18n)

I would

Setup a "Page manager"-page, and call it "Front".
Set the homepage to "/front".
Create one variant for every domain in the front-page. Fill with relevant content.
Create a ctools "Domain access plugin". That wouldn't be many rows of code, see my brief tutorial
Use the access plugin to setup a selection rule for every variant/domain.


404 errors for pages other than homepage when uploaded to web-server

Do you have an .htaccess file in your root of your installation?

Its one of the most common problems because its a hidden file and people keep missing uploading it to their web server

if you have the .htaccess file then its got to be your base url..change it like Jorge Córdoba said...

Uncomment (remove #) and change example.com...Like this:

# $base_url = 'http://www.example.com';  // NO trailing slash!

to

$base_url = 'http://sugandha.net63.net';  // NO trailing slash!

if it still doesn't work:

try using ?q= before the relative url..eg:

http://sugandha.net63.net/admin to http://sugandha.net63.net/?q=admin

if that works then you have to disable clean urls on the online installation


How to add constrain validation on entity_create

Entities aren't validated automatically when saved via the API. (I'd be interested in knowing more about why not.) See the validation API docs for examples of validating a field and a whole entity:

$violations = $entity->field_text->validate(); // single field
$violations = $entity->validate();             // whole entity

if ($violations->count() > 0) {
  // Validation failed.
}

To find all possible constraints, look for anything extending (possibly indirectly) \Symfony\Component\Validator\Constraint.


Welcome to the community! It's nice to see interest from people who come from other angles :)

Although this type of question isn't suitable for this platform, I'll try to answer anyway. If you want more help I recommend you try chatting on IRC with other Drupal developers and see what they recommend.

Unfortunately no one has managed to write a programming book for non-programmers, at least I'm not aware of any. If that were possible then no one would write programming books for programmers ;)

You'll probably need some PHP intro course if you want to start with Drupal, then pick up any Drupal development book that is beginner friendly.

You could probably also get by by using code snippets available online in tutorials and on drupal.org. There's plently already available if you're trying to solve common problems.

But the Drupal projects don't include only the engine part, there's the database side of things. You can try to learn basic SQL. There are excellent books you can find, and plenty of freely available intros online too.

You mentioned patches, that is a workflow side of things, versioning code, you need to learn Git for that. Also a lot of free online help in that department.

It's a long way to go if you're a newbie but want to get to a point where you can solve most Drupal problems yourself. If you're not doing it for your own pleasure, if you want to build projects for others, maybe honing your existing skills would be better, in partnership with someone else who complements you. There are plenty of Drupal programmers who can't CSS and don't have the breadth and depth of knowledge about existing Drupal modules, how to configure Views for common cases etc.


Test class could not be found, namespace/autodiscovery issue?

It turns out that the issue was that MigrateControllerTest was defined as an abstract class. Defining it as a regular class cleared this up.


You can do this by using Panel module.

How can you use so I refer to Link1 & Link2


How can I sort entity type query results with pseudo values?

Some thoughts...

You should be able to do aggregation in your queries; try looking at QueryAggregateInterface and ConditionAggregateInterface. However this interface does seem to be pretty simple. The Views plugin implements full 'having' and 'group by' functionality, but probably in a way that's difficult to access outside views.

You might investigate using the Symfony Doctrine class or plain PDO to do it the 'old way'.

I am pretty sure you won't be able to calculate based on an external API; the database needs all the values to hand, either in a table or as query-provided data. Some databases do support advanced functionality like REST queries, but any code doing this won't be portable and so won't be available as standard in the Drupal interfaces.

You could possibly do the API lookups in advance (in e.g. php) and then pass them to a temporary table for the DB to check.


Taxonomy Access Control module - don't display term instead of disabling it

There is an issue in the issue queue regarding (https://drupal.org/node/1209154) this where the maintainer has given some options for a potential fix and has tried a few options out, however there is still no proper fix for the problem.

The module already handles the back end and not allowing users to submit those values, the disabling is really only for visual reasons, so removing via js is a viable solution in this case.


What does it mean "Rebuilding" in a feature? Can it be resolved?

Drupal's "Features" reflect a status of:

rebuild when rebuilding database for latest code for unoverriden features
revert when rebuilding database for latest code for any state features

Rebuilding updates features that are not deliberately overridden for latest code changes. It works during cache clear but can be slow if there are several features enabled on the site, and if there is a lot to clear in Drupal's caches.

If the server/cache clear and rebuild process are interrupted and freeze up, you may need to reset the lock on the feature state.  See https://www.drupal.org/node/928730

If you find this happens frequently, try increasing the mysql timeout and php memory limits.

You may also want to refer to this troubleshooting post about "overridden" features:  https://www.drupal.org/docs/7/modules/features/troubleshooting-reasons-features-may-be-stuck-as-overridden


Programmatically insert an image with caption

in the log entry it shows that [:db_insert_placeholder_7] and [:db_insert_placeholder_8] elements of the Array were empty - that might be the reason why Insert statement failed for the caption field:

Array
(
[:db_insert_placeholder_0] => field_steps
[:db_insert_placeholder_1] => node
[:db_insert_placeholder_2] => 455
[:db_insert_placeholder_3] => 863
[:db_insert_placeholder_4] => article
[:db_insert_placeholder_5] => 0
[:db_insert_placeholder_6] => und
[:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] =>
[:db_insert_placeholder_9] => field_steps
[:db_insert_placeholder_10] => node
[:db_insert_placeholder_11] => 455
[:db_insert_placeholder_12] => 863
[:db_insert_placeholder_13] => article
[:db_insert_placeholder_14] => 2
[:db_insert_placeholder_15] => und
[:db_insert_placeholder_16] => Wild Roses: fiori che sembrano appena sbocciati, che sottolineano ancora una volta la sua grande cifra stilistica, composizioni perfette per ogni dolce e speciale occasione.
[:db_insert_placeholder_17] => full_html
)
in image_field_caption_field_attach_update() (line 234 of /sites/all/modules/image_field_caption/image_field_caption.module).

also, [:db_insert_placeholder_16] - contains a string with 173 characters - is the caption field big enough?

hope this helps


Programmatically created nodes are shown only after re-saving

SOLVED: I was using a timestamp for the generated dates, but it needed to be a string like: "1967-01-15T00:00:00". I needed to look up the values in my database directly, devel / dpm() did not show a difference.


Rule to update referenced node after customer completes checkout

This question seemms to be a variation of Populate an entity reference field, which suggests a solution like so:

Add Condition: “Entity has field”, checking for your reference field
Add Action: “Fetch entity by id”, supplying your node/user id from another field in the dataset and providing a meaningful name
(Note: This solution implies you get the id by a simple field value in your dataset; you might want to add another condition to register the id first)
Add Action: “Set data value”, which you now can supply your entity object from the step before (hence a name you'll identifiy in the dataset)

Apart from some Rules "Event" you probably need to add to it (related to your "After customer completes checkout"), this should be pretty close to what you're looking for.


Drupal 7 to 8 migration The "taxonomy_term_reference_plain" plugin does not exist

Yes, taxonomy terms are now treated as general entities rather than special (for the most part), so some of the taxonomy-specific formatters were inevitably removed.

I believe the entity_reference_label formatter is the natural replacement for Drupal 8.


How to redirect Add to Cart link to product page?

Using Drupal Rules Module:

To redirect directly to checkout after a user clicks 'add to cart'

Admin -> Configure -> Rules -> Add New Rule
Give it a title of 'Add to Cart - Redirect to Checkout'
Set React on event to: After adding a product to the cart
Add new Action - set this to 'Page redirect'
Give it a value of 'checkout' and save.

Now when users click your add to cart button, they will be taken directly to checkout.  Alternatively, you can send them to /cart by change the value in step 5.


How to get a field value of custom block?

Fields of custom blocks are in block content. So you have to load the block content first, before you can get the field value:

$block = \Drupal\block\Entity\Block::load($block_id);
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
if ($block_content) {
  $field_value = $block_content->field_block_alt_title->value;
}


Can I simulate a hook using Devel's PHP execution?

The main problem with simulating any hook is that the hook only makes sense in the context of whatever is doing the invoking.

Hooks get fired either from a module_invoke() or a module_invoke_all().  These functions assume that the hooks have already been found and exist in the registry.  They also take into account the invocation order (by weight, then alphabetically by module name).

The process and preprocess hooks are little different as the hook parameters get passed in by reference, and there is a more complex calling scheme, so the order really does matter for what is present in $variables.

The net result is that you can't really fake out a hook without actually implementing the hook somewhere.

Personally, I keep a devel module around with the most common hooks stubbed out as empty functions.  I also stub out common process/preproess and form alters.  This way I can dpm() something whenever I want without needing to do a cache clear.  For example, I have a high-weigh module with

/**
  * Implements hook_form_alter().
  */

function mytestmodule_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id, 'form_id');
  // dpm($form, 'form');
  // dpm($form_state, 'form_state');
}

in it.  This way, Drupal already knows about the hook in the registry.  All I need to do is uncomment / edit the function as needed.


Ajax callback return 500 Internal Server Error

Change the callback into this:

function get_channel_program($channel_id){
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

Change the jQuery into this:

$('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {
     ...
     $.get('/ajax/channel/'+channel_id+'/get-program', function(data) {
     alert("got "+ data);
   });
});

This uses HTTP GET verb.

  According to the design of the HTTP specification, GET (along with
  HEAD) requests are used only to read data and not change it

instead of POST

  The POST verb is most-often utilized to create new resources.


How to display a block in the webform confirmation page?

It is funny how you have a part of answer in your question. Since you have a block, in "Show block on specific pages", check "Only on the listed pages" and type-in node/*/done (more on wildcards)

Get back if I missed something here.


No. Core REST & REST Views aren't the right solution here. You don't need a custom module for this.

As you mentioned, JSON API module supports inclusion of entity references in a single resource request. Each entity requested has a property called relationships which are references to other entities that can be included with via the include parameter. References, within references (e.g. a node referencing a media entity, that references a file entity) are supported too, albeit with some work to follow references (e.g. when you a request inclusion via the include property you're given an array property, included, which you still have to sort through via id).

If you're looking for a Drupal API that follows entity references within returned entity objects, you should use the GraphQL module as it will allow you to define your own data spec that can expand entity references as you see fit.


CAS username field value to be manually added to the existing user on import?

I find out the solution for the CAS_username import in CSV method. The method of db_insert in (authmap) table, which dynamically insert the CAS_username in respective field.

The authmap table is present in external authentication module.

    db_insert('authmap')
    ->fields(array(
     'uid' => $uid,
     'provider' => 'cas',
     'authname' => $row[0],
     'data' => 'N;',
     ))
    ->execute();

So this is the method, i dynamically update the CAS_username using CSV. If any suggestions or update in that. Kindly Prescribe it.


How to keep multiple drupal websites up to date

You could write scripts to do this.  You'd probably want to tie in to the Drupal unit testing module as well.

I can't provide you with any actual examples, because I'm not sure how it would be done reliably.

In my opinion, you're looking at a business problem that can't be fixed with a programming solution.  If I were in your shoes, I would start charging customers an ongoing maintenance fee for upgrades.


You can use Field Collection module to achieve this.

Using this module you can create group of field, such as class and grade in one collection. Also you can set 'Number of values' to unlimited for field.

Thanks!


How to show a random image from unlimited image field using Views?

1) Click on your image field

Under Multiple Fields Settings, uncheck display all values in the same row.

2) Add Global: Random as your sort and remove the default sort (content post date).


Setting View Filter Operator to "Greater Than Or Equal To"?

The operators you get in a Views exposed form depends on the type of data that is stored. If you store a text string you can't use GT or LT, instead you can use starts with or ends with.

Most likely your problem is that you are storing numbers as text in the database instead of storing them as numbers.


Finding all Basic Pages not referenced by a main-menu entry

I had to wrap the cast in a TRIM function:

drush @[redacted] sqlq "SELECT nid, title FROM node WHERE node.type = 'page' AND node.status = 1 AND (node.language = 'und' OR node.language = 'en') AND CONCAT('node/', TRIM(CAST(node.nid AS CHAR(7)))) NOT IN (SELECT link_path FROM menu_links WHERE menu_links.menu_name = 'main-menu') ORDER BY nid"


Page not found when trying to access custom module

So much could be going wrong from a finger fudge standpoint here, so just make sure you have something very similar to this going on:

For example, in quick.info:

name = quick module
core = 6.x
description = quick module
package = quick package

In quick.module:

<?php

function quick_menu() {

  $items = array();
  $items['quick/hello'] = array( // change to the url you want
    'title' => 'Quick Hello',
    'type' => MENU_CALLBACK,
    'page callback' => 'quick_hello',
    'access arguments' => array('access content'),
  );

  return $items;
}

function quick_hello() {

  $content='Hello. Thank you for surfing over to ' . $_GET['q'];
  return $content;
}

Obviously make sure your module is enabled and not so obviously that all caches are cleared, but past that, the most important piece of the above is the 'quick/hello' when it comes to page found/not found :)


Where do I programmatically create new roles?

You have many place to create your roles, a simple way for you (As you says that you don't know nothing about Drupal) can be create a custom page (read the post) if you follow the example in the myPage() function you can go trough your list of roles and create each role in a loop, something like this;

public function myPage() {
...
  /* Read your roles
   * $my_roles[0]['id'] = 'client';
   * $my_roles[0]['label'] = 'My Client';
   */
  for ($i = 0; $i < count($my_roles); $i++) {
    //your data array
    $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
    //creating your role
    $role = \Drupal\user\Entity\Role::create($data);
    //saving your role
    $role->save();
  }
...
}

And if you go to your page you will create your roles.

EDIT: As Kevin says is better in other places like the hook_install()

Follow the steps to create a module and implement the hook_install() (Read at the end of the page how to do it)

Inside the hook implementation you will put the code:

/**
 * Implements hook_install().
 */
function YOUR_MODULE_install() {
    /* Read your roles
     * $my_roles[0]['id'] = 'client';
     * $my_roles[0]['label'] = 'My Client';
     */
    for ($i = 0; $i < count($my_roles); $i++) {
      //your data array
      $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
      //creating your role
      $role = \Drupal\user\Entity\Role::create($data);
      //saving your role
      $role->save();
    }
}

To create your roles you only need install your module.


I ended up slowly working my way towards the result, my main issue was trying to get the dpm to show me what content I can change - but that's just because I'm, still slightly unfamiliar with how the whole process runs

function MYTHEME_menu_tree__user_menu(&$variables) {
 return '
'. $variables['tree'] .'
';
}

function MYTHEME_menu_link__user_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $element['#localized_options']['attributes'] = array('class' => 'my-btn');

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

function MYTHEME_preprocess_block(&$variables){
  global $user;
  $block =& $variables['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $variables['content'] = check_plain($user->name) . $variables['content'];
    }
  }

}


How to use Token Replace only if the field has a value?

You can use the 'clear' option of token_replace to clear any tokens it can't find a replacement for.

<?php print token_replace('[node:author:url]', array('node' => $node), array('clear' => TRUE,); ?>">

As documented here: https://api.drupal.org/api/drupal/includes%21token.inc/function/token_replace/7.x


There are lots of ways you could do it - blocks, panels, template overrides.  The easiest way for you would probably to create a custom block and put the html in that.  Then you'd be able to set the block visibility to exclude the /contact page.


Provided you installed the Metatag and Metatag Open Graph extensions, you need to:

Go to the metatag configuration page (/admin/config/search/metatag).
Edit the desired config
Under the Open Graph tab, fill the Image field with the relative path to your image

Save your config.
When expanding the config you modified, you can see the list of metatags you set (on my example I edited the Global configuration). You can see that og_image is in it.


As it clearly says Parameter comment must be on the next line at position 1...

Correct way of documenting your function is..

/**
 * Fetch node object properties.
 *
 * @param object $node
 *   contains information about campaign.
 *
 * @return array
 *   Webform properties.
 */

For more information on commenting standards check Drupal Coding Standards Documentation in D.O


It has no effect because Drupal doesn't know what event to fire on.

If you look at the switch statement in ajax_pre_render_element() you can see that it has default events for all core element types. But it it doesn't know about your element type, and no event is provided, so it doesn't know how to continue. It returns the element as-is rather than attempt to make a decision its not qualified to make.

To fix you should just be able to pick an appropriate event for the code to fire on, e.g.

$form['test_element'] = array(
  '#type' => 'customelement',
  '#title' => 'Custom element test',
  '#required' => TRUE,
  '#ajax' => array(
    'event' => 'click',
    ...
  ),
);


I had a similar problem but not with leaflet.  It seems the geocoder could not parse kml files with polygons, only points.  I had some railroad routes that worked fine on google earth but not in drupal 8.  I redrew the routes that were "single lines" and it worked fine.


Can't figure out how to set a context with t()

The second argument of the t() function are the replacements and not options.


Print key value as a class along with the label for a list field?

You should not actually want to do this in your node.tpl file. Drupal uses a system of (pre)processors to alter variables before they get rendered. That is where the logic should go.

Have a look at this topic that has a lot of explanation and references https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates

Once you have your output ready you should be able to do the styling with CSS.


Quick Edit of nodes in Views works. You can see this on the frontpage, which is a View.

However this works only for Views which show content.

If you have a View which shows content and want to choose the fields and customize the layout, you can create a custom viewmode, configure the fields there and put the layout in the twig files of the view mode.

Of course this does not provide all features of a View which shows fields and the module Editablefields. For this you would have to wait until this module is ported to D8.


Use the following function to remove any duplicate messages of a certain type:

/**
 * @param $type - the type of messages that should be checked
 *
 * Removes any duplicate messages from the messages session
 */
function remove_duplicate_messages($type) {
  $stack = array();
  if(isset($_SESSION['messages'][$type])) {
    foreach($_SESSION['messages'][$type] as $k => $msg) {
      if(in_array($msg, $stack)) {
        // Message is already set - remove it
        unset($_SESSION['messages'][$type][$k]);
      } else {
        // Add message to stack
        $stack[] = $msg;
      }
    }
  }
}

Example use:

remove_duplicate_messages('warning');


Create a draggable table and save weights

With the help from @Leigh I found the problem. I was setting some keys on $form['table'][$node->id()] and then overriding $form['table'][$node->id()] at the bottom.

I have moved a bit around in the code and now it works perfectly.

$form['table'] = [
  '#type' => 'table',
  '#header' => [
    '',
    $this->t('Weight'),
    $this->t('Title'),
  ],
  '#attributes' => [
    'id' => 'my-module-table'
  ],
  '#tabledrag' => [[
    'action' => 'order',
    'relationship' => 'sibling',
    'group' => 'draggable-weight',
  ]],
];

foreach ($nodes as $node) {
  $weight = $node->weight;

  $form['table'][$node->id()] = [
    'data' => [],
  ];
  $form['table'][$node->id()]['#attributes']['class'] = ['draggable'];
  $form['table'][$node->id()]['weight'] = [
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#title_display' => 'invisible',
    '#default_value' => $weight,
    '#attributes' => [
      'class' => [
        'draggable-weight'
      ]
    ],
  ];
  $form['table'][$node->id()]['label'] = [
    '#markup' => $node->label(),
  ];
}


How to synchronize two check boxes values, upon change?

I got it working this way:

/**
 * Implements hook_block_info
 */
 function mymodule_block_info() {

  $blocks['block_notify'] = array(
                           'info' => t('Notify me'),
                           'cache' => DRUPAL_NO_CACHE,
                           );

   return $blocks;
}

/**
 * Implements  hook_block_view
 */
 mymodule_block_view($delta = '') {

 $block = array();
 switch ($delta) {
               case 'block_notify':
                 $block['content'] =  drupal_get_form('mymodule_example_form');
                 break;

              }
  return $block;
}

function mymodule_example_form($form, &$form_state) {

 global $user;
 user_full = user_load($user->uid);
 $val = $user_full->field_user_message_notification['und'][0]['value'];

 $form['form_notify'] = array(
                         '#type' => 'checkbox',
                         '#default_value' => $val,
                         '#title' => t('Notify me by email when I receive a new message'),
                         //'#description' => t("Check this option to be notified by email when you receive a new message"),
                         );

drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule_request.js', 'file');
global $user;

return $form;
}

function mymodule_example_form_submit($form, &$form_state) {
// Submission logic.
 global $user;
 $user_full = user_load($user->uid);
 $edit = (array) $user_full;
 $edit['field_user_message_notification']['und'][0]['value'] = $form_state['values']['form_notify'] ;
 user_save($user_full, $edit);

 }

Then to trigger form submit on checkbox change I just added the follwing javascript in mymodule_request.js

jQuery(document).ready(

function ($)
{
 jQuery.noConflict();

 $checkBox = $("#edit-form-notify");

 if( $checkBox.length != 0)
 {
    $checkBox.click(
        function(){
            //        alert('hello');
            this.form.submit();
            }
          );

 }
});

I can now just select the "Notify me" block in my panel by " add content" in panels.


insert read-only multilingual text to user registration form

You should be able to translate your strings at admin/config/regional/translate/translate, just search a word contained in the two hungarian strings (case sensitive!), click on the edit link of the relevant string and you should be done.


Your way of implementation is partially wrong. Please try it like that:

function eventhistory_menu() {
  $items['personal-history'] = array(
    'title' => 'Event history',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('eventhistory_edit_form'),
    'theme callback' => 'eventhistory_template',
    'access callback' => TRUE,
  );

  return $items;
}

function eventhistory_theme($existing, $type, $theme, $path) {
  return array(
    'eventhistory_template' => array(
      'variables' => array('output' => NULL, 'hist_form' => NULL),
      'template' => 'eventhistory_template',
    ),
  );
}

function eventhistory_edit_form($form, &$form_state) {
 $form['#tree'] = TRUE;
 $num_hist = 0;

 $form['history']  = array(
   '#type' => 'fieldset',
 );

 if ($form_state['hist_num']) {
   for ($i = 1; $i <= $form_state['hist_num']; $i++) {
     $form['history']['num' . $i] = array(
       '#value' => 'Edit',
       '#type' => 'submit',
     );
   }
 }

 return $form;
}

I've discarded the historypage_rendered function from your code and called the form directly in hook_menu implementation. I also added the theme callback to hook_menu, and also renamed your form function to follow Drupal coding standards.


As you seem to have learned the Redirect module is really for page-specific redirects (this single URL redirects to that URL), not patterns, as your case seems to require. For this a server-side redirect is really the way to go. Not only is it a standard solution to this kind of problem, but it can happen independent of Drupal, so there is no need to bootstrap Drupal just to process the redirect.

I think the specifics of setting-up a server-side redirect a a bit are a bit beyond the scope of this space (as it's not a Drupal-specific concept), but there are lots of resources out there on the topic, and I think you'll find that it's not too hard. You mentioned that it feels like "Voodo", but I think it will prove far more straightforward than a module-based solution implemented in php. Here's one example stackexchange post that might be relevant to your case.

All that said, because your question does ask for a moudle-specific way to do it, here are some notes on that too. This is much less ideal, as noted above, but it's worth referencing. For this I think you would want to trigger a drupal_goto() inside of hook_init(). A very simple-case example of this pattern can be referenced in this post, and interpolated for your example:

/**
 * Implements hook_init().
 */
function mymodule_init() {
  $path = current_path();
  // preg_match() could also work instead of drupal_match_path()
  if (drupal_match_path($path, 'file/*')) {
    drupal_goto('sites/default/' . $path);
  }
}

I suppose there may be real use cases for this kind of module-based approach, but as I noted above, I really don't think your case is one of them. You would probably be best-served with a service-side redirect (in Apache/.htaccess).


Filter on boolean with NULL (unset) value

Just for posterity, here's the approach I ended up using:

The Field Defaults contrib module allowed me to set all null values for the new field in pre-existing content, so I was able to use the boolean checkbox I wanted.

There's no need to patch core to deal with this, because it won't happen again with newly-created content. As soon as the node is saved, the field has a sensible default value.


The piece you are missing is RewriteCond.

This should redirect just the subdomain

RewriteBase /
RewriteCond %{HTTP_HOST} ^red\.sitename\.com$ [NC]
RewriteRule ^(.*)$ http://sitename.com/$1 [L,R=301]

Note also that the separator needs to be escaped as \. to prevent it from being used as a single character match in the pattern.  The [NC] also tells Apache to ignore case during the match.


How to insert html tags to a node content?

To use html tags in the Body field of a Basic page content type (for example) you need to select "Full HTML" or "Filtered HTML" in the "Text format" dropdown menu below the input text box (see image). As far as I know, only fields of type "Long text and summary" and "Long text" allow you to select Full or Filtered HTML.

To configure text formats and permissions go to Configuration -> Content authoring -> Text formats (www.example.com/admin/config/content/formats).

For more information see Text filters and Input Formats.