How to sub_process a non-associative array in migration.yml

I've written a process plugin that transforms a sequential list into an array of associative sub-arrays, so sub_process and migration_lookup can use them.

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Transforms an array of values into an array of associative arrays.
 *
 * The inner array will be filled with one key. E.g. ['alpha', 'beta'] becomes
 * [[value => 'alpha'], [value => 'beta']]
 *
 * Use this plugin to preprocess a numeric/non-associative array for other
 * plugins that requires an associative array as input, such as the sub_process
 * plugin.
 *
 * Available configuration keys:
 * - source: Source property.
 * - keyname: name of the key to be used for the associative sub-arrays,
 *   defaults to 'value'.
 *
 * Example:
 *
 * @code
 * source:
 *   my_flat_array:
 *     - category1
 *     - category2
 * process:
 *   my_associative_array:
 *     plugin: deepen
 *     source: my_flat_array
 *   field_taxonomy_term:
 *     plugin: sub_process
 *     source: '@my_associative_array'
 *     process:
 *       target_id:
 *         plugin: migration_lookup
 *         migration: my_taxonomy_migration
 *         source: value
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "deepen",
 *   handle_multiples = TRUE
 * )
 */
class Deepen extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $keyname = (is_string($this->configuration['keyname']) && $this->configuration['keyname'] != '') ? $this->configuration['keyname'] : 'value';

    if (is_array($value) || $value instanceof \Traversable) {
      $result = [];
      foreach ($value as $sub_value) {
        $result[] = [$keyname => $sub_value];
      }
      return $result;
    }
    else {
      throw new MigrateException(sprintf('%s is not traversable', var_export($value, TRUE)));
    }
  }

}


Exposed filters drop down select translated but not displaying on view

For translating exposed filters, you need to enable all translation modules FIRST. And THEN create your views.

Because there is a multilingual option to pick filters, the translatable one.

User: Example (field_example:language) (translated)
Language - Appears in: user:user.

So if you want a multilingual site, install all translation modules FIRST, and then create your views with multiple filters.


Firstly, will be better if you host a Drupal site on the separate domain/subdomain.

About your error, seems you forget copy all files (for example a folder with themes).

About the DRUPAL_ROOT constant, you shouldn't change it.


How to create a view that filters profiles based on current user's 'interested in' field value?

Solution that worked for me:

I used MyModule_views_query_alter hook and added a join to the field table and the condition that matches the choice of logged in user and gender of users in db.

if ($view->name == 'profile_list') {
        $logged_in = $GLOBALS['user']->uid;
        $pr = profile2_load_by_user($logged_in,'main');

        $join = new views_join();
        $join->table = 'field_data_field_gender';
        $join->field = 'entity_id';
        $join->left_table = 'profile';
        $join->left_field = 'pid';
        $join->type = 'inner';

        $query->add_relationship('field_data_field_gender', $join, 'profile');

        $view->query->add_where(0, db_and()->condition('field_data_field_gender.field_gender_value', $pr->field_looking_for['und']['0']['value'], '='));
    }


you have to install the Views Bulk Operations and Administration views module. After that, go to the users management interface (admin/people), select the users and select "Change user roles".

PS 1: You can select users by role (1 on the attached picture)

PS 2: If you need to select ALL of the users, just click the button "Select all xxx rows in this view" (2 on the attached picture)

2/ For selecting only users without role:

You'll have to modify the Views who handle the display:

Go to http:///admin/structure/views/view/admin_views_user/edit/system_1
On the "Filter criteria" section, click on "User:Roles"
Check the "Expose operator" box
Save and go back to the user selection page
Select the 'Only has the Authenticated user role' on the "Role" dropdown

That should really do it now! :)


Here is a preprocess alternative (maybe you will need access to some info to make custom html classes).

use Drupal\Core\Template\Attribute;

/**
 * Implements template_preprocess_html().
 */
function MODULE_OR_THEME_preprocess_html(&$vars) {

  if (is_array($vars['attributes'])) {
    $vars['attributes'] = new Attribute($vars['attributes']);
  }

  $vars['html_attributes']->addClass('goes-to-HTML-tag');
  $vars['attributes']->addClass('no-trans');
}


Notice: Trying to get property of non-object

You didn't print line numbers of the second error so I don't know if they happen on then same line. Maybe your notice is from something else.

What you could try is to print out the variable using print_r, vardump, debug or use the Devel module which creates some wrapper functions like dpm to print variables with Krumo.

It should be impossible that the same variable is an object and isn't an object at the same time. But it's hard to say more with the info you provided.

Update:
From your comments, I can see why you are getting the errors:

print $user_profile->field_country['und']['0']['value'];

Error >> Notice: Undefined index: und ...

print $user_profile['field_country']['und']['0']['value'];

Fatal >> Cannot use object of type stdClass as array

The problem as I marked in the error message is that und is not defined in the field value. So $user_profile->field_country is ok but $user_profile->field_country['und'] is undefined. The reason could be that it doesn't have a value set or that the language for the field isn't undefined. You should like I suggested above, print out the variable to see what it contains.


You need to add a FILE_STATUS_PERMANENT to the status of the file on form submit then save the file.

$file->status = FILE_STATUS_PERMANENT;
file_save($file);


Is this the correct way to add a page with hook_menu()?

No, the menu items are fine. The problem seems with your block display configuration settings.
There is no permission with these menu items; give some loosely coupled permission (such as access content) to these callbacks. Function names should be prefixed with the module name to avoid clashes with other modules.
function my_module_menu() {
  $items['my_page'] = array(
    'title' => 'my_page',
    'description' => 'my_page',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  $items['my_page2'] = array(
    'title' => 'my_page2',
    'description' => 'my_page2',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  return $items;
}

function my_module_my_function() {
  return '';
}


Apache Solr: get list of "More Like This" nodes programmatically

Here is the solution that I came up with.

function mymodule_similar_nodes($node) {
  if (module_exists('apachesolr_search')) {
    $output = '';
    $env_id = 'solr'; // machine name of solr server
    $delta = 'mlt-002'; // "More Like This" block delta
    $block = apachesolr_search_mlt_block_load($delta);
    $solr = apachesolr_get_solr($env_id);
    $context['search_type'] = 'apachesolr_search_mlt';
    $context['block_id'] = $delta;
    $docs = apachesolr_search_mlt_suggestions($block, apachesolr_document_id($node->nid), $solr, $context);
    $view_mode = 'teaser'; // view mode, e.g. 'full', 'teaser'...
    foreach ($docs as $doc) {
      if ($doc->entity_type == 'node') {
        $similar_node = node_load($doc->entity_id);
        $similar_node = node_view($similar_node, $view_mode);
        $output .= drupal_render($similar_node);
      }
    }
    return $output;
  }
}


How to hide the "help-block" on an Image field in the Comment Form

Drupal 7

I done it through the node_view_alter hook and my custom theme.

In the theme's template.php file I added the following function

function MyThemeName_node_view_alter(&$build) {
  if ($build['#node']->type !== 'My_Node_Type'){
    return;
  }

  // Your image field can not exist while saving comment.
  if(isset($build['comments']['comment_form']['My_Image_Field'])){
    // We can't use the unset function. Otherwise we can get something like this:
    // Notice: Undefined index: #file_upload_description in theme_file_widget_multiple() (row 863 file .../docs/modules/file/file.field.inc).
    $build['comments']['comment_form']['My_Image_Field']['und']['#file_upload_description'] = NULL;
  }
}

This removes the entire
...
 element.


Views issue: How to pull content from two different taxonomy vocabularies on same page

I tried it myself and views filter OR group is not working.

I think you just hit on a known bug.

Follow the discussion in this issue and this one and apply the latest patches mentioned and see if you can make it work.  Make sure that you post back with your experience (did it work or not) so you can help this issue move along and eventually make it into a release.

As a workaround consider using 1 vocabulary (instead of 2) that holds all terms and your views filtering does not need an OR group.


Display field from referenced entity using Display Suite and Views

You have to configure a new view mode for vocabularies (admin/structure/ds/view_modes). Let's call it "country"

Then on your newly created view mode (admin/structure/taxonomy/{tax_name}/display/county) configure the fields you want to show. In your case this will be the term name and the country.

After you done that you have to go to the manage display of your product content type and select the "teaser" view mode. There, on your taxonomy field, choose "Rendered taxonomy term" as format. Then click the button on the right and choose "country" as view mode.


As @W.M. said, i will use Conditional Fields module Conditional Fields along with Field Collection Module.

Essentially you will first define collections of fields (this is a kind of grouping of fields that are related. ie retina screen details), and then you can make this fields collections to appear if another field value is set using Field Collection.


How to alter image captcha title in drupal 7

use hook_form_FORM_ID_alter() and Form API pre_render function. E.g:

// Explains pre_render. This is when you create a form;
function feedbackForm($form, &$form_state) {

  $form['#pre_render'][] = 'feedbackForm_pre_render';

  $form['name'] = array(
    '#title' => t('Ваше имя'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

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

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Отправить'),
  );

  return $form;
}

function feedbackForm_pre_render($element) {
  $element['captcha']['captcha_widgets']['captcha_response']['#title'] = t('Защитный код');
  return $element;
}

You can also use hook_form_alter() function:

function MY_MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);

  if($form_id == 'FORM_ID') {
    $form['#pre_render'][] = 'feedbackForm_pre_render';
  }
}


How to load a webform via ajax inside custom JS?

Try the following steps :

Create follow this how to create contact form block
Create route for example form/contact-us-block :

custom_module.routing.yml

custom_module.get_contact_form_block:
  path: '/form/contact-us-block'
  defaults:
    _controller: '\Drupal\custom_module\Controller\TutorialController::getContactFormBlock'

getContactFormBlock Action in your controller

public function getContactFormBlock() {
    //- Set your block id here
    $bid = 4;
    $block = \Drupal\block_content\Entity\BlockContent::load($bid);
    $build = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
      ->view($block);
    return render($build)->__toString();
  }

Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
        $.ajax({
          url: 'form/contact-us-block',
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    })(jQuery, Drupal);


Pager extention not working in dynamic database query

This issue is related to the use of extenders.  When using an extender it is important to note that $query is not altered in place. A new query object is returned from extend(), and if it is not saved to a variable it will be lost.  See Extenders documentation for more info.

To achieve this with the OP code, one would need to modify the following section:

  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

Full working code is as follows:

function playground_page() {
  $build = array();

  $build['intro'] = array(
    '#markup' => 'This is a testing ground for Drupal concepts.',
  );

  // Example of table join. Display content created by current user.

  // Construct base query.
  global $user;
  $query = db_select('users', 'u');
  $node_table_alias = $query->join('node', 'n', 'n.uid = u.uid');
  $query
    ->fields($node_table_alias, array('nid'))
    ->condition('u.uid', $user->uid);

  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    $key = 'node_' . $node->nid;
    $build[$key] = node_view($node, 'teaser');
  }

  $pager_args = array('tags' => array('<<', '<', NULL, '>', '>>'));
  $build['pager'] = array(
    '#markup' => theme('pager', $pager_args),
  );

  return $build;
}


AFAIK core's does not support (and could take a while to do so) keyed based translation (like Symfony or other do). Theres an idea queued but seems to fall on deaf ears.


How to set the views exposed filters default value programmatically?

function example_views_pre_build(&$view) {
    if ($view->name == 'VIEW_NAME') {
        $view->display[$view->current_display]->handler->handlers['filter']['field_country_tid']->value = array(55, 91);
    }
}

This code worked for me. Check your views module version as well. I am using Views 7.x-3.14.


Don't show a field when a more important field is shown in a View Drupal 7

Use the Views Conditional module. It does exactly what you want to achieve.

  How to use Views Conditional in your Views:

  Create a view. Add some fields under "FIELDS".
  Click on "ADD" next to fields. Scroll down to "Views: Views
  Conditional", probably found near the bottom of the list.
  Add and configure fields...
  Choose a field to run a condition against, and provide values
  accordingly.
  Save, views conditional handles the logic and returns as specified.


How can i set a pagination in detailed page

What you're describing is one of Drupal's most commonly used modules, Views. Views lets you:

Select any content you want of your choice (in your case blog posts)
Show only the fields you want on that content (in your case a title link & description).
Display it in a form of your choice (in your case a dedicated page with a pager).

You shouldn't have any trouble finding tutorials on Views. For example, here is one from Acquia.


apachesolr search form block that points to search page

There is an issue queue asking for such feature:
https://drupal.org/node/326375

I also found a module (a sandbox) for Drupal7 to export for each search-page a search-block:
https://drupal.org/sandbox/incrn8/1315802


How do I filter an entityreference field based on other fields?

Your question reminds me of this similar question you may or may not find it relevant.

Alternatively, you could use Masquarde

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

Video Tutorial


Newly (created by Drupal) dir not writable after first upload?

It's the server software that controls the file permissions, you need to have that set up correctly first. Drupal is then granted access to the dedicated folder for site uploads and other generated files necessary for the site activity.

It's very important for your site security to have the files' and folders' owners, groups, and permissions correctly set up, and this is a part of any Drupal installation.

This is a long but detailed resource on this: Securing file permissions and ownership

Usually you need to make the www-data user the owner of the files/ folder, this is the Apache server user on a lot of installations but YMMW, it can be called something different. And it's important to give all the necessary permissions for that user and the group too, but not more than necessary to keep it perfectly secure.

Doing this step during Drupal installation usually ensures you don't stumble upon file-upload-permission related issues.

Also check your Status Report for any messages related to file uploads. You will also have entries in the Latest log entries if the system encounters something worth throwing an error for. And check the File system related admin pages (under Configuration), try saving the form there and see if you get any errors and get more info about your case.

Did you use some special Drupal Vagrant setup?


use jquery to add a div wrapper to a dynamically created drupal modual div

You may be looking for this

$("#edit-secondary-wrapper").wrap("

");

This wraps the div with id 'edit-secondary-wrapper' with a parent div with class 'row'.


How can I get rid of the paddings and margins that come with the webform?

You can override Drupals styling rules. Just use your browsers (Chrome, Firefox) developer tools to inspect elements for whats styling rules they have. Then override them in your themes stylesheet(s).


Nested <a> elements (anchor tags) are forbidden in HTML syntax.

Nested links are illegal by w3.org rules.


Will painless upgrading from Drupal 8 alpha 3.x to beta be possible?

No.

Upgrading from a previous 8.x version will be supported starting with the first beta.

Upgrading from 8.x-alpha will break, I know of at least one issue that will make major changes to the entity/node storage.


Look at the value of $base_url value on /sites/default/settings.php. It may help. Also don't forget to clear the cache on your test site.

If the absolute URL in the menus is not specified directly on the menu items (through Structure / Menus) maybe it was embedded within the template and you'll have to search for the code on the .tpl files of your theme.


Add text after input field with form api (field-suffix)

You can use the #field_suffix property for exactly that:

  Text or code that is placed directly after a textfield. This can be used to add a unit to a textfield.

For example:

$form['a_textfield'] = array(
  '#type' => 'textfield',
  '#title' => t('A Label'),
  '#size' => 10,
  '#maxlength' => 15,
  '#description' => t('A Field description'),
  '#required' => TRUE,
  '#field_suffix' => 'Suffix'
);


Why there are random line breaks in emails sent through drupal?

It seems it's drupal's mail processor that inserts all these line breaks.
I fixed the issue by installing MimeMail (and MailSystem).
It allows the use of html to format all outgoing emails.

I hope this will be helpful to somebody out there.


How may I show the top 4 most recent result and then randomize in Views?

I'm not sure if I understand your requirement correctly but you can the following:

Create a views of node (teaser, fields.. whatever you need)
Sort by date (following the granularity you need)
Add a "Global: Random" sorting


Sending emails on a specified interval, based on a date field

I've built a similar feature for the Commerce Recurring module, but instead of sending mails, it creates orders. Here's how I did it.

Interval field module would become handy so you can control how often the action happens (sending mails i.e.).

You could create your own cron event or just rely in the Drupal one, here's a the rule used for generating orders, yours would probably be simpler:

  $rule = rules_reaction_rule();
  $rule->label = t('Generate recurring orders on cron run');
  $rule->tags = array('Commerce recurring');
  $rule->active = TRUE;
  $rule
    ->event('commerce_recurring_cron')
    ->action('commerce_recurring_get_due_items', array(
      'number_items' => 5,
      'timestamp:select' => 'site:current-date',
      'provides' => array('commerce_recurring_entities', 'commerce_recurring_entity'),
    ));

  $actions = array(
    'commerce_recurring:select' => 'current-recurring-entity',
    'timestamp:select' => 'site:current-date',
  );

  $loop = rules_loop(array(
    'list:select' => 'commerce-recurring-entities',
    'item:var' => 'current_recurring_entity',
    'item:label' => t('Current recurring entity'),
  ))->action('commerce_recurring_provide_order_properties', array('commerce_recurring:select' => 'current-recurring-entity'))
  ->action('commerce_recurring_generate_order_from_recurring', $actions);
  $rule->action($loop);

  $rules['commerce_recurring_cron_generate_orders'] = $rule;

The calculation of the due entities (commerce_recurring_get_due_items) is a rules action that calls this function, based in Entity Field Query to calculate those entities "due" to actions:

/**
 * Return recurring entities with due dates.
 */
function commerce_recurring_rules_get_due_items($number_items = 0, $due_date = NULL) {
  if (empty($due_date)) {
    $due_date = new DateObject();
    $due_date = $due_date->getTimestamp();
  }

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'commerce_recurring', '=');
  $query->propertyCondition('status', TRUE, '=');
  $query->propertyCondition('due_date', $due_date, '<');
  if ($number_items > 0) {
    $query->range(0, $number_items);
  }
  $result = $query->execute();

  $recurring_entities = array();
  if (!empty($result['commerce_recurring'])) {
    foreach($result['commerce_recurring'] as $recurring_entity) {
      $recurring_entities[] = entity_load_single('commerce_recurring', $recurring_entity->id);
    }
  }

  return array('commerce_recurring_entities' => $recurring_entities);
}


How to list members in a group using views Drupal 7?

I had forgotten to add Groups Audience as a field in the Profile type created by Profile 2 which in my case was "Main Profile".


With the newest version of Features, it makes it really easy to just add the fields of the content type to the feature. Features are not meant to hold content, like entire nodes. Here's a good example of a feature I've built.

(http://i.stack.imgur.com/rYC7l.png)


how to get the NodeID into views-view-field--field-image.tpl.php to create an  redirect

This is in a view correct? I believe you need to use node_load($nid) to load the node data first in order to fetch it. I would try something like this

$node = node_load($nid);
$nodeurl = url('articles/' . $node->nid);


You can use an inline template:

  public function build() {

  return array(
    '#type' => 'inline_template',
    '#template' => '
<svg>{{ var }}</svg>
',
    '#context' => array(
      'var' => $svg,
    ),
  );

You can use the inline template with an empty context, if you have no vars that need to be escaped:

  return array(
        '#type' => 'inline_template',
        '#template' => '
<svg>...</svg>
',
        '#context' => array(),
      );


How to make custom jquery method accessible from Drupal.behaviors, across multiple javascript files?

I use a slightly different JS pattern with Drupal, which is based on the Javascript Module Pattern.

var FOO = (function(me, $, Drupal, undefined) {
  me.name = "FOO";

  function do_something_awesome () {
  }

  me.do_stuff = function do_stuff () {
  }

  function init (context, settings) {
    me.do_stuff();
    do_something_awesome();
  };

  Drupal.behaviors[me.name] = {
    attach: init
  };

  return me;
}(FOO || {}, jQuery, Drupal));

Anything directly attached to me will be public on the FOO.  The rest is private.  Typically, I will pass in FOO into the closure in dependent libraries.


how to set the author of the feed item to the author of the feed source in feed importer?

I had a hard time getting this to work.

My current settings work.

Feed Importer
-attached to Feed (content type)
-RSS parser
-Mapping: Description to Description, Title to Title, Item GUID to GUID (Unique), Item URL to URL (Unique), Published Date to Published Date, and Feed Node: User ID to User ID.  It is important to have a unique identifier or you get duplicate imports.

The Feed Itself
-Set "Authored By" to a Drupal user on your site.   This lets you custom the user. Create a new user if necessary. I created a couple dummy users just to get their names to appear as feed item authors.


You can use the Menu Icons module to implement the functionality you are looking for - I've done this multiple times.

You simply need to customize the menu_icons_css_item.tpl.php file so that the image is displayed using the CSS image replacement technique rather than positioning the image as an icon-like background. For roll-over functionality, each image you upload with the image icon module would need to include the static and roll-over versions of the menu image.

Here is sample content of a menu_icon_css_item.tpl.php file I've used before. This is for Drupal 6, so some of the syntax may need to be updated if you are using Drupal 7.

<?php
$base_url = $_SERVER['DOCUMENT_ROOT'];
$image_info = getimagesize($base_url.$path);
$width = $image_info[0];
$height = $image_info[1]/2;
?>

ul.links li.menu-<?php print $mlid ?> a {
  background-image: url(<?php print $path ?>);
  background-repeat: no-repeat;
  background-position: 0 0;
  height:<?php print $height?>px;
  text-align: left;
  text-indent: -9999px;
  width: <?php print $width?>px;
}

ul.links li.menu-<?php print $mlid ?> a:hover {
  background-position: 0 <?php print $height?>px;
}

After you've created a customer menu_icons_css_item.tpl.php file in your theme, you will need to delete the CSS file that the Menu Icons module previously generated, so that it will generate a new file using this template. It should be in your sites/default/files folder.

Of course, if you do not need to allow site admins to update menu item images via the Drupal UI, you could just implement the CSS image replacement technique within your theme, without needing a helper module like Menu Icons.


If I recall, you need to use the json_ specific query functions to query within a tuple.

There is an example query on the JSONB module page demonstrating this. This module is not required, but does have an example of how to write a db_query:

  If you wanted to query for JSON records that were in the 2005-2006
  timeframe for high school graduates, you could do the following:

$results = db_query("SELECT point
      FROM (SELECT jsonb_array_elements(field_jsondata_value) point FROM {node__field_jsondata}) points
      WHERE point->'DataType' = :type
        AND point->'TimeFrame' = :frame
        AND point->'Education' = :education",
      array(':type' => '"Percent"', ':frame' => '"2005-2006"', ':education' => '"High school graduate"'));

  You would receive the fourth object only. The function
  jsonb_array_elements expands data at runtime to query data in this
  manner.

I don't think Drupal core supports the usage of these functions outright, maybe it does, but I accomplished this in both Drupal 7 and 8 with db_query.


Try contextual range filter module that lets you define a range filter applies that rule

Start value <= Filter value >= End value.

For your case you have to define two filters.
for start date with that rule

filter start date <= node start date >= filter end date.

for end date with that rule

filter start date <= node end date >= filter start date.


Module/Method to cleanup content of Drupal site?

Normally, when I have encountered this, there is too much variety to do much automated cleanup.  You can do something like this, though

$sql = "
  SELECT n.nid
  FROM {node} n
";

$result = db_query($sql);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid, NULL, TRUE); // bypass internal cache
  $node->body = _filter_htmlcorrector($node->body);
  node_save($node);
}

Either stick this in a custom menu entry or make a simple script for it.  Depending on how many nodes you have, you may need to use the Batch API.

_filter_htmlcorrector will fix bad HTML to an extent, and I have also used check_markup with luck, too.  For check_markup, you just need to figure out the numeric filter number to use.

Other than that, you really do need to play with the processing you do in the loop.  This will give yourself a head start, but you still need to edit each article and manually check/fix things.


This issue was solved using a function in my template.php file to get the field data out of entities, which I found here.

/**
 * Returns field values as actual entities where possible,
 * also allows selection of individual items to be returned
 */
function field_fetch_field_values($entity_type, $entity, $field_name, $get_delta = NULL, $get_key = NULL) {
  $values = array();
  if (isset($entity->$field_name) && !empty($entity->$field_name)) {
    foreach (field_get_items($entity_type, $entity, $field_name) as $delta => $item) {
      $value = $item;
      $keys = array_keys($item);
      if (count($keys)==1) {
        $key = $keys[0];
        switch ($key) {
          case 'nid':
            $value = array_shift(entity_load('node', array($item[$key])));
            break;
          case 'uid':
            $value = array_shift(entity_load('user', array($item[$key])));
            break;
          case 'tid':
            $value = array_shift(entity_load('taxonomy_term', array($item[$key])));
            break;
          case 'vid':
            $value = array_shift(entity_load('taxonomy_vocabulary', array($item[$key])));
            break;
          case 'value':
            $value = $item['value'];
            break;
        }
      }
      else {
        if ($get_key && isset($item[$get_key])) {
          $value = $item[$get_key];
        }
        elseif (array_key_exists('value', $item)) {
          $value = isset($item['safe_value']) ? $item['safe_value'] : $item['value'];
        }
      }
      $values[$delta] = $value;
    }
  }
  if (is_numeric($get_delta)) {
    return isset($values[$get_delta]) ? $values[$get_delta] : NULL;
  }
  return $values;
}

I then created the code below in my node.tpl page to check how many 'body' fields were in the array.

<?php if (render($content)) :
$contArray = array();
$summary = field_fetch_field_values('node', $node, 'body');
$contArray = $summary;
foreach ($contArray as $value) : ?>

<?php print $value; ?>

<?php endforeach; else : ?>

There is currently no content for this page.

<?php endif; ?>


Remove an item from list of taxonomy terms prior to rendering

Instead of using unset(), you can use #access = FALSE, like this:

$build['field_terms'][0]['#access'] = FALSE;


Strict warning: Only variables should be passed

You should attrubute the result of function to variable and then pass to render. The difference is that in sencond case you're passing certain variable instead of result of function.


Write a boolean function in template that determines if the logged user is either the node author or admin

Put this to template.php file of your theme:

function YOUR_THEME_NAME_preprocess_node(&$variables) {
  global $user;

  if(in_array('administrator', $user->roles) || $variables['node']->uid == $user->uid) {
    $variables['is_admin_or_author'] = TRUE;
  }
  else {
    $variables['is_admin_or_author'] = FALSE;
  }
}

then in your node.tpl.php or node--your-content-type.tpl.php you'll have a variable $is_admin_or_author with either TRUE or FALSE value.


Yes indeed. a major frustration and it just makes no sense the way it is. i asked this same question a year ago and it has still not been solved. if you solve it please put the solution here.

meantime, you can use jquery appendTo() to solve it in a very ugly way. the price will initially load above the attributes and then jump down to the correct place above the cart button. it is not a pretty site but at least it works.


Get the value of a field inside a paragraph field in hook_preprocess_field

You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
   print_r($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}


A particular content type forces preview before save. How do I turn this off?

You can set this option easily:

Edit the content type
Click "Submission form settings"
Set "Preview before submitting" to Optional (or Disabled if you don't want previews at all).


System requirements says:

  Although PHP 5.3 is supported by Drupal 6.14 core and higher (see the release notes for 6.14), some contributed modules may not be compatible with PHP 5.3, and some PHP 5.3 configurations still show warnings with Drupal 6.14; work is ongoing to resolve the latter in #360605: PHP 5.3 Compatibility.

The issue linked in the requirements page is actually marked as fixed; this means that Drupal core is completely compatible with PHP 5.3 since Drupal 6.14.


How to get tid on behalf of node id (nid) in Drupal 8?

A reference field doesn't have a property value. You can use entity to load the term or target_id to get the term id:

$tid = $node->field_tags->target_id;


What operation should I use to write node's information in an email when the node is saved?

Thanks to a bit of a to-and-fro in your other questions (this one and this one) I think I know what the problem is.

Without going into great detail, the content module (CCK) also implements hook_nodeapi(), in order to commit the field data to the database. What's currently happening is that the hooks implemented by your module are being called before the hooks for the content module, which means at the time your implementation of hook_nodeapi() is run, CCK's implementation has not run; hence the data not being found in the database.

In my experience unless you explicitly set the weight of certain modules, they're ordered by name alphabetically, and as your module name begins with 'a' it does make sense that this would happen.

To get around it you just need to increase the 'weight' of your module in the system. Have a look at How to update a module's weight for more information but essentially you want to run a query like this against your database:

db_query("UPDATE {system} SET weight = 100 WHERE name = 'yourmodulename'");

After that clear Drupal's caches and you should see things starting to behave a bit differently.


How to change client session variables during a functional browser test?

I am not sure if the storage you use to save the my_session_key attribute is shared between the testrunner and the site that gets tested, and that could explain why the test fails.

Why not test exactly the case of the inbound path processing, e.g.:

public function testToken() {
  $options = [
    'query' => [
      'param' => 'value',
    ]
  ];
  $this->drupalGet('<front>', $options);
  // Check site name is NOT Drupal.
  $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
}

Good luck in any case!


Just have an htaccess entry that redirects /user and /admin to the front page.


The function you need is menu_tree_set_path.  It will be released with Drupal 7.9.

If you can't wait, the workaround is to use this code in hook_init:

<?php
$item = menu_get_item();
$item['href'] = '<the href of an existing menu link>';
menu_set_item(NULL, $item);
?>


How can I see full server request to track suspicious requests?

I can't think of a module that would do this for all the different anti-spam modules. I know that the CAPTCHA module implements this for its own fields.

An alternative is a simple custom module that implements hook_form_alter to target the the desired form, adds a new submit handler to the form and store the submitted information using watchdog.


users not able to post to discussion board

I don't have a Drupal 6 site handy to check this but the problem should be caused by either authenticated user permissions (global Drupal permissions) or if you are using field-specific permissions, that would also prevent a user from seeing that field. Please check what permissions authenticated user has for taxonomy related actions (I'm assuming you are using taxonomy to display forum containers?)


I would like to duplicate the default product layout grid in a Commerce Kickstart2 site

It's because the CSS for the list elements is not being applied

display: inline;
float: left;
min-height: 380px;
height: auto;
margin: 0;
padding-right: 5px;
padding-bottom: 30px;
width: 230px;

So you need to change the CSS selector so that it does apply.

I think that isn't the right answer though, instead of duplicating the template I think you should edit the view so that it shows your brand pages with the brand info at the top rather than put it in the template (if that is what you're doing).  It'll take a while to work out but the site will be much easier to maintain over time.


Sort content of views with drag and drop

The Draggable Views module might be what you need. There is a version of the module for Drupal 8.

According to the module description,

  DraggableViews makes rows of a view "draggable" which means that they
  can be rearranged by Drag'n'Drop.

I tried the following instructions in the documentation page on a vanilla Drupal 8.2.6 installation, and it worked fine (see screenshot below).

  Activate the module and navigate to the edit-page of an existing
  view.
  Now go to the Format section and choose Table.
  Make sure you have the "Content: Title" field, place it as your first field.
  Add the field "Draggableviews: Content" at the Fields section, place it after the "Content: Title" field.Make sure not to check
  "Exclude from display"; if you do the view will permit drag and drop
  but the changes will not be saved.
  Add "DraggableViews: Weight" at the Sort criteria section and place it as the first Sort criteria. Save the view and you're done.


It doesn't really make sense to use sprintf (or any other string formatting/replacement functions) here - the API can already accommodate what you need in a much more structured manner:

$options = ['query' => ['q' => $exchange . ':' . $field]];
$url = Url::fromUri('http://finance.google.com/finance', $options);
$link = Link::fromTextAndUrl(Unicode::strtoupper($field), $url);


You can remove it using hook_html_head_alter like the following:

/**
 * Implements hook_html_head_alter().
 */
function myTheme_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $head_element) {
    if (strpos($key, 'drupal_add_html_head_link:shortlink') === 0) {
      unset($head_elements[$key]);
    }
  }
}

PS : the above code remove links with rel="shortlink" if you want to remove links with rel="canonical" just add another if and change shortlink by canonical.


If you can profile your site that's always helpful. https://drupal.stackexchange.com/questions/724/why-is-drupal-7-so-slow

https://groups.drupal.org/node/210683 - Older post but some patches have still not been committed.
https://groups.drupal.org/node/415883 - Speedups for the DB layer (caches mainly).

Because of windows checkout this post and this group
https://groups.drupal.org/node/242443
https://groups.drupal.org/drupal-windows


How Can I change the fields order without using CCK

In my views cck will always overwrite the weight you assign programmatically, best way should be arranging the cck fields in order you want.
If you want to change order on the fly using javascript can be an option too,but not sure if it is good option
for example

jQuery('.field-name-field-test-taxonomy').insertAfter('.field-name-field-simple-text-field');

where ".field-name-field-test-taxonomy" and ".field-name-field-simple-text-field" are the wrapper div for cck fields respectively.with out the above js code the default taxonomy field was coming before the simple-text field but with we simply change the order.
hope it helps.


How to get addressfield geocoded on import with Feeds?

The way that your Geocoded data will populate after save indicates that there is some hook in the geocoding module that triggers after a save. Perhaps the initial save in feeds bypasses this.

I suggest you find in the Geocode module the point at which this save is triggered, but as a work around for you which should work, trigger another save once feeds has saved your node.

Create a custom module with a hook_feeds_after_save, then call $entity->save() on it again to issue a re-save and that should force your Geocoded values to populate.


How can I run a query in the views in the context of the user access?

I've found possibility to do it in hook_views_post_build:

function MY_MODYLE_views_post_build($view) {
  if($view->name == 'MY_VIEW_NAME') {
    $query = $view->build_info['query'];
    $query->addMetaData('account', user_load(47));
  }
}

I've noticed that we have SelectQuery object only after query build (in views.inc $this->query->build($this);).

After it only one hook is executed views_post_build.


Is possible for a module to know when one of its blocks is being output on the dashboard, and change the content of that block?

You could check the url argument that the block is displayed on and then if it matches an expected pattern i.e. /dashboard then you can alter the contents of the block. This solution only really works if you've coded the block yourself.

Update: This method will still work, although I'm not familiar enough drupal 7s dashboard module to comment further. The only thing I would suggest is to output page variables and see if there is anything set by dashboard module.


Jcarousel Images loads in list then conform to horizontal block

If you're setting overflow:hidden you also need to give the same element a static height, e.g.

#slideshow-wrapper{overflow:hidden;height:300px;}


Stuck developing a new library module for "vminpoly". "Drupal.behaviors" confusion

So I had a few problems with this. First of all my .module file defined a library because that felt like the proper way to do it. However I received errors in the console and needless to say that it didn't work. After Googling the error I found out that it happens when everything is in the head.

So I removed the library implementation. Then the script itself didn't work. Again after searching on Google I found a fork of it where the guy had fixed those errors. This can be found at: https://github.com/gfaceless/vminpoly

I created a directory called lib, then placed parse-css.js & vminpoly.js in it.

My .module file became:

<?php

/**
* Load all files / JS
*/

drupal_add_js('if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }', array('type' => 'inline', 'scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/parse-css.js', array('scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/vminpoly.js', array('scope' => 'footer'));

Also removed dependencies[] = libraries from the .info. Lastly, for me it didn't kick in unless I aggregated my CSS files.

Hope this helps others. Now my vh, vw and vmin length units work across browsers. Happy days!


Assigning roles and permissions Drupal 7

If you go on www.yoursite/admin/people/permissions#module-user you can decide witch kind of user can edit user permissions, so in your case only admin and shop_admin.

Of course you do not want the shop_admin to edit admin permissions, and all the pages where you can edit single user permissions are forms so you can use hook_form_alter in order to hide unwanted options or add conditions based on user role


How to theme a Quiz in Drupal 7? - part 2

\sites\all\modules\quiz\Quiz.css --> this is the place to change.

CSS class definition to be created for: "quiz-question-body" - this is for the question itself.


How to use an image with Responsive Image style as a background?

What you're trying isn't going to work on a background image. You'd need to do this yourself with javascript. How i've done it previously is added data attributes to the div for each breakpoint e.g.

<div data-mobile-image="mobilestylename/aaa.jpg" data-desktop-image="desktopstylename/aaa.jpg">

Then in javscript use matchmedia or a body class if its already being added by your theme to know which breakpoint you are in and then do

var mobile_image = $('.mydiv').data('mobile-image');
$('.mydiv').css('background-image',mobile_image);


I managed to it with some custom coding basically i alter the form add a one more option to group audience field and then on form validation I am checking if user has input that field then I am making a db query to grab all og groups on site and then assign the group ids to the group audience field,looks kinda hackish but did'n get any better solutions.


How can I change Menus depending upon domains (url name)?

This is how I would do it:

Create a main menu per site
Create a context condition plugin for domain names
Create a context per domain
Create a context per site and place the menu block in the navigation region for each context

Profit

If you need to put the same links in multiple menus, check out the multiple node menu module.


How to get the "label" of "Allowed Values" for a text list programmatically?

Load the field config and look for the key/value pair from the allowed value list?
Much easier though is using the field formatter for this field type OptionsDefaultFormatter:
$build = $user->field_foo->view(['type' => 'list_default']);

What you do with $build depends on the use case. Put it in a render array to be rendered later or
$output = \Drupal::service('renderer')->renderPlain($build);

if you need it now and can't wait until the page is rendered, for example if you want to send an email.


How does one keep a session alive across two different URLs?

You can use Bakery Single Sign-On System module.
https://www.drupal.org/project/bakery


What is the node:id cache tag equivalent for blocks?

I just figured myself. The cache tag for custom blocks is simply:

block_content:7


Urls without question mark are served with 404 in Drupal 7 with Nginx

After some debugging, I think, I can understand what happens.

Take a look at this Nginx rule from http://wiki.nginx.org/Drupal:

  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().
            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }

I'm using the Drupal 7 rule and it tells Nginx to just execute the /index.php without any argument handling. Next, Drupal initializes and runs the drupal_environment_initialize() function, which calls the
request_path() function. Here Drupal tries to parse the $_SERVER ['REQUEST_URI'] variable. And of course, here is no special handling for malformed urls, I see in my logs.

I think, that's the difference between my old Drupal 6 install and Drupal 7.

Another rewrite rule from Nginx
No url parsing by Drupal

Basically the question is not so big, if some search engine is too dumb to create malformed urls, it's not my problem. But I wanted to handle it, so I modified the Nginx config, by adding a rewrite string, which redirects malformed urls:

  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().

            # redirect bad urls like /page&a=b to /page?a=b
            rewrite ^/([^?]*?)&(.+?)=(.+?)$ /index.php?q=$1&$2=$3 permanent;

            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }


Why comments replies are not showing as indented?

What you can do is to give the "reply" (it might have a unique id or class), some margin left to indent it under the comments.

The reason that it is indented in Bartik, is that Bartik is the standard theme and is fully compatible with drupal core.


Change print $node_url To a Link Fields Value

If it is a field with in the node then you should be able to use the $node object.

The object contains all the fields associated with the node.

if you are not sure of the name of the field then you could try to print the object using the print_r function.

You could also try try the $content object which contains the fields as well.

print render($content['field_viewslink']);

That should render the variable.


Organising content using Taxonomy and Views

Yes it is possible. You should learn Panels too. Panels works very nice with Taxonomy and Views. Try lullabot video tutorial about views, very good.


entity_get_form_display setComponent throws "plugin does not exist" regardless of type

OK, I've dug around and I think I've got a fix for this myself.

The first thing is to fix the code above; the two 'type' entries SHOULD be different, and should match values available in the dropdowns in the admin UI:

entity_get_form_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'text_textfield'])
  ->save();
entity_get_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string'])
  ->save();

The second thing is that the entity's baseFieldDefinitions() were also defining a 'view' formatter type and a 'form' formatter type, but for an undeletable base field:

$fields['name']->setSettings([
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ])
  ->setDisplayOptions('view', ['label' => 'above', 'type' => 'string'])
  ->setDisplayOptions('form', ['type' => 'text_textfield'])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Originally, the form display here was also 'string'. This is obviously nothing to do with the programmatic field adding itself, but when you run:

entity_get_*display(...)->setComponent(...)

the return value is $this i.e. the display object. So chaining ->save() causes the ENTIRE display to be saved: including base fields. Only at this point did the broken configuration in the base fields suddenly cause a problem.

But, ensuring that:

the 'type' for form display ALWAYS matched a value available in the admin UI for content types
and similar for view display
and ensuring this across both the new field AND base fields

fixed the original problem. Phew.


Difference between Media and Asset module

Looking at this issue in the media module issue queue, the main technical difference (apart from UI) would be that the Asset module creates its own entity while Media uses the core managed_files API. In other words: Asset is 'an island' and other modules must specifically support Asset module. Integration with media module is easier because it uses core infrastructure.

There actually is a request to merge parts of Asset & Media code.

I took the module for a quick spin, it looks pretty easy but less flexible then the media module. However, I always found the media module configuration very complicated (file styles) because of its flexibility probably.


Entity filed query for sorting by title and weight both?

This is more of a straight PHP question than a Drupal question, but it looks as if you have a bug in your value comparing function. It should return 1 if you want $a to sort greater than $b, it should return -1 for $b to sort greater than $a, and it should return 0 if the items should sort equally. But your function will only ever return 0 or 1. Try replacing your last return statement with return ($a_weight > $b_weight) ? 1 : -1;


Sharing the same code base and one database

This is very much possible using the domain module:

  "The Domain Access project is a suite of modules that provide tools
  for running a group of affiliated sites from one Drupal installation
  and a single shared database."

Which is currently under development for Drupal 8 here:

https://github.com/agentrickard/domain

This of course assumes you are not talking about actual Drupal multi-sites which are intended to share the same codebase but always have separate databases.


Instead of trying to compare the result of two views and find the difference, which is highly inefficient and difficult, it will be a lot easier to create a new view that filters out the users that that has posted within a day.

You should be able to duplicate ViewA and reverse it's filter(s). It should at least provide a good starting point.


Extending Entityreference Field Class to contain additional input fields

The error is on the field item list class.

What you are missing is the list_class definition in the annotation of your field type, for anything that's an entity reference, you need to explicitly specify it, since annotations aren't inherited. See EntityReferenceItem:

*   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",


Could you try changing the ordering for the grid to be vertical and not horizontal. I am assuming that the you are using a grid as the format for displaying your data in the view.


Take a look at the Smart IP module. It may be what you are looking for. Excerpt from the module's project page:

  Identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($_SESSION) with array key 'smart_ip' and Drupal $user->data object with array key 'geoip_location' of the user but optionally it can be disabled (by role) at Smart IP admin page. Other modules can use the function smart_ip_get_location($ip_address) that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.


In Drupal 8.1+, password hashing and checking is managed by a service that can be replaced in your site's services.yml file.  You need to provide your own implementation of PasswordInterface.

Instead of replacing the hash method, it would be safer for your implementation to inherit from PhpassHashedPassword and override the check() method to accept your MD5 hashes (but otherwise use the parent implementation). You can use a dedicated prefix to detect old hashes. And thanks to the PhpassHashedPassword::needsRehash($hash), your password will be securely rehashed over time.

For instance, the following code expect you old hashes to be prefixed with BAD$ in the database.

class MyPasswordService extends PhpassHashedPassword {
  function check ($password, $hash) {
    if (substr($hash, 0, 4) == 'BAD$') {
      // Migrate MD5 has
      $stored_hash = substr($hash, 4);
      $computed_hash = ... old and insecure hash code ...;
      return $computed_hash && Crypt::hashEquals($stored_hash, $computed_hash);
    }
    return parent::check($password, $hash);
  }
}


Stop Youtube when changing between tabs (Quicktabs)

I think this post should help you: https://stackoverflow.com/questions/1094397/how-can-i-stop-a-video-with-javascript-in-youtube.

As @Pan Chrono said, it's not a drupal related question, more a youtube one.

What you basically need is:

change the way the youtube video is embed. It's actually using an iframe, you need a "embed" tag.
add "enable_js=1" to your URL so you can use Youtube Api
add a custom JS file to your page, and do some little jQuery code so that the video is stopped (with var myPlayer = document.getElementById('playerid'); myPlayer.stopVideo();) when you click on one of your tab


Translation Table:

  This module presents your taxonomy terms or menu items in a table, and
  each language has a corresponding column. Just fill out the
  translations and click Save.


Use CKEditor for textareas in custom form

Use the text_format element type and CKEditor will catch your field:

  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
  );

If you have issues with showing CKEditor in popup use additional #pre_render:

  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
    '#pre_render' => array('ckeditor_pre_render_text_format'),
  );


First of all, you are supposed to write to $entity_field[0]['value']. Second problem is that fields operate on entities, not nodes, so you need to use $entity instead. You can always use Devel module and dpr($entity) to see what's in it.

node id should be in the entity field if it is a node. In which case you can load it with node_load().


I would recommend you to disable payment method by default on which you have to operate(enable/disable). In rules you can check the condition where you have to enable the particular payment method & in action you can simply enable the payment method you want to.

This is what I have done in one project...as in action part it's hard to find remove option.


Make custom field added to comments available in comment.tpl.php

All you gotta do is add <?php print render($content['field_rating']); ?>


Is it possible to combine several template files togather and make single integrated template instead?

In drupal 8 there's this rule called theme inheritance and backward compatibility, what you have to do to accomplish what you want is to make sure that your subtheme does not inherit any core theme's HOOKS

You might want to play around in your subtheme and set your base theme to null
I haven't checked it myself but it might work.

And then of course you have to define new preprocess templating rules in your themename.theme file using theme_suggestions_page_alter function, you can read more here

Then based on what you defined in your .theme file you may proceed with creating a unified template file

Also you might want to read this suggestion that somewhat explains a similar use case


Keep menu open for custom content entities

My solution turned out to be the contributed module Menu Trail By Path: because I can fine-tune the actual URLs in all of my entities' YAML files, I can define the hierarchy easily.


Active a menu  when the menu entry is a view page

I guess you could achieve this with Menu Position module, where you can set an active parent for specific node/content types.

https://www.drupal.org/project/menu_position


Lost Social Connection Icons after uploading custom images

After troubleshooting with @nosssweat, it turns out this is an issue with Adobe PS saving empty PNG files. Surprise!

To fix, I switched to 24-bit PNG and was able to save the web-optimized format correctly. All issues fixed here.


How to import an SQL file and COMPLETELY erase the previous one

You can use drush:

drush sql-drop; drush sqlc < path/to/sql/dump/file.sql

Understand it will drop your entire Drupal db and the second command will rebuild it from your dump file.

You can create a base dump from:

drush sql-dump > path/to/save/dump.sql

Here's the link to the drush commands website, select sql from the menu on the left drush commands


How to get each field value in views-views-unformatted--view-machine-name.html.twig?

I have found a Way using Kint, You can get field values in views-view--unformatted.html.twig

if you want a specific field

To get text fields value

{{row.content['#row']._entity.field machine name[0].value}}

To get image fields src

{{file_url(row.content['#row']._entity.field machine name.entity.uri.value)}}

To get image alt,title,width,height

{{row.content['#row']._entity.field machine name[0].alt/title/width/height}}

  Note :  replace field machine name with your fields machine name

If you Want to loop through multiple field

{% for i in range(0, 10) %}
  {{ row.content['#row']._entity.body[i].value }}
{% endfor %}

If you Want raw value

{% for i in range(0, 10) %}
  {{ row.content['#row']._entity.body[i].value|raw }}
{% endfor %}


User name who flagged in Global Node flag

For those who are in similar situation, I'd like to inform that at the time of writing, This is Not Possible with Flag. Flag module is just Boolean true/false.

I changed the flag to Vote using VotingAPI and Plus One modules. The VotingAPI has Views integration and via views Relationship, I could get the User information and Vote Timestamp to display in the page.


Language detection URL domain on localhost

It is better that you configure a subdomain or even a complete domain. For example, site1.localhost and site2.localhost and that you change your apache or web server to point to the Drupal root folder. Even you can change your OS hosts and link to fake domains, for example, site1.example.com and site2.example.com.

For multi-domain and multi-language I would recommend these modules which work like a charm:

Domain Access
Internationalization

You can add new sites and in each site have one or more different languages. These would solve all your problems as it works very well and it is pretty good in configuring content served from a single installation to several different domains and languages.


Try to do the form_alter, only if url has a #hash

if (preg_match('#^user/reset/(.+)#', $_GET['q'], $matches)) {
  //here for new user
}


Use chrome/firefox's inspector and click on the edit link that will highlight the element that's sitting over the top of it and you can sort your CSS out for that element


Trying to make a filter taxonomy menu with multiple vocabularies

I think that you mean "taxonomy vocabularies" when you say "taxonomy menu". Because actual menus like the navigation are not really suitable for this task.

Scince you are using Commerce Kickstart, you can simply use multiple Search Blocks as Filters and join their results. The View "Display Products" that comes with Commerce Kickstart by default actually has already a Block with the "Price" Filter on it.

I am assuming that your product display already has fields for the Term references to your taxonomy vocabulary. Also assuming you have not changed these settings yet, go to Administration » Configuration » Search and metadata » Search API » Product display » Fields and select the fields of your product that you want to filter for. Then reindex them and go to Administration » Configuration » Search and metadata » Search API » Product display » Facets, select your new fields and edit their display (e.g. checkboxes for color and ranges for price). Make sure you select "AND" as an operator if you want to have the products that match every filter.

Once you have that, go to Administration » Structure » Blocks and put the newly created blocks on the sites you need them on (e.g. /products)


Possible to use default user picture in rewritten views field?

You can use no result behavior option to show the default picture for the user's image.

Here is my screenshot :

If you want to combine two fields then you have to take two field firstly in view fields and shown their output in diffrent-2 field after that you can combine both fields in new field using rewrite option. The first two field output is hidden who's value you want to combine.


Exporting my custom content tables for a module

You should look at the Features module. It will generate a module, which you can merge with your custom code.


reference a view page with entity reference

View Reference Module makes it possible

Defines a field type View reference which creates a relationship to a
Views display and allows the view to be displayed as the content of
the field.

OR
Entityreference View Widget Module is another solution

This module provides an advanced Entity Reference widget that uses a
view embedded in a modal dialog for selecting items.
In the Field UI for the Entity Reference field select "View" as the widget

Edit your Content Type or Entity
Add or Edit the field with "Entity Reference"
Next make sure your "field" - "widget type" is set to "View"

Check for the following "field" settings in your content type field:

"View": make sure you select your "Entity Reference View Widget"
Pass selected entity ids to view


You are using Organic group module. So this module also provides two views called Og members and Og Content. Now download the module Views Field View which allows you to embed views as field in other view. See the Readme.txt file for more detail.

Create a new view and embed other two views Og members and Og Content in new view.


Node or Taxonomy reference field with "Add new item" on node creation page

For node reference fields, I use References Dialog to include a link for adding the referenced node. Looks like they are working on taxonomy references.


Megamenu might be of use.

  Mega menus are a type of menu drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:

  The information architecture of your navigation is made clearer and is visible all at once
  The amount of clicking, searching, and navigating is reduced


How can I loop through checked entity reference values with a taxonomy condition?

The first (crucial) part of your rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

So add a loop related to the flavors that got selected. After you do, you should iterate over each item in that list (= each flavor).

And for each iteration you should then perform an appropriate verification if it is a premium flavor (in which case you want to add $5). But, within Rules Actions, you cannot just add another Rules Condition (as you may have noticed) ... Except if you use the Conditional Rules module (which is exactly the purpose of this module ...).

Done

PS: are those funds still available?


Can anyone help me translate this Javascript code line the Drupal Way?

jQuery("input:text:visible:first").focus();

Becomes

Drupal.behaviors.focustextfield = function(context) {
  $("input:text:visible:first:not(.focustextfield-procd)", context).addClass("focustextfield-procd").focus();
}


drupal 7: trying to make use of Compressing JS and CSS causes Major Error

There is probably an error with the file-system? Go to admin/config/media/file-system, check the settings or just hit the save button again. But backup your site befor you do this. Have you tried to upload a file? Do you get any other cache / temp error? Did you clear the cache?


Site aliases: Use a different PHP path on remote

From example.aliases.drushrc.php:

  Although most aliases will contain only a few options, a number
  of settings that are commonly used appear below:

...

  'php': path to custom php interpreter. Windows support limited to Cygwin.

So try somtehing like:

$aliases['example'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com',
  'remote-host' => 'www.example.com',
  'remote-user' => 'user',
  'php' => '/path/to/php/on/the/server'
);

You could try that. If this doesn't work I would suggest to update your drush version (locally and on the server) and try again, before doing any strange symlinking on the server.


How can I remove an entry from the blog front page?

The blog module builds this page in the function blog_page_last().

The query in blog_page_last() does have a node_access tag so you could use hook_query_TAG_alter() to add a condition but may be tricky to just target that one query on that page.

I think a better option would be to use hook_menu_alter() to change the callback for the blog menu item to a function in your own module. In this function you can just copy the code from blog_page_last() but add a additional condition for your new promoted field.


There is the session_expire module, and this module's page has some information about garbage collector confs and stuff.


As suggested by Berdir you can look at Devel module and at how it's implementing that. The following code was "extracted" from Devel

1) Create the routes

Create the file mymodule.routing.yml in and inside define a route callback (which is used for create the dynamic routes)

route_callbacks:
  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'

Create the class MyModuleRoutes for generate yours dynamic routes in src/Routing

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class MyModuleRoutes implements ContainerInjectionInterface {

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function routes() {
    $collection = new RouteCollection();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $route = new Route("/mymodule/$entity_type_id/{{$entity_type_id}}");
        $route
          ->addDefaults([
            '_controller' => '\Drupal\mymodule\Controller\MyModuleController::doStuff',
            '_title' => 'My module route title',
          ])
          ->addRequirements([
            '_permission' => 'access mymodule permission',
          ])
          ->setOption('_mymodule_entity_type_id', $entity_type_id)
          ->setOption('parameters', [
            $entity_type_id => ['type' => 'entity:' . $entity_type_id],
          ]);

        $collection->add("entity.$entity_type_id.mymodule", $route);
      }
    }

    return $collection;
  }

}

2) Create the dynamic local tasks

Create the file mymodule.links.task.yml and inside define a deriver

mymodule.tasks:
  class: \Drupal\Core\Menu\LocalTaskDefault
  deriver: \Drupal\mymodule\Plugin\Derivative\MyModuleLocalTasks

Create the class MyModuleLocalTasks for generate yours dynamic routes in src/Plugin/Derivative

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModuleLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $this->derivatives["$entity_type_id.mymodule_tab"] = [
          'route_name' => "entity.$entity_type_id.mymodule",
          'title' => t('Mymodule title'),
          'base_route' => "entity.$entity_type_id.canonical",
          'weight' => 100,
        ] + $base_plugin_definition;
      }
    }

    return $this->derivatives;
  }

}

3) Create the controller

Create the class MyModuleController in src/Controller

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class MyModuleController extends ControllerBase {

  public function doStuff(RouteMatchInterface $route_match) {
    $output = [];

    $parameter_name = $route_match->getRouteObject()->getOption('_mymodule_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = ['#markup' => $entity->label()];
    }

    return $output;
  }

}


how to stop annoymous users to login in drupal

There is the restrict by IP module, which can solve the use-case pretty fast. For the second part, depending on if you are in 7 or 8, you would want to write code to handle a request to either of the routes, evaluate the allowed IPs against the user IP, and do a redirect. Would be easier and more manageable vs the htaccess route, in my opinion.

You can disable user registration by disabling it in the admin (only admins can create accounts).

Furthermore, no one can even get to /admin or administrative pages without the right permissions anyway, so if they are not logged in, it isn't really an issue. That just leaves the login and forgot password page. Forcing a redirect within admin paths might also interfere with things like AJAX actions as well - I would probably leave that alone.


Add to cart button not displaying inside custom text in drupal 8 views

AFAIK you can't rewrite the output of rendered entities (add to cart form) with replacement patterns for in D8 views.
I ran into this same problem and discussed it with the maintainer of the commerce_variation_cart_form module. You can read about it here: https://www.drupal.org/project/commerce_variation_cart_form/issues/3081903
Specifically this from comment #17 https://www.drupal.org/project/commerce_variation_cart_form/issues/3081903#comment-13269416

All the render code runs including the form generation and extra field addition, but anything in a views field rewrite is then run through Xss::filterAdmin() to remove dangerous tags, and apparently form is a dangerous tag


How to show another text if field val 0?

AFAIK  this is the correct way:

{% for item in items %}
    {% if item.content == 0 %}

balance

Yes {{ item.content }}

    {% else %}

balance

Nope

    {% endif %}
{% endfor %}


We're doing something similar.

The User gets a role, that determines what he may buy
A custom field on the productVariation lists which roles it is available for
In a preprocess function we compare the user's roles to the accepted roles on the variation and set a flag
twig evaluates that flag

Since we only have 5 products, where we have to differentiate, this works. I imagine if you had hundreds, it might be cumbersome.


Attach a node to a menu link OR attach custom fields to menu links?

Look into like Menu Views or GigaMenu or MegaMenu ... there are a few solutions that let you place a view in a menu.

Then you can either add a field to a content type such as, "include in featured menu" of type boolean, that you use as a Filter in your View. Or, re-use the "promote to frontpage" re-labeled to fit your needs on a specific content type.


For the location to be displayed on the google map,You need to install few modules:-

Install GMAP and LOCATION module,
Install GEOLOCATION and its dependent modules.
Add a field in content type with field type GEOLOCATION  and widget type GOOGLE MAP.
With this, When the user will ad content,he will be able to mark the location of the area of the power cut on the map.
Refer this GEOLOCATION for further help.


The tokens available when rewritting the output of a field correspond to the values of the other fields you have selected in the view. They must also be above the field you are rewritting in the field order.

In order to get the URL, you should add a node path (or link to node) above your current field and mark it as "hide from display".

The token will now be available!

PS - If you want to link to the node's url, you can always just select the option to display the field as a link to its node.


I'm trying to set a $page variable but it's not working.

<?php

/**
 * Implements hook_preprocess_HOOK()
 *
 */
function YOURTHEME_preprocess_page(&$vars) {

    // All you need to do is to set the appropriate preprocess variable:
    $vars['show_messages'] = false;

    /**
    We also have $vars['page'] which is an array.

    $page = $vars['page'];
    This array is a Drupal Render Array which means would pass through drupal_render() function.
    In a Render Array keys starting with # are attributes and the others are children elements.
    Read more about that on @see https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_render/7

    */
}


Custom widget not rendered within field group

OK. I finally found the problem based on the example code here.
The problem was that I constantly used "form" instead of element. Once I had replaced that the rendering was correct.

$form['b2share_fieldset']

instead of
$element['b2share_fieldset']

However, the huge downside is that now I don't know how to access the field information as $form_state isn't working anymore.

EDIT: After applying some minor changes in the code I can confirm that this approach works. The fully functional code can be seen on github.


How do I programmatically populate a field if another one is empty?

Create a custom module, in mymodule.module use hook_node_update

function mymodule_node_update($node) {

  if (!isset($node->field_example[LANGUAGE_NONE][0]['value'])) {
  // If field example is not set (is empty), then...

     $new_value = // ...do some stuff to compute a new value for the field.
     $node->field_example2[LANGUAGE_NONE][0]['value'] = $new_value;
     field_attach_update('node', $node);

  }

}


First look into Theme information in views:

In Row style output, copy one of the template names:

This lists all available .tpl for your views and now Create an empty php file with your chosen template name in your themes template folder.


Taxonomy and Views - Creating a view based off of user selection

There are a few ways to accomplish this; i'll offer up my easy answer.

You can show all of the nodes associated with a taxonomy tag by adding the "Taxonomy: Term" filter (select the taxonomy term ID filter). Select your relevant vocabulary, and then select 'dropdown' for your Selection Type.

Click 'Expose' to show a dropdown box to your users. When a user selects a tag from your dropdown, your results will be filtered according on the Operator you have chosen.


Set restriction on user by country for language translation content

You can use Translation Access module.

This module provides per-language access control for creating and updating nodes by adding a list of checkboxes for each available language to the user add/edit form (only visible to users with 'administer users' permission).


How can I add menu items when importing nodes into Drupal 7 (with the Feeds module)?

You can try the sandbox project Feeds Menu

  Adds mapping elements for menu entries for feeds


CMS Vs Framework? Is Drupal A CMS, Framework, or CMF (Content Management Framework)?

Drupal is Content Management Framework (for Developers) as well as Content Management System (for Non-Programmers).

Drupal is a highly configurable open source and an application development framework providing the following features:

Drupal provides the structure for Web applications which is far more complex than a CMS such as:

Extend the functionality (using contributed or custom code).
Communicate with other Web applications.
Run applications written in PHP and other languages behind the scenes.
Provide responsive pages or integrate front-end languages.
Scale to handle large traffic numbers by making use of server technologies and provide the foundation for other as yet unthought of innovations.

Drupal is one of the most highly extensible frameworks available, and has the built-in ability to grow with your organization. Drupal was built from the ground up with a uniquely sophisticated granular level control system that provides unparalleled extensibility. With its vast feature-rich capabilities and growing community you’ll never outgrow Drupal.
Pre-made functionality in Drupal can be overridden through hooks, or you can find workarounds that Do Not require modifying other modules.
Drupal maintains a vigilant security community, providing security release updates on an ongoing basis to achieve maximum site security, which is one of the reasons even the U.S. Government and governments around the world use Drupal.
Drupal's modular architecture allows complex solutions to be "assembled" quickly and reliably. Over Fifteen thousand modules are available for Drupal.

CMS (Content Management System) features of Drupal:

Drupal comes with many tools to help you organize, structure, find and re-use your content. Categorize with taxonomy, automatically create friendly path urls, create custom lists, associate content with other content on your site, and create smart defaults for content creators.
Manage content with an easy-to-use web interface. Drupal's flexibility handles countless content types including video, text, blog, podcasts, and polls with robust user management, menu handling, real-time statistics and optional revision control.
Drupal comes with great options for new user accounts and user permissions. Users can be assigned one or more roles, and each role can be set up with fine-grained permissions allowing users view and create only what the administrator permits. The Drupal 7 admin theme makes administering a site easier than ever.
Drupal's focus on social publishing can help you create sites and applications to help your users express their opinions and engage with one another. You can have tight control over who can create, view, administer, publish and otherwise interact with content on your site.
Drupal's presentation layer allows designers to create highly usable, interactive experiences that engage users and increase traffic. Use an existing Drupal theme for your site, giving it an instant identity! If you can't find one you like, try designing your own which others can use, too.


Can't restrict permissions on forum topics?

The problem is that you selected "Bypass content access control" for the authenticated users. That means the previous permissions you chose for the authenticated users are not considered: You didn't give the permission of editing any forum topic, but as authenticated users are selected to bypass the content access control, Drupal will not check if they can edit any forum topic, and it will give them that permission.

If you look at the code of node_access(), the function that returns TRUE when a user has the access passed as argument for the node passed as second parameter, you will notice that it execute the following code:

if (user_access('bypass node access', $account)) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}

What you reported are only the Drupal core permissions, not the one set by the Forum access module. For the Drupal core permissions, you didn't report if the authenticated users have the "View published content" permission; without that, any published content would not be visible to any users, except the user #1, and the users with the "Administrator" role, for which Drupal automatically set all the permissions, but then leave you the possibility to disable some permissions.

The other problem is the conflict between Drupal core permissions, and the permissions set by the Forum Access module; when you use that module, you should not use the permissions used by Drupal core core, such as the ones you reported. If Forum Access needs to control the permissions, then the permissions you shown for the forum topics should not be set.

If the users get an "Access denied" error for every node, even if those are not forum topics and they have the permission to view published nodes, then the problem is something else. The first think I can think of is that those nodes are unpublished: There is an option in the content type settings that set its nodes as published, when created; if that option is not selecte, the nodes are created unpublished. It could also be a problem with an installed module (which is not Forum Access, as it doesn't handle permissions for other content types); in that case, I would not be able to give a hint about which module is causing the problem, but I see the same problem when the theme used as default theme was not enabled.


Drupal gives `Notice: Undefined index: highlighted in include ..` error during theme creation

this is probably stemming from the default page.tpl.php which is expecting to find a region highlighted.  The best approach IMHO would be to create a custom page tpl that excludes the regions you don't use, and includes the regions you do.

You can find the default page.tpl.php under modules/system - just copy the file to your theme directory (or sub folder templates) make the changes you want, and then clear the cache


Adding translation files to install profile?

Have you seen http://zgadzaj.com/drupal-installation-profile-with-multiple-languages ?

Also you can try to export it with Features

  Features

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

And for more especific export data

  UUID Features Integration

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.
  What's that you say? You thought features was only for configuration?
  This module is meant to be used in the cases where certain pieces of
  content straddle the line between pure content and configuration.
  You've to configure the entity types / bundles to be exportable. Read
  the Documentation for further information.


Are you sure there are no differences in the codebase? This would explain the issue. The plugins/routes are cached in the database until you clear the cache. Then they are rediscovered from the codebase and the missing plugins or routes become visible. It's not necessarily that the code is missing physically, it can also be a problem with autoloading.

If there is a problem with syncing the codebase by git/composer, use another tool, for example rsync. Make sure to sync the complete codebase, also the files in the root folder.


Is there any need to check the block name when my module just define a block?

While your module defines only a single block, technically no, it's not necessary.

But, as soon as you want to add another block, you'll need to distinguish between that and the existing one, so you'll need to check the block delta.

It's a good practice to get into, even if it's not strictly necessary to test the delta in the block view function.


Add multiple co-authors while creating node

I suggest you look at these two modules

https://www.drupal.org/project/references
https://www.drupal.org/project/entityreference

They're both quite similar.

They allow you to add user reference fields to your content type. On the field you created, set the number of values to be unlimited and then the author can select as many co authors as they want.


How do I override the Bootstrap3 user registration form?

Why don't you alter the user registration form by adding fields at admin/config/people/accounts/fields there is an option Display on user registration form.

This will then modify the User entity to use those fields, which may mean your membership_request node is not needed, but if it still is you can use Rules to automatically create a node when a user registers.


Change the order of a sort criteria in views to a custom hierarchy

Add a relationship Content: belt level (or whatever your node reference field is called) to the view.

Then add a new sort, choose Content: level int (or whatever the integer field is called) and under 'relationship' choose the one you just added.

That should do it.


You can use Administer views but to quickly achieve this I would use the hook_form_alter.

Do something like this, Although I would recommend you set this restriction to specific role but for this example I am going to ignore roles. Within hook_form_alter you do

if($form['#form_id] == 'node_admin_content') {
   unset($form['filter']['filters']['status']['filters']['type']['#options']['article']);
}

You can change the ['article'] to whatever the machine name of your content type is. use devel to find out what elements the $form variable contains.


Currency resolver - Cache problem on platform.sh

Solution is to add cookie to routes.yml file in .platform folder and than push it to the platform branch. After that currency resolver will work.


Register Drupal Commerce user before checkout completes

If you are wanting to do something during the checkout process, your best bet is to use a hook_form_alter() on the checkout forms and add your own submit handler. In this case you're looking at the commerce_order_account_pane. Remember that panes are fieldsets within a per-page form, so you'll want to look for the router page form and put your submit handler there.


node.html.twig

{{ content.field_something.value }}

Show

custom.js

(function ($) {

$('.field-something').hide();
$('.show').show();

$('.show').click(function(){
    $('.field-something').fadeIn(2000);
    $('.show').hide();
});

}(jQuery));

Your Theme's style.css

.field-something { float: left; padding-right: 5px; }
.show { color: blue; cursor: pointer; display: none; }

Example DEMO


Prevent multiple registrations from the same email using + character

Check email before register user with add your custom validator in hook_form_alter, then check user email without +secondpart :

As a Example you can Try something like this (I didn't test this but it can give you a good clue to achieve what you want )

 function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id){
       if ($form_id == "user_register_form") {
            // add your custom validator
            $form['#validate'][] = 'my_custom_email_validate';
       }
     }

in your custom validator check it with regular expression

function my_custom_email_validate($form, $form_state, $form_id){
    // dpm($form_state['values']);
    $mail = $form_state['values']['mail'];
    preg_match_all('/(.*)\+.*(@.*)/',$mail,$matches);
if($matches){
    // this mean it has  xxx+xx@xxx pattern
    $clean_mail = $matches[1][0].$matches[2][0];
    $user_load = user_load_by_mail($clean_mail);
    if($user_load){
        form_set_error('mail',t('Sorry,This email used before.don\'t waste your time dear spammer'));
        return false;
 }
}


Help with basic hook for my first module

dpm and dsm can be a little tricky in some hooks, and you may need to time a cache clear with a page reload to see them fire.

Better to use something like watchdog or actually alter the page content.

Your function looks good, so try this from the example module. More chance of seeing the effect:

function checkout_pane_example_commerce_checkout_pane_info_alter(&$panes) {
  if (!empty($panes['cart_contents'])) {
    // Change the title of the "Cart Contents" pane.
    $panes['cart_contents']['title'] = t('Your big wonderful shopping cart brimming over with shopaholic nonsense');
  }
}


determine value differences between form submissions

If you're looking for a non-SQL way to get data out of the database the db_select() function (which returns an SelectQuery) is the way to go. For obvious reasons there's no implicit API implemented for your custom data tables (you'd need to create that yourself).

Without knowing your schema this can't be totally accurate, but the basics are:

$query = db_select('my_table', 't')
  ->fields('t', array('field1', 'field2'))
  ->condition('some_column', 'some_value');

$results = $query->execute();
foreach ($results as $result) {
  // $result is an object, use it...
}

SelectQuery has a bunch of helper methods to get specifically formatted data out of the database, so chances are you won't need to loop over the data. You can find a list of those helper functions (and info on the alternative, SQL based approach that still uses the API) here


Design views display and views filters separately?

Views results (sometimes in Fields Format), Exposed Filters, Attachments are all output into their own HTML containers. But you can override each View output in templates (look under Theme: Information under Advanced View settings).

For whatever purpose you can create two different Views, or two Displays in the same View, define Fields in one, and define Filters in the other. Then later you can export both, combine and replace the relevant parts of the export into one and Import with an override of the existing View so you end up with a combined configuration.

But why would you want to separate them in the first place? You can add exposed Filters to a View, work on CSS to style them, then later add Fields and style them.

It isn't necessary to have the exact same Fields a in View that you want to use as Filters. Fields and Filters are independent. Maybe this is what has been tripping you up?

You can have Filters that filter out one Content type and also filter by creation date. While in Fields show Titles, Author and Taxonomy terms. A completely different set of information in those sections.

A lot of confusion may be coming from nomenclature. Views Displays are the different outputs you create according to your needs (Page Display, Block Display). Fields are bits of information defined in Content types. Views Results can be displayed as Fields. Filters control qualitatively what is shown in Views, if you expose them then users can change that themselves (Exposed Filters you usually see above Results that let you control the filters on the fly).


How to target specific sites with Drush when using Multisites?

When you say "core site", do you mean the site in sites/default?  Is it an option to just delete the settings.php file at sites/default/settings.php?

If you'd like to manage your aliases in an alias file, create a file ~/.drush/mysite.aliases.drushrc.php:

$root = '/path/to/root';

$aliases['site1'] = array(
  'root' => $root,
  'uri' => 'site1.com',
);

$aliases['site2'] = array(
  'root' => $root,
  'uri' => 'site2.com',
);

See this link for an example.

Then, to refer to one site:

drush @site1 status

or -

drush @mysite.site1 status

To refer to all sites:

drush @mysite status

Maybe you want to get more fancy than this, though.  If you have more aliases in your alias file (e.g. for 'dev' and 'live' sites, you can make your own lists:

$aliases['dev'] = array(
  'site-list' => array('site1', 'site2'),
);

Then:

drush @mysite.dev status

If you want, you may also store your alias file in /path/to/root/drush or /path/to/root/sites/all/drush, but if you do this, Drush won't be able to find your alias file unless you specify --root on the commandline, or change your working directory to be somewhere inside of /path/to/root.


Create a menu block based on path using views

You can simply use Menu Block module to accomplish this task. If you want to display a block on specific pages just goto the relevant block configuration and under " Show block on specific pages" select "Only on listed pages" define the following

student/*

Now your block will appear only if this URL pattern will match. No matter what you have used to create your block.


A similar way would be to use Entity Views Attachment (EVA) along with a Product News content and utilize the tagging on the product to obtain a related news view


Change block location on page by page basis?

I am assuming 'recent content' is "just" the output of a view, so, if I that is correct, you can create any numbers of blocks with that content by just going into views and clone()ing the display and thus creating another block that could then be placed wherever you want.