Send e-mail after entityform submission using field from referncing node

First you have to add a condition "this entity has the field". Then you will be able to access this field in the selector in other condition.


A lot of templates are used to output a single Views display. It depends on your particular case which level you want to override. These templates are probably the best way to control the output of the views where ever you want to print them.

One template outputs the outer views divs, another is for particular format options, others are for controlling rows output. So you have to investigate and override the templates where you want to change the HTML for that particular view.

You can strip each individual Field of its wrapper and even field HTML in its Style settings directly in Views.

You can see the template suggestions under Theme: information in D7 Views, and in D8 you have to turn on the debugging mode to see the suggestions in page output.


loop view fields inside views-view--[view-name]--page.tpl

Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

<?php print $fields['field_images']->content; ?>

<?php print $fields['title']->content; ?>

<?php print $fields['title_1']->content; ?>

<?php print $fields['another_field']->content; ?>


Fivestar module defines a field.
Add a field to a content type. If fx you add a field named "test" of type fivestar reting to a content type then you can find the table with the name "field_data_field_test".


Your missing link is the entity function, which returns the referenced entity object:

$host_entity->host_field->entity->remote_field->value


Command to start nodejs? Server.js and app.js missing

If you're downloading the app from github directly, follow these instructions:

Download the archive
Extract to a folder oustide of Drupal's root (this app is separate to your Drupal installation so shouldn't be within)
cd to the folder and run npm install
Run cp nodejs.config.js.example nodejs.config.js, edit the resulting file as required
Run node app.js

Voila, server up and running.

If you're using the npm install drupal-node.js approach, the instructions are a bit unclear. To clarify:

Create a folder outside of the Drupal root
cd to it and run npm install drupal-node.js
Run cp node_modules/drupal-node.js/nodejs.config.js.example nodejs.config.js, edit as required
Run node node_modules/drupal-node.js/app.js to start the server

You should see the same result as the first method.


How to merge loggedin and annoymous user's cart in drupal commerce

I have solved this, by custom code.
First you create a login handler like.

<?php
function custom_module_form_alter(&$form, $form_state, $form_id) {

    if($form_id == 'commerce_checkout_form_checkout'){
        $form['buttons']['continue']['#submit'][2] = 'paypal_check_handler';
    }
}

function paypal_check_handler(&$form, $form_state){

    $order_number = $form_state['order']->order_number;
    $return = _get_current_stock($order_number);

    if($return['status']=='goto_paypal'){

     }else{
       db_query("UPDATE commerce_order SET status = 'cart' where order_id='$order_number'");
       drupal_set_message("We are sorry - Following items are no longer available in stock after you added them in shopping cart. <br/>".'&ldquo; '.$return['product_name'].' &rdquo;');
       drupal_goto('cart');
    }
}

/**
 * This function check current stock.
 */
function _get_current_stock($order_id) {

    global $user;
    $order = commerce_cart_order_load($user->uid); // get user order details
    // get all product id of current order
    $results = db_query("SELECT cp.product_id AS product_id, cli.quantity AS order_qty,fcs.commerce_stock_value AS stock_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id WHERE cli.order_id='$order_id' AND cli.type IN ('product','commerce_auction_lineitem') ")->fetchAll();
    $product_ids = $qty = $stock_qty = array();
    /*
     * @var $product_ids            : Product ID array.
     * @var $qty[$product_ids]      : get each Product order quantity.
     * @var $stock_qty[$product_ids]: get each Product stock quantity.
     */
    foreach($results As $value){
        if(!empty($value->product_id)){
            $product_ids[] = $value->product_id;
            $qty[$value->product_id] = (int)$value->order_qty;
            $stock_qty[$value->product_id] = (int)$value->stock_qty;
        }
    }
    // product id array convert in string forn sql.
    $product_ids_query = implode($product_ids, ',');
    /*
     * Here get product remaining stock
     * @stock   : Stock
     * @order   : Order qty in order table ( status is checkout_payment).
     * @avail   : available qty
     * @stock - @order = @avail
     */
    $results2 = db_query("SELECT cp.title AS product_name, cli.line_item_label AS line_item, cp.product_id AS product_id,cli.quantity AS order_qty, FORMAT(SUM(cli.quantity),0) total_order_qty,  FORMAT(fcs.commerce_stock_value,0) AS total_stock_qty, FORMAT((fcs.commerce_stock_value - SUM(cli.quantity)),0) As available_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id LEFT JOIN commerce_order AS co ON co.order_id=cli.order_id WHERE co.`status`='checkout_payment' AND fcs.commerce_stock_value!=0 AND cp.product_id IN ($product_ids_query) GROUP BY cp.product_id")->fetchAll();
    $available_qty = array();
    foreach($results2 As $value2){
        $available_qty[$value2->product_id] = $value2->available_qty;
        $available_product_name[$value2->product_id] = $value2->product_name;

    }
    $redirection_var = array();
    $redirection_var['status'] = 'goto_paypal';
    foreach($product_ids AS $product_chk){
        if(!empty($available_qty[$product_chk])){
            $current_stock_qty = (int)$available_qty[$product_chk];
        } else {
            $current_stock_qty = (int)$stock_qty[$product_chk];
        }

        $ordered_qty = $qty[$product_chk];
        if($current_stock_qty > 0){
            // go to paypal
             $redirection_var;
        } else {
            $current_product_name = $available_product_name[$product_chk];
            $redirection_var['product_name'] = $current_product_name;
            $redirection_var['status'] = 'not_goto_paypal';
            return $redirection_var;
        }
    }
    return $redirection_var;
}
?>

Thankyou :)


Override name of file field link in Drupal field.tpl template

There is an easier way to approach this without having to go through the template file:

On the 'edit' page for your content type, you can set it to 'enable description field'

which will add a new field to your content form that will let you override the label for the file, ex:

This should be easier than trying to parse the template approach and will work seamlessly with other modules that interact with the file field.


Number Slider for exposed filter using Drupal 6

Better Exposed Filters has that functionality built in

  ...

  What else can I do with BEF?

  Use the jQuery Slider widget for greater-than, less-than or in-between types of filters

I've never used it for D6 but the project page doesn't mention the slider being missing from that version or anything so it should be there.


How to fallback to default language when listing nodes in a view if no translation is available

Try the Alternative Language Module. There a lot of sub modules, but the base one will give you the functionality you are looking for.

  Allows a language to specify an alternative language. If a node
  translation for a specific language does not exist, Drupal will try to
  load the translation for the alternative language before throwing a
  404.

  This module is useful if you have multiple languages and only one
  language is typically translated. Rather than create all of the other
  translations and maintain those, the non-translated languages can load
  the node from the alternative language.

  For example, you have the following language configuration:

  / - US English - default
  /en-ca - Canada English - alternative language is US English
  /fr-ca - Canada French

  There is a node /contact, you will get three URL's:

  /contact - US English
  /en-ca/contact - Canada English
  /fr-ca/nous-joindre - Canada French

  There are only two versions of the
  node, US English and CA French. The CA English uses it's alternative
  language and loads the US English version so all three pages work and
  the URL's are correct.


Autocomplete field search start character limitation?

Will you explain the search that you are using (ex.solr, default).
Basic limitation of characters is 3. if you want to increase this go to admin/config/search/settings and change the length of Minimum word length to index to your-limit and re-index the site. If you type minimum word length then only your search send a request to server.


How to add / remove tabs from user profile?

If you don't want to use a contrib module like TabTamer then, In Drupal 7,   you can use hook_menu_alter to disable the MENU TAB by using access callback

    /**
     * Implementing hook_menu_alter
     * Restrict MENU TABS access
     */
    function MODULE_NAME_menu_alter(&$items) {
        if(/* check your conditions */) {
            $items['user/%user/hybridauth']['access callback'] = FALSE;//Change the MENU PATH as per your requirement.
        }
    }

Note

Get the MENU PATH by printing $items variable.


Your formatting made me twitch, so I fixed it up for you.

Drupal JS Coding Standards

Also you weren't using a behavior, so I fixed that too:

Javascript in D7

(function ($) {
  Drupal.behaviors.textFieldClearer = {
    attach: function (context, settings) {
      var clearMePrevious = '';

      // clear input on focus
      $('.clear').focus(function() {
        if($(this).val() == $(this).attr('title')) {
          clearMePrevious = $(this).val();
          $(this).val('');
        }
      });

      // if field is empty afterward, add text again
      $('.clear').blur(function() {
        if($(this).val() == '') {
          $(this).val(clearMePrevious);
        }
      });
    }
  };
}(jQuery));


Status message appears multiple times on status stream

According to this that module uses Views to create the blocks, so it could be just a matter of "Reduce Duplicates" on the filters, or checking the "Distinct" option on the view itself.


Menu tree page data not rendering any data if the page does not exist in drupal 7

I have guessed what happens. It seems that Drupal does not render much of the content in order to aliviate load of the system. So in admin / site / site-information, you establish a different page for 404, and you can customize it. It will now include all menu, links, etc. and personal translatable messages you want to add.


You can not export Drupal core blocks directly.  You can can either write it in a custom module, see http://fourkitchens.com/blog/2012/07/18/building-custom-blocks-drupal-7.
Or, you could recreate it using boxes: https://drupal.org/project/boxes, which can be exported using Features.

Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.
Boxes provides an inline interface for editing blocks, allowing you to change the contents of blocks without going to an admin page.
Boxes provides exportables for its blocks via the (required) Chaos tools module. This allows modules to provide blocks in code that can be overwritten in the UI.

Or, you could copy and paste the block contents into a new block too.


You can install Drush (see Installing Drush on Ubuntu or How to install Drush server-wide in less than one minute); after, you can install a module with drush:

to download a module

drush dl modulename

to enable the module

drush en modulename

Also, you can use wget to download the module, and make a directory inside the modules directory (in this case the modules directory is /home/youruser/public_html/sites/all/modules/).

    wget http://ftp.drupal.org/files/projects/modulename-6.x.tar.gz
    mkdir -p /home/youruser/public_html/sites/all/modules/modulename
    tar -zxf modulename-6.x.tar.gz -C /home/youruser/public_html/sites/all/modules/modulename

Enable the  module in "Administer > Site building > Modules."


What would be the parameters for a services to receive a JSON file?

drupal_json_output($resultsarray);

you will get json data


How to disable "add comment form" from a OG group content?

Go to the group permission page, and uncheck the comment option for non-members.


I achieved 'Out of office' flag functionality using rules module.

Placed an out-of-office flag on user profile and set visibility rules (panels) to show flag only if its user's own profile
Within flags used flagging form to capture user out-of-office message
Added an extra field 'out-of-office' within user's profile.
Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form.
Created a rule to delete the text from 'out-of-office' field on unflagging


How do I get content to display using Views and Panels?

For Views to work in panels, you should create a Content Pane in your view.

You will likely be using a contextual filter if it's a node / user / taxonomy view so add it, and check provide default: content id from url (for a node).

Then in the Pane Settings section, click Argument Input. You will see your contextual filter listed. Choose "From Context", "Content ID".

Your view should now work as expected.


if you have a custom module let's suppose it called custom_module, your custom_module.module implement hook_preprocess_HOOK.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-id-name by your block id
  if($vars['derivative_plugin_id'] == 'block-id-name') {
    //- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;

  }

Edit :
if you don't know the exact block id you can install Block Content Machine Name module, it will give you the possibility to give a machine name to your custom block, and then implement the hook like the following:

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-machine-name by your block machine name
  if (isset($vars['elements']['content']['#block_content']) &&
    $vars['elements']['content']['#block_content']->get('machine_name')->value == 'block-machine-name'
  ) {
    $vars['#cache']['max-age'] = 0;
  }
}


It's using a transparent png to fade out the background and give that box shadow type effect on the right.  Look at class fade-bg and you'll see how.


How can I increase the 128 character limit of a menu path?

You should be able to fix this by using hook_form_alter() and override the default maxlength for the input field, and then change the field in the db to varchar(255) if it isn't already.

Another option would be to use a token value for the path and change the value on output using theme_menu_item().

Perhaps the best option after all would be the Custom Tokens module. I haven't tried it so I can't say if it works.

The downside with tokens is that you would have to make one token per URL, or possibly use a part of the URL if it's generally the same.


How to get the parent comments (in a custom module)?

This code does the trick:

  $threads = explode('.', $comment->thread);
  $thread = "";
  $pnids = array();
  for($i=0;$i<(count($threads)-1);$i++){
        $thread .= $threads[$i];
        $local_thread = $thread."/";
        $result = db_query('SELECT c.cid FROM {comment} c WHERE c.nid = :nid AND c.thread = :thread AND c.status = :status',
        array(':nid' => $comment->nid, ':thread' => $local_thread, ':status'=>'1'));
        foreach ($result as $record) {
            $pnids[] = $record->cid;
        }
        $thread .= ".";
  }

However this code produces 1 DB query for each parent. I don't know if it is feasible/better to include all the :thread in a single query with OR.


Howto limit access to a main menu link using drupal 7 api

hook_menu_alter only gets executed when you clear cache or rebuilding menu. I would suggest if you want to debug the $items variable, What I used to do
is do print_r($items) and die() after that. Then I would try to clear the cache from the admin UI or save it into watchdog for debugging.


I'm not sure how a regular filter will be able to grab the current day

Add your date field to the filter.

You will then see this screen

Click apply and continue

Click on select a date, and select relative date

Put today as your relative date.


How can I change page title in search results page?

Install and enablde Page manager and Panels.
Go to admin/structure/pages, on the line "search-node", click enable, then edit.
Add new variant -> Create variant -> Choose any suitable layout -> Continue twice.
On the final page in the Wizard, expand "Substitutions". You should see two keywords in there, copy "%keywords:raw" to the empty "Title" field above
Below the keywords, click a cog in any suitable region, in the popup click Widgets, and select "Search form".
Repeat step 6 for "Search results".
Click "Create variant", followed by "Update and save".

Take variations for choosen layout into account, and your configuration should now look something like this


Get field value in an entity form validation

I am also interested. Please post the answer if you solved.

This code:

$node = node_load($form_state['node']->nid;);
$node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

solves in case you are editing a previously saved node (and the nid is then existing).


Drupal 7: Views RSS module - fields not showing up

First think first: On a RSS feed you can't have as many <xml_tags> as you want. It's fixed-predefined for web concurrency.

Now a quick and dirty tutorial:

Enable Views RSS, Views RSS: Core Elements, Views RSS: DC Elements
Add new view without create a page or a block
Add a Display Feed
Format-> from RSS Feed to RSS feed- Fields
Fields->Add the basic fields (It will display nothing!)
Format->Settings->Item elements : core Map the fields to RSS elements (do the same for Item elements : dc)
Feed settings->Path: give a path
Save..
Browse the URL, for debug (and not fancy Chrome/Firefox styling) CURL example.com/rss


Where to check for node value constraints on services data receive

To have more control on the node creation you need to write up your own service for nodes using  hook_services_resources(). By default you can control only the access for creating a particular node using permissions.

If you need to control node creation via node values, you need to go with your own services.


Do you have French language on you site?
You should not change code of contrib modules. You can override, extend it in your custom module.
If you have fr  language on site , back t() with EN labels, go to admin/config/regional/translate/translate try to search EN labels and translate them.

Another way to get translations, use module l10n_update, it can get translation if they available on Localization servers.


How to add more condition to my conditional field

You can use jquery to check and uncheck the field

$('#myCheckbox').attr('checked', true); // Checks it

$('#myCheckbox').attr('checked', false); // Unchecks it


The book module has this bit of code in it to enable a user to choose which parent a node has:

$form = array(
  '#type' => 'select',
  '#title' => t('Parent item'),
  '#default_value' => $book_link['plid'],
  '#description' => t('The parent page in the book. The maximum depth for a book and all child pages is !maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
  '#options' => book_toc($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['mlid'])),
  '#attributes' => array('class' => array('book-title-select')),
  '#prefix' => '
',
  '#suffix' => '
',
);

Take a look at the description in particular. When you sub in the relevant variables, it reads:

  The maximum depth for a book and all child pages is 9. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.

Emphasis mine.

So the limit intentional, it (necessarily) matches up with the maximum depth for a menu in the same system.

It would technically be possible to patch core and increase MENU_MAX_DEPTH to something larger, but bear in mind that other parts of the system rely on it (for example the number of p* columns in the menu links table), so it probably won't be as simple as all that.


Rule to check if a date value is a specific day of the week

I had myself many troubles with Rules and dates too. There are several open issues in Rules about dates. So the solution that I offer is very cumbersome and to be honest I don't like it too, but it seems to be the only thing to work. Improvements are of course welcome. Maybe there is also some module which I miss.

Note that this is about Rules ver. 7.x-2.7. The solution involves both some PHP code and components.

So the first issue at hand is that it seems Rules cannot change the format of a date variable in a data comparison, or to properly convert the data type.

Therefore I am using a rule to get the weekday from the variable, then pass it to a component as a variable (integer). In that component I can easily do a data comparison for the interger and procedd with any actions.

In order to get the weekday, I create an action "Add a variable". In there, I use some PHP code in order to directly get the week day. Here is the second issue: Rules do not seem to properly expose the variables in PHP. Therefore I specify the type of the variable as text, and then I specify the value using one of the replacement patterns in the direct input mode (otherwise a date will not be available in the data selection mode). Now we have the date as a string in a variable. Let name the variable variable_added.

The second action is to "Set a data value". In there, you specify:

<?php
$datetime = new DateTime(DateTime::createFromFormat('D, d/m/Y - H:i', $variable_added));
return $datetime->format('w');
?>

We create a DateTime object from a hard-coded format. This has to be the Drupal long date format which Rules seem to use for their date formatting. There got to be an API function that returns the current format which atm I miss, and so we have it hard coded to get us going. Replace this with your installation's custom format from /admin/config/regional/date-time, also consult this. Then we use DateTime::format to get the day number.

So now we have the day number as a string. The third action would be to convert the above variable to an integer, and then in a fourth action you would call the rules component passing on the converted variable along with any other variables you would need.

Appendix: My test case rule export.

{ "rules_test_date" : {
    "LABEL" : "Test date",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php" ],
    "ON" : { "cron" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[site:current-date]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "data_set" : {
          "data" : [ "variable-added" ],
          "value" : "\u003C?php\r\n$datetime = new DateTime(DateTime::createFromFormat(\u0027D, d\/m\/Y - H:i\u0027, $variable_added));\r\nreturn $datetime-\u003Eformat(\u0027w\u0027);\r\n?\u003E"
        }
      },
      { "drupal_message" : { "message" : [ "variable-added" ] } },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "variable-added" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      }
    ]
  }
}


A database table can have at most one primary key, but it can have multiple unique keys.
Replacing the primary key in that table is not a good idea, because Drupal code rely on the fact the primary key is vid. You cannot set any field as primary key: it must a field that contains unique values for each row; if the field you choose can have the same value for multiple rows, then it's not a candidate for primary key.


Pull webform submissions in different webistes to one end-point

Ultimately, there are several ways to accomplish a 'sync' across multiple sites.
However, without more technical information the options are generic at best.  Webforms that include uploads or images may require additional work to configure.

Bottom line, the webform data lives in a table in the database, on each site.  The best solution may not be a module but rather a cron job pulling that data and serializing it on a collection site.  This would be a custom script collating and creating webform content on the collection site.  As such, the webform Node ID would not necessarily be preserved.

Another approach, if the cron job is not preferred... might be to use the built-in mail function from webform, or to create a Rule to send the webform data to a mailbox.  The collection site can be configured to create node content processed from that mailbox.  One benefit is that this could be a non-webform content type.  As such, you can add fields and act on that data in a way to manage it and you could also in this way preserve a record of the original Node ID so that a reference to the source site is possible.  Other fields might be the site URL, notes, if action is required... and so forth.

Here are some references that might be useful in the latter approach:

Add content to your site via email using https://www.drupal.org/project/mailhandler - Mailhandler
http://drupal.stackexchange.com/questions/69134/send-mail-to-email-addresses-from-webform-when-a-content-is-saved - Send mail to email addresses from webform ...
https://www.drupal.org/project/webform_rules - Webform Rules module

Of course, it matters if you're using D6 or D7.  Mailsave & Mailhandler are both included in one popular approach using D6 and Mailsave doesn't have a D7 version.


Webform Submission not Working with .tpl.php file

Stick this at the bottom:

<?php echo drupal_render_children($form); ?>


I think it's more a taste/customization vs convenience here.
Using XAMPP can install way more stuff than needed and SysAdmins doesn't like this ;) installing each piece individually allows you to select exactly the pieces you need and also there's less risk to be bothered by some strange library or configuration that XAMPP may set up.

So to sum-up:

you're tech-savvy, you want to manage and configure your VPS and aspire to become a SysA, go for the separate install.
you don't want the hassle of configuring (and eventually debugging) each parts, go for XAMPP.
if you want even less troubles, go for a fully managed/optimized hosting platform like Acquia Dev Cloud.


How do I wrap a div around specific fields in a view?

To add CSS classes you don't need to use Twig, you can do it using the Views UI

Click on your field. Then under style settings, checkmark customize field HTMl and select DIV as your element. Checkmark create css class and type your class name.


You could either:

Add {text-align: center} to your footer region or block.
You could specify a width for your block and add {margin: 0 auto}.


math operators for text fields in views filters

You'll want to create a different field of type "number" for that.

You might be able to do something like creating using Computed Field to create a new field that takes the value of your original field and changes it to an integer with  $num = (int)$str;


There's no ready module for this, since stripe.com has https://stripe.com/api so it should be made as custom module for payment


How to populate DB values in content type field, drupal 7

You have to install Content Construction Kit (CCK) module. After installing this module you get a text field for Allowed value function in field setting of desired field. Put the function name here to get country list. Also put following function in a module.  You may have to modify query as per your requirement.  After doing all these thing you will able to get country list in that field.

function _get_country_list(){
    $country = array();
    $query = db_select('country', 'c');
    $query->fields('c', array('country_name','country_id'));
    $result = $query->execute();
    if ($result) {
        while ($row = $result->fetchObject()) {
            $country[$row->country_id] = t($row->country_name);
        }
    }
    return $country;
}


How to add css to specific blocks or view with CSS injector module?

I am try already this but i think it would be helpfull

Use php section to add css against any view or block
and try this one

<?php
if ( $block->module == 'your_block_id/name'){
          //add some code here
}
?>

Or can do it by add a class in view or block


Value or label inside a exposed search form and change input form

For adding text to your input field, can be done in one of two ways

    function myhook_form_alter(&$form, &$form_state, $form_id){
        if($form_id == "views_exposed_form"){
         dsm($form); // print $form array on the top of the page
          if (isset($form['title'])) {
            $form['title']['#attributes'] = array('placeholder' => array(t('Enter Keywords to search...')));
    }
  }
}

Or use Compact form

  Compact Forms presents text fields for selected forms in a more
  compact fashion using jQuery.

  The form item/element fields are overlaid with their respective
  labels. When the user focuses a field the label fades away nicely, and
  if the field is left empty the label fades back in again.

For changing the All to choose location

function your_module_name_form_alter(&$form, $form_state, $form_id) {
      if($form_state['view']->name == 'your_view_name') {
        $form['your_dropdown_name']['#options']['All'] = t('- Choose Location -');
      }
}


Best way to break up node edit forms smaller, more manageable forms?

I use the field group module to simplify things.  This allows you to easily make collapsible groups of collapsible field sets, use horizontal and other types of tabs, and split a single form into multiple pages.

With the field group module, you can also easily add a css class to any group of fields, which makes it straightforward to theme that specific field (change the background color, increase text size, etc.) for emphasis.


How to override a twig template for only a specific page?

As you mentioned your main issue is whatever data you are fetching it is overriding the all page-title on the site which you do not want. So to solve that follow following steps,

For common understanding I am referring bartik theme. I am showing with example to my local site so it will be very practical to understand.

In bartik.theme file,

function bartik_preprocess_page_title(&$variables) {
  $variables['staticString'] = 'Explorer ';
  $variables['user_profile_view'] = (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical'); }

in page-title.html.twig file,

{% if title %}
  {% if user_profile_view %}

{{ staticString }}{{ title }}

  {% else %}

{{ title }}

  {% endif %}
{% endif %}

Output image,
On user page,

On other page(It will not interfere),

So, this way you can Override the page-title of user-profile page and can insert your own defined variable. So, this answer is with static variable, now same way, you have to just replace that variable with your dynamic variable, so it will get change based on your code.

Note: In solving this question, I have asked another question here: How to get the part of URI and pass it to as a argument?.


Adding Facebook Like-button to the User menu in the top-right corner

As an alternative to adding the like-button in the actual link items, maybe you should consider add it via a block or similar above/below your menu.

Checkout the Facebook social plugins integration module.


How can I print user field values in page.html.twig?

To print user fields on the page template create a Views block and place it in an existing region.

At best you first added a new view mode for User under https://example.com/admin/structure/display-modes/view and then on https://example.com/admin/config/people/accounts/display select the newly created view mode and place the fields you like to display.

Then create the view, have it display Users and in the very right under ADVANCED add a contextual filter for User ID. Select Provide default value and choose User ID from logged in user, save. Then in the very left under FORMAT > Show > User select the view mode you created earlier.

Don't print user values on the page template.

page.html.twig is for printing regions.
page.html.twig is cached per user role. Next user with the same role will get displayed initially cached values of another user.
The user object with all field values isn't fully loaded by default, you would need to preprocess the user first.
Templating should be done when you need to structurally change markup.


This answer should help:
https://serverfault.com/questions/488444/nginx-rewrite-convert-querystring-to-path/488480#488480

I would try something along the lines of:

location @drupal {
  if ($arg_lang) {
    rewrite ^(.*)$ $arg_lang/$1? permanent;
  }

  rewrite ^ /index.php;
}

The above assumes that requests with ?lang=XX do not have any other arguments, and that the request does not already have the language prefix in the page request (ex: /XX/node/123?lang=XX).


use hook_theme_registry_alter.

Example:

function MYMODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['table']['function'] = '_MYMODULE_my_table_theme';
}

function _MYMODULE_my_table_theme($variables) {
...
...
}


You should use Form API to create and manage file uploads and their management. You can do something like this instead:

...
$form['file'] = array(
    '#title' => t('File'),
    '#type' => 'managed_file',
    '#description' => t('File formats: %format. Maximum: %max_size. Resolution %resolution', array('%format' => 'Jpg, Jpeg, Png, Gif', '%max_size' => '800 Kb', '%resolution' => '80x100')),
    '#upload_location' => 'public://',
);
...

and submit function:

...
$node = node_load(32);
$file_d = $form_state['values']['file'];
$file = file_load($file_d);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'node', 'TYPE', $file->fid);
$file_info = image_get_info($file->uri);

$file_arr = array(
  'fid' => $file->fid,
  'alt' => '',
  'title' => '',
  'width' => $file_info['width'],
  'height' => $file_info['height'],
  'uid' => $file->uid,
  'filename' => $file->filename,
  'uri' => $file->uri,
  'filemime' => $file->filemime,
  'filesize' => $file->filesize,
  'status' => 1,
  'timestamp' => $file->timestamp,
  'rdf_mapping' => array(),
);

$node->field_ftest[LANGUAGE_NONE][0] = $file_arr;
node_save($node);
...


Why doesn't LinkFormatter::viewElements bubble cache metadata?

Is this causing a bug for you, or are you just trying to understand how it works at all?

Making the token system integrate with the cache system happened very late in the Drupal 8 development cycle (see https://www.drupal.org/node/2528662).

Note that if that optional Token::replace(…, …, …, BubbleableMetadata $bubbleable_metadata = NULL) argument is not passed, it does check whether this token replacement is happening within an active render context (see the hasRenderContext() condition in ::replace()) and if so, it bubbles it automatically, directly onto the render context. Since Linkformatter::viewElements() is only ever called during rendering, AFAICT it should actually be working fine already, thanks to that automatic bubbling. We should not be relying on that, but precisely because it was added so late in the D8 development cycle, we had no choice but to resort to such approaches to minimize disruption.


If its showing the wrong map, you might be displaying the wrong view mode. Make sure you have set the gmap display for view mode full.


Import or Programmatically create nodes with Videos

Your best bet is to use the Migrate module. It's got a kinda steep learning curve but plenty of documentation available.

The Migrate Extras module provides integration with the Media module, which could help with the video field specifically.


That table is used by the BatchQueue class; on the top of the page I linked there is the following note:

  Stale items from failed batches are cleaned from the {queue} table on cron using the 'created' date.

For some reason, in your case they are not being deleted during cron tasks; probably cron tasks are not enabled in your site, and the setting that allows cron tasks to be executed through JavaScript is not selected.
In any case, once batch operations are completed (which means also when the updates have been completed), it is safe to delete those database rows.


You can use  'menu_name' => 'primary-links'; in your code and of course you have to alter the primary-links to the menu of your choice.

$items['budget/view'] = array(
  'title'             => t('Ver gastos'),
  'description'       => 'Veja quanto é que anda a gastar',
  'page callback'     => 'page_budget_view',
  'page arguments'    => array(2,3),
  'access callback'   => ($user->uid > 0),
  'menu_name'         => 'primary-links',
);


We used OG extensively in many sites with stores that are auto-created when a user registers.  You can check out one of them here - www.craftsaid.com - each "store" is an OG.  We also did the same thing on Bandromeda.com.

Install Organic Groups Module - http://drupal.org/project/og
Install Rules Module - http://drupal.org/project/rules

After you have created a content type for your Group type (this can be anything you want it to be - if you're not familiar with OG it is an incredibly powerful platform that allows users to create groups to which other members may subscribe - essentially you create one content type as the "group" type itself and then any other content type can be set as "group content" that may be added to a given group) go to /admin/workflow/rules and add a rule for Event = After saving a new user account with an Action = Create a new entity with parameters of Entity type: Node, Content type: Your Group Content Type, Title: [use tokens to create your title configuration]

This will auto-create a Group upon registration.  Otherwise you could simply create a link to node/add/store (or whatever your group content type is) from wherever makes the most sense in your site.

That is a very basic explanation - there are probably 50 ways you could implement this to accommodate your general description of your need.  Hope that helps!


Assuming that you have chosen 'block' as the display rather than 'page', you have to set 'Use Ajax' to 'Yes' in the Advanced options (See this issue on Drupal.org: http://drupal.org/node/1115782#comment-4384348):


Is it possible to restrict access to anonymous user to specific content types based on the author?

I don't think it looks like the best idea - sometimes you have to fire an author and get someone new. Author-based solutions may get complicated in such situations. Usually I use Taxonomy Access Control - I'm restricting users to view only content with particular term, and only give access to that term to particular authors. Simple, and without need of any custom coding.

Note one important restriction:

  While Drupal 7 makes support for additional databases possible, TAC does not currently support databases other than MySQL/MariaDB/etc. or Postgres. See #1266674: Support other databases for more information.


7: How to import simple channel-level rss data to the parent feed node created by Feeds module?

You can try to use the patch supplied in https://drupal.org/node/1689374?


How can I ensure that availability calendar only show one month at a time?

I found a css fix for this:

availability_calendar.base.css

adding

.cal-viewport { width: 220px !important; }


Use taxonomy_get_term_by_name when there are duplicate names across multiple taxonomy categories

Yes, you should pull the term ID directly from the field value rather than first rendering it to a term name, then trying to look up the term based on the name.


How to add collapsible help text to a form?

What about putting it into a fieldset ?

$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

$form['fieldset']['some_text'] = array(
  '#markup' => '
Here is some very useful text.
',
  '#weight' => -1,
);


Hooks are plain PHP functions that follow a specific name schema. As such, the same function name cannot be used from two modules.
Furthermore, Drupal is not able to understand if c_a_b() is the implementation of hook_a_b() done from c.module, or the implementation of hook_b() done from c_a.module.
To answer the question, yes, there would be conflicts and (in the case both the modules are installed) PHP errors.

Use something other than a single underscore for hook namespacing aims to not use a single underscore to separate the module name from the hook name, for example two underscores. Doing so, c__a_b() would be an implementation of hook_a_b() done from c.module, and it would not be confused with c_a__b(), the implementation of hook_b() done from c_a.module.
There is also Module names should not contain an underscore, which would avoid any ambiguity with c_a_b(). As underscores would not be allowed in module machine names, c_a_b() could just be the implementation of hook_a_b() done from c.module. (That feature request is set to closed (won't fix); at the moment, it's not going to be implemented.)

As for two modules invoking the same hook for different purposes and/or with different parameters, that is going to cause conflicts and errors.
The code invoking hooks calls a function basing on its name (<module>_<hook name>) directly passing the arguments to the function. If the arguments don't match the function parameters, PHP will raise an error; if the arguments match the function parameters, there will be other errors, as a hook supposes to be invoked in a specific moment, as described in the hook documentation. Imagine what would happen if a module would invoke hook_user_delete() after a user deleted a node; the modules implementing it would delete the data associated to that account from their database tables, since hook_user_delete() is documented to be invoked before a user account is deleted, not any data associated to the deleted node.

In both the cases, the only solution is naming hooks and modules in a way to avoid conflicts.

As per https://www.drupal.org/project/hook, that URL returns a 403 error because there is an unpublished project. (I can visit the project page because I am a webmaster on Drupal.org.)

The project has been created to avoid somebody would name a project Hook.


Drupal multi-site Aegir caching strategy

Use what your comfortable with for maintenance and configuration.
Probably, depending on config. (I don't use nginx)
Not crazy, it allows for a very quick switch time to another webserver.

I have varnish combined on my webservers with a separate apache reverseproxy doing ssl termination.

A little custom hook triggers a reverse proxy update on a Aegir migrate task.


Show list of node titles from a certain taxonomy term

You have to enclose table names in curly braces {} everywhere they appear, not just in the FROM and JOIN clauses. So the correct query would be

SELECT {node}.title, {node}.nid
FROM {node}
INNER JOIN {term_node} ON {node}.nid = {term_node}.nid
WHERE {term_node}.tid = %d
ORDER by {node}.title ASC

You can also use table aliases instead.

If you use table prefixes, your query should have resulted in an error. Turn on PHP's error reporting if you did not see any error message.

If you do not use table prefixes, then the reason is, that the database query simply returns an empty result set (i.e. no node is tagged with the taxonomy term that has 5 as tid).

Also note the following:

In the line

$nodes = l($node->title, 'node/'.$node->nid);

you overwrite the previous result and thus the previous result is lost. But if a result would actually exist, at least the last result should be printed. Nevertheless, use

$nodes[] = l($node->title, 'node/'.$node->nid);

to be able to use all results.
You pass three arguments to the query (5, 0, 30), but the query only has one parameter (term_node.tid = %d). Are you sure that 5 is the tid you are interested in? The other arguments are ignored.
If you create a new revision of a node that has the requested term and then remove the term from the new revision, the node will still appear in the result set. Join on the vid of the node instead of on the nid to prevent this.


How to add profile2 field data to a programatically created user

You need to create the new user's profile:

$profile = profile2_load_by_user($user->uid, 'ae_sa');
if(empty($profile)) {
  $profile = profile2_create(array(
    'type' => 'ae_sa',
    'uid' => $user->uid,
  ));
}

// Fill fields
$profile->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile->field_bio[LANGUAGE_NONE][0]["value"] = $bio;

// Save the newly created OR updated profile
profile2_save($profile);


How can I have a URL like www.example.com/about?language=ja to set Japanese for the page?

just to be sure:
at admin/config/regional/language/admin_language, enable "Session" Detection method
make sure request/get parameter set to language
make sure you have about page in 'ja' language

try to visit yoursite.com/?language=japanese, it should be translating interface/etc - this way you can check translation is working.


How can I have separate databases for each domain (countries) of my Drupal website?

It is pretty simple to set up a multi-site with a single codebase. You could have the following directory structure (source):

-- core

-- modules
   -- contrib
   -- custom

-- themes
   -- contrib
   -- custom

-- sites
   -- site1.com
         -- modules
            -- custom
            -- contrib
         -- themes
            -- custom
            -- contrib
         -- files
         -- settings.php
   -- site2.com
         -- modules
            -- custom
            -- contrib
         -- themes
            -- custom
            -- contrib
         -- files
         -- settings.php
   -- site3.com
         -- modules
            -- custom
            -- contrib
         -- themes
            -- custom
            -- contrib
         -- files
         -- settings.php

The directories

--core

-- modules
   -- contrib
   -- custom

-- themes
   -- contrib
   -- custom

will be available to all your sites.

It is the

-- sites

directory that is responsible for the multisite. Take -- site1 as an example:

The modules, themes, and files for the site1 could stay in this directory. What is not mentioned in the documentation is the use the settings.php file. Each site could have its own settings.php file. This is typically a copy of sites/default/default.settings.php. This also means that each site could have its own database. And the entry for the database is made in the $databases array inside their respective settings.php files.

If you want to share config:

The steps that could be followed:

Point the virtual host (domain) for site1.com to the Drupal root, i.e. the directory which has core, modules, themes, etc.
Visit site1.com and install Drupal normally.
Edit the sites/site1.com/settings.php to add the location of the directory where you wish to save the configuration yml files using the variable $config_directories[CONFIG_SYNC_DIRECTORY] = '<RELATIVE_PATH_TO_DIRECTORY>';
Export configuration using Drush - drush cex. This will export complete configuration in the configured sync directory.

For site2.com and more subsites:

Dump the database of site1.com and clone it to a new database to use as a database for site2.com. Cloning the exact same database is important as the configuration management works on cloned sites and not freshly installed ones. This is because the site's UUID needs to be the same.
Have the value of the cloned database in sites/site2.com/settings.php. This means you do not have to install Drupal again. Just using the database of an already installed Drupal site.
Copy the variable $config_directories[CONFIG_SYNC_DIRECTORY] along with its value from sites/site1.com/settings.php to sites/site2.com/settings.php. This will let you use the same configuration for site2.com as well.
Follow steps 1-3 above to create more multi-sites.


view query alter : Subselects/query don't work with out brackets

I had found the soln myself; put NOT IN instead of <>.
NOT IN will make the value part inside the brackets


How to programmatically refresh the current page?

What you can do is still use Rules for this.

Go to your custom rule
Under the Actions section, click Add action
For Select the action to add, choose Page redirect.
For URL, place the internal or absolute path to where the page you want to go to a.k.a. be refreshed.
Then save the action. This solves your problem to refresh the page.
Now we add another action to display a message, click the Add action link again.
For Select the action to add, choose Show a message on the site.
Then place your message then Save.

This way, your actions based on an event is configurable just with Rules. This also opens an opportunity to convert your custom code to respond using Rule Events like to trigger the rule after a node is saved and etc.

Update

This is an option to programatically do the above method.

After the rule invoke method, add the drupal_set_message function
After the drupal_set_message method, you would need to add the drupal_goto function which you will pass a Drupal path or a full URL.


Disabling auto-translation from English to another language?

You can configure the administration language seperate to the content language by setting:

/admin/config/regional/language/detection:
Account administration pages: enabled

If you want to force this, set this setting at the top of the list.

Then there is in the user configuration of admin's the option to set a different language for the site and the administration pages language.

For other roles, just set the permission "Use the administration pages and help" to allow this setting to appear on the user page.


Best Practice: Remove UUID or default_config_hash from Custom Content Type definitions?

Yes, it is best practice to remove both.
Drupal Console provides these options:
drupal config:export:single \
  --name=config.settings.name \
  --remove-uuid \
  --remove-config-hash

Or export an entire set of YAML files of a content type directly to the modules install folder:
drupal config:export:content:type page \
  --module="demo" \
  --optional-config \
  --remove-uuid \
  --remove-config-hash

See https://drupalconsole.com/docs/en/commands/config-export-content-type


How do I render the main navigation menu?

Here is how to get the render Array :

  $menuService = \Drupal::service('menu.link_tree');
  $parameters = $menuService->getCurrentRouteMenuTreeParameters('main');
  $mainMenutree = $menuService->load('main', $parameters);
  $renderArray = $menuService->build($mainMenutree);

If needed, here is how to generate the HTML

$html = \Drupal::service('renderer')->render($renderArray);

Note : replace 'main' by menu name for another one.


How do I get $view->the actual row number?

user1090003 has the right answer.

  in views-view-fields.tpl.php or... you can have the row index like this $view->row_index

Further explanation:

In views-view-field--title.tpl.php (suggestion of views-view-fields.tpl.php), you already have the $view object available.   That view object has a property "row_index" that equals the current row number starting at zero.

Example of use:

    <?php print $view->row_index; ?>
    <?php print $output; ?>

Example results:

    0
    Node Title 1
    --
    1
    Node Title 2


If you're looking to retrieve $node objects and aren't afraid of formatting the info yourself, node_load_multiple() probably comes closest to solving your problem. The $conditions parameter is supposed to be deprecated, but you could use it to specify content type. If you want to use node_load_multiple() in the manner recommended by the API page, I believe you would just use a simple db_query() to retrieve the node ids (nids) of all content with a given type:

$nids = db_query('SELECT nid FROM {node} WHERE type = my_content_type');

Then you could iterate through the results to create an array of nids to pass to node_load_multiple().

$nid_array = array();
foreach($nids as $nid){
  $nid_array[] = $nid;
}
node_load_multiple($nid_array);

From there you're going to have to iterate through the $node objects returned to create your archive page. Depending on whether you're using path aliases, you might have to retrieve the alias for each node.

drupal_lookup_path('alias',"node/".$node->nid);

All that said, I would do this in Views in a heartbeat.


How to use "taxonomy_get_childern" function

In Drupal 7 you can use this code

  $nid = arg(1);//get the arugument
  if (arg(0) == 'node'  && is_numeric($nid)) {//check for node page
    $query = db_select('field_data_field_books', 'book');
    $query->fields('data', array('tid'));
    $query->innerJoin('taxonomy_term_data', 'data', 'data.tid = book.field_books_tid');
    $query->condition('book.entity_id', $nid, '=');
    $tid = $query->execute()->fetchField();//only one field
    $child = taxonomy_get_children($tid);//get your children
    foreach ($child as $ch) {
      print "Name===>" . $ch->name;
    }
  }


I would strongly recommend the Entityform module.  Going with this module, would allow you to take advantage of the countless contributed modules that add fields via field ui. Like the most useful for you would be the Rules and Views modules.

Rules would be used to create custom conditional actions when your form is submitted and Views would allow you to create custom displays using form submissions.


Assign existing field to new content type programmatically

No creating a new instance means you are attaching that field to a content type. Here $bundle is the machine name of the content type


Problem w/ Migrate Source CSV importing Body content w/ HTML

You could try to use PHP's html_entity_decode() on the source field:

process:
  nid: nid
  title: title
  body/value:
    plugin: callback
    callable: html_entity_decode
    source: body
  body/format:
    plugin: default_value
    default_value: full_html

PS: You've written that your source CSV doesn't contain encoded entities... have you checked the display settings for your field? (Manage > Structure > Content types > NODE_TYPE > Manage display). It could be that the import is correct, but the render settings are incorrectly set to something like plain text or a |raw filter in a Twig template file.


Slideshow does not work in Safari or Chrome

Try putting your slideshow in the main content region and see if that works. Also, try setting a width in the css class associated with the slideshow.
Sd


What is the order of preprocess functions?

The order in which the preprocess functions are called in Drupal 7 is

template_preprocess
template_preprocess_HOOK
MODULE_preprocess
MODULE_preprocess_HOOK
ENGINE_engine_preprocess
ENGINE_engine_preprocess_HOOK
THEME_preprocess
THEME_preprocess_HOOK
template_process
template_process_HOOK
MODULE_process
MODULE_process_HOOK
ENGINE_engine_process
ENGINE_engine_process_HOOK
THEME_process
THEME_process_HOOK

Source : https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7


How do I check the current user session?

You can't really do something like that in Drupal 8.

The short story is that we use Symphony for the Request / Response flow, so actually bootsrapping Drupal is a lot more complex than simply requiring the bootstrap.inc file. If you look at the index.php file, you can see an overview of a request in Drupal 8:

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

Most of this happens in the DrupalKernal::handle call. You could probably make a custom script that hooks into Drupal, but it probably will be a lot easier and more maintable to actually have this code be part of your Drupal installation.


I figured this out. ticking the 'display' box on the file field in the product form and settings appropriate permissions worked.


How to cancel an order transition if failure is detected in Commerce 2 / State Machine

We don't have a "cancel" or "reverse" feature right now, but it would be worth a feature request in the State Machine queue. The main thing you / we'll need to overcome is what to do in the event a transition in progress has already saved data, triggered 3rd party services, etc. Presumably, there are certain things that should prevent a transition from being reversed (e.g. I've refunded a payment card and therefore must move the order to a canceled or at least unpaid state). However, other things may fall somewhere in the middle ... be allowable and not prevent reversal.

Lisa had a great idea, too, in that you could define the reverse transition explicitly yourself and trigger it in the event that you had a failure condition in your active transition. That would allow you to encode your own logic for checking / reversing transition side effects.


Delete multiple entites without loading them - running out of memory

Loading/deleting one at a time may use less memory:

use Drupal\node\Entity\Node;

$nids = [21,12,45,67];
foreach($nids as $nid)
{
  $node = Node::load($nid);
  $node->delete();
}

Each loop will overwrite the previous instance of $node, releasing the memory.


render call in hook_node_presave uses admin theme

One way to work around this is to go to /admin/appearance and uncheck Use the administration theme when editing or creating content.

Alternately, you can create a separate user account that does not have permission View the administration theme and use that account to create content.


How do I access a view's results with a custom module?

$view = \Drupal\views\Views::getView('my_view_name');
$view->execute();

foreach ($view->result as $row) {
    //dont remeber if $node is fully loaded
    $node = $row->_entity;
    // if not, add this
    $node = Node:load($row->_entity->id());
    $response[] = $node->[FIELD]->view('full'); // full display
}
return $response;


Default views argument that can't be overriden?

If the "User: Current" filter is not an option for you, then you can use a hook_views_pre_execute() to modify the argument before the query is run.

In your custom module (assuming you have one argument):

function mymodule_views_pre_execute($view) {
    switch($view->name) {
        case 'name_of_view':
            global $user;
                if ($view->arg[0] != $user->uid) {
                    $view->build_info['query_args'][0] = $user->uid;
                }
            break;
    }
}

Even if a different argument is supplied in the URL, the current user's id will still be fed back into the view.


How to list Content A nodes on Content B's page using Entity Reference fields and Views (with Paragraph field Bundles attached)

Simply under Advanced (far right), for Contextual Filter add your entity reference field. In my test, I called it "Made by" field_made_by.

Note: The view preview will be blank as the view edit page does not have an ID. Just place to your Musician page and it will show up then.

  However, when using paragraphs module to add node bundles is more
  complex because technically a paragraph bundle is it's own entity, so
  Content A references a Paragraph Bundle with an entity reference field
  within its bundle (LOL). It gets pretty complicating. Any help with
  that?

Then make a view of Paragraph and not of Content.

Then add relationship of Paragraph referenced from field_paragraph (paragraph field)

Then in contextual filter add field_made_by (entity reference field).


How to export the config files of a content type to a module?

You can do exactly this with the Features module.

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it contains additional information in its info file so that configuration can be checked, updated, or reverted programmatically.

While ignoring the related config from configuration management with Config Ignore at the same time. Which also takes wildcards so you don't have to enter every single config object by hand.


In a custom module, you need to alter the contact form and add an #ajax attribute to the submit button:

function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['actions']['submit']['#ajax'] => array(
          'callback' => 'ajax_test_dialog_form_callback_modal',
    );
}

And then provide this method, using OpenModalDialogCommand, in your module too:

    function ajax_test_dialog_form_callback_modal($form, &$form_state) {
      $response = new AjaxResponse();

      if ($form_state->getErrors()) {
        unset($form['#prefix']);
        unset($form['#suffix']);
        $form['status_messages'] = [
          '#type' => 'status_messages',
          '#weight' => -10,
        ];
        $response->addCommand(new HtmlCommand('#my_form_wrapper', $form));
      }
      else {
        $content = 'Something to show in the modal';
        $title = 'Hi, I'm a Modal';
        $response = new AjaxResponse();
        $response->addCommand(new OpenModalDialogCommand($title, $content, array('width' => '700')));
      }
      return $response;
    }

  Here I'm making use of the form element status_messages to display
  validation errors, otherwise we pop up a modal with custom text.

With drupal_get_messages() you could get the system messages and clear the queue.

Don't forget to make the classes available

use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;


How do I redirect users from Japan to a certain subsite?

You can have country based redirection to any internal, or exernal path using the Context, Context GeoIP, and the Context Redirect modules.


Delete a node after X weeks it was created

If you're looking for a developer-centric solution, you can invoke hook_cron() in a custom module to clean up old nodes:

function MYMODULE_cron() {

  // Other conditions can be altered/added as neeed
  $query = \Drupal::entityQuery('node')
    ->condition('created', strtotime('-2 week'), '<=');
  $nids = $query->execute();
  foreach ($nids as $nid) {
    $node = node_load($nid);
    $node->delete();
  }
}


CCK field value count is never less than 1

As far as CCK is concerned, there is still a value, it just happens to be blank (most likely an empty string, depending on what type of field you're using). If you modify your code to check the raw value, you should only see output when there is an actual value:

if ($node->field_tip != NULL) {
  foreach ((array)$node->field_tip as $tip) {
    if (!empty($tip['value'])) {
      print "
" . $tip['view'] ."
";
    }
  }
}


How to make a taxonomy term display a field

Create a view which shows surname of person given a username. Use https://drupal.org/project/viewfield and add it as field in the taxonomy and it should show surname.

By default linked users are not listed under taxonomy terms (read here : Assigning User's In Taxonomy Terms) and there is another useful post: https://stackoverflow.com/questions/11524357/how-to-link-a-user-with-taxonomy-terms


How to show search results in view within panels?

If I understand the question correctly, you would like to send users from a search form to a specific (custom) search results page (which happens to also have some other panels etc on it).

I do not believe the panels/page manager aspect really affects how the search box operates, in which case all we have to do is specify where you would like the search form to send the user.

The following code (for an imaginary module entitled customsearch just found existing module entitled custom_search, not related).

creates a block to hold a search form (you can then place this wherever you want)
constructs a simple textfield search form to go in the block
defines a custom submit to pass the search argument to your customised search results page

1)

// Implements hook_block_view().
function customsearch_block_view($delta = '') {
  if (user_access('search content')) {
    $block['content'] = drupal_get_form('customsearch_block_form');
    return $block;
  }
}

2)

// Implements hook_forms().
function customsearch_forms() {
  $forms['customsearch_block_form']= array(
    'callback' => 'customsearch_box',
    'callback arguments' => array('customsearch_block_form'),
  );
  return $forms;
}

// Form builder; Output a search form for the search block's search box.
function customsearch_box($form, &$form_state, $form_id) {
  $form['customsearch_form'] = array(
    '#type' => 'textfield',
    '#title' => '',
    '#title_display' => 'invisible',
    '#default_value' => '',
    '#attributes' => array(
      'title' => t('Search the website'),
      'placeholder' => t('search the website'),
    ),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Search'));

  // define function to determine search destination
  $form['#submit'] = array('customsearch_search_box_form_submit');

  return $form;
}

3)

// overide submission of search query from block
function customsearch_search_box_form_submit($form, &$form_state) {
  $searchterm = $form_state['values']['plus_search_form'];
  $search_path = 'specialcustomsearch'// replace with the path to your search results page
  // pass search term to your search results page as argument
  drupal_goto($searchpath .'/'. $searchterm);
}


I was wrong about not pulling from a stale cache. Credit goes to Jeff who does not want it:

Changing a filter does not mean the image toolkit renders the image again. This only happens once the /files/styles folder is cleared out. Once I did this, the quality improved and I don't see a difference between old and new anymore.


Using feeds and xpath to import multiple images into a node

The issue was resolved.

Feeds importer was working correctly all along. The problem it seems was with the actual images themselves. I didn't realise, but the in some cases the source images where huge (in excess of 18Mb) It just co-incidentally happened that the large image was the second image for the node. Thus when the feeds importer failed. It actually looked like it worked but only managed to import the first image.

When I resized all the images and then re-imported them, it imported all the images correctly.

There is still an unresolved issue in that the import was failing silently. After a few tweaks import suddenly failed with server 500 errors. That's when the apache logs showed a memory allocation error.

Once I saw that, I was able to determine the issue was related to the source images.

I guess the outcome of this is don't assume the problem is related to something you did.


How would I by default have a dropdown block expanded instead of collapsed?

Remove $('.mapsindeed-dropdown-block .content').hide(); from the above, and replace it with the following code:

$('.mapsindeed-dropdown-block .content').addClass('expanded');


The link of "Pdf version" on node page does not appear in chrome

It was the permission issue. I granted the permission to the authenticated and anonymous users and it works for me.


Views and Filtering Data not getting results

Create a relationship to the invoice type content type in the view and then add filter for the status field of invoice type taking relation ship when adding the field in the filter.

Relationship can be found under the Advanced section of the view. Pick the suitable Entity Reference for the relationship to invoice type here and add the relationship.

After that if you add the status field to the filter options you have the option to use the relationship for that field.


How to convert a command line table (drush output) to any spreadsheet? (csv,excel,ods)

Check out this new feature from the latest dev version of Drush 8.x-6.x:

$ drush @dev pm-list --format=csv
Administration,Actions permissions (VBO) (actions_permissions),Module,Not installed,7.x-3.1
Administration,Administration Development tools (admin_devel),Module,Not installed,7.x-3.0-rc4
Administration,Administration menu (admin_menu),Module,Enabled,7.x-3.0-rc4
Administration,Administration menu Toolbar style (admin_menu_toolbar),Module,Not installed,7.x-3.0-rc4
Administration,Administration views (admin_views),Module,Enabled,7.x-1.1
CCK,CCK (cck),Module,Enabled,7.x-2.x-dev
CCK,Content Migrate (content_migrate),Module,Disabled,7.x-2.x-dev
CCK,Location CCK (location_cck),Module,Enabled,7.x-3.0-alpha1
... etc.

If you are at all wary about using a dev version of Drush, you could check it out following the version control instructions at http://drupal.org/project/drush/git-instructions.  Then, you can use git checkout 7.x-5.8 to go back to latest stable, and git checkout 8.x-6.x to go back to latest dev, and use stable most of the time, and the dev version when you want to output something in another data format.

Update:  Note also that Drush 8.x-6.x-rc4 is out now, which is pretty well fit for general consumption.

Update 2: Note that this is a standard feature now in Drush 6 and Drush 7 (master branch of Drush on github)


Guzzle includes a mock handler that lets you provide a mock HTTP response. Docs are at http://docs.guzzlephp.org/en/latest/testing.html. Here's how you might use it in your unit test:

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

/**
 * Test the getMembershipClasses method.
 */
public function testGetMembershipClasses() {

  $body = file_get_contents(__DIR__ . '/Mocks/membership-class.json');
  // This sets up the mock client to respond to the first request it gets
  // with an HTTP 200 containing your mock json body.
  $mock = new MockHandler([
    new Response(200, [], $body),
  ]);
  $handler = HandlerStack::create($mock);
  $this->mockHttp = new HttpClient(['handler' => $handler]);

  $anonymousWebServices = new AnonymousWebServices(
    $this->mockHttp,
    $this->mockState,
    $this->mockConfigFactory
  );

  $membership_classes = $anonymousWebServices->getMembershipClasses();
  $membership_classes = json_decode($membership_classes->getContent());

  $this->assertNotEmpty($membership_classes);
  foreach ($membership_classes as $membership_class) {
    $this->assertTrue($membership_class->IsActive === TRUE);

  }

}

You can queue multiple mock responses by adding them to your handler at creation time:

  $mock = new MockHandler([
    new Response(200, [], $body),
    new Response(400, [], 'Request malformed.'),
  ]);

Or you can add them after your client has already been instantiated, as long as you keep a reference to your mock handler around. If you have multiple test methods, this is a lot easier to read and maintain:

public function setUp() {
  $this->mockHandler = new MockHandler();
  $handler = HandlerStack::create($this->mockHandler);
  $this->mockHttp = new HttpClient(['handler' => $handler]);
}

public function testSomething() {
  $this->mockHandler->append(new Response(200, [], 'apples and bananas'));
  $responseBody = $this->mockHttp->get('http://example.com')->getBody();
  $this->assertEquals($responseBody, 'apples and bananas');
}


From a similar issue - you can find details here (or just search for views preprocessor):

A preprocessor will give you access to the data, instead of rendered html which you find in the tpl file.

  There aren't dynamically generated preprocess functions; instead, all
  of the theme functions use the base preprocessor automatically. So
  views-view--my-first-view.tpl.php still uses
  template_preprocess_views_view(&$vars) as its preprocessor function.

  You can add preprocess functions for specific views with the exact
  same naming conventions. Note that that it's named *preprocess not
  preprocessor_.

  Note that currently Drupal's design requires that you have the
  .tpl.php file in order to have the preprocess function (though you
  could drop in a generic preprocess function and do switches based upon
  information contained within the $vars['view'] variable. There's an
  issue for this which is fairly easily found by going to the Drupal
  queue and searching in the 'theme system' queue.


Which Drupal module support spatial filtering with apache solr module

Have a look to the Search API Location module. There is also demo site.

  The Search API spatial module (7.x-2.x branch) adds the possibility of location based searching to the Search API module.
  Currently only Apache Solr is supported as server.
  You can find a demo on http://spatial.mollux.be.


I think the idea of using a feed is an attractive one. I don't think there's any way to push a menu definition out as a feed using existing modules, though.

I'd write a very simple module to provide a single callback that would fetch the menu definition and theme it as xml or json (easier). That could then be fetched at intervals by your other sites.


Manually laying out specific articles on page

There is (as often) more than one way of solving this.

The dirty and easy way of doing it is with Blocks and Regions, like in Drupal 7. You'll need regions in your theme to be laid out the way you want (and be responsive). Then you manually add nodes/blocks to the regions you have laid out. Even the method of choosing nodes/blocks can be done in different ways.

The sophisticated way of building such a page is with the Layout builder and Paragraphs or a similar module that allows you to reference things.

One Content Type will serve as the container for the layout and all the other content you want shown there. Although it's possible to apply it to only the one node, the one you'll be using for the front page, you decide what makes sense structurally and procedurally in your project.

With Paragraphs you create different reference possibilites for the content you want displayed, and then arrange them with the Layout builder. The Paragraphs and Layout builder parts are usually done up front, you build them once and have it ready when new content is created.

When you publish new nodes and want to update the front page node to show it you will only have to change the references within the front page node to keep the layout and have different content in each "box area".

You can, of course, create more than one layout in your theme, so when needed also choose a different layout for the new content combination.

It's a super powerfull new approach in D8 that makes your Drupal site feel like a website builder software. It does require some effort up-front, so it all depends on your specific needs.


Drupal 8 views doesn't have a Theme: Information section, or at least it doesn't have information about themes.

Twig is the themeing engine, so you'll need to get information there. You can enable twig debugging in a services.yml file:

parameters:
  twig.config:
    debug: true

This will print out theme-able names for views in the html. On a site I'm looking at the print out only gives one option for the view:

<!-- BEGIN OUTPUT from 'themes/custom/sitename/templates/block--views-block--our-leadership-senior-management.html.twig' -->

But the block that holds the view has a number of options:

<!-- FILE NAME SUGGESTIONS:
x block--views-block--our-leadership-senior-management.html.twig
* block--views-block.html.twig
* block--views.html.twig
* block.html.twig
-->

The x indicates that's the template I'm using.


There is (AFAIK) no module that will do this for you.

But you will be able to add and process any additional criteria for logging in by using hook_user_login to insert your own business logic into the login process.  In this hook, you may insert code to redirect those users that you do not want to login to a page that explains the situation.  There is an example on how to redirect logins in the comment thread in the API documentation for hook_user_login  on Drupal.org.

For sake of completeness, I also mention that it is also possible to stop users not meeting specific criteria from registering in the first place.  To do this, you add an additional validation callback function for the registration form processing using hook_form_FORM_ID_alter.  There is a question on Stack Overflow that explains how to do this in detail for Drupal 6.


How to place custom menu in user profile

I have been searching for this for 2 days now, and decided to go for bounty. But, didn't know the solution was so simple. I tried doing the same on fresh install of Drupal and it worked fine. And kept on adding the modules one by one, again testing the functionality for any change.
It appeared to me that after disabling Menu token module, the requirement worked absolutely fine.
Then I checked to see if I gave a wrong token replacement. And the menu structure which i was using was as below

--My Account with path [node:url:absolute] which i thought would direct to same page.
----Edit Account with path user/me/edit
----Edit Account with path user/me/edit-profile
----Logout with path user/logout

And I used gave the path as *user/** in the Visibility settings of the block(highligted of corporate theme) as discussed in question and comments above,

The Problem identified(as per me) was that I was considering user profile page as a node which I think now is wrong, so the token [node:url:absolute] was actually a wrong token and hence the menu was not displaying on user page. What I did is changed it simply to [current-page:url] (as I wanted the user to be on same page, and I suppose we cannot give # in the path of the menu to achieve it)as shown in fig below and used the same visibility settings and it worked :)
So, basically the parent menu path was wrong which created the problem. Nevertheless, it was good learning experience!!


Simple AJAX callback fired on form submission button click

You also need a submit function.

You can have a look here. It's a complete example with submit handler and callback. In this case I altered the form as I didn't create it but is quite similar. Also a really nice post is here


CCK fields don't appear on the "node add" form for authorized user

Most likely you have a module enabled that adds access control for each field. Check your permissions setup.


How to use the Profiles2 module for Drupal

The URL is dynamic, per-user and per-profile... for my site, it's something like the following: user/[user-id]/edit/[profile2-machine-name].

This would be different depending on

the user whose profile is being edited
the profile2 profile that is being edited for that user

Alternatively, of course, you might want to just go to your 'my account' page (at /user), click on 'Edit,' and then in the local menu tasks (under the edit tab), you can click on the profile2 profile you'd like to edit.

With regard to a template to change the page, I'm not sure if there is one. You could do a hook_form_alter() in a custom module to change the form values a bit, but you might want to look around the profile2 documentation or module itself to see how these pages are built.


There is a way to do what I am trying to do:
in your product_display display mode, in your product field, you chose: rendered entity, and in rendered entity options, you will be able to select your new product display mode.

I hope this helps somebody.


How to handle DB updates when my Drupal source is in git?

Yes, if you update the files on the production site, all you have to do is to run the update.php or drush updatedb additionally.
For migrating functionality from staging to production site, you might be interested in Features. It allows you to export various "pieces" of functionality and transfer them to another installation; this can include content types, fields, views and image styles, to name a few.

Hope this helps!


Drush shell scripts such as the one you show above do not automatically bootstrap to any argument passed to them.  (EDIT: This is due to a bug.)  You have a few options.

1: Force the bootstrap:

$site = drush_shift();
drush_bootstrap_max_to_sitealias($site);
drush_invoke('core-status');

2: Do all of your work in a subshell:

$values = drush_invoke_process($site, 'core-status');

Those two should get you started.  Note that option number two will re-bootstrap Drupal in an isolated subshell every time you call drush_invoke_process.  drush_invoke always works on the currently-bootstrapped site, and you can only bootstrap once.  Therefore, that drush_invoke('use', ...) trick won't work.  'use' is only for use in the shell, not in scripts.

There's another error above.  This code isn't working as you expect it is:

$result=drush_invoke('core-status');
drush_print($result['output']);

What's really happening here is that drush_invoke is printing the output of drush status to stdout, and drush_print is printing nothing.  You'll get $result['output'] if you use drush_invoke_process.

In my somewhat biased opinion, the Drush chapter of the Definitive Guide To Drupal 7 covers these topics pretty well.  It is available for download as a free sample chapter at http://definitivedrupal.org/book/26-drush


How to upload a csv file with an admin form?

In your custom form create input button like

$form['upload_csv'] = array(
        '#name' => 'files[mycsv_data]',
        '#type' => 'file',
        '#title' => 'Upload csv'
    );

Next in form submit you can use

file_save_upload($source,
                array('file_validate_extensions' => array('csv')),
                $destination_dir,
                FILE_EXISTS_REPLACE)

Here for getting uploaded file details like file name and file path you can use $_FILES global variable.

and then,

if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}


How to load a view's ajax when the view is programmatically loaded

You have to enable ajax in the views. Probably you have to do it in both parent and child view.

To do so : go to Advanced -> Use Ajax


You need three functions.

1) module_submit.
2) Create a function to send the mail.
3) create hook_mail.

a complete example: file sendmailtest.info

name = sendmailtest
description = sendmailtest
core = 7.x

file sendmailtest.module

<?php

function sendmailtest_menu() {
 $items['sendmailtest'] = array(
   'title' => 'send mail test',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('sendmailtest'),
   'access callback' => TRUE
 );
 return $items;
}

function sendmailtest($form, &$form_state){

 $form['submit'] = array(
  '#value' => 'Send Mail Test',
  '#type' => 'submit',
 );
 //Fundamental devolver el objeto-array form
 return $form;
}

function sendmailtest_submit($form, &$form_state){

 drupal_set_message('Test ok');

 sendmailtest_send($form_state['values']);

}

function sendmailtest_send($form_values) {
  // All system mails need to specify the module and template key (mirrored from
  // hook_mail()) that the message they want to send comes from.
  $module = 'sendmailtest';
  $key = 'sendmailtest';

  // Specify 'to' and 'from' addresses.
  //$to = $form_values['email'];
  $to = 'jeremiselxi@gmail.com';
  $from = variable_get('site_mail', 'admin@example.com');

  // "params" loads in additional context for email content completion in
  // hook_mail(). In this case, we want to pass in the values the user entered
  // into the form, which include the message body in $form_values['message'].
  $params = $form_values;

  // The language of the e-mail. This will one of three values:
  // - user_preferred_language(): Used for sending mail to a particular website
  //   user, so that the mail appears in their preferred language.
  // - global $language: Used when sending a mail back to the user currently
  //   viewing the site. This will send it in the language they're currently
  //   using.
  // - language_default(): Used when sending mail to a pre-existing, 'neutral'
  //   address, such as the system e-mail address, or when you're unsure of the
  //   language preferences of the intended recipient.
  //
  // Since in our case, we are sending a message to a random e-mail address that
  // is not necessarily tied to a user account, we will use the site's default
  // language.
  $language = language_default();

  // Whether or not to automatically send the mail when drupal_mail() is
  // called. This defaults to TRUE, and is normally what you want unless you
  // need to do additional processing before drupal_mail_send() is called.
  $send = TRUE;
  // Send the mail, and check for success. Note that this does not guarantee
  // message delivery; only that there were no PHP-related issues encountered
  // while sending.
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  if ($result['result'] == TRUE) {
    drupal_set_message(t('Your message has been sent.'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }

}

function sendmailtest_mail($key, &$message, $params) {
  switch ($key) {
    // Send a simple message from the contact form.
    case 'sendmailtest':

      $message['subject'] = 'Test subject';

      $body= 'Test Body';
      $message['body'][] = check_plain($body);
      break;
  }
}


Make 'Full HTML' the default text format

If I remember it correctly, the order that the text formats appear (depending on the permissions you as a user have on using the text formats) is set on the example.com/admin/config/content/formats page. Just use the cross icon on the left to drag an re-order the various formats. Put the Full HTML on the top to make it the first choice.


Help adding multiple blogs / content areas on a page

You define new block regions in your theme, and structure your page.tpl.php to print the regions in the desired structure.  You should look through the theming tutorials

If that is the layout for a single page only, you might want to look into Panels, though be warned that there is a bit of a learning curve.

For styles of blocks, you can override the default CSS in your theme.  Your theme's CSS files will load after the defaults, so it will take precedence.


Try the Backup and Migrate module:

  Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.


More on recommendable caching practices?

There is great info on views caching on this Q&A. It should answer your questions 1-3.
The 4th should probably be asked as a separate question.


The answer is that they are certainly not redundant.

It's true that one can accomplish the same end result using a  bash script that includes drush commands (at least the building part).  But, if what we are looking to do is to integrate our process into a CI framework like JenkinsCI, then using something like phing (ant or capistrano could be substituted here) is the way to go.

With phing we can break up the build process into distinct segments that can report back to Jenkins in an intelligent way.

So for example.  Say that as part of my build process I use drush to enable two modules, node and shouldfail.  Then the build should fail.  But if all we do is tell JenkinsCI to run the following shell command, JenkinsCI will say that the build PASSED:

drush --quiet --yes @staging en node shouldfail

Clearly that's not right.  However if instead we use ant or phing to define the same process, we can also add some fail logic that Jenkins understands, and therefore fail as it should.  The following phing build script tries to do the same thing as the former command, but fails as we expect it to:

<project name="staging" default="enable modules" description="Jenkins Staging Build">

    <target name="enable modules">
      <exec  command="drush --quiet --yes @staging en node shouldfail" error='error' checkreturn="true">
      </exec>
      <loadfile  property="en.error" file="error" />
      <if>
        <contains string="${en.error}" substring="warning" />
        <then>
          <property name="en.fail" value="Could not enable all modules" />
        </then>
      </if>
      <fail if="en.fail" message="${en.fail}" />
    </target>

</project>

BTW ant and phing are almost identical.  The advantage for PHP developers in using phing is that they can more comfortably extend phing.

As for Drupal development and drush being as good as it is, I don't see too much value in extending phing, and think that running exec tasks would suffice to create a smart build template.

Well, in order to answer my question I ended up investing the time to figure out phing.  It's actually pretty intuitive and it doesn't take too long to figure out.


Contact Forms - Change Recipient Address Dynamically - D8

The contact_storage module has a feature that allows you to create a list that include a key, value and e-mail and then the mail is sent to that.

You can either use that, or you can do it yourself in a similar way. You could use a term reference for example and have a field on your terms for the e-mail. The relevant code is in contact_storage_mail_alter():

$contact_message = $message['params']['contact_message'];
foreach ($contact_message->getFields() as $field) {
  if ($field->getFieldDefinition()->getType() === 'contact_storage_options_email') {
    // One of the Option email item fields. Add the recipient to the message.
    foreach ($field as $delta => $item) {
      $label = $item->value;
      // Obtain the email to add to the message, using the label.
      $email = $item->getFieldDefinition()->getSetting('allowed_values')[$label]['emails'];
      $message['to'] .= ',' . $email;
    }
  }
}

}


After I overrode a block template for a primary links, block-edit-link doesn't show anymore...?

Ok, tracked down the reason - every block requires to have a className of block:

<div id="block-menu-primary-links" class="block">
    <?php echo $block->content; ?>
</div>

Once I added this, contextual links regained the functionality. Still not sure where it comes from though, or if it's the only thing sufficient in all cases.


If the image is a CCK field, make sure the correct formatter has been selected for the image field and it has not been excluded from the RSS display at admin/content/node-type/YOUR-TYPE/display/rss.

If it's an attached image, check that it is displayed as part of teaser (or full body) and that Feed content is set to teaser (or Full text) at admin/content/rss-publishing.


As far as I know (anyone, correct me if I'm wrong!) this is not possible in the routing system. You can however add a path alias, and make "/ruta-de-acceso/a/contenido" an alias in the Spanish language for '/path/to/content'.

Now the problem with path aliases, compared to routes, it that they are considered content, not core or configuration. As a result there is (again: AFAIK) currently no way to export them and deploy them to a server. For a recent project, I solved that with some custom code in the .install file of a custom module. You can see the code in this Github gist: Drupal 8: Custom path aliases exported to code.


How do I show the total number of votes for "Rating" option in Fivestar?

The output for average votes is set in the fivestar.theme.inc file, which is located at fivestar/includes. You have to overwrite the function theme_fivestar_summary on line 248 (version 7.x-2.1). In order to do this, simply copy the whole function to your theme's template.php file and make the necessary adjustments. I've already done that for you in the code underneath:

function YOURTHEME_fivestar_summary($variables) {
  $microdata = $variables['microdata'];
  extract($variables, EXTR_SKIP);
  $output = '';
  $div_class = '';
  $average_rating_microdata = '';
  $rating_count_microdata = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= '' . t('Your rating: !stars', array('!stars' => $user_rating ? $user_stars : t('None'))) . '';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    if (isset($user_rating)) {
      $div_class = 'combo';
    }
    else {
      $div_class = isset($votes) ? 'average-count' : 'average';
    }

    $average_stars = round(($average_rating * $stars) / 100, 1);
    if (!empty($microdata['average_rating']['#attributes'])) {
      $average_rating_microdata = drupal_attributes($microdata['average_rating']['#attributes']);
    }
    $output .= '' . t('!stars',
      array('!stars' => "$average_stars/5")) . '';
  }

  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = ''. t('No votes yet') .'';
    }
    else {
      if (!empty($microdata['rating_count']['#attributes'])) {
        $rating_count_microdata = drupal_attributes($microdata['rating_count']['#attributes']);
      }
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '' . intval($votes) . ''));
      if (isset($user_rating) || isset($average_rating)) {
        $output .= ' (' . $votes_str . ')';
      }
      else {
        $output .= ' ' . $votes_str . '';
      }
    }
  }

  $output = '
' . $output . '
';
  return $output;
}


{{ language }} variable not available in block template

You can solve this with a preprocess hook:

mytheme_preprocess_block(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['language'] = $language;
}

The language variable will then be available in your block template as it is in the page one.


How to restrict access to page by URL depending on which page you came from

depending on which page you came from

per se is impossible, because people can easily forge their referer header. What you need to do in your specific, form related situation is to:

In form submit handler, set session variable, like $_SESSION['acces_valid_to'] = time() + 3600 - this will store time one hour into future for specific user.
In access hook, for example hook_node_access if we are talking about nodes, test if this variable is set, and if it is still valid. If not, send 403 Forbidden.
If you want, you can unset it after any page view, that will make sure your user will view his page only once.

If you will have specific problems with any of these steps, ask next, more specific question.


How to translate products with Drupal commerce module?

Entity translation allows to to translate products. To be able to translate the title, you will need to replace it with a field and use that instead. There is the Title project to help with that, but I haven't yet tried if it is compatible with Commerce products.


Allow markup inside drupal 8 Link function

Use the Markup class:

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;

$url = Url::fromUri('http://www.example.com');
$linkText = 'My link <br> containing tags';
$linkMarkup = Markup::create($linkText);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();


How do I select the most recently created entity item in Rules

If one 'price entity' is created based on the daily prices per day, you could use the 'after saving new content' action, restricted to your price entity type (provided you entity can be seen as a node.)  Then, calculate the values for your products at that time, using the values within the newly created price entity.

Otherwise, you could put a 'last entry' field on you entity and use another rule to set this field to 'true' on a newly created entity and 'false' on all other entities.  Then, set a condition on the original rule that filters entities based on this field.


How do I insert a   tag inside the   tag on my main menu

Rather than building the anchor tag, and passing the result of url() to check_plain(), you should call l(), which builds the tag for you.
Remember to set $options['html'] to TRUE (where $options is the last parameter passed to l()), when the string you pass as first argument to l() contains HTML tags; by default the function assumes $options['html'] is FALSE.


How to discover events for event dispatcher

You can simply use the Drupal console.

List all the events that could be debugged:

drupal debug:event

drupal dev

Show the information for the specific event, for example "commerce_order.commerce_order.update":

drupal dev commerce_order.commerce_order.update


Show products based on the location (country) of the visiting user

According to the countries module page:

  Views Integration

  The 2.x branch supports View operations. The views filter is supported via 'select list' in the following way:

  Create a Relationship (under 'Advanced') to 'Field: Country (field-country)' ('Country' being the field label, 'field_country' the field name).

  The field is shown twice in the list

  Field: Country

  Field: Country (field-country)

  The first one is not working. This broken relationship has been removed in the latest dev version.

  Add a Field/Filter/Sort of type 'Countries: xyz' with the new relationship.

Also, you might consider Nick's answer for hiding the product "Add to cart" based on country.