IE has a header for controlling this, X-UA-Compatible.  Normally, people set this to 'IE=edge,chrome=1' which disables compatibility mode and tries to force Google Chrome Frame.  If you want to emulate IE7, you can use 'EmulateIE7'.

In Drupal 7, it is best to use a hook_html_head_alter for this

function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['MYTHEME_ie_compatability'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'name' => 'X-UA-Compatible',
    'content' => 'EmulateIE7',
    ),
  );

  $head_elements['MYTHEME_ie_compatability']['#attached']['drupal_add_http_header'][] =
    array('X-UA-Compatible', $head_elements['MYTHEME_ie_compatability']['#attributes']['content']);
}

This sets the <meta> in the <head> and also sets an HTTP header in the response.

In Drupal 6, you could use

function MYTHEME_preprocess_page(&$variables) {
  drupal_set_header('X-UA-Compatible: EmulateIE7');
}

You can also do this via Apache (eg, in .htaccess) with

<IfModule mod_headers.c>
  Header set X-UA-Compatible EmulateIE7
</IfModule>


How to override/enhance file_save_upload() function of file.inc?

Drupal runs on a Never hack core policy.

The Drupal way to add a watermark to image is to use hook_form_alter to modify the form submit and do your things with $form_state['values']['YOUR_FIELD']

Eg:

function mymodule_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
   case 'YOURFORMID':
     $form['#submit'][] = 'yourModule_yourform_submit';
     break;
   }
 }

function yourModule_yourform_submit($form, &$form_state) {
    // do what you want to do
    // use $form_state['values']
}

Or Try ImageCache Actions module.

  Watermarking - a much requested addition that enables you to place any
  image anywhere over a source picture, with alpha transparency


hook_form_alter add field after submit button to exposed view

The submit button will likely be inside an Actions element, which has a default weight of 100.
You could add your field to the actions element:
$form['actions']['include_card'] = ...

At which point the weight of include_card will be relative to the buttons/etc that are inside the actions element (and 25 will probably work).
Another option would be to position your element directly after the actions:
$form['include_card'] = [
  '#type' => 'checkbox',
  '#title' => t('Include gift card'),
  '#weight' => $form['actions']['#weight'] + 1,
];


Not being able to find better solution nor documetation, I built this working hack:

add a fake text field entity. IE: for articles: http://yoursite/admin/structure/types/manage/article/fields  > Add field > Add text plain field
hook the view in a custom module:

function MYMODULE_views_pre_render(ViewExecutable &$view){
  if( $view->id() == 'VIEWID' ){
    foreach($view->result as $r) {
    // from https://www.drupal.org/comment/reply/295383/12504094
    $node = $r->_entity;
    $flag_link = [
      '#lazy_builder' => ['flag.link_builder:build', [
      $node->getEntityTypeId(),
      $node->id(),
      'FLAG',
    ]],
    '#create_placeholder' => TRUE,
  ];
  $flag_link = render($flag_link);
  $r->_entity->set('field_fake_flag_field', $flag_link); //.
    }
  }
}

print (finally) your flag link in the twig template:

{{ rows[i]['content']['#row']._entity.field_fake_flag_field.0.value }}

Twig is cool. It takes a while, sometimes.


How to display one block among two block in Drupal?

This sounds like you're going to need to use something like Context to toggle the display of each of the two blocks depending on the context of the page.

See this tutorial for more info on how that works.


How to send author an email after they post content?

One easy way to do that is with the Rules module

Event: After saving new content
Action: Send email.

Here's an example Rules export (for article) that can be imported via the UI at admin/config/workflow/rules/reaction/import

{ "rules_review_notification" : {
    "LABEL" : "Send review notification email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "[Notification] Content submitted for review",
          "message" : "Your content has been submitted and will be published after review."
        }
      }
    ]
  }
}


Redirect loop after installing SecureLogin module

I have managed to fix the issue by commenting out the $base_url configuration I had set up in settings.php. Now the site redirects correctly but still shows some unsecured content (styles and scripts from the header mainly).


Can I disable a cookie from a contrib module, in this case fontawesome I believe

The Font Awesome Icons module provides an option to use the Font Awesome library locally rather than from a CDN. It's the CDN that is creating the tracking cookie, so if you follow the instructions to download Font Awesome to your own server, you should not have that cookie to worry about.
The Dropdown Language module simply extends Drupal's built-in language switching, which defaults to storing the language in the current session, so will not require any additional cookies.


How to uncheck url path settings in node form alter for existing content?

Here is your answer two ways of doing it

Method 1:

function module_node_update($node) {
  if($node->type == "blog"){
        $node->path['pathauto'] = TRUE;//to be checked
        $node->path['pathauto'] = FALSE;//To be unchecked
  }
}

or either you can do it in node_presave

Method 2:

function module_node_presave($node){
 if($node->type == "blog"){
            $node->path['pathauto'] = TRUE;//to be checked
            $node->path['pathauto'] = FALSE;//To be unchecked
      }
}

Try and let me know hope it helps
:)


How to add comment field to custom entity

In order to any changes on BaseFieldDefinition effects, you should uninstall/install your module.
your syntax seems Ok and I  only guest you did some changes after your module( entity) installed.


Files uploaded via custom configuration form are eventually lost

The trigger is the 'status' property of the file. It defaults to temporary, and Drupal clears out temporary managed files on a cron run.

To fix, add this to your form's submit method:

$fid = $form_state->getValue('homepage_image')[0];
$file = \Drupal\file\Entity\File::load($fid);
$file->setPermanent();
$file->save();


You can use commerce_cart_order_load() to load the order for the current user, and an EntityMetadataWrapper to extract the relevant field data, and commerce_line_items_quantity() to get at the actual quantities. e.g.

if ($order = commerce_cart_order_load($GLOBALS['user']->uid)) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity = commerce_line_items_quantity($order_wrapper->commerce_line_items);

  // Do something with $quantity...
}

This code can be used in a module or theme.


Taxonomy Term View not showing image field

Heh, well, as said in the comment, be sure to either have the same field or add all image fields :)


How to use Rules to fetch domain Whois Data, parse the data and save it to fields?

When you want to use Rules, you still need to have a connection between Rules and the API. The Rules module by default cannot make API requests (though some contrib module might provide it).

As an alternative I'd like to present to you, the Feeds module.

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

This module is designed to perform (periodic) requests to external API's and store the data locally. Plus there are a lot of video tutorials out there to help you with this.

The downside is that feeds by default cannot save to an ECK entity (it can save into a node). The Feeds ECK Processor is currently under review and not yet ready for production. The Feeds Entity Processor might work (suggested on the Feeds ECK Processor application page), but this is unconfirmed. Or you can use Feed Rules to obtain the data with Feeds and then send it to Rules where you can attach it to your entity.

So far this seems possible. The only problem is that feeds does not accept input parameters, so you'd have to create a new feeds importer for every domain...

It is probably not the answer you were hoping for, but perhaps someone else knows how to resolve this last missing piece.


Is it possible to create a custom theme function?

you don't have to use hooks in your theme functions.   you could create your own function called theme_table_custom()  and use that in your template files.

if for some reason you must use the hook, you could include the original drupal code in the function and include a check for a table id or something, which would then fire your custom code.


Does Drupal keep timestamps of every time node is updated

Yes, Drupal stores the updated date, but for that you need to enable revisions on  the content types you need it. From your revision table, you can get when a node has been modfied. You can also get how many times you have created a revision and other revision details.

Check the node_revision table; you will get the details.


Can I add a link to the node reference when using the autocomplete widget?

This'll do the trick (I've tested it this time ;) ):

foreach($form['field_lessons'][LANGUAGE_NONE] as $key => $lesson) {
  // If we have a default value for the nid, we have a populated node reference
  if (isset($lesson['nid']) && is_array($lesson['nid']) && $lesson['nid']['#default_value'])) {
    // Get the nid
    $nid = $lesson['nid']['#default_value'];

    // Create an edit link
    $link = l('Edit', "node/$nid/edit");

    // Add it to the element
    $form['field_lessons'][LANGUAGE_NONE][$key]['nid']['#suffix'] = $link;
  }
}


I would use the Entity Reference module (rather than user reference). I would then create a view (display: entity reference) filtering only Users with that desired role.

In the field settings you can choose the designated View under "Entity Selection" - "Mode": "Views: Filter by an entity reference".

This is at least how I solved this problem in the past. I hope this helps.


Using an entity wrapper to change node->body value (with localization)

Documentation is up to date now.

Examples from drupal.org :

 $wrapper->author = 0;
 $wrapper->url = 'dummy';
 $wrapper->author->mail = 'foo';
 $wrapper->author = NULL;
 $wrapper->author->set($GLOBALS['user']->uid);
 $wrapper->author->set($GLOBALS['user']);

 // Localization Here
 $wrapper->body->set(array('value' => "The second body."));
 $wrapper->language('de');
 $wrapper->body->set(array('value' => "Der zweite Text."));
 $wrapper->language(LANGUAGE_NONE);
 $wrapper->set($node);

 $wrapper->reference->name->set('foo');
 $wrapper->reference->set($wrapper);
 $wrapper->save();
 $wrapper->delete();
 $wrapper->type->set('article');
 $wrapper->author = $user->uid;
 $wrapper->{$property}[0] = '2009-10-05';
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->$name->value();
 $wrapper->parent[] = $term_parent2;
 $wrapper->field_tags[1] = $term_parent;
 $wrapper->field_tags->set(array(2));
 $wrapper->field_tags = NULL;
 $wrapper->$field_name->set(NULL);
 $wrapper->field_text[0] = 'the text';
 $wrapper->field_text[0]->set(array('value' => "The second body."));
 $wrapper->field_text2->summary = 'the summary';
 $wrapper->field_text2->value = 'the text';
 $wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
 $wrapper->field_file[0]->description = 'foo';
 $wrapper->field_file[0]->display = TRUE;
 $wrapper->field_file[1]->file = $file;
 $wrapper->field_file[] = array('description' => 'test');
 $wrapper->field_file = NULL;
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->field_image->alt = 'foo';
 $wrapper->field_image->file = $file;
 $wrapper->field_image = array();

You can follow this link to see full documentation and examples about entity metadata wrappers and localization.

Documentation about entity metadata wrappers on Drupal.org


Website is getting very high load due to "UPDATE cache SET data..."

Given your server already has APC installed, you do not need to keep cache in database at all. And probably shouldn't.

Install APC module (for older Drupal versions see Cacherouter or Cache Backport) to move your cache from MySQL to RAM. Without it, APC only caches opcode, not Drupal's cache data. Also, APC Status or APC Admin module helps with monitoring.

It might be wise to exclude form cache from APC and keep it in database, but that's material for another question.

For APC optimization, see this question.


pass argument as a wildcard to node/add/Article/560012

You will need a module for that but it's easy :

the scenario is this :
on screen 1 , you've got a form which contains a select list , when user submits this form , will redirects to a content creation form , the important thing is that the coupon id must be passed to it .

so the solution :

you will have a submission function for your first screen form

function first_screen_form_submit($form, &$form_state) {
  //enter some codes here to get nid of selected coupon
  //.
  //.
  $form_state['redirect'] = 'node/add/coupon-share/'. $nid;
  drupal_redirect_form($form_state);//this will redirects you to form and passes the nid
}

now you must alter the node creation form :

//Implement hook_form_BASE_FORM_ID_alter()
function YourModuleName_form_node_form_alter(){
  if(isset($form['type']) && isset($form['#node'])) {
    $type = $form['#node']->type;
    switch($type) :
        case 'coupon-share':
          $passedNid = arg(3);
          $passedNode = node_load($passedNid);
          //now you have the coupon node available here and can fill your field with it
          //.
          //.
          breake;
  }
}


I had a similar requirement (actually a bit more complicated, as I needed Facebook, Twitter and Instagram posts). I ended up creating my own Drupal 8 module - Social Feed Aggregator (https://www.drupal.org/project/social_feed_aggregator).

The module creates a new Social Post content type, allows you to enable each required feed integration, and set up a cron job to refresh the feed data.

You can then simply create a Views block to show the feed data.


Depending on the complexity of your nodes (if using custom fields or references) you might be able to use the node export module to export the nodes as CSV files and on the new upgraded site use Feeds to import them. Keep in mind that if the nodes NID are needed for an specific menu the NID might not match.

Note: you might also want to check the migrate module as well as the deploy module.


What's the relative path to a user's profile?

There is no, and can not be always correct relative path.

Relative path is relative, and there is no infinite amount of paths to user profile, to be in the same relation with each and every path in your system. There cannot be. What you need is to properly generate an absolute path instead.

So instead of the code you are using, use Drupal's built-in link generator, l():

<?php print l('some divs', 'user'); ?>

or, if above is not feasible, url():

<a href="<?php print url('user'); ?>"> some divs... </a>


Limit menu items available as possible parents on node creation

For Drupal 6 there is http://drupal.org/project/node_menu_parent. A Drupal 7 version exists only as attachment in an issue: http://drupal.org/node/1138946
You may consider http://drupal.org/project/menu_position which sets the active menu item when viewing the page based on certain rules.


How to hide certain content types from a Link field

The short answer is that D8 core link field will always look for all content types. You have to write custom javascript to filter it I believe. To make life easier, I would try Link Field Autocomplete Filter, but personally I like Linkit module much more for its ability to integrate with media.


This should work for you:

$referenced_nodes = db_query("SELECT `field_FIELD_NAME_nid` AS `nid` FROM {content_field_FIELD_NAME}");
while ($referenced_node = db_fetch_object($referenced_nodes)) {
  $node = node_load(array('nid' => $referenced_node->nid));
  // Do your stuff here
}


Replace YouTube URL with player in nodes and comments?

Use the Googtube module for this. It will provide you with an additional input format, which you can use wherever you want.

From the project page:

  Googtube allows users to embed Youtube, Vimeo and Google Videos in a simple way without tags. When users post a url to videos the link is automatically converted to a video witch is actually embed code.


Override Search module's textfield CSS ID

It is the same thing as you did above

$form['search_block_form']['#attributes']['id'][] = 'custom_css_id';


Show nodes contaning same company term in Views

Create a new block view either selecting the single content type or all. Now, we will add two contextual filters. Content Id and the field which has taxonomy term id.

Configure Content Id filter as follows:

Provide default value: Content ID from URL
Under More tab - Check next to Exclude

Configure field which has taxonomy term id as follows:

Provide default value: Taxonomy term ID from URL
Uncheck: Load default filter from term page
Check next to Load default filter from node page, that's good for related taxonomy block
Multiple value handling: Filter items that share any value.
Under more tab check: Allow multiple values.

That's it. After saving your view go to bock page and enable it where ever you want.


You need to check with this two Google Site Search & Google Custom Search Engine modules.


Views OOP approach - Let Views extend from Meta/Parent View

When you change something on any of the different displays (other than master), there should be combobox at the top that says "for" which defaults to "All Displays" meaning that the change will apply to all displays. But you can select "This Block" or "This Page" so that the change only happens to that particular display.

Also, if you go into views settings "admin/structure/views/settings" you can set "Always show the master display" which I usually do.


Thumbnail: i need to have a fixed width and variable height (in proportion)

From the image styles settings for the "Scale" action:

  Scaling will maintain the aspect-ratio of the original image. If only
  a single dimension is specified, the other dimension will be
  calculated.

So if you specify just the width to 200px, the height will be calculated while maintaining the aspect ratio of the original image.


What is the proper way to set up the front page?

In Drupal 8 you can disable the /node route by disabling the view called "Frontpage", effectively eliminating the frontpage concept.


How to Add product type donation into cart programmatically with custom amount(100 or 200 or something)?

No code needed, just watch the video about "Donations with Custom Line Item Types in Drupal Commerce". Some more details about it (= quote from that link):

  This screencast shows how to use a custom line item type to allow your customer to specify a user-defined amount to donate. The line item has a Donation Amount field on it, and we then create a product display node that uses that custom line item. Finally, we use a custom rule to update the "price" of the donation product to the amount the customer has chosen.


Need Help Finding Permission Needed for Entity Reference Content Type field

I found the answer to this one. It was the permission 'Bypass content access control' under 'Node'. I gave this permission to the one user role and then removed 'add content' from the shortcut bar so they could only use the link I gave them to create the one specific content type I want them to create.


Is it possible to show a menu in a view as buttons?

with https://www.drupal.org/project/menu_link_attributes
you can add a css classes to each menu item so that you can theme it as needed.


What is the difference between hook_field_attach_validate() and hook_field_validate()?

hook_field_validate()
 Should be used to validate the form for your modules fields.

hook_field_attach_validate() works on field_attach_validate() which is more for back end validation.

  This function does not perform field widget validation on form
  submissions. It is intended to be called during API save operations.
  Use field_attach_form_validate() to validate form submissions.

Are the fields ones which your modules is creating, or are they fields from a third party module?

The #element_validate property may be what you need to validate another modules fields.


allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.

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


Garbage values in From: in the email sent from Webform

If you fill out the form and submit it does your message contain similar encoded data in the from field?

If not, then it's likely these are spam submissions.

Try adding Spamicide and/or reCAPTCHA to filter these out.


Migrating Multisite Setup to Localhost Running Nginx 404 for /files

I sorted this out. I'm using VVV Varying Vagrant Vagrants for my local development environment, https://github.com/Varying-Vagrant-Vagrants/VVV

Needed to customize the nginx configuration files for my site to accommodate a Drupal installation. The issue with the /files folder contents being 404 was largely due to this. After I configured nginx correctly for Drupal it worked like a charm.

You can find a sample config file here for Drupal: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/


Assuming testing() is a page callback, you want this:

function testing()
{
  $form = drupal_get_form('cart_confirmation_form')
  $output = '
' . render($form) . '
';

  return $output;
}

Though personally I'd built it as a render array:

function testing()
{
  $page = array
  (
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('cart_confirmation_form')
  );

  return $page;
}


Access by role based on term referenced in the node

If you're wanting a custom module based solution, Drupal has hook_node_access() which lets any module control access to a certain node. In your case, you want check the $node object on a 'view' $op and return the appropriate NODE_ACCESS_* constant which tells Drupal when the user has access to the node.

// @TODO: Replace 2 with your curator RID.
define('MYMODULE_CURATOR_ROLE_ID', 2);

function MYMODULE_has_terms($node) {
  // @TODO: Define logic that checks if node taxonomy field has certain terms.
  return FALSE;
}

/**
 * Implements hook_node_access().
 */
function test_node_access($node, $op, $account) {

  // Only step in when curators are viewing 'submission' nodes
  // and allow access if a node is tagged with certain terms
  if (is_object($account) && user_has_role(MYMODULE_CURATOR_ROLE_ID, $account) ) {
    if (is_object($node) && $node->type == 'submission' && $op == 'view') {
      return MYMODULE_has_terms($node) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}


How to redirect to another page after submitting the ctools modal form

This is a bit old, but hopefully it'll help someone. Down where you write your commands[] array. Change it to something like this. In the submit function of one of the earlier forms I set the redirectpath parameter on the object, then i just use that in ctools_ajax_command_redirect() after calling the dismiss modal function ctools_modal_command_dismiss().

  // If $output is FALSE, there was no actual form.
  $commands = array();
  if ($output === FALSE || !empty($form_state['complete'])) {
    // Dismiss the modal.
    $finish = _aap_main_add_finish($form_state['object']);
    $commands[] = ctools_modal_command_dismiss();
    ctools_add_js('ajax-responder');
    $commands[] = ajax_command_html('#ctools-sample', $finish);
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect($form_state['object']->redirectpath);
  }
  else if (!empty($form_state['cancel'])) {
    // If cancelling, return to the activity.
    $commands[] = ctools_modal_command_dismiss();
  }
  else {
    $commands = ctools_modal_form_render($form_state, $output);
  }


How to add custom login logout links in Bootstrap theme?

It can be done this way

<?php
global $user;
 if($user->uid):?>

 My Account

 Log Out

<?php else: ?>

 Log in

<?php endif; ?>

Hope it will help


How do I add an image field to my node.tpl.php template using render($content['field_example'])?

Ok, so here was the problem. My field_poster was nested in a Field Group under display settings. Apparently, you need to include the parent field group if you want to render child fields outside the group.

So, if my container field group is named group_fieldgroup1 I need to use the following to render my field:

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

You can render the entire field group by using the following.

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


You could try the Masquerade module for Drupal.  It allows you to switch users if you have the right permissions, so you could switch mid-session to a user with a different role etc.

Another thing you could try, though non-Drupal, is multiple sessions within Firefox.  Look here, here and here to see if that could help you.


The easiest solution would be to add the code in your theme. This is done by adding

scripts[] = path/to/file.js

in your theme's .info file. If for any reason don't want to handle this in your theme, you could instead add the javascript from within a module, using hook_init

function module_name_init() {
  drupal_add_js(drupal_get_path('module', 'module_name') . '/path/to/file.js');
}

For the javascript to execute on document ready, you can either use jQuery's ready event, or use a behavior.

This could look like this:

(function ($) {
  $(document).ready(function() {
    // jQuery's document ready event
  });
})(jQuery);

(function ($) {
  Drupal.behaviors.name = {
    attach: function(context, settings) {
      // Drupal's behavior execute on document ready.
    }
  };
})(jQuery);


Views: Filter if Value of a field equals logged in user display name?

You can use contextual filter as suggested by @Smalution. Go to your view click on add Contextual filter on right side of it, then select the field you want to use as a filter and do as shown in below image:

To use with name try this:


Configuration - > Zones admin page missing?

Use the European Union VAT

As it has France and France (Corsica)


How can i set different language for 2 different domain?

Go to http://example.com/admin/config/regional/language/configure
Enable URL
Save
Go to Configure
Select Domain

Keep configuring it all.


How to Embed Views Exposed Filter for only one field

Make a views tpl file with name views-exposed-form--view-name.tpl.php in your theme in this file <?php print_r($widgets); exit; ?> this will give you your widgets then print your widget like this: print $widgets['your widget name']->widget ; in end  print $button;


How do I hide nodes that shouldn't be directly accessed from users and search engines?

The Rabbit Hole module provides this feature.

  Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


How do I make my site with pre-loaded content and pre-loaded config available to others without creating a distribution?

One of the support staff at MoreThanThemes was kind enough to provide some direction on how they do this. You can see the result in the structure of their free or paid themes. In short, the steps are pretty simple for what might be termed a cloned installation. The steps are basically the following.

Create a clone of the site that you want to install (https://www.youtube.com/watch?v=9NMRwkTzrCM describes that pretty well)
In the clone, overwrite/replace the /docroot/default/settings.php file with the docroot/default/default.settings.php file
Make a clone of the original database (e.g., using MySQLDump, PhpMyAdmin copy or drush sql-dump) and install it in a new database instance that you will use for the cloned site.

If you also have removed the Umami distribution and the minimal distribution from core, then the installation wizard will automatically bypass the choice for which install profile to use. In that case, the installation wizard only asks for the database information, where you will use the information for the cloned database. That will be all you need, and you will have a installed clone of your original website.

From my testing, it looks like the UUID of both sites are the same, just as if you had cloned the original site. So, the main use case from what I can see for this scenario would be if you wanted to share a copy of your site with other people, including the content (like the theme companies do). The only difference from a regular distribution like Umami or OpenAtrium from the user's standpoint is that they have to load the database file on their own before they do the installation. But from a developer's standpoint, this seems to be a much easier approach to sharing a website with the content and should be adequate for many users who want to test out your site.

I am surprised that this is not more widely documented and perhaps I have missed something here. But in my tests so far, this seems to be all that is needed. Hopefully this will help someone else who may need this simpler approach.


How can I do a multi-level sort in Views?

In Views, under the "Format" heading you format is already "Table", Click the Settings link, Scroll down until you see "Grouping field Nr.1" and choose date.  Then use "Grouping field Nr.2" for the next one.


how do I make Drupal Zen sub theme mobile friendly?

I have just checked the Superfish project status and there are bug reports that Superfish breaks with jQuery versions 1.9 and above. Check what version of jQuery is loading and check if there are any Javascript errors in your browser console.

If that is the problem, you may have to wait for the next version update, or roll back to jQuery 1.8 for the time being.

Superfish jQuery 1.9 Bug Report


How to create "Custom Forms" that trigger own business-logic / do not create any Content

Create your form by using the drupa FAPI.
Set-up a path to your form using hook_menu.
Call your custom communicatin code from your FAPI submit handler.


How to troubleshooting a D7 website that doesn't load (Gateway Timeout)

I solved the problem disabling the Database logging module.

I had the same problem also in another website (D7 + Database logging module, solved disabling the Database logging module)

Hope this helps.


Overriding hook_preprocess_html page contents set by a module

Check out John Albin's graph for the different preprocess functions you can use http://john.albin.net/sites/default/files/theme-system.png (from http://john.albin.net/drupal/arrays-of-doom) for a "complete" reference of what could be happening.

Without looking to the code to see if you've got another alternative (such as field_attach or another render option), I'd go for hook_process, that's always going to go after preprocess. If it's a theme function, you can use hook_theme_registry_alter and override the theme callback.

Now an answer after seeing the code.

If you want, you can stick with hook_process_html, but as you said, the content is already rendered and is way harder to remove.

One thing you can do is to increase the weight of your second module in comparison with the one that has the preprocess that you want to override, that way, you could do a preprocess_html and it always will come after the other one.

A couple of ways of doing this, one is on hook_install as you can see in this doc page: https://www.drupal.org/node/110238

  $weight = db_select('system', 's')
              ->fields('s', array('weight'))
              ->condition('name', '[the_other_module_name]', '=')
              ->execute()
              ->fetchField();
  db_update('system')
    ->fields(array('weight' => $weight +1))
    ->condition('name', '[your_module_name]', '=')
    ->execute();

If you can't or don't want to do this, there are a couple of modules that can help you: Modules weight and Util


Most importantly, you should be calling $handler->saveTranslations(); after setting the translation. Your updated code should look like this:

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

$new_lang = 'fr';

$meta->language($new_lang);

// The body field is set to be translatable.
$meta->language($new_lang)->body->value = 'Some French Body';

// Other fields are changed, but not shown here

$handler = entity_translation_get_handler('node',$node);
$translations = $handler->getTranslations();

// This is a convenience way to initialize the translation data for
// the new language.
$new_translation = array(
  'language' => $new_lang,
  'source' => $translations->original
) + $translations->data[$translations->original];

$handler->setTranslation($new_translation);
$handler->saveTranslations();
$meta->save();

As a last note, the title property of a node is not translatable, unless you use the Title module. In that case, you should probably use the $meta->title_field accessor to change the value.

Good luck!


Do you know why it is not working ?

Because it seems to me that you're playing the guessing game.

How about installing the Devel and adding kint($form) to inspect the $form array?

You will see its

$form['actions']['submit']['#value'] = t('Post Comments');


drupal_add_js and variables into anonymous functions, objects undefined?

As of Drupal 6 javascript is put inside function that we assign as a property of Drupal.behaviors. Example,

Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};

Drupal 7.x:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
    // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

So your code should be

(function($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      var my_var = Drupal.settings.mymodule.lang;
      console.log(my_var);
      console.log(language);
    }
  };
})(jQuery);


Although I know this solution is not best and structural method and is better solve this issue but sometimes we just need a solution and want save the time(maybe it be some issue with commons distributes.
Sometimes I do this trick in some projects

if you want translate all keystring  in every where use

 $('body').html( $('body').html().replace(/keystring /g, "TranslateString"));

and also if you want only some specified(with specified class and page class) string use

$('.checkout-review .field-name-phone-mobile .field-label').html($('.checkout-review .field-name-phone-mobile .field-label').html().replace(/keystring /g, "TranslateString"));

You just need put one of them in JS file.


I don't believe there is a Drupal specific option, but you can utilize a module like XML Sitemap:

  The XML sitemap module creates a sitemap that conforms to the
  sitemaps.org specification. This helps search engines to more
  intelligently crawl a website and keep their results up to date. The
  sitemap created by the module can be automatically submitted to Ask,
  Google, Bing (formerly Windows Live Search), and Yahoo! search
  engines. The module also comes with several submodules that can add
  sitemap links for content, menu items, taxonomy terms, and user
  profiles.

and then use a number of third party online or software based options for visualising xml data.  A quick search in google yielded a number of options for 'visualise sitemap'


If you haven't already, try using button rather than submit type.

'#type' => 'button',

  When the button is pressed, the form will be submitted to Drupal,
  where it is validated and rebuilt. The submit handler is not invoked.

Perhaps this will prevent that formSingleSubmit behavior from running???

If the above doesn't work, since all the formSingleSumit behaviour does is prevent form from being submitted if it hasn't changed and nothing else. Therefore, you don't need this behaviour and since Drupal is global, you could just do in custom.js:

delete Drupal.behaviors.formSingleSubmit;

OR set it/override it to empty

Drupal.behaviors.formSingleSubmit = {};


You could give Alternative Database Cache a try. Set the minimum cache lifetime and you should see pages cached within the cache lifetime window not being cleared. Clearing the cache when a comment is saved is default behavior; look at the bottom of the comment_form_submit function if you wish to see the call to cache_clear_all.

As for the cookie, it is most likely being set because of calls to drupal_set_message; also noted is comment_form_submit calls user_cookie_save


Overhead, if there is any, is of little concern. This is pretty much a stylistic concern. As such, the important part is a consensus among developers so there is clear readability expectations.

drupal.org has documentation when it comes to template coding standards. In this case, little-as-possible PHP tags usage is preferred (the concern here is readable HTML rendering, not code execution) with use of PHP's alternative control structure:

<?php if ($a == $b):?>
   a equals b
<?php else: ?>
   a does not equal b
<?php endif; ?>

See the documentation for further style guidelines with templates.


How to provide the ability to upload media to the server?

I think Media is a great module unless if your client will upload and use the same PDFs/MP3 once a time.

But if your client plan to use at severals places the same Media, so Media module is for you.

Also, give a look at Scald, seems to be a promise module.


Check a sample code provided in How to change Drupal's default language programmatically? You can trigger this code yourself based on your requirement.

Another way of doing this can be is 'Use another language than "default" as standard'. And You can find an example of hook_language_negotiation_info() on Drupal 7 default language after translation.


unable to set dateboosting in apachesolr with D6

For the legacy date field that the ds_ dynamic field is set to use in the 1.6 version schmea.xml, you can use the rord() function. It's not considered best practice any longer but it works with field types that don't enable using ms(). More information at Solr Wiki. The example query goes like this (copying it here to avoid link rot):

recip(rord(creationDate),1,1000,1000)


How to set up component on another site?

Here's what I did:

Transferred component files from one site to the other to the same directory.
In the components.module file (which for me was up a couple of levels from the place I dropped the component files) paste in any hooks the correspond to the component (my component was an image gallery which used Masonry, so there were some hooks there).
Ensure the render function is relating to the right theme. See my other issue here for more info.
Clear caches, rebuild registry.

It's not the best response, but I hope it helps someone.


Global php view for conditional profile image

It's possibly the result of syntax errors.

This is where you can see the benefits of well formatted code.

If you format your code like this it becomes more obvious that you have errors in your code (I assume $row->picture actually is a file ID):

$file = file_load($row->picture);
if (isset($row->field_primum)) {
  if ($row->field_primum == "1") {
    print theme('image', array('path' => $file->uri));
    else ($row->field_primum == "2") {
      print();
    }
  }
}

Problems I can see now are:

There you can see that the else actually has no if statement because it is inside the second if statement.
The else also shouldn't have the condition. If it needs the condition then use elseif.
You mention that the field you are using is a boolean field, in which case the values will be 0 & 1, not 1 & 2.
The second print statement should be printing a string so the string should be wrapped in quotes.
You are incorrectly using the a tag to print an image. You should use an img tag for images and an a tag for links.

I would think it should be more like this:

if (isset($row->field_primum)) {
  if ($row->field_primum) {
    $file = file_load($row->picture);
    print theme('image', array('path' => $file->uri));
  }
  else {
    print('');
  }
}

Note that I also moved the file_load() call inside the if statements because there is no need to load it if you aren't using it.


Where can you change the #type of a checkbox?

Beside preprocess you can add code to the rendering of form elements in #pre_render, #theme, #theme_wrappers and #post_render. Part of the rendering pipeline of checkboxes is for example CompositeFormElementTrait::preRenderCompositeFormElement:

  public static function preRenderCompositeFormElement($element) {
    // Set the element's title attribute to show #title as a tooltip, if needed.
    if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
      $element['#attributes']['title'] = $element['#title'];
      if (!empty($element['#required'])) {
        // Append an indication that this field is required.
        $element['#attributes']['title'] .= ' (' . t('Required') . ')';
      }
    }

    if (isset($element['#title']) || isset($element['#description'])) {
      // @see #type 'fieldgroup'
      $element['#attributes']['id'] = $element['#id'] . '--wrapper';
      $element['#theme_wrappers'][] = 'fieldset';
      $element['#attributes']['class'][] = 'fieldgroup';
      $element['#attributes']['class'][] = 'form-composite';
    }
    return $element;


How to improve the clarity of hierarchical taxonomy terms in edit forms?

One way you could approach this is to use select boxes with an 'add more items' button.

I use Simple Hierarchical Select for single value selections in a taxonomy with levels, but there's no reason you can't use it for multiple selections.

If that module doesn't make an 'add more items' button pop up then put the field in a Field Collection, yes even by itself.  I know for a fact that you can have multiples of those.


Best way to insert video (vimeo and youtube) into content

The easiest way by far, is to use video embed field. I have built a video sharing site with a co-worker that generates very high rates of traffic. He built the site mostly by himself 80% in a couple of days, and the video embed module was used heavily for the management of video content types.


How to decide wich responsive base theme is better for a certain project?

Yes, it really does depend on your needs.  I went through this exercise last year.  These were my considerations.

Since we are a web design/development shop, we needed a base theme that we could potentially use for the majority of future Drupal 7 work.  For Drupal 6, we had been using Zen, but decided to start fresh with D7.

At the time, the decision really boiled down to Omega, Adaptive Theme, and Boron.  From here, I worked out what my dream requirements were (in no particular order):

Uses 960.gs seamlessly
Responsive layouts
As much config as possible via the UI
HTML5 starter templates
Works well with Panels

#1 and #5 are debatable pluses, but were hard requirements.

Something that works well with Context was also nice, but not a hard requirement because we leverage Panels so much.  Mobile integration was not a requirement for us, beyond the response layouts, also due to Panels.

At the time, Omega was the only real match.  960.gs can be added to any base theme, but the UI control over the grid and grid assignments is a huge bonus for us (allows clients and non-technical people to change layout without needed to bug the developers).

Now that we have several Omega-derived sites deployed, I still think we made the right decision and am glad we put a lot of thought into the process.


How do I select a page using views_embed_view?

I found the answer after a good deal of research and testing.

views_embed_view() does not have a way to do this. However, we can use the same method that views_embed_view() used.

1  $view_args = array($terms); //, $search_text
2  $view_object = views_get_view($view_name);
3  $view_object->set_current_page($offset);
4  $html = $view_object->preview($view_display, $view_args);

Line 1,2, and 3 are a simplified version of views_embed_view(). I'm bypassing permissions here so check out the function code to see how to do that part.

Line 3 is the part that sets the pager offset and solves my problem.

Note: their are two functions for setting the page offset and I used the wrong one the first time and it caused a log of confusion. The first function view->set_offset does not seem to work. I think it sets the correct value in the view object but without doing the theme and query work. so view->set_current_page is the one you want to use. I think it goes through the pager plugin to set the query and theme implications as well as set the offset.


There is another solution for that. Try to use the FacetAPI module: http://drupal.org/project/facetapi

Then you can create a view and integrate the taxonomy terms with the drupal search as explained in the following link:

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/


EntityFieldQuery with pager and db_or using addTag

I found the answer to this issue.

Apparently the THEME_query_search_alter hook was triggered twice (also saw this happen when altering the standard Drupal user search query) and the new table was therefore joined into the final database query twice.

So when it tried to find results in the same table two times it kinda broke the search results, and returned these many many results instead of just a few.

The fix was then to check if the new table was already joined into the query, and this is how I did it (only changed the THEME_query_search_alter hook):

function hedeselskabet_query_search_alter(QueryAlterableInterface $query) {
    $keywords = $query->getMetaData('keywords');
    $words = "%" . $keywords . "%";

    if (!array_key_exists('n', $query->getTables())) {
        $or = db_or()->condition('title', $words, 'LIKE');
        $query->leftJoin('field_data_body', 'n', 'node.nid = n.entity_id');
        $or->condition('n.body_value', $words, 'LIKE');
        $query->condition($or);
    }
}

And now everything works. :)


Menu item path saved as node/nid instead of alias

Both nid and aliases are not guaranteed to be stable and unchanged, nid being a bit less prone to mutation. What you seem to really need, are UUID Links. It should allow you to store links by the unchangeable UUID, not localised nid.

There was also a sandbox project UUID Menu for just the case, but it seems it was never properly initiated.

The other approach is to export both content and menu as a Feature. This problem is in Features' issue queue and in UUIDs for Menu Links issue queue, unresolved yet. But in the second one patches exists.


How and where is the $variables variable used in templates etc. generated in Drupal?

The $variables associated array that are passed into functions such as MYTHEME_item_list($variables) are initialized by the caller of that function.


How to load jquery cookie library for anonymous user

For available Jquery and Jquery cookie for anonymous user, it should add it on  theme libraries dependencies , as example if your theme name is themename  on themename.libraries.yml add

  dependencies:
    - core/jquery.cookie


They're provided by the core Contextual Links module. If you don't don't need them at all disabling that would be the easiest thing to do.

There's also the Hide Contextual Links module if you want finer-grained control.


Checking your URL, I see that going to http://www.huf.co.nz/user gives a 404 (page not found) from your web server, but http://www.huf.co.nz/?q=/user render's Drupal's login page.  This means that for some reason, "clean URLs" -- i.e., URLs that don't have the "?" in them -- aren't set up right.

It isn't clear what web server you're using from the 404 page.  If you're using Apache, then just look at the README file in the base of the Drupal install, or go to https://www.drupal.org/documentation/install/beginners, since looking at your HTML you appear to be using Drupal 7.42.  Apache is the easiest web server to set up, since Drupal ships with a .htaccess file that sets things up for clean URLs.

Drupal 7 also ships with a web.config file for using IIS, if you are serving Drupal from that web server.

If you're using something like nginx, you need to add a bit of configuration in order to get the web server to properly turn your URLs into the format that Drupal needs to see; nginx won't read a .htaccess file.  If you are using nginx, Google "perusio drupal", or go to https://github.com/perusio/drupal-with-nginx.

If you're using anything other than those 3, you'll need to find someone who knows how to translate an Apache type configuration into that web server's configuration.


Using hook_form_alter(), how do I write a multi-select field?

I think you are searching for the #multiple attribute:
multiple
Used by: select
Description: Indicates whether the user may select more than one item.
Values: TRUE or FALSE
<?php
return array(
  '#type' => 'select',
  '#title' => $title,
  '#default_value' => $value,
  '#options' => $options,
  '#description' => $description,
  '#multiple' => $multiple,
  '#size' => $multiple ? min(12, count($options)) : 0,
  '#weight' => -15,
);
?>


Different image width on a node and on block

You can always make the image fit the container with CSS.

For example:

.block .content img {
  max-width: 100%;
  height: auto;
}

If you're using Bootstrap, you can achieve the same effect by adding the class img-responsive to the image.


How do I hide the AJAX Cart block when cart is empty?

OK, in the meantime I found the solution.

1.) Set "Block title" in the appropriate block configuration to <none>. (http://<mysite>/admin/build/block/configure/uc_ajax_cart/0) (you'll see later why)

Block title:
<none>

2.) Copy the UC AJAX Cart template files (uc_ajax_cart_block_content.tpl.php, uc_ajax_cart_block_content_empty.tpl.php) from http://<mysite>/sites/all/modules/uc_ajax_cart/templates/
to your own theme's templates directory (http://<mysite>//sites/all/themes/<mytheme>/templates/).

3.) After that, open both copied files (which are now in your template directory) in a text editor.

4.) Delete (or put in a comment) the content of uc_ajax_cart_block_content_empty.tpl.php, and upload the edited file to the server.

5.) Prepend the following to uc_ajax_cart_block_content.tpl.php to have the block title back:

        <?php print t('Shopping cart')?>

(The rest should stay intact!!)

6.) Clear the theme registry cache (http://<mysite>/admin_menu/flush-cache/theme), and you're done.

UPDATE:
the method above breaks the toggling opportunity of the shopping cart content (if the following is checked in the settings: "Make the shopping cart block collapsible by clicking the name or arrow.") when clicking on the block title ("Shopping Cart"), because the title part is also updated with AJAX from the uc_ajax_cart_block_content.tpl.php file, BUT there IS a solution in jQuery, which you have to put in your own JavaScript-file (which is e.g. put in your theme's .info file), and it looks like this:

$(document).ready( function(){
    if( $('#ajaxCartToggleView').length > 0 ){
        // live: "Attach an event handler for all elements which match the current selector, now and in the future." (http://api.jquery.com/live/)
        $("#ajaxCartToggleView").live("click", function(){
            ajaxCartToggleView();
            return false;
        });
    }
}


How to drush enable a module only if is not installed

You can use grep command to filter out the modules from disabled list to only which are appearing to your list, e.g.

drush -y en $(drush pm-list --status="disabled" --pipe | grep -f tmp.txt)

Other way is to use SQL query:

drush -y en $(drush sqlq "SELECT name FROM system WHERE name IN ('$(cat tmp.txt | paste -sd, | sed "s/,/','/")');")

which may be more complex, but quicker (especially when you replace drush sqlq with mysql -e command.


Syntax to display only the node body using node embed module

That should be only [[nid:1234]] without body in it, as it embeds body by default. Also, make sure you've enabled the filter at admin/config/content/formats/TEXT_FORMAT.
Edit: Adding my comment in here to make it more clear.
If you wish to only show body of a node within node, you can do so by:

Turning on the "Node Embed" view mode at admin > structure > types > manage > CONTENT_TYPE > display

Changing the settings of the "Node embed" mode to only display body of the node. Node embed module uses this view mode by default (if enabled for a particular content type).

You will now be able to use the above syntax without any need to specify any options.

P.S. - You could use the Display Suite module to have a better control the display of the fields.


show content type fields from user on another content type

I wonder if it may be better to just add all personal info fields to the User entity itself instead of creating a whole new Content Type (go to Configuration > People > Account settings and add fields such as website, twitter, etc to the user entity). Then simply create a view of articles and create a relationship to the user entity by choosing Content: Author. Then simply add user fields to your list of fields in the view. Am I missing something in your question? (it's not very clear). Let me know and I can edit this answer.

Edit after your comment: Since you are interested in providing these info fields to specific users, I would then explore the profile2 module, which allows you to add additional fields for certain users. You can create different profile types with different fields, and allow certain roles to have access to specific profiles. In your View you can create a relationship to Content: Author first, and then one to the profile, then add those profile2 fields to your list of fields in the view.

Otherwise, if you still want to do this with a Author bio content type, I would suggest that you add an Entity Reference field to the User, and then you can use that as a bridge to your Article. Let me know if you want more details on this.


Here is how to update body field :

$nodes = Node::loadMultiple();
foreach($nodes as $node){
  $html = $node->body->value;
  $html = str_replace('blue','red',$html);
  $node->set('body', [
          'summary' => 'the summary',
          'value' => $html,
          'format' => 'full_html', // probably,
          /**
           * Correspond with format you need in admin/config/content/formats
           */
   ]);
   $node->save();
}


How to implement Node Access based on a Term in the user's profile?

Haven't tried it myself yet, but Taxonomy Access Control looks promissing:

Automatically controls access to nodes (based on their taxonomy terms).

Configuration page for each user role.

Three node access permission types: View, Update, Delete.


drush migrate:status comes back with SQLSTATE [hy000] [2002] No such file or directory

I had this problem when upgrading/downgrading php to work with drush migrate. Check if the mysql.sock is right in php.ini:

First check what php.ini file is used in terminal:

php --ini

Then open the php.ini file and change/add:

pdo_mysql.default_socket=/Applications/MAMP/tmp/mysql/mysql.sock

or the mysql.sock you are using. To find your mysql socket in terminal use:

mysql_config --socket


What data type to use for Commerce price field in a rule with a Views Loop (Views Rules)?

Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

  The price field is and will continue to store price amounts as integers ...

So give it a try to use "integer" for your Commerce price field. If needed, also use a Rules Action like "convert the data type" (of that price field) to convert your actual input to an integer.


ubercart: finding order id when admin is editing order

I found the answer after posting the question:  (Valid for Ubercart 7.36)

if (in_array('administrator', $user->roles)) {
dpm (" do fancy stuff");
dpm($_SESSION['ucga_order_id']);

$order_id = $_SESSION['ucga_order_id'];
 uc_order_comment_save($order_id, 0, t($admin_text), 'admin');

dpm ("end admin fancy");

}


Turns out this was a permissions thing after all. The entire web/modules directory needs to be read/writeable by Drupal.


product display image not showing drupal

I believe you need to add a relationship to your view between the node and the product display.

Hope this helps...


It's kinda hard to test for the ones not having this theme.

Looking at the demo for the theme I can see it is using Superfish module to display this menu.

So, after removing the menu element try to flush the cache (from /admin/config/development/performance). If still doesn't work, go check on Structure->Blocks and see the superfish block... click on configure and be sure it is using the same menu. You have more settings in there, and you can look into the module (Superfish) settings, too.


Most entity controller implementations of ::load() will return entities in the same order as the array of IDs passed in to be loaded. This is the case with DrupalDefaultEntityController and EntityAPIController, which are the two most common controllers.

In this case you could structure your initial query to get a list of IDs to be loaded with EntityFieldQuery and then use the results of that to pass to entity_load.

Looking at your original example, you just need to load a list of products based on the product field on a node. Here's a quick example of what it would take to handle that (since you don't need EntityFieldQuery):

$node = node_load($nid); // If you don't already have access to the node
$wrapper = entity_metadata_wrapper('node', $node);

$product_ids = $wrapper->field_product_select->raw();
$products = entity_load('commerce_product', $product_ids);

This works because the field data is always queried with order by delta when using Drupal core's field SQL storage: https://api.drupal.org/api/drupal/modules%21field%21modules%21field_sql_storage%21field_sql_storage.module/function/field_sql_storage_field_storage_load/7


How can I grant users permissions to edit certain views (add/remove fields in a view) in drupal?

If your client need only to edit the basic settings of some views (header, footer, title, or empty text...), you should give a try to the Views UI: Edit Basic Settings module. It allows you to define which views are editable by a certain role.


Anonymous user having user relationships

I ran into a very similar issue... Here's the code I used (modified to reflect the affected $user->uid as 0):

<?php
$anon_uid = 0;
$admin_uid = 1;
// The next line makes it appear as though the relationship was deleted by the original
// user in the relationship. You might want to change the value though since Anonymous
// should normally be denied access to do this. For example, to make it appear as
// though each of Anonymous's relationship was deleted by user 1, change $anon_uid
// to $admin_uid (next line ONLY)
$anon_deletedby = user_load(array('uid' => $anon_uid));
$anon_friends = user_relationships_load(array("user" => $anon_uid));
foreach ($anon_friends as $friend) {
  user_relationships_delete_relationship($friend, $anon_deletedby);
}
?>

PLEASE BE SURE TO BACK UP YOUR DATABASE AND TEST THIS IN A NON-PRODUCTION ENVIRONMENT FIRST.


How to alter default ajax_view default ScrollTop?

As @Clive mentioned it is because your JS order load is wrong(your JS loaded before than views JS)
I suggest you instead add JS in hook_init put it in hook_form_alter or in hook_page_preprocess

drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js',array(
            'type' => 'file',
            'scope' => 'footer',
            'weight' => 100,
        )
);


For its functionality you need to follow these steps:

Make an Application on Facebook.
Visit https://developers.facebook.com/apps/ and create a new application.
While making the application on Facebook don't forget to disable the Sandbox Mode.
Add a Website domain name on which you want to use the fboauth login button.
From there copy the  App. ID and App Secret to /admin/config/people/fboauth

That would work for you.


This works for me...

$destination = drupal_get_destination();
$destination['destination'] .= '#div_id';
$options = array( 'query' => $destination);
print l('Review', 'content/login', $options);


Import contacts from different social networking sites and invite to my drupal site

You would use the invite along with the Contact Importer

Invite

  Invitations are important to create network effects and exponential
  growth of a community of interest. This module provides an Invite a
  friend feature to allow your users to send and track invitations to
  join your site.

Contact Importer

  Contact Importer provides a form for your users to enter their email
  address and password. The contacts from their address book are then
  retrieved.

  Contact Importer can be used with any Drupal form. No codding
  necessary. It can be used with an invite module, a user import module,
  an emailing module, or anything else that you can think of.

  The current release interfaces with the Octazen or Open Inviter
  retrieval services. But the architecture is modular and can be very
  easily extended to use other retrieval services such as Contact Mines,
  ImproSys, or IpInvite.


Add contextual link to panels "custom content" pane?

Try FAPE, Field API Pane Editor. It is a separate module from ctools.

It does make it much easier for non-technical users to edit a field or a single pane of a page.


How can I attach a line item field to a custom checkout pane?

Got the answer just after posting : so the correct one is

field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode = NULL, $options = array())

First parameter

entity_type is the entity type you want to attach, not the one you want to attach to (see why non native english speakers have problems sometimes... Duh !).

Second parameter

entity expects an object , not a string ! Don't do

field_attach_form('commerce_line_item', 'my_line_item_type' ...

but :

$line_item = new stdClass();
$line_item->type = 'line_item_liberte';

field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));

In checkout pane context, load the line item

function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));
  //...


How to have an environment specific drush.yml?

Reading https://github.com/drush-ops/drush/blob/master/examples/example.drush.yml it seems you can put a site specific drush.yml in a sites directory. It is merged with the global file(s).

PS! I haven't tested this myself.


Using a custom view for a taxonomy term page

Maybe I am misunderstanding what you are saying, but Views comes with a view for taxonomy/term/%tid. Once enabled, when you visit http://example.com/taxonomy/term/44, Views will show its own page, and not the default page output from Drupal.


How do I add a custom CSS file for default theme?

In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes, for everything: asset libraries. Asset libraries can contain one or more CSS assets, one or more JS assets and one or more JS settings.

More details on
https://www.drupal.org/developing/api/8/assets


I doubt that with some many fields for a single node you'll be able to "speed up that function". However, whenever time (and budget?) permits, you should consider what's mentioned in the (illuminating) article titled  "Relativity Model for Drupal". This is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

Note the speed in the last item above ...
The small handful of modules (cfr. the last bullet) is like so (apart from Drupal core):

Chaos tool suite (ctools)
Date
Entity API
Entity reference
Entity connect
Field Group
Token
Pathauto
Views

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".


How to put two form elements in a row using Drupal Form API?

This is a CSS issue. All you need to do is limiting the width of both elements and then float them to the left; this will make them inline. Be sure to wrap them both in a div with the "clearfix" class to clear the float.


Views can be great for some things, but sometimes it can add more complication then it is worth. Trying to achieve this in views seems like it could be one of those situations.

If you are familiar with coding, it might be easier to process the list of authors, grab the entity_reference from them, create an array from those where you don't repeat the values and then output the numbers associated with each value.

If looking to do this solely in views, you could use https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7 to grab the results and process them and then output the rows as desired.


How do I configure the Stock module in and know how many products are sold out of stock?

You can follow the below step:

Go to  Content management -> Content
Filter content for content type "Product"
Edit your product content
Click on "stock" link in top of page
Set the "Stock" and "Threshold" quantity and check "active" check-box save the form.

Edit:

Code snippets to display total and sold item from stock:

$output = '';

$array_sku = uc_product_get_models($node->nid, FALSE);

foreach ($array_sku as $sku) {
  $stock_level = uc_stock_level($sku);
  $stock_count = db_select('uc_order_products', 'up')->fields('up', array('nid'))->condition('up.model', $sku, '=')->execute()->rowCount();

  $total = $stock_level +  $stock_count;

  $output .= "
SKU:" . $sku . " Total :" . $total . ", Sold out:" . $stock_count . "
";

}

print $output;

Kindly see that above code will be check stock level for each different SKU of the product. If there is attribute of the product and each attribute has different SKU, then it will display the stock for each sKU of the product.

You can add this code in node--product.tpl.php file in your theme directory.


How do I alter a form submission handler?

Stupid question but have you cleared cache to register the new hook?
Also, try inspecting the form in hook_form_alter to make sure you are attaching the handler to the correct action.
Lastly, I've found that I usually need to reorder the array to include my handler first in order for my actions to actually trigger on form submissions using Drupal core forms that have existing handlers.
As an example, I did like:
$form['actions']['submit']['#submit'] = array_reverse($form['actions']['submit']['#submit']);

which will reverse the array. I also sometimes use array_unshift to pop my handler at the start of the array if the other handlers need to retain their order.


How do I install multiple drupal sites in a single installation?

Look at Aegir to help you, and/or look at the multisite documentation.


Grant temporary permission during function call on registration page

What you want is not possible. Drupal does its best to prevent cross site request forgery, but same site request forgery is not even an established term.

Any candidate for a solution can be circumvented by a script that automates downloading and parsing the registration form, creating the appropriate HTTP request for the AJAX call and sending it to the server.


Check out the imagechache_action table, that should have the information you are looking for.


How to deal with too much product variations / attributes?

Views Bulk Operations? There is also the Commerce Bulk Product Creation. Some more details about it (from its project page):

This module facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.
The module also provides various ways to create display nodes for the newly-created products:

Redirect user to node creation form (with title and product reference filled in).
Silently create display node referencing all created products.
Silently create one display node for each created product.

This will greatly speed up the task of adding numerous products at once.


Place the fields inside of the fieldset:

$elements['grouped_fields']['field1'] = [
  '#type' => 'textfield',
  '#title' => t('Field 1'),
];
$elements['grouped_fields']['field2'] = [
  '#type' => 'textfield',
  '#title' => t('Field 2'),
];
// ...


How to make mail messages use the UTF8 character encoding?

Content-Type: multipart/alternative; means that there are parts that can have their own encoding set. If your mail sending modules decide they need multipart, mail should be formatted like that:

MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary

--boundary
Content-Type: text/plain; charset=utf-8

This part uses UTF-8.
--boundary
Content-Type: text/plain; charset=iso-8859-1

This part uses ISO 8859-1.
--boundary--

code sample source here

If you called everything the way module docs tells you to, and UTF-8 data is not in the UTF-8 part, then you just found a bug in one of your modules.


hook_entity_view() will only be invoked for modules so no chance of putting it in a theme unless you want to change how something works under the hood.

It's not a problem though, as all alter hooks are invoked for themes; so you can use hook_entity_view_alter() instead.

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete entity content structure has been built.


How to use the table header instead of an exposed dropdown to sort a Views table?

Go to Table Setting and check the column Sortable of the field (like the image) and then click the Apply button and Save your view.

You will see the link in the table header


If you store settings.php in the default folder, then Drush will already behave as you desire.  If settings.php is in some other folder (e.g. 'site1'), see the site-set command (drush help site-set)


There is already module File downloads in the ubercart which allow user to sell file with the product.

Install the module File downloads from the module list.

Assigning directory to file donwload:

Go to Administration -> Store -> Configuration -> Product
In the File download settings section, set the path of the directory of the files and save the form.

Uploading files:
- Go to Administration -> Store -> Products -> View file downloads
- Upload files into directory (which you have configured in above step) using upload file action.

Adding files to product:

Edit your product and you will get the feature link in top of page. click on this link.
In feature form, you can add file download feature to the product and it will redirect you to form to assign file to product.
Select file name in File download text field. This is autocomplete field, so you need to configure correct files and save form.

When the user purchase product and pay the amount, it will send a link to user in his mail to download the files.

Regarding your second question, there is module Ubercart Marketplace.

  Ubercart Marketplace adds multiple seller support to the Ubercart
  module. It includes a series of modules that limit the access to
  Ubercart functions for sellers. Additional functionality is added to
  support this from both a marketplace seller's point of view and the
  store administrator's view. Sellers (with the proper access
  permissions) gain the ability to view their products, track and
  fulfill their orders, and monitor their sales reports. Store
  administrators can view seller reports based on seller order statuses
  and seller sales. Support is included for Paypal Mass Payments, with
  which an administrator can automatically pay his/her sellers for
  custom periods.

Kindly see that Ubercart marketplace is still in development version for Drupal 7, so may be there could be some issue in this module.


Translate website with prefix URL when everything is on domain

No

Not with the core code.

Avaliable solutions

Language Domains would allow you to create alternative domain prefixes, like ru.example.com and www.example.com leading to different languages.
Domain Locale - this one I never used, but it promises to "customize language sets per domain"


Can relationships be used to show Content and linked content in the same view

create a view filtering by classroom node types
add a relationship like "Entity Reference: Referencing entity", it is related to teacher nodes that are referencing the classroom node.
after this, add the classroom node fields and using that relationship, add the teachers fields.
in the format views settings, you can choose a field to grouping this nodes, so, choose the node reference field.

This view configuration, it will works only if the node reference field is in teacher node.


According to the Form API Reference, #prefix & #suffix are valid properties of the form element, so you should be able to:

$form['#prefix'] = '
';
$form['#suffix'] = '
';


How can i remove duplicate encoding meta tag

If the <meta charset="utf-8"> tag is appearing twice in the rendered HTML, chances are one of the instances is hard-coded in your theme's html.tpl.php template, while the other is inserted by the metatag module.

I'd recommend checking your theme templates. In some cases, freelancers with little Drupal knowledge may create several page level templates duplicating the head, header, and footer markup too.

As Alfred noted in his comment, removing this tag should be done server side and not via javascript.  While it does add a few bytes to download of the page, it does not critically effect search engines from detecting the page's content for indexing.


The best way to implement this is to implement a custom display formatter for the link field. You can either do it directly in a custom module by implementing hook_field_formatter_info.

Or without try out Custom Formatters module if you want to avoid custom code:

  The Custom Formatters module allows users to easily create custom Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables, Features or Drupal API Field Formatters.


The drush command 'rets-import' could not be found

The file that integrates DRealty with Drush drealty.drush.inc is kind of in an odd place within a drush folder of the module.

http://cgit.drupalcode.org/drealty/tree/drush/drealty.drush.inc

Drush will scan the root level of a module folder or your .drush directory for drush include files but I dont think it will randomly scan deeply into module directories. I recommend moving this file into your .drush folder and clearing the cache, then trying from your site folder again. Eg,

cp ./drealty/drush/drealty.drush.inc ~/.drush
drush cc drush
cd YOUR_DRUPAL_PROJECT/sites/all/modules
drush -u=admin -d rets-import


Link Mini Panel thumbnail formatter to node

If you go to the view display page and click on the field of your thumbnail, on the settings page scroll down and you should see a drop-down with title of Link image to. Choose content and save.


I have successfully used notifications on 2 Drupal 6 sites. I like it. Subscriptions had a good reputation but Notifications looked to be more modular and extensible; however, what tipped me towards notifications was the fact that it seemed that the Organic Groups developers were keen to support it and I was looking at putting OG onto my sites (which I subsequently did)

I have the 6.x.2 version of notifications, which seems stable and does what I want.  Very limited experience of the 6.x.4 version suggested it was not stable so I did not persist with that and it remains in beta after 2 years.

Now I have recently been involved in the development of a Drupal 7 site. Although it is over 18 months since D7 was released there is no full Notifications version yet and the module is flagged as Seeking new developer and has been for a significant length of time.  Apparently a quick upgrade was done when Dr7 was released with some limited functionality (what though?) and there is an Alpha2 version which seems to have been receiving some considerable attention (but last updated June).

On this basis, you might be safer to go with Subscriptions which now has a full Dr7 release if you have any thoughts of migrating to Dr7 or developing other sites that might use Dr7. That is mainly to avoid the difficulties in mastering two admin UIs and to protect you in case Notifications really is moribund.

Subscriptions is in the hands of a very experienced developer who has been maintaining it for a long time.

Please note that I have not done a systematic comparison of Subscriptions and Notifications for Dr6 though I did spend quite a while investigating the two at one time several years ago.  See my contribution here:
http://groups.drupal.org/node/12645
(This contains contributions by many others and is useful for an insight into the position in 2008! But Subscriptions and Notifications will both have been enhanced since those posts were written).


Intercept data of a field of a node Drupal 8

That sounds like a job for hook_node_presave(NodeInterface $node) to me.

That is always called before a node is saved. To optimize it, you probably want to limit your call to only do it for new nodes or when the value changed (compare your field value with the value of $node->original, note that that only exits when updating, so you want to check something like this:

if (!empty($node->field_yourfield->value) && ($node->isNew() || $node->field_yourfield->value != $node->original->field_yourfield->value)) {
  // do your call here, change $node in any way you want and it will be saved with those updated values
}

The same works for any entity type. You could also limit it to running on form submissions, but this has the advantage that it also works in case nodes are updated or created through other ways.


Twig's slice filter behaves unusual for non English languages

As the trim was enabled from both twig as well as display format, it was not working. So keeping the display format for that field to Default, it solved my issue.

For other users who might face such problem, just keep in mind to set only single trim (either from back end or front end side)


I assume you know the path of the link you need to change and that's all?
If so this should work for you.
Note that I have put comments in place of any error/success reporting, which you can add if you want it.

It also assumes you know how to integrate this into the migration.
This shows the menu link saving only.
I can expand to show migrate integration although that is really a separate question.

Note: The paths used for menu items are drupal internal paths, not path aliases. To convert a path alias to an internal path you can use drupal_get_normal_path().

// Variables used below. Set these to the values you need.
// The current path of the link.
$path = '';
// The menu the link is in. If you don't want to be menu specific remove the menu_name part of the SQL below.
$menu = '';
// The new path for the link.
$new_path = '';

// Get the menu link ID for the given path in the given menu.
// If you donb't know the menu it is in you can omit that part of the query.
// This also handles the case where there are multiple menu links for the same
// path.
$mlids = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND menu_name = :menu", array(':path' => $path, ':menu' => $menu))->fetchCol();
if ($mlids) {
  // Loop through the matching menu items and update them.
  foreach ($mlids as $mlid) {
    if ($menu_link = menu_link_load($mlid)) {
      // Set the new menu link data.
      $menu_link['link_path'] = $new_path;
      // Save the menu link.
      if (!menu_link_save($menu_link)) {
        // There was an error saving the link.
      }
      else {
        // The link has been saved successfully.
      }
    }
    else {
      // Menu link $mlid not found.
    }
  }
}
else {
  // No menu links were found for this $path.
}


Drupal 8: Node form submit/update - how to redirect to a custom page with an code-based approach different than hook_form_alter()

While the other solution is perfectly valid, I mark this answer as accepted since it comes closer to what I was looking in first place - the new way to alter forms.

Eventually the solution can be found right here:
https://www.foreach.be/blog/how-manipulate-forms-drupal-8

In summary (quoted from the article):
1 ) The first step is to write a service that intercepts the original UserLoginForm and directs to the adapted form

2)  Changed the route to return the adapted NewUserLoginForm instead of the original UserLoginForm

3) The new form extends the old form and inside the buildForm method you add in the beginning

$form = parent::buildForm($form, $form_state);

This step was missing in the example tere


Button with Drupal Behavior jQuery Conflicting with AJAX 'Add More' Button on Unlimited Cardinality Field

So I went with a different approach to achieve the same thing. Instead of adding a button using the '#button' or '#submit' property in hook_form_alter, which was causing the conflict, I added a button with the following code:

$form['field_starting_weight_garbage']['und'][0]['value']['#prefix'] = '<div>';
$form['field_starting_weight_garbage']['und'][0]['value']['#suffix'] = '<input type="submit" value="No Change" class="form-submit" id="garbagenochange"></div>';

& adjusted the Drupal Behavior to attach to this element (id="garbagenochange").

I still don't know exactly what was causing the conflict or how to fix it, but this does what I need, so I'll go this route.


The Global Redirect module will help you with that issue.

It has a redirection system specific for language prefixes, preventing content duplication.


How to get the field and value of a content type in drupal 8?

You can get all the field definitions for a content type using getFieldDefinitions from the Entity Field Manager service. The definitions are indexed by field name, so you can iterate on the keys of the returned array for any of the nodes in your site.

An example would be the following:

<?php
  // Get the definitions
  $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

  // Load a node for which you want to get the field values
  $my_node = \Drupal\node\Entity\Node::load($my_nid);

  // Iterate through the definitions
  foreach (array_keys($definitions) as $field_name) {
    // Get the values for your node
    // Use getValue() if you want to get an array instead of text.
    $values[$field_name] = $my_node->get($field_name)->value;
  }


How to remove target id from selected term reference field

You need alter autocomplete js like this

 function theme_name_js_alter(&$javascript,
  \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $path = \Drupal::service('path.current')->getPath();
  $path_args = explode('/', $path);
   if($path_args[1] == 'twc-partners'){
   //kint($javascript);
     $javascript['core/misc/autocomplete.js']['data'] = drupal_get_path('theme', 'theme_name') . '/js/autocomplete-custom.js';
 }
}

This code add in theme file .Please download file from here.


In Drupal 8, the date form element uses the HTML5 date input format by default.  Chrome is one of the browsers that support this.  So, it looks like your browser is using US style dates.

Changing to

$form['date'] = [
  '#type' => 'date',
  '#title' => $this->t('Date:'),
  '#attributes' => [
    'type' => 'text', // <=== CHANGE THIS
    'placeholder' => 'dd/mm/aaaa',
    'data-drupal-date-format' => ['d/m/Y'],
  ],
  '#date_date_format' => 'd/m/Y'
];

should work, but I would recommend using a datetime element and configuring it for date-only inputs.  You can also configure that to not use the HTML5 inputs.


How do I change the overridden feature to default

Features takes configuration from the database, and stores it as code. When a feature is "Overridden", this means there's a difference between what is stored in the database, and what is stored in the files.

This can happen because you've made changes directly to, for example, the Views that are exported. However, it can happen for less obvious reasons.

Sometimes, when you enable a new module, this module may add additional data with a default value to the export of a module. This suddently means that when Features compares the db and files, there's more data in the db, and you have an overridden feature.

Because there are a large number of reasons you can end up with overriddes, there's no surefire way of handling them. You need to install the diff module to inspect that the difference actually is. Then you can determine if you want to "Revert" the feature (copy the Feature file data into the database), or "Re-create" it (create new Feature files, which you can then overwrite the original feature with).


hook_menu() not available for ajax loaded links

You need to add 'access callback' => TRUE, to your menu item.

Your menu callback should look like the following:

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

  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}


Why is the drush views-list command complaining (incorrectly) that views is not enabled?

This is working just fine for me on a d7 site using Drush 5.4.  You are getting that message because module_exists("views") is returning false.  Your next example shows that views is enabled, which implies that module_exists("views") should be returning true.  Perhaps your site is not always bootstrapping cleanly under Drush?

Try:

drush ev 'var_export(module_exists("views"));'

Add on the 'sudo' as you do above, if you really need it.  The sudo does give me pause; I prefer to set up my permissions in such a way as to allow Drush to run without it.  Sometimes sudo changes your environment subtly (e.g. your $PATH may change), although I cannot think of a reason why it would cause you trouble in this instance.  In any event, if the test above returns 'true', then you've stumped me.  If it returns 'false', it indicates that there is something inconsistent or incorrect about your environment.  You'll have to dig deeper to find out what it is.

Edit: I'm wrong, there could be other reasons why you are getting that error, even if module_exists("views") returns 'true'.  It probably boils down to drush_bootstrap_to_phase() failing when called from _drush_bootstrap_and_dispatch(); however, I can't imagine why this would fail for views-list, but work for pm-list.  More data is needed.

Edit 2: Try again with Drush All-versions-5.x-dev (or check out head of master from git).  This is usually the first thing I suggest, but I thought that none of this code had changed recently. Turns out that enabling / disabling a module now clears the cache, but this feature was added after Drush-5.4 went out.  drush cc drush should do the trick in the interim, but you won't need to explicitly do this in the future.


How to check if Drupal user is logged in via htaccess?

Drupal does store the session value in the cookie variable after the user is logged in. However, the name of this cookie is not fixed. It is basically a string that comes from the value returned by PHP function session_name; and starts with SESS. It would be hard to find and I would not recommend using regex, as I personally don't like it much.

If you really want to implement a solution with the cookie, I would suggest the following:

Implement hook_user_login() in a custom module:

function MODULE_user_login() {
  // set a new cookie here, with static name and value.
}

Implement hook_user_logout() and delete the cookie by setting an expiry date of past.

You can now use this cookie in your .htaccess!


Try this

<?php print render($content['your_field_name']); ?> this will print that field value .


How to create a single image style for both landscape and portrait images?

ImageCache Actions

  Aspect Switcher new 2009-08 - lets you perform different actions or
  use different dimensions based on whether the image is 'landscape' or
  'portrait'


Expose Date Filter instead of Start & End Dates

I've been trying to solve a similar problem: creating a membership list per a specific date (based on "membership date" field with start and optional end date elements). Here is my current solution - hope it helps!

Environment
 1. I use VIEWS, RELATIONS and the PARTIAL DATES module and added a partial dates range field type to the Relation between a person and the organisation. This allows multiple memberships and "fuzzy" start and end dates if exact data is unavailable (i.e. "member since 1995"). You can probably put the date range field directly on your event node, and you may be able to use the standard date field if you don't need to allow for "fuzzy" dates.
Note that the Partial date range field automatically calculates timestamp values for "from" and "to" dates.

In the view, I added 2 exposed filters
 - "partial_date_timestamp_to" >= selected date
 - "partial_date" <= selected date
I also added 2 non-exposed filters to allow incomplete nodes to be shown (since membership data is not always perfect) you might not need this if your events always have complete, valid start and end dates.
So my filter criteria now reads: (partial_date_timestamp <= selected date OR partial_date_timestamp is empty) AND (partial_date_timestamp_to >= selected date OR partial_date_timestamp_to is empty)

It works, but entering the desired date in timestamp format isn't very user-friendly. Next step is to get desired date from user by a more comfortable method, then convert the result for the view filter.


How to export and import from View in Drupal7?

You can use views data export module.

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

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML.


How do I Group Repeatable Fields Programatically?

I would pick option 3: Create a custom field type that holds all 3 values in one table. This works fine with views. This can be done with Drupal console to simplify the process, see generate:plugin:field. I would also create a separate module for the the plugin with the custom field type so you can test enabling and disabling you main module without running into dependency issues. The advantage of this method over all others is all the data is held in one DB table which keeps things simple and is more efficient.

To briefly touch on your other options, 1 seems dirty and prone to problems. 2 is not bad and does give you more flexibility but means more code and more database tables. If you don't need the added flexibility then there is no need. Paragraphs, Option 4 will create as many DB tables as a custom entity but with less flexibility (you can't add methods to the ContentEntityBase) and more reliance on contrib modules. This is only a good option if your a site builder and don't want to worry about coding.


Adding AJAX to drupal commerce checkout pane

I think it might have to be related with the classes on the checkout form, if you check the commerce shipping module - it has a good ajax example on replacements - you can see how it does:

// Add a radios element to let the customer select a shipping service.
$pane_form['shipping_service'] = array(
  '#type' => 'radios',
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'commerce_shipping_pane_service_details_refresh',
    'wrapper' => 'commerce-shipping-service-details',
  ),
);

And then it forces the class with a prefix:

$pane_form['service_details']['#prefix'] = '
';
$pane_form['service_details']['#suffix'] = '
';

The ajax callback is the usual one:

/**
 * Ajax callback: Returns the shipping details form elements that match the
 * currently selected shipping service.
 */
function commerce_shipping_pane_service_details_refresh($form, $form_state) {
  return $form['commerce_shipping']['service_details'];
}

So definitely possible, check the css classes you're dealing with.


There is something wrong with you basepath.

in your .htaccess file make sure you uncomment this line

  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

and in your settings.php file you may have to change your $base_url

 $base_url = 'http://localhost/gisele-drupal';  // NO trailing slash!

let me know if that helps


Basically what you want to do is conditionally add a class to the field that aligns text to the right. I was wrong in my comment about hook_page_alter, I don't believe it has access to everything you need.

set up a new field, called field_content_persian, check boxes/radio buttons, valued English and Persian, default to English
in Manage Display, hide the label, and move the new checkbox field ABOVE the body. It must render first for this method to work
add CSS - ie. style.css

.align-text-right{
  text-align:right;
}

to template.php add:

function THEMENAME_field__field_content_persian__CONTENT_TYPE_MACHINE_NAME($vars){

  if($vars['element']['#items'][0]['value'] == 1){
    drupal_static('isPersian', true);
  }
  return "<!-- empty -->";
}

function THEMENAME_field__body__CONTENT_TYPE_MACHINE_NAME($vars){

  if(drupal_static('isPersian'))
  {
    $vars['classes_array'][] = 'text-align-right';
    $vars['classes'] .= ' text-align-right';
  }
  return theme_field($vars);
}

If you have a theme named Bartik, and a content type named Article, they would look like this:

Bartik_field__field_content_persian__Article() and

Bartik_field__body__Article()

What this does:

in the first function (field_content_persian), it checks for the value of the checkbox, and if it finds it is 1(persian if order of elements in checkbox is correct - modify as desired), it sets a temporary static variable. Then it returns an empty string so that the field itself doesn't display - NOTE: this function MUST return something, anything, or Drupal will bypass the function and call the default
in the second function it checks for the variable, and if it finds it, adds the class to the body field.


Views could do this and you might also want to use views calc, setup a view to display all orders with a filter to show only last day, then add the field for amount and use views calc to sum the total.


How to set "Entity has Field" when the Rules Event is unrelated to the entity?

Here are the steps to get this to work (whatever your existing Rule looks like ...):

Assume your current rule has some actions (= SomeRulesActions).
Create a new Rules Component like so:

Use parameters related to the user (= say ParmUser) and  payment (= say ParmPayment).
Add the Rules Conditions related to your custom field, which you should have available via the ParmUser.
Add Rules conditions identical to SomeRulesActions, using ParmUser and/or ParmPayment.
QA-test your Rules Component using the "Execute" link in front of it (in the Rues UI).

Update your existing rule like so:

Delete all Rules Actions corresponding to SomeRulesActions (their equivalents are now included in the Rules Component you created in the previous step.
Add a Rules Action to execute the Rules Component you created in the previous step.

Easy, no?

An alternative solution where you don't need an extra Rules Component, is to rework your Rules logic by using the Conditional Rules module. If you wonder how to do that, use this link.

Ps: I'm assuming this is about D7.


Access page.tpl.php variables from html.tpl.php

Sounds like a perfect use case for the more generic hook_preprocess:

function MYTHEME_preprocess(&variables, $hook) {
  if ($hook == 'page' || $hook == 'html') {
    $variables['shared_var'] = 'foo';
  }
}

$shared_var will be available in both html.tpl.php and page.tpl.php. This will be processed twice, so if it's expensive to build the vars, make sure you statically cache them.


Corresponding entity references: two way sync

On the CNR module page, it has introduced the replacement....

  New development is done in the http://drupal.org/project/cer module. This expands the corresponding node reference functionality to enitities. Please focus all attention on getting a stable release of cer as soon as possible.

It can do the exactly same thing as CNR...


I run drush command as MAMP Integrated PHP, It works!

I add alias command to my shell:

$ vim ~/.bash_profile
alias drush='/Applications/MAMP/bin/php/php5.5.3/bin/php /opt/drush/drush.php'