Using hierarchical select to display a particular section of content

As far as drupal 6 views 6.x is concerned. You need to ensure you are saving the taxonomy heirarchy as additional terms in the database. Ensure also you are saving the entire lineage from the view. Finally Add a filter with Taxonomy: Term ID and leave this using default values.

(1) Ensuring you are saving the taxonomy heirarchy as additional terms:

-edit your "Results" content type, go to manage fields and edit the heirarchical field. Somewhere on this page you will see 'Save values additionally to the core taxonomy system (into the 'term_node' table).'

(2) Ensure you are saving the entire lineage:

-on the same page as above follow the link to oonfigure this heirarchical select on a separate window.. 'Due to limitations of CCK, there is a separate form to configure this Hierarchical Select widget's settings'

(3) Go back to views and add that filter I mentioned above.


The name of your template block--sidebar_first.tpl.php is correct. Clear the cache to override the template.
OR
Put this function in template.php and clear the cache. You will get the suggested template for your block.

On suggested name replace double underscore with double dash for your tpl file, and clear the cache.

function THEMENAME_preprocess_block(&$variables) {
    print_r($variables['theme_hook_suggestions']);
}


Using the AWS PHP SDK version 1.6.2 instead of the latest solved the problem. sites/all/libraries/awssdk/sdk.class.php does not apply for at least version 2.1.1.


How can I access untranslated field values in a translated view row?

It seems not to be possible to access untranslated field values in a rewrite token pattern for text fields. You can get the untranslated value from the field in a template by using the row entity and getting the untranslated entity {{ row._entity.getuntranslated().field_dossier_status.value|clean_class }}, but using templates in Views I would avoid if possible. So this may be a better approach:

Static

Supposed that there is a limited number of CSS classes, in most cases CSS is static, use a field field_dossier_status of the type list (text) with a allowed values list:

dossier-status-class-1| Dossier Status Class 1
dossier-status-class-2| Dossier Status Class 2
...

You can translate the second part of the allowed values in Translate content fields.

Now if you access the raw value from this list field in a Views token pattern __value you get the untranslated first part

and this result:

Dynamic

If the CSS is dynamic you can use a dynamic method for the allowed values, see Dynamic Default and Allowed Values for List Fields in Drupal 8, which btw. gave me the initial idea for this answer to the question you asked some days ago. You could even parse the dynamic CSS for the classes it provides and fill them in the allowed values list.


How to use Drush for Particular Project?

Goto each project folder to run drush command as project wise.
If you are using multi-site goto the project folder under sites directory and execute your drush command.


Is it possible to redirect after "pushing" a file to the user?

As far as I know, that is not possible. You can either send content (in your case a file), or redirect. Not both. This is a limitation of the HTTP protocol


What is the proper way to show a visitor an error?

Have your POST code inside a validate function, that runs last, after all other validation has passed.

Ex: $form['submit']['#validate'][] = 'mymodule_post_to_api';

and use form_set_error('form', 'Failed to connect to API, try again later'); inside your catch.

For POST's errors, don't wait for someone to report. Programmatically make Drupal send yourself or whomever maintains the code, an e-mail with the form fields & error details.

See How to programmatically send an email?


Facet block is not getting display on search page created by view

It's working now. There was an issue with context which was overriding block layout property and that's the reason facet block was not rendering on the page.

Summary: If you are using context on the page then block layout property will not work for rendering the block. So need to configure block in the context.


When and where is calling menu_link_save safe and appropriate?

Yes, hook_enable() sounds correct.

To find examples, on way is look at what's using the function on drupalcontrib.org.  That points to menu_enable(), which is even a core function.


How to filter URLs for embedded IMG tags?

If you mean disallowing <img> elements where the src isn't on a whitelist, then you can make a custom input filter.

The first step is to make a hook_filter_info to declare your input filter.  You would then make a callback function that does the work.

The callback would do some regex matching, looking for <img> elements and pulling out the src attributes.  Then regex match the src against your whitelisted domains.  If everything is OK, let the image pass, else replace it with whitespace.

Finally, make a hook_menu which sets up a settings page so you can enter your whitelist via the UI.

Once you have done all of this, you add your filter to the appropriate input formats.  When the page gets rendered out, the filter will be applied.

All of this is rather easy.  The heavy listing is the <img> regex, but I suspect 15 min of googling will find some good ones.


3 domain names for one instance of Drupal 8

I am doing something very similar to migrate some D5, D6 and D7 sites to one D8 site.
Currently I have this solution:

(1) Have one master domain that serves all content (i.e. proreos.de).

(2) Have some paths (routes) that serve special content for different domains (i.e. /asde/* -> serve content for anwalt-seiten.de/*)

(3) Have ThemeNegotiatiors (ThemeNegotiatorInterface) watching for that special routes to set the 'other' theme (like asde-theme).

(4) Have inverse proxies (apache2 mod_proxy) on the "other" domains that deliver the subcontent from the master domain (i.e. anwalt-seiten.de/index.html -> proreos.de/asde/index.html)

The advantage I hope to have from this approach:

(a) Have all data in one place (proreos)

(b) Have presentation separated from model (special themes)

(c) Have scalability (by inverse proxies).

But I don't have real experience cause I am still developing. Hope it helps anyway.


how to use EntityFieldQuery by language?

$language variable  is better to be in the function as:

 function getListNode(){
   global $language;
   $query = new EntityFieldQuery();
   $query->entityCondition('entity_type', 'node', '=')
         ->entityCondition('bundle', 'content_type', '=')
         ->propertyCondition('language', $language->language, '=');
   $nids = $query->execute();
   return entity_load('node', array_keys($nids['node']));
 }

it works for me
good luck


How can I stop a message (displayed via drupal_set_message()) from being printed?

I admit to not having used it before but the Disable Messages module looks like it would do the trick:

  Gives a site owner options to disable specific messages shown to end users.

  Features:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

I think a regular expression would probably be best for this particular message (because of the replacement done using t()); something like this should work:

^Location taxonomize: [0-9]+ new terms saved$


I usually avoid calling drupal_add_js() and use the #attached property of the render array. The advantage of using #attached is that you don't need to implement additional hooks, the js is only added when needed, and (as I've been told) it works better with caching. Your code would look something like this:

function myid_print_menu() {
  $items = array();
  $items['myid_print/table_pager'] = array(
    'title' => 'Table Pager',
    'page callback' => 'myid_print_table_pager',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function myid_print_table_pager() {
  $build = array(
    '#markup' => 'Hello world!',
    '#attached' => array(
      'js' => array(
        array(
          'data' => '$(document).ready(function () { alert("Hello!"); });',
          'type' => 'inline',
        ),
      ),
    ),
  );
  return $build;
}

Disclaimer: untested code, please let me know if it doesn't work as expected.


It seems file_transfer was removed in favor of BinaryFileResponse.

  Symfony has a Symfony\Component\HttpFoundation\BinaryFileResponse
  class that can be used to deliver files through PHP to the client. It
  also supports X-Sendfile and X-Accel-Mapping via
  BinaryFileResponse::trustXSendfileTypeHeader().

  file_transfer() has been dropped in favor of that.

  Drupal 7:

<?php return file_transfer($uri, $headers); ?>

  Drupal 8:

<?php
use Symfony\Component\HttpFoundation\BinaryFileResponse; ...
return new BinaryFileResponse($uri, 200, $headers);
?>

When looking for exact replacements and changes in D8, check the relevant api.drupal.org doc page and change records. I find it really comprehensive and has almost every change.

On a side note, I would reevaluate the module code if it happens for you to file_trasnfer() a file. Entire menu system was replaced with Symfony components and I think the odds are, you are still using the old system if it happens to file_transfer() or use some request-response thing in the site.


How can I override certain breadcrumb segments?

The default breadcrumb builder is defined in the system services file and has the priority 0:

system.services.yml

  system.breadcrumb.default:
    class: Drupal\system\PathBasedBreadcrumbBuilder
    arguments: ['@router.request_context', '@access_manager', '@router', '@path_processor_manager', '@config.factory',  '@title_resolver', '@current_user', '@path.current']
    tags:
      - { name: breadcrumb_builder, priority: 0 }

If you want to turn off the default breadcrumb builder you define one with a higher priority. This is an example for taxonomy terms:

taxonomy.services.yml

services:
  taxonomy_term.breadcrumb:
    class: Drupal\taxonomy\TermBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 1002 }

With the method applies() you choose for which routes the breadcrumb builder should be used:

TermBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
      && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
  }

The breadcrumb manager checks all applies() methods, starting with the highest priority, until it reaches the default breadcrumb builder, which applies for all routes:

PathBasedBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return TRUE;
  }


How can I get the taxonomy title from its machine name? (drupal 7)

The correct way to obtain a Label of a taxonomy vocabulary would be something like this:

$vocabulary = taxonomy_vocabulary_machine_name_load('machine_name');
echo check_plain($vocabulary->name);

However, looking at your screenshot, I guess you actually want to have the field Label of the taxonomy reference field.

In that case your question is a duplicate of How do I get a field label by the field name?


Drupal 7 inserting space before inline HTML tags upon rendering

If you use "Full HTML" text input rather than "Filtered HTML", then Drupal won't parse or modify your markup.


Edit/View Tab in Region other than Content

Have a look at the Delta Blocks module which is included in omega. It moves these tabs (and other things like Messages) into blocks.


Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page

You may try to test a new module called Commerce Drush which has the following syntax:

drush commerce-order-add 1
drush --user=admin commerce-order-add MY_SKU123

Manual solution

For creating an order programatically in Commerce, you can use the following code (it works with drush as well, e.g. drush -vd -u "$1" scr order_code-7.php).
Please note that commerce_payment_example module is required.

<?php

  if (!function_exists('drush_print')) {
    function drush_print ($text) {
      print $text . "\n";
    }
  }

  $is_cli = php_sapi_name() === 'cli';

  global $user;

  // Add the product to the cart
  $product_id = 5;
  $quantity = 1;

  if ($is_cli) {
    drush_print('Creating new order for ' . $quantity . ' item(s) of product ' . $product_id . '...');
  }

  // Create the new order in checkout; you might also check first to
  // see if your user already has an order to use instead of a new one.
  $order = commerce_order_new($user->uid, 'checkout_checkout');

  // Save the order to get its ID.
  commerce_order_save($order);

  if ($is_cli) {
    drush_print('Order created. Commerce order id is now ' . $order->order_id);
    drush_print('Searching product ' . $product_id . ' in a Commerce system...');
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    if ($is_cli) {
      drush_print('  Cannot match given product id with a Commerce product id.');
    }

    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  if ($is_cli) {
    drush_print('  Found a Commerce product ' . $product->product_id . '.');
  }

  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  if ($is_cli) {
    drush_print('  Added product to the cart.');
  }

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  if ($is_cli) {
    drush_print('Saving order...');
  }

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

  // Redirect to the order's checkout form. Obviously, if this were a
  // form submit handler, you'd just set $form_state['redirect'].

  if ($is_cli) {
    drush_print('Checking out the order...');
  }

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);
  }

  if ($is_cli) {
    drush_print("Marking order as completed...");
  }

  commerce_order_status_update($order, 'completed');

  if ($is_cli) {
    drush_print("\nDone.");
  }

Note: As suggested in the comment, if you got error about payment method is unknown while saving the order, make sure you've specified it, e.g.

$order->data['payment_method'] = 'commerce_payment_example|commerce_payment_commerce_payment_example';
commerce_order_save($order);


views_get_view_result in template.php? I want global variables using view results

The theme_preprocess() function is jused to preprocess EVERY SINGLE template. What you do by now: for EVERY SINGLE template you run a view (I am not sure if it gets chached during to a single page request - so it may be that you run the view a hundred times during one page request). This may hit your servers capabilities.

1.) It is bad practice to run any views in the theme layer. Please assure that on the theme level no data alteration or processing is done any more no matter if done in a preprocess function in template.php or - even worst - in a tpl-file.

2.) Please consider a better place where to add this information by views. Where exactly do you want to add the classes? Which element?


Trying to programmatically alter the id of an exposed filter in views

I think you might be using the wrong tool for the job. It sounds like this is a theming problem, not a views data structure problem (which would use something like hook_views_pre_view().

You can override the template views-exposed-form.tpl.php to override the markup of the exposed form & the preprocess function template_preprocess_views_exposed_form() to override the markup form widgets:

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // @TODO: alter markup of $vars['widgets']['filter-MYFILTER']->widget.
}

Alternatively, the views UI provides a means to change the id element by changing the Filter identifier underneath the More fieldset which also changes the URL query parameter used as well.


View by Taxonomy terms hide empty terms unless they have children

Your friend is:

  Taxonomy term: Representative node

This is a  duplicate, by the way.


I think what you are looking for is contextual filters.

You should add a contextual filter to your view and set the path to %.
What kind of filter you should use depends on if Car a taxonomy term or a node and so on.

In the following example I have set my path to stores/% and a store is a node with a associated taxonomy term. I can display stores marked with a specific term by going to http://example.com/stores/england or http://example.com/stores/sweden.

You find the contextual filters under the advanced tab.

Here are the settings for the filter. Arguments from the url will be transformed into Term ID.

* EDIT * Perhaps this link will help you Views contextual filters taxonomy name


AJAX request failing each time I try to invoke php function from module

Routes don't have leading slashes:

$items['foo/ajax/tag'] = array(

Clear caches, and assuming the callback function exists and writes something to the buffer, it'll start working.


Well, this is embarrassing... By blindly following the guide I forgot to add <?php to the beginning of ExampleController.php. All these new .yml-files made me forget all about "normal" PHP I guess. Problem solved.


Altering views exposed form - Adding select list separator causes error

The key values in the field are strings but in your altered version they are numbers. Change 1 to China etc.


First of all, when you search for translations they are case sensitive. don't include aditional spaces, it has to be exact, but it can be partial.
If one translation was previously made and the same word appears in many places it will list it, but what applies is the first translation made (sorted by time)
You have to make sure that your Log Out is really a tranlation

in my case it appears in chain: /admin/settings/language as Log out @username, so if I translate this, it works in the other languages
there is another Log out in the chain with the same name...so be careful


In node reference field settings page (content type -> manage fields -> name of field) in "global settings area" set "number of values" to 3.

Thats it.
Hope this helps.


Make autocomplete window appear above accordion pane

Doh - I was so close.

The answer is to simply copy the function you want to override to your own custom JS file but make sure to wrap it in a document ready function!


I just got Advanced Poll with the sandbox module Advanced Poll Field Image to do the trick!


It seems that this is not implemented yet. Related issue is here.

An alternative would be to use hook_requirements() in your module's .install file. You can check here if the conflicting module is present during the installation process and prevent the system from installing the module.

Here's example code that would go in your module's .install file:

/**
 * Implements hook_requirements().
 */
function YOUR_MODULE_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    // Called during regular use of the website.
    case 'runtime':
    // Called while the update.php is being executed.
    case 'update':
      // Do not allow administrators to install the module if conflicting module
      // is already installed.
      //
      // You can move this code to any other phase as well.
      if (\Drupal::moduleHandler()->moduleExists('ARCH_ENEMY_OF_YOUR_MODULE')) {
        $requirements[] = [
          'title' => t('Name of your module'),
          'value' => t('Arch enemy module'),
          'description' => t('Explain that administrators need to uninstall the module before proceeding.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

You can see a working example of hook_requirements() in my Drupal 8 boilerplate repo on Github.

Hope this helps.


Expose a custom view filter based on custom field in another node

Thanks to the clues provided by Geoff in a comment, I found the answer.
My mistake, (doing too much work), was  to create my own foreign key, test_set_id.   Drupal uses node_reference fields for such joins. Using node reference, associated content can be directly accessed after adding the relationship in the set-up view screen, without any code.
I also ended up creating an additional master parent content type, to hold some generic test_set information, and to give the child nodes something to point to.


Check which cache is relevant (e.g. cache_content, cache_views_data) for this content and clear this cache explicitly. If you call cache_clear_all() without parameters you "only" clear the page and block cache. Take a look at the code of cache_clear_all() to see the details.


Give permissions to user of the same role

You can used module content access, he does that easily.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type

Or you have node access which add a tab on each node to control permission for this node (you can configure role or user) I never really used it because there's no very stable version for d7.


How to link two content types from each other

You can save it to a single table by creating one entity reference field and invoking it on both content types.


How can I get the responsive image style id from a FileFieldItemList

This setting is not a field setting. Because a field can be part of different displays. You have to look for this setting in a view mode. For example if you configure the image field of the article with a responsive image style, your view mode would contain something like this:

core.entity_view_display.node.article.default:
  content:
    field_image:
      type: responsive_image
      weight: 0
      settings:
        responsive_image_style: *responsive_image_style_id*


How do I set filters to reset automatically on new search?

To fix this I created a new block and inserted this code:
<script>
    //unchecks all checkboxes
    function clearCheckBoxes(){
        var uncheck=document.getElementsByTagName('input');
                    for(var i=0;i<uncheck.length;i++){
                        if(uncheck[i].type=='checkbox'){
                            uncheck[i].checked=false;
                        }
                    }
    }
    //this function makes sure that new searches aren't hindered by filters set for previous searches.
    jQuery(function(){
        if(typeof(Storage) !== "undefined"){
            //retrieve what's in search box and remove whitespace
            var currentsearch = document.getElementById("searchbar").value;
            currentsearch = currentsearch.trim();

            //if search box has a value that differs from the session storage search value then filter checkboxes are unchecked and url is sanitized of categories
            if (currentsearch.length > 0){
                if (sessionStorage.getItem("squery")) {
                    let oldsearch = sessionStorage.getItem("squery");
                    if(currentsearch !== oldsearch){
                        clearCheckBoxes();
                        location.pathname = 'simplepathname';
                    }
                }
                // set session storage search value equal to current value
                sessionStorage.setItem("squery", currentsearch);
            }
        }
    });
</script>


Forcing OpenID login instead of Drupal own authentication

I simple solution would be to alter the login form to remove the username and password fields.

Here is some sample code to get you started:

/**
 * Alter the login form page
 */
function MYMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
  _MYMODULE_alter_login_form($form);
}

/**
 * Alter the login form block
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  _MYMODULE_alter_login_form($form);
}

/**
 * Function to change a bunch of things in the user_login form (both the block
 * and login screen).
 */
function _MYMODULE_alter_login_form(&$form) {
  unset($form['name']);
  unset($form['pass']);
}

Unfortunately I don't know of any contrib modules that will do this for you; the good news is that I have wrote 95% of the module for you. ;)


1,
in file composer.json add

"require": {
"drupal/core": "~8.5"
}

Remove line

"replace": {
    "drupal/core": "^8.5"
}

remote folder vendor
remove file composer.log

alter run

composer update --with-dependencies


First, define a library in your theme that links to the font.

[THEME].libraries.yml:

fonts:
  css:
    theme:
      # Do not include http: or https.
      # Should start with a double slash.
      //fonts.googleapis.com/css?family=Source+Sans+Pro: { type: external }

This library is loaded by adding it to the theme's [THEME].info.yml file:

libraries:
  - [THEME]/fonts


Where is the button that will translate all countries from Countries module in all my 10 languages?

For large tasks like this consider automating. and not just using "Drupal". Can you make a CSV file of your countries list? Then write a small Bash, PHP, Ruby or any script to ask Google for the translation(s) 1 by 1. Then given your new big CSV file of English + 10 other columns of languages. Loop through the file rows and do a database insert to Drupal to create the translations ...

From the final CSV of country terms translated I would then try to use the Feeds or Migrate module to import them to Drupal, if I didnt want to write much code.


cannot see tabs for manage fields etc with administrative toolbars add content bar

It's an incompatibility between administration toolbar and your theme, and maybe overlay if you are using it. No one placed it like that on purpose, it's just a clash between 3 sets of CSS each written without knowing how other will look.

You can try one or many of the following:

Use Administration menu instead of toolbar.
Use Shiny as admin theme
Toggle overlay - if it's on, maybe without it it'll be OK? If it's off, maybe it'll help?
Create a subtheme and deliver CSS that will position stuff the way it should be for your particular case. Firebug or Chrome are good for fast prototyping your fix.


The only good way is to use the 'add a class'-option in views. That allows for maximum flexibility and should not break if something in the view changes. (block-view-id-something can break when numbers or names change).

One you have added a css class to the field, something like horizontal. Then you can define it in your theme file css with .horizontal {...}.

But since themes can update their css, overwriting your changes, you are even better off using an extra stylesheet in your themes folder. Give it any name you want, add the .horizontal {...} lines. Then open the *.info file in your theme and add stylesheets[all][] = <stylename>.css.

If it might break after a style update, all you have to do is add this line again.


Is there any way to use views contextual filters in block configuration?

The contextual filter is not possible to be exposed on a block. It is only possible with filter criteria.

The other posibility is use a taxonomy term view and use the module Taxonomy menu or Taxonomy menu block to show a list of taxonomy terms on a block.


Get user register form fields in edit profile form page

You can edit all forms in drupal using hook_form_FORM_ID_alter

So The only thing you need is the FORM_ID , to get that you can open any desired form , then using firebug or some tool like that you can recognize the ID of form.

in your special case the form ID of user edit form is : "user_profile_form" , so you can create a custom module and implement YOURMODULE_form_user_profile_form_alter()

inside print elements as you desire.


I would suggest trying the Chosen module. It provides autocomplete functionality with multiselect capability. Using the multiselect field you can hold ctrl while selecting to keep the list open. Here's a demo.


How to keep the size of the database reduced?

Don't dump session, cache_*, watchdog table content (make sure to keep the structure).

For watchdog there's syslog replacement.

If you don't need the access logging in Drupal disable that module and dump that table as well.

For huge content driven websites with lots of edits (and revisions) clearing the revision tables from time to time might help too. (e.g. with node revision delete).


Views - How to suppress ajax errors without leaving a log entry in browser

This problem is solved by the Prevent JS Alerts module


When the Bulk Export module (part of the Chaos Tools Suite module) is enabled, it exposes a page (admin/structure/bulk-export) where views can be exported.

What you need to do is selecting the views you want to export, enter the short name of the module that will contain the views, and click on the "Export" button.

The page that will appear next contains three text area fields (<module name> is the short name you entered in the previous page):

One is for the content to place in <module name>.info
The second is the content to place in <module name>.module
The last is the content to place in <module name>.views_default.inc

The differences I can see between the code the module tells me to use, and the one you are showing are:

The implementation of hook_views_api() is the following.

/**
 * Implements hook_views_api().
 */
function sitetheme_views_api($module, $api) {
  if ($module == 'views' && $api == 'views_default') {
    return array('version' => 2);
  }
}

The implementation of hook_views_default_views() is the following.

/**
 * Implements hook_views_default_views().
 */
function sitetheme_views_default_views() {
  $views = array();

  $view = new view();

  // …

  return $views;
}

$views is an array of objects of the view class.


How to Integrate Non-Gregorian Calendars in Calendar Module?

You can use the latest development snapshot of the Calendar Systems module. It works fine.


"Fetch entity by property" for users that share terms with new node

I think the reason for this is that the 'Value' property is asking what you want to match in what you are looking for, basically in pseudo terms, what you've got above is:

Find the Entities of type: User
Where the Entity's property: RFP Category
Is equal to: The author of the node's Categories

This is where your selection falls down, because you're trying to search for a set of answers where the data matches an Array. If the node you create can only have 1 term entry (not multiple), I would use the action 'Add a Variable' and set it to the taxonomy term you've created on your node, something like

Add a Variable > Taxonomy Term > [node:RFP-Category] I'm guessing to your setup

This will create a new token for you which contains the Taxonomy term you're searching for. Then in your Entity query, you can use this as your value property

eg

Find the Entities of type: User
Where the Entity's property: RFP Category
Is equal to: [Your New Token]

If your RFP category has more than 1 or unlimited values, you will have to create a loop of the categories on the node first, then use 'Add a variable' and carry on with the same method


What's overriding my local_settings.php?

Enabling the Devel module fixed the issue. Ultimately, I think the issue is specific to the Mail System module and the unusual way it handles settings and defaults.


To answer myself here.

There is a module Views PDF that does the job. Not sure how i missed it earlier...


I am solving this problem by disabling Quiz and using only Webform, and writing a custom module that does the following:

use hook_form_alter to catch webform submissions
compare them to fields in an answer key

answer keys are of content type 'answer key'
they have a node reference field that references a webform

calculate percent that match
display a message depending on score

if 80% < x < 100% display answers
if 80% < x return that the quiz was passed
if 80% > x tell them they failed and redirect them back to the quiz page to re-take the test.


for me that submits the node:

(function (window, Drupal, $) {
  Drupal.behaviors.drafter = {
    attach: function attach(context) {
      var button = $('#edit-submit');
      var newbutton = button.clone().prop('id', 'edit-submit-drafter');
      var confirmationDialog = Drupal.dialog('#drafter-elements', {
        resizable: false,
        closeOnEscape: false,
        create: function () {
          $(this).append(newbutton);
        },
        beforeClose: false,
        close: function (event) {
          $(event.target).remove();
        }
      });
      newbutton.click(function (e) {
        button.click();
        confirmationDialog.close();
        return true;
      });
      button.click(function () {
        if (!confirmationDialog.open) {
          confirmationDialog.showModal();
          return false;
        }
      });
    }
  }
})(window, Drupal, jQuery);


use conditional fields to change a label on a field

I answered this similar D7 question How to change a fields label name based on another fields value?

(function ($) {

   (function Forever(){ // we create a function called Forever

   var grabselectedtext = $('#edit-field-test-und option:checked').text();
   // this grabs the text of the field you want to depend on.

     $('label').each(function(){
      if ($(this).attr('for') == 'edit-body-und-0-value') {

         if (grabselectedtext != '- None -') {
           $(this).text(grabselectedtext);
         } else {
             $(this).text('Field Two');
           }
         }

     });

   setTimeout(Forever, 1);

   })();

})(jQuery);

You want to attach this JS code to a library. Then attach the library via a hook_form_alter and check for form ID and content type.


You can place the favicon.ico in your theme folder (at the same level as your_theme.info) and it will be used automatically.

Works for Drupal 6, 7 & 8.

Note: The favicon is heavily cached by some browsers, you may need to go to extra lengths to see the new one.


Can't set arguments to a view for displaying all data

$args is an array that expects each field's contextual values to be passed in separately.

i think $args = array($journee, "all", $produit); ought to work.

you should only concatenate arguments into a string if its a multi-value single field situation and then I believe you join with '+' not commas.

EDIT

I missed what you were asking, if you have a contextual filter that is optional inside the view you can configure what happens when no value is provided (pick "display all results").

then when calling the view

as far as skipping an argument 'all' - the easiest way would be to move the order of the contextual filters so that the one that is allowed to be "empty" is last.

then instead of calling

$view = views_embed_view('export_emargement','page_1',$journee,$region,$produit);

call

$view = views_embed_view('export_emargement', 'page_1', $journee, $produit, $region);

or

$view = views_embed_view('export_emargement', 'page_1', $journee, $produit);

depending on if the user has selected a region


Drupal 7 "Panel Nodes" Content Pane Contextual Filter

I urge you not to use Panel Nodes. Panel Nodes are being deprecated in favor of Panelizer. The largest hurdle to getting rid of them is that I need to complete the upgrade path. I suggest that you

Move to Panelizer, following the upgrade path issue if you already have Panel Nodes.
If necessary, repost a new question with regard to Panelizer.


define custom jquery event to use in ajax form

The solution for your question is not handled compelety by back-end of drupal.

By default drupal ajax not support customized event
You can acheive your means by jquery and ajax(non-drupal ajax)
Something like this

For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'acess callback' => TURE, //you can set it with your permission
      );
  return $items;
   }

and in yourhalderjust need pass a block

function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);

}

and in your clientside get it with something like this

  $('#yourelement').change(function() {
    if( checkfor your means) {
         $.ajax({
                       type: "POST",
                       url: 'youruniqepath',
                       //data: {}, you can also pass block name and act more dynamicly
                      success: function (data){
                          $('#yourplace').html(data);
                      },});
         }

});


Did you try the Content Profile Tokens module? It is a sub-module of content profile 1.x.

Your content profile title could be a node title or a CCK field; the token [title] or [field_titlefieldname-raw] will provide the value you expect.


Print node title in custom block module twig file

return array_map(function($node) {
  return $node->label();
}, $nodes);

or if you want links:

return array_map(function($node) {
  return $node->toLink()->toString();
}, $nodes);


How to import config and content using config import and hook_update_N

Don't add content using hook_update_N() there's not really anyway to make that work if the entity types are in config. What you can do is just use something like default content and add you own step to config import to look to see if any installed modules provide default content and create that.


How to change the node breadcrum name & there url inside in drupal 7?

You can change the appearance of the breadcrumb using theme_breadcrumb function in your template.php
Here is a page with several snippets of example code you can use to get some inspiration on how you should write your code.


How to solve a situation where two or more routes with different controllers point to the same path ?

Drupal uses always the most specific route. If you define for the path /node/1

mymodule.routing.yml

route.for.node.1:
  path: '/node/1'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::content'
    _title: 'Override of node 1'
  requirements:
    _permission: 'access content'

then the custom controller \Drupal\mymodule\Controller\MyController::content is used instead of the node controller \Drupal\node\Controller\NodeViewController::view.

But I don't understand "Or Vice versa". For that you would have to remove the more specific route, so that the less specific node route for /node/{node} can take over again.

If you want a dynamic solution, you can route all nodes to your custom controller and then decide in this controller what to do, display the node or your own content.

For this you can extend the NodeViewController class and define a new view() function, in which you call parent::view() for the original node content. Then replace the class in a route subscriber:

$route->setDefault('_controller', '\Drupal\mymodule\Controller\MyController::view');

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


Get taxonomy terms page based on exposed filters value

It will be easier if you will use just one vocabulary. Smt like this:

English
- Rock
- Pop
- etc.
Spanish
- Pop
- Rock
- etc.

Then you can use hierarchical_select module to filter exposed lists automatically.

If you can't change vocabulary structure, you should use hook_form_alter() ...


Add tid or name as a class to each item of a taxonomy term

You can modify the output of any field with:

drupal standard field tlps

Possible override templates are:

field.tpl.php

field--content-type.tpl.php

field--field-name--content-type.tpl.php

field--field-type.tpl.php

field--field-name.tpl.php
So according to your specification in comment
"product_display"  and the reference term field is "field_product_specs"
your custom tpl file name should be field--field-product-specs--product-display.tpl.php

OR

Fences

Fences is a an easy-to-use tool to specify an HTML element for each
field. This element choice will propagate everywhere the field is
used, such as teasers, RSS feeds and Views. You don't have to keep
re-configuring the same HTML element over and over again every time
you display the field.


ASAF module redirects comment form to system/ajax#comment-cid after submission

You need to look in to issues of that module I found there one important information which help on this issue. https://www.drupal.org/node/2277137


How to grab the values of field collection items in a template file?

It turned out that I was making things too complicated: the theming can be achieved with CSS by using the default classes of the field collection. Hopefully, my code underneath can be helpful for others too.

.item-list li {
  list-style: none;
}

.field-name-field-plaats:before {
  content: "@ ";
}

.field-name-field-plaats {
  display: inline;
}

.field-items {
  display: inline-block;
}

.field-name-field-aantal:before {
  content: " (";
}

.field-name-field-aantal:after {
  content: "x)";
}

.field-name-field-aantal {
  display: inline;
}


Insert several lines in field collection programmatically

First be sure that that field in your field collection field setting accept multi value then try save your item with

  $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,);

and finally be something like

if(!empty($intervenant)) {

    // you should have $node here
      $field_collection_item = NULL;
      $field_collection_item = entity_create('field_collection_item', array('field_name' => ''field__doc_fc_intervenant_tab '));
      $field_collection_item->setHostEntity('node', $node);
      $field_collection_item->save(TRUE);
          foreach ($intervenant as $val) {
             if($val != null) {
      $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
        'revision_id' => $field_collection_item->revision_id,);
}
}
    $fieldcollection->save();
}


Webform twig template causes "the form has become outdated" error

The issue was I was not rendering out the {{ element.form_token }} element. I added that element and it works:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.form_token }}
  {{ element.actions }}

{{ title_suffix }}

</form>

This works which is why I submitted it as an answer. I do think it could be better written. This would require effectively using the twig 'without' filter which I can't get to work. I am creating a separate post about that as I feel they are different topics. The basic idea is I shouldn't have to fish or remember to render all the items that make up a drupal form such as form_build_id, form_id, form_token, or actions. I should render the entire element array and hide the fields I want to wrap in markup. Then I can explicitly render those fields. Something like:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element|without('elements) }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

{{ title_suffix }}

</form>

But that currently renders my_element_01 and my_element_02 twice.


Skip updating certain themes/modules on composer update

If you want to pin a version of a module you could do so by running this in your console:
composer require drupal/module_name:1.1

In case you have many modules also see my contributed module:
Composer Update Assistent
This module generates a commando to update all modules to the recommended version which can be copied to your console.


Paragraphs Collection (Behavior plugins) vs. Field Group

As you stated, the Paragraphs Collection module should be considered Experimental, and not used in Production environments:

  THIS PROJECT IS EXPERIMENTAL. DO NOT USE IT IN PRODUCTION PROJECTS. THERE IS NO UPGRADE PATH UNTIL A BETA RELEASE.

This is especially true if your plan is to use this on multiple sites, with the life expectancy of 5 years.

The common method in Drupal 7, and currently in Drupal 8 is your first point, to use fields for settings and use preprocesses and/or twig templates to turn those fields into classes/markup you want.

For re-usability, you will either want to use the Features module and a base theme, or create your own module that will handle the config, templates and styling.  I took that route with the Bootstrap Paragraphs module.


Help with view styling - template/css/whatever

To show fields you have to use views_php where you can check

if ($row->field_hide_track) {
    print $row->field_track_icon;
}
For filters you are on the right track you are showing terms as checkboxes you just have to style labels of the field just like DrupalCon Denver's site something like this.

views-exposed-form-schedule-page .form-item-edit-track-1 label, #views-exposed-form-schedule-page-1 .form-item-edit-track-1 label, #views-exposed-form-schedule-page-2 .form-item-edit-track-1 label {

background: url(/sites/all/themes/denver2012/images/track-1.png) 0 0 no-repeat;
}


Selecting from a column in a joined table in Views

I solved my own issue.

I needed to expose the joined table to views as well. So on top of setting up $data['students'], I also needed to set up $data['student_names'], with a join back to the original table. Here is my hook_views_data() in its entirity:

$data['student_names']['table'] = [
  'group' => t('Student'),
  'base' => [
    'field' => 'sid',
    'title' => t('Student'),
  ],
  'join' => [
    'students' => [
      'left_field' => 'sid',
      'field' => 'sid',
      'type' => 'inner',
    ],
  ],
];

$data['student_names']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
    'click sortable' => TRUE,
  ],
];

return $data;


How do I add a view with a module when installing a module?

If you have the YAML file, you can put this in: /modules/your_module/config/install.

Then the View will be imported, when the module is installed (but there will be no updates, if you change the YAML file, it will only be imported once).

Btw. to export the YAML file you don't need Features, you can do this with core (admin/config/development/configuration/single/export).

So you can remove the line uuid: from the YAML file, this is only valid for re-importing the YAML to the same or a cloned site.


UPDATE From the code you've added it looks like you want to add the class based on the node author. You can use much the same principle:

function MYTHEME_preprocess_node(&$vars) {
  $account = user_load($vars['node']->uid);

  foreach ($account->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

Each node will have the role-rolename classes added to it (see original answer below).

ORIGINAL ANSWER

Quick and easy way:

function MYTHEME_preprocess_html(&$vars) {
  global $user;

  // Loop over the user's roles and add a class to the body class array.
  foreach ($user->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

That adds classes like role-administrator and role-authenticated-user (and any other roles the user has) to the <body> tag. From there you should be able to target things easily with CSS (e.g. body.role-manager{background:red}).

Remember to clear Drupal's caches after you've added the preprocess function, or the changes won't get picked up.


The error was happening due to the fact that database records where not removed when a taxonomy term reference field was deleted. The solution was to install taxonomy orphanage module which removes such references.


"Filters" have certain meaning in Views. They are this little things that give "go" or "no-go" to result rows. What you seems to want is to rewrite user's input, not filter.

hook_form_alter I see in your tags is actually a good call. You can use it to append AJAX to onblur and make it rewrite field. Or you can use validation function

function yourmodule_form_validate($form, &$form_state) {
  $form_state['input']['yourfield'] = _mymodule_sanitize( $form_state['input']['yourfield'] );
}

to rewrite it after user's submit, but before it is used by views. This function takes &$form_state by reference. It means you are allowed not only to read it, but also write to it, and your changes will be visible for all submit functions attached to your form, and will be used in next rendering of your form in case of validation errors or multis-tep forms.


First get a list of all paths, and then check each path.  Here is a quick example, and see drupal_match_path():

<?php
  // $paths would be the value of the textarea,
  //    with path expressions separated by newlines
  $paths = "mypath/*\nmy-page-name\ntopics/cheese*";
  $aliases = db_query("SELECT alias FROM {url_alias}")->fetchCol();

  $matches = array();

  foreach ($aliases as $alias) {
    if (drupal_match_path($alias, $paths)) {
      $matches[] = $alias;
    }
  }

?>


Easy way to make an Installation Profile

AFAIK, there's no one module that does all that perfectly. But depending on what your site is made of, there are a few modules that can come pretty close. Profiler Builder is probably the closest thing to what your looking for.

  It builds the .info, .profile, .install, .make, and .make.example files
  necessary to turn a site into a distribution / installation profile
  and tar's them up as a download.

The Features module can also be very useful as it allows you to package together subsets of functionalities (e.g. modules and settings for an image gallery).


How to get plain link with views-data-export module in CSV?

CSV is not an interactive format. When you export column with literal "link" in it's data, you get link in CSV.

Instead of exporting word column, with link added at rewrite or template level, export column that actually contains the URL you want. For nodes, this issue indicates that you should be able to use 'Path' field, description: 'The aliased path to this node.'.


Auto fill content field with random values

This should be done in a custom module by creating a custom field type

Good starting points would be either one of serial or unique_field modules and changing the logic of how the number is generated to match the logic described in your post


How to add custom page.html.twig for views page?

page--[url of your view].html.twig

Put the file in drupal/themes/YourTheme/templates folder

Remember to flush/clear the cache to see the changes.


I've had some cases where clean url-s aren't working in offline mode. You should be able to log in using '?q=user' instead.


How to add a new responsive Layout for large viewports to Omega Theme

You need to copy the grids variable from the default alpha.info file, and add your new layout in your theme's .info file like so:

grids[alpha_default][name] = Default (960px)
grids[alpha_default][layouts][fluid] = Fluid
grids[alpha_default][layouts][narrow] = Narrow
grids[alpha_default][layouts][normal] = Normal
grids[alpha_default][layouts][wide] = Wide
grids[alpha_default][layouts][wider] = Wider  <- Your custom layout
grids[alpha_default][columns][12] = 12 Columns
grids[alpha_default][columns][16] = 16 Columns
grids[alpha_default][columns][24] = 24 Columns

# Default settings for the new layout
settings[alpha_layouts_alpha_default_wider_responsive] = '1'
settings[alpha_layouts_alpha_default_wider_media] = 'media query here'
settings[alpha_layouts_alpha_default_wider_weight] = '4'

You'll also need a new CSS file (called THEMENAME-alpha-default-wider.css) to manage CSS for that layout, but Alpha/Omega should handle the rest for you.


module's local *.tpl.php, defined in $theme_registry, "not found or invalid" when referenced later in module

drupal_get_form() expects the name of a function that builds a form array, e.g.

function MYMODULE_some_form($form, &$form_state) {
  $form['#theme'] = 'user_login_member_form';

  $form['foo'] = array(
    '#type' => 'textfield',
    '#title' => t('Bar'),
    '#default_value' => t('Baz'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  // Process $form_state['values']
}

// In a hook...
$form = drupal_get_form('MYMODULE_some_form');

You don't need to add the form function to a registry as such, just giving it the same name as the string you pass to drupal_get_form() is enough.

hook_theme() is for registering theme functions, which is why you're currently getting an error.

The Form generation docs have a bit more information, and the FAPI reference is invaluable if you're new to the form API. For theming the form, there are some excellent answers to this question which should help.


Why this code doesn't send an email with drupal_email()?

The answer's in your comments

//Therefore the first argument is  'mailform_form'

But you're using the string mailform as the first argument.

If your module is called mailform_form as your comments suggest, use this code:

drupal_mail('mailform_form','some_mail_key', $valid_email, language_default(), $params, $from, TRUE)

If it's named mailform, use your original call to drupal_mail, but change the name of your hook function to the correct one:

function mailform_mail($key, &$message, $params) {


Is `watchdog-show string` broken in 7.56?

No. Or maybe yes - broken for all versions of Drush. The problem is that Drush only searches the message column of the watchdog table, not the variables column too. A watchdog entry is built-up by a message - format string - where a variable can be inserted. If the text you are looking for is in the variable part, Drush won't find it.

Yes, this is very annoying. There is a related Drush bug - see https://github.com/drush-ops/drush/issues/408 Maybe you should comment and ask for re-opening?


How to store a nodes Fivestar average rating inside another field with computed fields

Eventualy I used a different methode to get the average value. Here's how

 //Get average rating and place in index review score
    $average_field = field_view_field('node', $entity, 'field_review_votes_average');
    $rating = $average_field['#items'][0]['average'];
$entity->field_index_review_score['und'][0]['value'] = $rating;


Which is the cache I have to clear to refresh list of view blocks?

If you use Drush you can clearly see there are cache for block and views. Clear both these cache and you will get the required result


How can I add the og to a menu when a new organic group is added?

You can try this module : http://drupal.org/project/auto_menutitle. It allows to automatically generate menu items based on the node title. If you enable this module on your og content type, it should do it.


How to allow only certain users access to certain fields of a node?

Install Field Permission module. In this module you can set permission on every filed of content types for different roles.

You can also modify hook_field_display_alter  to check for the user and the field id and see if the user is allowed or not. you should copy this in to your template file.


Cannot get subscriptions to send out at correct intervals

Setting cron to run every 3 hours does not necessarily mean that cron
  will actually run every 3 hours. This is because it is not truly
  automatic. Something needs to trigger cron to run. This trigger
  happens when a user visits the site. As part of dealing with the page
  request, Drupal will check for the last time that cron has been run
  and will run cron as part of the request if it is time to do so. If
  cron is set to run every three hours and three hours has passed since
  the last time it has run, it will run as part of the page request for
  the user that happens to hit the page at that time.

  But what happens if you have an extremely low traffic Drupal site,
  application or intranet? If no one visits the site at all, cron will
  not run. Or if a user visits the site and cron is run, and another
  user visits the site 2 hours and 59 minutes later, cron will not run
  because three hours hasn’t passed yet. If a third visitor visits 3
  hours later, then cron will run. But that is almost 6 hours since the
  previous cron run.

  Source: Why Drupal cron is not running as often as you think and how to fix it

The solution to this issue is to instead run/trigger cron from your server using crontab.

You can read about it here Why Drupal cron is not running as often as you think and how to fix it and goes over a solution using C-Panel.

If you don't have C-Panel you will have SSH into your server and manually add an entry to your servers crontab:

  The automated cron module has the disadvantage that it is triggered by
  a request, and the unlucky user who sends the request may experience a
  fairly long delay.  For this reason, the automated cron is typically
  used by smaller sites that are unable to create a cron job manually,
  e.g. using the Linux crontab.  If crontab is desired, Drupal console
  command may be used to simplify the configuration (rather than curling
  the long url show in /admin/config/system/cron.  Here is an example
  crontab entry:

30 * * * * web_user /var/www/html/vendor/bin/drupal --
root=/var/www/html/docroot cron:execute > /dev/null 2>&1

  This would execute Drupal cron once per hour at 30 minutes after the
  hour.

  Source: Automated Cron


How can I lead to 404 Page Not Found when View page has no result?

You should use the drupal_not_found() function. It sets the correct headers, omits blocks from the page output to conserve CPU and bandwidth, and is the correct way to set a 404 through code in Drupal.

Also see drupal_access_denied() which might be useful.


Is it possible to attach my own datetime class for using it in fields?

In your case, you do not need to define a new field type, you just need to write a new field formatter.

In Drupal 8, field formatters are used for displaying fields when displaying the parent entity (eg, a node view page) and when used in a view (even with field output).

Field formatters are easy to write in Drupal 8. In you case you just create a new plugin, and you can likely just extend one of the existing ones.  I suspect something like this would work for you

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimePlainFormatter;

/**
 * Plugin implementation of the 'Awesome' formatter for 'datetime' fields.
 *
 * @FieldFormatter(
 *   id = "mymodule_datetime_awesome",
 *   label = @Translation("Awesome"),
 *   field_types = {
 *     "datetime"
 *   }
 *)
 */
class AwesomeDateTimeFormatter extends DateTimePlainFormatter {

  /**
   * {@inheritdoc}
   */
  protected function formatDate($date) {
    // Do something awesome!
  }

}

Here, the DateTimePlainFormatter does all of the heavy lifting via inheritance and you just override the method that actually produces the date string to be whatever you need.  You can then use this on Manage Field Display, and other places you can choose a field formatter.

In Drupal 7, you can also just create a field formatter, but the process is more involved.  You would also need to create a views field output plugin, as Drupal 7 / Views 3 does not use field formatters with field output.


What is the purpose of the PHP class FileTransfer?

FileTransfer is an abstract class for transfering files that specific implementations should extend. The available implementations are FTPFileTransfer, SSHFileTransder and LocalFileTransfer, which are used to transfer files using different methods.

What separates it from the "traditional" file transfer is that it is designed to operate on directories that are not writable by the web-server.

An obvious example is the update manager, which, by using these classes, is able to dowload and install module and theme updates automatically.

A module might interact with one of these classes in order to transfer files via FTP or SSH.


View Title does not filter correctly by userid

Ok, i guess this is difficult to solve from here. First you should check the following settings in your view.

Display name (how your Page-View is named, for administrative purposes, will not affect the frontend)
Title (this is the name of your view at the frontend, it can be overridden with contextual filters)
Path (this is the URL of your view)
This is the Title of your menu-item.

If this is all in order, you probably have overriden your view-title with a contextual filter.

Check these settings:


How to allow users upload images to existing nodes?

The best / simpler way would be to create a second content type called 'image', and give user the permission to create nodes of type 'image'. You can add a CCK imagefield to provide an image upload field.

Then you will want to be able to store relationships between your movie node and the related images nodes. You can add a node reference field on the image content type. You can populate this field by default with the movie reference. So any image added in the website will be related to a movie.

You can then create a view that will list the images related to your movie ID.


During checkout, when I click on review order, I would like to do some additional validation

You can just do a custom validation handler on the checkout form. This would mean the validation is done before you get to the review order screen. Let me know if you need more details.


General DiScussion - using this view view-advanced-forum-topic-list
You can find it here - /admin/structure/views
view name - Advanced Forum topic list


I found it. Due to i only want to post month calendar only. To solve this, just disable day, week and year in the view.


dynamically choose filters/fields in an aggregation table on a View

You can expose the filters (and for markup and additional functionality, there is a nice module Better exposed filters). You can find it when adding a filter "Expose this filter to visitors, allow tthem to change it", under the advanced sction on the right (by default collapsed) you can group them into a block and then add them to your site whereever you need them.

Hope I understood the question the right way.


If you have the source code, you can integrate it with your Drupal's templates. Otherwise, I don't see how you could do it.


How to send email to multiple recipients on creation of new node using rules module?

To send emails to multiple persons on creating a new node, you have to create a new rule and follow these steps :

Create an event After saving a new content type and then select that particular content type.

After that add an action from Select the action to add select list and choose Send Email.

After that you can add multiple email ids in the To textarea separated by comma and space like this :
first_email@mail.com, second@mail.com, third@mail.com


How to add custom settings / attributes to a field

Ok, this is done with third party settings in hook form alter:

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $entity = $form_state->getFormObject()->getEntity();

  $form['third_party_settings']['my_module']['my_field_setting'] = array(
    '#type' => 'textfield',
    '#title' => t('My custom field setting'),
    '#default_value' => $entity->getThirdPartySetting('my_module', 'my_field_setting'),
  );
}

...and that's it. So awesome.


How to print YAML form in custom block under drupal 8

Install the module insert Block

Enable and configure the insert block text format in 'admin/config/content/formats'

Make a new block with your form so that your form is available as a block.

In your accordion block you can call your form block with the special insert block tags [block:module=delta]. Make sure the 'insert block' text type is selected.


EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set()

Body is a Field API field and not a native PHP variable, therefore you cannot assign values to it like that. Instead, you would need to pass an array with the following keys:

$entity->body->set(array(
  'value' => 'This is the body',
  'summary' => 'This is the summary',
  'format' => 'full_html',
));

If you wish to set the value for a specific language, you call prior to set:

$entity->language(LANGUAGE_NONE); // or 'en' or whatever

More on wrappers: https://drupal.org/node/1021556


Form states expanded or collapsed not working

This makes it work:

   '#title' => 'bleh',

It kinda makes sense...


PHP version changes and Drupal versions issues

It's impossible to say whether your specific setup, with your specific site, will or will not have problems after a PHP upgrade. You'll need to set up a test environment that mirrors your live server as much as possible - and test it. It's unlikely, but you may have contrib modules installed that rely on PHP 5.2, so you need to check your specific installation.

From my own experience, before I upgraded to 5.4 some months back I was running many, many Drupal sites on 5.3 (though not versions as old as 5.3.3, that's pretty old these days). In over a year on dev/test/live I've never seen a single Drupal problem that was caused by the PHP version.

On another note, you really need to update your version of Drupal. We're currently on 7.22 and there have been a lot of security/bug fixes since the release you have installed.

You might also want to have a look at the PHP5.3 compatibility group, there's more detailed information there.


Do you provide a (Basic) authorization header, as well as a X-CSRF-Token header in your POST?

See also:
https://www.drupal.org/documentation/modules/rest/start - "2.2 Unsafe methods & CSRF protection: X-CSRF-Token request header"

Edit:
So you should at least specify the following HTTP headers:

Content-type: application/json
X-CSRF-Token: [TOKEN RETURNED FROM A REQUEST TO /rest/session/token]


Actually, what you want to do is this:

function YOURTHEME_preprocess_page(&$variables) {
  // This disables message-printing on ALL page displays
  $variables['show_messages'] = FALSE;
}

function YOURTHEME_preprocess_node(&$variables) {
  $variables['messages'] = theme('status_messages');
}

How this works:
Drupal core checks the value of show_messages in theme_process_page. If it is TRUE (default) then it calls theme('status_messages') as above, and effectively empties the messages storage, so calling the same theme function later will just return an empty string. However, if we set that variable to FALSE, this prevents said theme function from being called in process_page, allowing us to get all the messages using the same theme function, in a template of our choosing.


Using hook_mail and drupal_mail you can create and send an e-mail.

Implement an e-mail use hook_mail:

function MODULENAME_mail ($key, &$message, $params) {
  switch ($key) {
    case 'mymail':
      // Set headers etc
      $message['to'] = 'foo@bar.com';
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello @username,', array('@username' => $params['username']));
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

To send a mail use drupal_mail:

drupal_mail($module, $key, $to, $language, $params = array('username' => 'John Potato'), $from = NULL, $send = TRUE)

Obviously replace the parameters: $key should equal 'mymail'

An e-mail is sent in a few steps:

drupal_mail is called
Drupal builds the e-mail
hook_mail is called for the specifics (implementation)
hook_mail_alter is called so other modules can modify it
drupal_send_mail is called


Trying to add profile2 fields to user/edit page

I do not think it is an issue regarding with your theme. I have also built a theme from scratch but its showing perfectly up there. You need to change the display settings while you edit your profile type. SO under profile type edit you would find options such as Manage fields, Display fields etc. Under Display fields there would be three tabs just below them...Default, User Account, and Profile Page. By default, the fields which are not required are hidden, you need to change them and then they should show up


Registering User Programatically with only Email Address

In your custom submit function you can do the following,

$email_entered = $form_state['values']['email'];

$query = db_select('users', 'u');
$query->fields('u', array('uid'));
$query->condition('u.email', $email_entered);
$row_count = $q->countQuery()->execute()->fetchField();

if ($row_count == 0) {
  // User doesn't exist, Save the user.
  $parts = explode("@", $email_entered);
  $account = new stdClass;
  $account->is_new = TRUE;
  $account->name = $parts[0];
  $account->pass = user_hash_password('bar');
  $account->mail = $email_entered;
  $account->init = $email_entered;
  $account->status = TRUE;
  $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
  $account->timezone = variable_get('date_default_timezone', '');
  user_save($account);
}
else {
  // User exists.
}

As you can see there is no way that you can get the name of the user so you have to use the email as the username. This will be stored in users.name field.
You also might want to mail the password to the user.


Remove the return $block in case 'calendar'
function businesshours_block_view($delta) {
$block = array();
switch ($delta) {
    case 'calendar':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('toto');
        break;
    case 'frontdoor':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('front');
        break;
}
return $block;
}

NOTE: Also check your visibility
Possible values are:

BLOCK_VISIBILITY_NOTLISTED: Show on all pages except listed pages.
'pages' lists the paths where the block should not be shown.
BLOCK_VISIBILITY_LISTED: Show only on listed pages. 'pages' lists the
paths where the block should be shown.
BLOCK_VISIBILITY_PHP: Use
custom PHP code to determine visibility. 'pages' gives the PHP code to
use. Most modules do not provide an initial value for 'visibility' or
'pages', and any value provided can be modified by a user on the block
configuration screen.


I suspect the only thing you're missing is adding the return from theme('pager') to the content you're building.

This is a small example that shows teasers for all nodes in the system, with 10 per page. You would use this in a page callback function:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();

$content = node_view_multiple(node_load_multiple(array_keys($results['node'])));

$build = array(
  'content' => $content,
  'pager' => array(
    '#theme' => 'pager',
    '#weight' => 10
  )
);

return $build;

More specific based on your comments:

if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}


How to access the contents that are created by custom content type using module

You can use Views to list content of custom content type.

Update(Programmatically load nodes):

<?php
$type = "custom_content_type";
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $node):
?>
<?php print $node->nid; ?>
<?php print $node->title; ?>
<?php endforeach; ?>

Ref: https://api.drupal.org/api/drupal/modules!node!node.module/function/node_load_multiple/7


I have just learned that in order to use Global: Combine fields filter, you must set "Show" (under the "Format" section) to "Fields". My issue was I had it set to "Content" and couldn't select the fields in the settings for the filter.


How do I change the dependencies of a library from another module

My flot plugin is called timezone_js. I created a file, timezone_js.module and added a call to hook_library_info_alter.

function timezone_js_library_info_alter(&$libraries,$extension){
  //We need to add this module as a dependency of the flot module.
  if ($extension == "flot_d8") {
    $libraries['flot']['dependencies'][] = 'timezone_js/timezone_js';
  }
}


Adding CSS to specific nodes doesn't work

See if the hook is being called or not.
Try printing some of the node variables inside the hook.
Also try adding the libraries based on path alias which is configurable anytime unlike nids which differ based on the instances.
If you are to follow path approach,

function themename_preprocess_page(&$variables) {

   /*Get Url based on the url alias of current path */
    $current_path = \Drupal::service('path.current')->getPath();
    $Url = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    /*Attached calendar script for this page alone */
   if($Url =="/contact/open-office-hour"){
     $variables['#attached']['library'][] = 'themename/calendar';
   }
}


I had a similar issue with a recent OpenAtrium update (2.50). Apparently Chosen changed how it gets applied to fields, and this caused it to be turned off for select fields. In my case, it was as simple as visiting admin/structure/types/manage/<content-type>/fields/<field-name> and setting the option "Apply Chosen to the select fields in this widget?" to "Apply." This is done on a field-by-field basis.


Is there a way to change how a form button looks?

There are two basic ways in Drupal to remove the class, a PHP hook or a Twig template. It's only possible to describe this in a general way because the question doesn't contain details about which theme and templates are in use.
For a PHP solution find out which hook is adding this class and then implement the same hook in your custom theme. If the attributes contain the specific class you've added to the form build, then remove the conflicting class.
For a Twig solution enable Twig debug, find out which template is rendering the button now, and copy it to your theme's templates folder. Then do the same thing as described before in Twig:
{% if attributes.hasClass('btn-outline-primary') %}
  <input{{ attributes.removeClass('btn-primary') }} />{{ children }}
{% else %}
  <input{{ attributes }} />{{ children }}
{% endif %}


Ahah helper alwas getting error, but on other page no error

In .module file, I have to load .inc file. That's what I forgot! :(

include_once(drupal_get_path('module', 'act') .'/act.edit.inc');


Add custom tag in RSS XML header Drupal 7

Maybe it's because I don't know the views module well enough but I could not get views to do this at all. Instead I created a simple module that outputs an RSS feed. Use:

header("Content-type: text/xml");
print '<rss version="2.0">';

to have PHP output the correct headers.

EDIT: not sure it makes sense to just post the code but I can describe it:

1) The code below creates the page where your XML feed will live (should be in *.module file):

function xml_sender_menu() {
   $items['feed'] = array(
     'title' => 'RSS Feed',
     'page callback' => 'rss_feed',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );

     return $items;
}

2) Then in the same file create a function called "rss_feed()" (this name should be the same as the 'page callback' => 'rss_feed', in the above array) which will contain the code that produces the actual website. The function doesn't need to return anything.

3) http://cyber.law.harvard.edu/rss/rss.html contains a good readable description of the RSS specification, use Drupal API/PHP to output the data you want into the correct fields. For example I used the node's title to fill in the <title> field in RSS by doing this:

$sourcetitle = htmlspecialchars($node->title);
    print '<title>'.$sourcetitle.'</title>';

4) At the end output all the closing tags </channel> & </rss>

I don't know what data you are trying to fill your RSS feed with, so can't really be any more specific. Finally, copy/paste the output into an RSS validator to make sure you are not missing anything.

** Something I just realized: if you are adding other fields that aren't in the RSS specification, it's no longer an RSS feed. Instead you are just getting a plain old custom XML feed, don't know if that makes a difference to you.

HTH


Using migrate with a multi-page / paginated source

You can parse paginated sources with migrate but it takes a little work overriding MigrateListJSON - you may want to ignore the $jsonContainer part - that's just because the result set in our service is in a container (hence this class is abstract).

abstract class BSBaseMigrateListJSON extends MigrateListJSON {
  /**
   * String containing the JSON container name.
   */
  protected $jsonContainer;

  /**
   * Contains the default limit for pagination of the service.
   */
  protected $serviceLimit = 50;

  /**
   * Return an array of the IDs found in the list URL.
   */
  public function getIdList() {
    migrate_instrument_start("Retrieve $this->listUrl");
    $data = $this->getTree();
    migrate_instrument_stop("Retrieve $this->listUrl");
    if ($data) {
      return $this->getIDsFromJSON($data);
    }
    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns the amount of items to be processed.
   */
  public function computeCount() {
    if ($data = $this->getTree()) {
      return count($data[$this->jsonContainer]);
    }
    // Else fail and return N/A results.
    return NULL;
  }

  /**
   * Returns an array of crids.
   */
  protected function getIDsFromJSON(array $data) {
    $ids = array();
    foreach ($data[$this->jsonContainer] as $item) {
      $ids[] = $item['id'];
    }
    return $ids;
  }

  /**
   * Returns the list URL decoded JSON response.
   */
  protected function getTree() {
    $items = array();
    $offset = 0;

    do {
      $url = $this->rebuildUrl($offset);
      $json = $this->getTreeData($url);
      $data = drupal_json_decode($json);
      $items = array_merge($items, $data[$this->jsonContainer]);
      $offset += $this->serviceLimit;
    }
    while ($data['moreResources'] == TRUE);

    // Return data if any is present.
    if (!empty($data)) {
      $data[$this->jsonContainer] = $items;
      // @todo Consider whether just returning $items is feasible.
      return $data;
    }

    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns a constructed url with offset if required.
   */
  private function rebuildUrl($offset = 0) {
    $url_parts = parse_url($this->listUrl);

    // Build the query parameters.
    if (isset($url_parts['query'])) {
      parse_str($url_parts['query'], $url_parts['qparts']);
      foreach ($url_parts['qparts'] as $key => $value) {
        if ($value === '') {
          $url_parts['qparts'][$key] = NULL;
        }
        elseif ($key === 'q') {
          $url_parts['path'] = $value;
          unset($url_parts['qparts']['q']);
        }
      }
    }

    // If the offset is zero then we can simply return the original list URL.
    if ($offset == 0) {
      // Handles overriding the service limit if there's already a limit set in
      // the list URL.
      if (!empty($url_parts['qparts']['limit'])) {
        $this->serviceLimit = $url_parts['qparts']['limit'];
      }
      return $this->listUrl;
    }

    // Add the offset to the query parameters.
    $url_parts['qparts']['offset'] = $offset;

    // Build parameters to pass to the url function.
    $url_params = array(
      'path' => $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'],
      'options' => array(
        'query' => isset($url_parts['qparts']) ? $url_parts['qparts'] : NULL,
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
        'external' => TRUE,
        'https' => (bool) $url_parts['scheme'] == 'https',
      ),
    );

    return url($url_params['path'], $url_params['options']);
  }

  /**
   * Returns the data from the given list URL.
   */
  private function getTreeData($list_url) {
    if (empty($this->httpOptions)) {
      return file_get_contents($list_url);
    }
    $response = drupal_http_request($list_url, $this->httpOptions);
    if (!empty($response->data)) {
      return $response->data;
    }
  }
}

This code probably won't work as-is for you as it's specific for our service, you'll most definitely need to change this line: while ($data['moreResources'] == TRUE); and anything to do with offset depending on how your service works but it's a start for how to proceed.


How to point parent menu item to a link and sub menus too

You can do this by using below modules :

Path Breadcrumb

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

Menu Breadcrumb

  By default, Drupal 6+ use the Navigation menu for the breadcrumb. This
  module allows you to use the menu the current page belongs to for the
  breadcrumb.


Image captcha module not showing in admin after updating Drupal to 7.35

I discovered that the upgrade has renamed the path of submodule Image captcha to sites/all/modules/captcha0/image_captcha instead of the correct sites/all/modules/captcha/image_captcha (renamed filename value in table system of database. Physical path not changed). After that I have been forced to reinstall the module.

This is simply not serious, This seems a Drupal or a module bug and I have spent very bad hours trying to figure out what went wrong when I followed steps one by one and was very cautious.


Drush does not acknowledge release of new core update

drush rf
will refresh the available releases and at that point you should be able to run
drush up
or
drush up drupal.


DB log message: login failed for user xxx

These are often spammers, but might also be malicious users who are trying to break into your site (for example, to use it to post malware, distribute files, or as an email relay). If your set of users is small and well known then you should only be worried about these messages if they are for actual accounts on your site - that would be an indication of a brute force attack.

If your site is Drupal 7 then you already have some built in protection against brute force.

Some modules that might be useful to improve the overall login security of your site.

http://drupal.org/project/user_restrictions
http://drupal.org/project/password_policy
http://drupal.org/project/mollom - configured to show a captcha on the login page
http://drupal.org/project/tfa
http://drupal.org/project/ga_login
http://groups.drupal.org/node/235938


Adding ThirdPartySetting to webform entity results in wrong module dependency

Please use hook_webform_third_party_settings_form_alter() in mymodule.module and discard the submit handler which should solve that:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_webform_third_party_settings_form_alter().
 */
function mymodule_webform_third_party_settings_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\webform\WebformInterface $webform */
  $webform = $form_state->getFormObject()->getEntity();

  // Do stuff.

  $form['third_party_settings']['email_element'] = [
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('E-mail element'),
    '#default_value' => $webform->getThirdPartySetting('mymodule', 'email_element'),
  ];

  // Do not add submit handler.
}

Webform's WebformThirdPartySettingsManagerInterface wraps Core's ThirdPartySettingsInterface which is why I think you're seeing that behaviour.


How to disable/enable all products in commerce?

It will take just a few steps to create a view for your commerce product
fields values manipulation:

add a new View:

"show group" set to Commerce Product "of type" - type of
     you commerce product, you want to change fields values;
"display format" set to "Table";
press "Continue & Edit";

In "fields"  group add "Bulk operations:Commerce Product" field:

set checked "Modify entity values " in "Bulk operations" group;
press "Apply" button;

That are the main settings for your operation view. Just add fields and filters whatever you want.
Save your view and use it for change field values using bulk operations.


How to display menu in view Block in drupal 7

If you use Views 3 then install Views Menu Area module, you can show any menu in the views block.

Enable the module
Edit your preferred view
Click "Add" link in header/footer section
Check "Global: Menu area" and click "Add and configure footer" button
Enter label and select the menu you wish to list links from
Click "Apply" button and save the view

also take a look at Menu Views module.


How to really remove the node title of an embedded node?

node_embed uses node_view() and drupal_render() to display a node.

With the default node.tpl.php, the title is always displayed unless the node is rendered as a "page". The "page" variable is determined in an obscure way in template_preprocess_node(), and is typically false with embedded nodes. So the title will be rendered.

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

I see two ways to prevent this:

A custom node template for the view mode that is used by node_embed, in your theme.
Use a display suite layout for the given view mode. With display suite, the usual node template is ignored, and the title is just one among other visual elements to be positioned in the display. I prefer this solution, because I like display suite :)

node_embed ships with a dedicated view mode 'node_embed', which is used by default for embedded nodes. So this is the one you need to configure or target with a template.

BTW, at the time of this writing, the module page of Node embed says it is no longer supported. There is another module, Entity embed, which seems not to have this problem.


$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute();

while ($term = $terms->fetch()) {
  // $term contains the object for the taxonomy term.
}


No, that's not possible with drupal_http_request().

You'll need to use httprl, curl_multi, or something like that.


What module controls Commerce Kickstart 2 add to cart popup?

From Commerce Kickstart 7.x-2.0-rc3 and up, the module is Commerce add to cart confirmation
(Previously this functionality was a part of the base product feature and couldn't be disabled).


How to use rules to take a user from a group content page to the group page the content belongs to?

Many approaches available here. You can use the rules link module to do this. It can fetch the parent node and redirect to it when the link is clicked.
https://www.drupal.org/project/rules_link

However, check if organic groups provides tokens that you could use to build the link in html. Or a php snippet to grab the nid of the parent if it exists and print it as part of a link.

The other option is crumbs, the breadcrumbs module that automatically outputs the subgroup hierarchy.
https://www.drupal.org/project/crumbs

If you are using panels, I'm pretty sure there's a replacement pattern for the parent if you create custom content.


How do I completely overwrite an array in JSON serialized data field

A colleague suggested a solution that worked.

The Field Settings has a group of settings called "Serialization Options" which includes a checkbox option for "Namespace the data". In my initial configuration that box was checked. I unchecked the box and saved the field settings and my problem was solved.

Final solution: Uncheck "Namespace the data" in the Field Settings.


Use product entity field as filter in Views

I recently learned how to do this kind of thing.

You need Page Manager which comes as part of Chaos Tools for d7, and Panels.

In Page Manager, enable and edit the path /node/%node
Set the selection criteria to node-type = showcase
Create a context based on the entity reference field, or if that doesn't work you might need the Relation module.
Create another context based on the power field (you might like to use a taxonomy for that)
Make a view that uses the context to choose the products to display
Back in page manager, under Content, use Panels to determine where and how you want node and the view to display.

Follow the first link ("learned") for a much more thorough tutorial.


Need help optimizing a site for speed and response time

You can use both as per my knowledge.

For Drupal generally, Varnish works for unauthenticated users traffic and memcached will cache authenticated users traffic.

Memcache saves your DB from doing a lot of read work, Varnish saves your dynamic web server from CPU load by making you generate pages less frequently.

But in your case I think Varnish is better option.


Getting path alias on the base of term id

To get the alias of a term : drupal_get_path_alias('taxonomy/term/[tid]').

Just a suggestion : To print the breadcrumbs you should try Custom Breadcrumbs module.


How to dynamically Prepopulate / Prefill addressfields

I cant find any reference of hook_form_entityform_alter if it is available you will want to take out the hook part and replace this with you module name.

I have re written the code using hook_form_alter. You will need to replace $address1 etc with your own code.

function letter_addresses_form_alter(&$form, &$form_state, $form_id) {

// Ensure, we're updating field info on the correct entity type
//This needs to be more specific incase more entity forms are created
if ($form_id == 'yourformname_entityform_edit_form') {

// Only do this for a new, not-yet updated entityform -NB might need a 'return' here
if (!isset($form['#entity']->is_new)) {
//Populate the entityform addressfield with values from the user addressfield
$address1 = "address1";
$address2 = "address2";
$county = "county";
$postcode = "postcode";
$form['field_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $address1;
$form['field_address'][LANGUAGE_NONE][0]['#address']['premise'] = $address2;
$form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = $postcode;
  }
}


How can I get a block to display only on node view in Drupal 6

In the visibility textarea of your block, select PHP code and put the following:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && (arg(2) == '' || arg(2) == 'view')) {
  return TRUE;
} else {
  return FALSE;
}
?>


Get the value of one field from another in the same form

The formElement method in your widget class should include $form_state as one of its arguments. The value of all the fields in your form should be available in the $form_state object:

example: $form_state->getValue('field_b');


How should I display fields for a content type?

You can use display suite module to theme your node.

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

If you want to theme your node using code, then you should create template for your node. Check this link for reference.


How do I programmatically get the field type of a specific field?

With "get the field type of a specific field" you probably mean a specific field of an entity. There can be fields with the same name that have different types in different entities.

For example the field type of a field in a node:

$field_type = $node->get($field_name)->getFieldDefinition()->getType();

can be different than that of the same field in a comment:

$field_type = $comment->get($field_name)->getFieldDefinition()->getType();


Drupal Commerce : Shopping Cart Checkout for Orders

My initial thought is for you to check out the commerce_add_to_cart_extras module.  Granted, it's still in its dev version, but you can create a view with products, specify quantity, and bulk-ly add to cart.

To go straight to checkout, you may need to add a little redirect in the submit handler for that button.


How to copy current directory into Drupal profile folder via drush?

I actually had to specify extra type: "profile" (to follow this example), so type is specified twice (type of project, and type of download), as below:

api: 2
core: 7.x
projects:
  drupal7:
    type: "profile"
    download:
      type: "copy"
      url: "file://."

Then this would work fine:

$ drush make --no-core profile.yml drupal-7.39/
Beginning to build profile.yml.
drupal7 copied from file://..

To avoid copying docroot/ it-self, it's good to actually create a separate folder for profile (as specifying wildcard won't work).


How to change the look and feel of exposed filters in a block

If you want more control over your exposed form template, you an write a template file for it. This article will help you to define template file.

Otherwise you can change the appearance with css, And you can use form alter in case of alter any elements.


How can I modify the values in variable table using phpmyadmin?

As stated in comments serialized string variable lenght must match the integer prefixed, eg

s:20:"example@example.info";

drush vset is alot better for this kind of adjustements.

That beeing said, for users with drush 4.5 where modifying more complex variables is not available (use variable-set with arrays and objects. Accept JSON via STDIN like cache-set), direct access to database can be handy way to tweak the system. Remember to clear caches after.


Automatic generate a parent category when adding a new node

You have content types a)Songs b)Artist

Create a node reference field with artist, in Songs content type. So when you add a new song you can you can select the artist belongs to that. I hope no need of taxonomy.

You can create two page displays in view by selecting necessary fields and give the appropriate path as you wish.

Hope this may help you!