The default drupal .htaccess settings should have your browser cache this image for 2 weeks. If this is not working I recommend installing the mod_expires module & the mod_headers module on your server. If 2 weeks is not long enough, you will need to modify your .htaccess file to set the expires & cache control headers for this file. An example of that below:

<FilesMatch "my-big-image\.jpg$">
  <IfModule mod_expires.c>
    # Enable expiration.
    ExpiresActive On

    # Cache this file for 1 year after access (A).
    ExpiresDefault A31556926
  </IfModule>
  <IfModule mod_headers.c>
    # Make this file publicly cacheable.
    Header append Cache-Control "public"
  </IfModule>
</FilesMatch>

At a bare minimum, you can try adding this line to the bottom of your .htaccess file. This doesn't require any apache modules to be installed and it should have your sever send back a small 304 instead of a large 200.

FileETag MTime Size


How to add product thumbnails to Checkout?

You can override the theme function uc_cart_review_table to accomplish this.

function YOUR_THEME_uc_cart_review_table($variables) {
  $items = $variables['items'];
  $show_subtotal = $variables['show_subtotal'];

  $subtotal = 0;

  // Set up table header.
  $header = array(
    array('data' => theme('uc_qty_label'), 'class' => array('qty')),
    array('data' => t('Products'), 'class' => array('products'), 'colspan' => 2),
    array('data' => t('Price'), 'class' => array('price')),
  );

  // Set up table rows.
  $display_items = uc_order_product_view_multiple($items);
  if (!empty($display_items['uc_order_product'])) {
    foreach (element_children($display_items['uc_order_product']) as $key) {
      $display_item = $display_items['uc_order_product'][$key];
      $image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart');

      $subtotal += $display_item['total']['#price'];
      $rows[] = array(
        array('data' => $display_item['qty'], 'class' => array('qty')),
        array('data' => $image, 'class' => array('image')),
        array('data' => $display_item['product'], 'class' => array('products')),
        array('data' => $display_item['total'], 'class' => array('price')),
      );
    }
  }

  // Add the subtotal as the final row.
  if ($show_subtotal) {
    $rows[] = array(
      'data' => array(
        // One cell
        array(
          'data' => array(
            '#theme' => 'uc_price',
            '#prefix' => '' . t('Subtotal:') . ' ',
            '#price' => $subtotal,
          ),
          // Cell attributes
          'colspan' => 4,
          'class' => array('subtotal'),
        ),
      ),
      // Row attributes
      'class' => array('subtotal'),
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => array('cart-review')), 'sticky' => FALSE));
}

With the code $image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart'); you can read out the product image and add it to the table.


You could also try specifying by url string "education/*" or even node ID instead.


Get a configuration option from node type structure

Node type forms save their data in variable table prefixed with form field name and suffix will be node type.

If field was $form['MY_SETTING']=array(...); you can get the value with variable_get('MY_SETTING_' . $node->type, '');


Go to this content type's "Manage  fields" page and add new field with "Flashcard" type. Set number values you want (I think you will need Unlimited). Go to "Manage display" page and change your new field formatter from "Default" to "Cycle". Create a new node with a couple of Flashcard pairs.


Views pager when view is running on Node Id

I've used Previous/Next API for this kind of situation (it's only dev, but it worked for me, YMMV).


What Drupal tables to export from broken site

Not at the database table level, no.  There's a contributed module in Drupal called "Features" that lets you export content types, fields, views and some other configuration into a custom created module, but you would need a functioning site to begin using it.


What is the best way to stop a node from loading in a node hook?

You can't prevent a node from loading but you can deny/grant access to it. Write a custom module and implement hook_node_grants($account, $op) && hook_node_access_records($node). Here is a good example.

or, you can implement hook_node_access($node, $op, $account) but this hook will not be invoked  for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.)


Programmatically get the continent from ISO2

Continuing the answer from the initial question, I think you have to load the Country entity to replace the token with what values you are after.

Based on looking at the Countries module, it stores countries as a custom entity:

/**
 * Implements hook_entity_info().
 */
function countries_entity_info() {
  $return = array(
    'country' => array(
      'label' => t('Country'),
      'plural label' => t('Countries'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'base table' => 'countries_country',
      'token type' => 'country',
      'fieldable' => TRUE,
      'module' => 'countries',
      'entity keys' => array(
        'id' => 'cid',
        'name' => 'iso2',
        'label' => 'name',
      ),
      'bundles' => array(
        'country' => array(
          'label' => t('Country'),
          'admin' => array(
            'path' => 'admin/config/regional/countries',
            'access arguments' => array('administer site configuration'),
          ),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Country'),
          'custom settings' => FALSE,
        ),
      ),
    ),
  );
  return $return;
}

/**
 * Loads a country entity by ISO alpha-2 code.
 *
 * This is also a menu wildcard loader.
 *
 * @param string $iso2
 *   An ISO alpha-2 string. This is case-insensitive.
 *
 * @return object
 *   A country object loaded by the entity controller.
 */
function country_load($iso2) {
  // The URL's should be case insensitive.
  $iso2 = $iso2 ? drupal_strtoupper($iso2) : $iso2;
  return entity_load_single('country', $iso2);
}

It looks like the iso2 value is the entity id, based on this code and the helper load function here, so, you can access the full entity when a token is replaced by:

/**
 * Implements hook_tokens().
 */
function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node']) && array_key_exists('MYTOKEN', $tokens)) {
    $country = country_load($data['node']->field_prgm_country[LANGUAGE_NONE][0]['iso2']);
    // $country should be a fully loaded Country entity with all its fields and properties
    // check out $country here with ksm($country);exit;
    $replacements['[node:MYTOKEN]'] = // data you want to show;
  }

  return $replacements;
}

It looks like the Country module provides its own country: scope of tokens, but I do not know how (or if) they work in the context of fields on a node. This should get you closer at least.


How to create a sort features In Drupal?

Use advanced_forum module.
See the image attached, it provides sort option.


image_style_url no longer creates images

There was a change on the Image derivative URLs by the Drupal 7.20 update, as the 7.20 release notes also states:

The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)
As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD.
In addition, any code which programmatically generates a link to an image derivative without using the standard image_style_url() API function will no longer work correctly if the image does not already exist in the file system, since the necessary token will not be present in the URL.


There is a space missing between the dash and the item:

libraries:
  - mytheme/global-styling

And be careful with the indendation. Better use 2 spaces for each level. One space is difficult to see and if you miss one, the whole yaml-file will be invalid.


How to tell if a function is being called by javascript?

JavaScript cannot directly call a PHP function. If you think that JS may be 'triggering' the call of that validation handler, then there must be an AJAX event going out to the backend, which then calls the validation handler. If that is the case, the request will go out to the system/ajax URI on your site (unless it has been intentionally changed to a different URI - you can double check this by viewing the 'Network' tab in Google Chrome's developer tools), which will then handle the request and dispatch it to the validation handler.

So...

You can check the $_GET['q'] value in your validation handler:

if ($_GET['q'] == 'system/ajax') {
    // AJAX request
}
else {
    // other request
}


Limit amount of adding a certain Paragraph per Content type

Things which only should be unique to a node, should better be attached directly to that node.

There's already a feature request on DO. But I'd recommend you to solve this by attaching these things directly to the node, with standard image or text fields.

-- node type
  |__ hero image field
  |__ intro text field
  |__ paragraphs field

The only other alternative I see is to add multiple Paragraphs fields to your content type and then limit them to only one type and one item.


I was able to figure out the issue. Its a bug in the views which doesn't handle the nested views. More about this issue can be found in https://www.drupal.org/node/1016602

I had to override a javascript function in views to fix it. But since it was very use-case specific, I am not sharing the details of the same.


Boolean single on/off field - how to make it NOT render the off option?

You can hide them either through CSS or you can unset them using the form_alter if you are using forms. Look at the code below
In this code, I am unsetting the author on the comment form.

function Mymodulename_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    if($form_id == 'comment_form) {
      unset($form['author']);
    }
  }
}

If you've added the field to some node then you can unset them using this code.

unset($node->field);


taxonomy terms that get URL aliases and then end up being ugly google sitelinks

you can manage which links are used for sitelinks in Google's webmaster tools.

To change the description that is used you can use nodewords (or metatag for D7).

Here is some more info about the recent change in Google's sitelinks feature.


How to redirect exposed view filter form submission?

Thanks for the additional info, it adds a lot of light to the issue. I am not exactly sure what is going on but maybe an explanation of what drupal does might give you an "A-ha! That's where I entered some info wrong" moment:

In the code, drupal/views/etc uses form redirects:

$form_state['redirect']= VARIABLE OR CODE TO SET IT TO A PATH

that is obviously mangling the redirect into:

http://domain/?date_start=12

What is interesting here is it is setting that url to the date_start value instead of adding that to the url:

http://domain/myselfcare/communications?order=destination&sort=asc&date_start=12

So here, instead of adding ?date_start=12 to the end of

http://domain/myselfcare/communications?order=destination&sort=asc

it's replacing it all (additional vars get the ?= changed to an &=)

So, I'd look at how you are defining date_start in your view forms and see if anything odd pops up there.  That or in your theme code setting the redirect to that directly.


Howto pass the uid of a node to a view inside a dynamic display suite field?

You are incorrectly setting the 'Argument input' for the Content Pane. It needs to be Node -> Author

Then you need to make sure that you pass the correct argument to it from the Dynamic Field in Display settings for the node. Make sure that you select 'View Panes' and not 'Views'. When you do it will show you the View pane view that you created, and when you select that it will present you with a select list titled: 'Content: Author uid', from which you select the only choice available, which is 'Node being viewed'.

I also do not think that setting the 'When the filter value is not available' in views will have any effect at all. This content pane display is only used for the dynamic field which will always get an argument.


How can I let users register for a certain node type?

I was finally able to associate the event using the Node Registration module.

  Allows (authenticated and/or anonymous) users to register for events. Events are nodes with certain node types. You can enable registration for any node type and add fields and manage display per type and per node.

The module depends on Value is and Entity as well as Views and CTools.

What you'll have to do after installation:

Go to admin/structure/types/manage/<course>/edit, where <course> is your course
Enable registrations at the bottom under Registration Settings
Go to admin/structure/node_registration/manage/<course>/fields and add fields to your registration form, as required.
Don't forget to enable the right permissions too for anonymous users.


Better way to associate ticket quantities with event dates?

If you want to continue down the road you are on now, having an event description node and separate event date nodes, I would recommend you take a look at the References module.

If you want to keep all information within one node for a given movie/event, perhaps take a look at the Field Collection module.  The article Create Multigroups in Drupal 7 using Field Collections may assist you to accomplish this.


Rules- How can I make a variable/token with the site URL minus the language path?

Use Drupal global variable $base_root for that.


url of each listed nodes in a view using the content format

Read the comments of the default node.html.twig under /core/modules/node/templates/. Any variable listed there should also work in node--article--teaser.html.twig.


How can I redirect a user after adding a node that also added a new taxonomy term?

I'm not positive I understand the why, but the redirect-on-saving-new-node-with-new-terms bit should be reasonably straightforward.

I've suggested two possible methods below because the timing of db inserts/updates etc around node creation is a bit intricate, and you may need to shift the task to an earlier or later stage in the process. For example, the API docs mention that the db write cannot be presumed to be complete during hook_node_insert(), and it definitely won't be on hook_node_submit(). So your mileage may vary :)

You'll need to create a custom module (here's a stackexchange question on creating modules if you don't already know how) that either:

implements hook_node_submit()

This is the very likely to be the simpler/more reliable of the two methods.
implements hook_node_insert()

In this method, it is possible that drupal_goto() will conflict with the redirect specified in the node form's $form_state['redirect'], so it's probably the worse of the two possibilities.

Method 1: implement hook_node_submit()

From inside yourmodule_node_submit(), you'll need to:

Make sure that a node with this nid does not already exist!
find out what terms (if any) are in the new node ($node is passed into the function)
load all the terms for the relevant vocabulary, probably with taxonomy_vocabulary_load()
check to see if any of the node terms are not in the full list
modify $form_state['redirect'] if required

See drupal_redirect_form() for a bit more information on what happens with $form_state['redirect'].

Method 2: implement hook_node_insert()

From inside yourmodule_node_insert(), you'll need to:

find out what terms (if any) are in the new node ($node is passed into the function)
load all the terms for the relevant vocabulary, probably with taxonomy_vocabulary_load()
check to see if any of the node terms are not in the full list
if that's true, use drupal_goto() to redirect accordingly


How to add Colorbox to a field in a twig template?

You really would want to use:

{{ content.field_product_image }}

The field display setting will pass the image style to it, and I assume colorbox has a field formatter or tie in here as well. Supply a field Twig template to strip extraneous markup divs.


How to Lazyload any src object in node body

I think he means to add this to mytheme.theme

/**
 * Implements hook_page_attachments_alter()
 */

function MYTHEME_page_attachments_alter(array &$attachments) {
    $attachments['#attached']['library'][] = 'blazy/load';
}


Passing Promo Code to Drupal Commerce via URL

There are a number of ways you could do this. Probably the best way is to use a custom module, define a menu path with a token, and do it all in PHP. But I live mostly in the GUI world. You could also do this using Rules.

I have done something similar in a 10 minute youtube video that describes how to use rules to construct a url that passes in information and does things (like adding a product to a cart, or in your case you could use it to add a discount/apply a coupon).

Video: Using Rules to create a url to add a product to cart

Step by Step

Download Rules URL Arguments
Create a rule that fires on the event "Drupal is initializing"
Add a "Text Comparison" condition. Compare the site:current-page:path token against your first parameter "promo" for a url like "test.com/promo?coupon=123"
Add all of the actions you need to react to the rest of the parameters. In the video you'll see how to get at those parameters in the url.


The selector added to "Apply Chosen to the following elements" section would be

.view-filters .views-exposed-form select

in order for Chosen plugin to be applied to Views exposed filter with select drop-down widget.


Conditionally register a user based on fields

Forms have a validate and submit function(s). Submit never runs unless all validation passes.

So all you have to do is add a custom validation

/*
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['#validate'][] = 'mymodule_registration_validate';

}

/*
 * Custom Validation
 */
function mymodule_registration_validate(&$form, FormStateInterface $form_state) {

  $field_name = $form_state->getValue('field_name'); // Gets the value entered by the user
  // Note: depending on your field type & settings sometimes this value is an
  // array, so you may have to keep drilling down.
  if($field_name != 'Hello World') { // perform check
    $message = t('Only Hello World is allowed'); // message to display
    $form_state->setErrorByName('field_name', $message); // set error
  }

}

$form_state->setErrorByName will display an error message and highlight the offending field in red.

If  you want to redirect use $form_state->setRedirectUrl($url);


How to avoid certain variables from being cached?

If the variables come from the current user, then add this cache context to the build array you return:

$build['#cache']['contexts'][] = 'user';


How to inherit base class dependencies without redefining theme in child class service arguments?

The question asks:

Is there any way to inject the Base Class service , when defining a
child class service (NodeHandler , ParagraphHandler) without using the
arguments: part in the service definition

Yes. For example, look in core.services.yml to see how this is done in core Drupal. Most core Drupal plugin managers have a parent service named default_plugin_manager. The default_plugin_manager service is defined like this:
  default_plugin_manager:
    abstract: true
    arguments: ['@container.namespaces', '@cache.discovery', '@module_handler']

As you can see, there are three services injected into the default_plugin_manager service. Because it is declared as "abstract", this service definition is more like an alias or a placeholder - it's simply there to define a set of arguments. Note there's no class associated with this service.
A concrete plugin manager, for example the plugin.manager.block service, is then defined like this:
  plugin.manager.block:
    class: Drupal\Core\Block\BlockManager
    parent: default_plugin_manager
    arguments: ['@logger.channel.default']

This service has FOUR arguments injected; the three defined by the parent default_plugin_manager plus the addition argument defined here.
When you look at the concrete class BlockManager that implements this service, you see that BlockManager has a constructor that looks like this:
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, LoggerInterface $logger) {
...
}

As you can see, this constructor takes four arguments. The first three defined by the default_plugin_manager service and the last one defined by the plugin.manager.block service.
Core Drupal defines a DefaultPluginManager base class which is extended by BlockManager and other plugins. BlockManager accepts all four arguments in its constructor. Note that if the parent (DefaultPluginManager in this case) has a constructor then you need to call that from the subclass constructor. This way many different plugin managers can extend DefaultPluginManager and inherit those three injected services.
In your specific case, your services.yml file might look like this:
  my_parent_service:
    abstract: true
    arguments: ['@entity_type.manager', '@request_stack', '@sacd_user.permissions', '@logger.factory']

  sacd_rest_api.node_handler:
    class: Drupal\sacd_rest_api\service\NodeHandler
    parent: my_parent_service
  sacd_rest_api.parapgraph_handler:
    class: Drupal\sacd_rest_api\service\ParagraphHandler
    parent: my_parent_service

You do not need a create() method anywhere, and you do not need to use ControllerBase at all.


How to define profile types per group type in the Group module?

... can I define a profile type per group type?

Sure (yes?) you can, it's what in the Group module is called "Group Specific Roles".

  Group profile types seems to be global ...

Here you're talking about what in the Group module is called "Special Global Role" or "Configured Global Roles".

For more details on this, refer to the answer to "What are the various roles supported by the Group module?".

Be aware: this answer applies to D7, as in the question (for D8 it would be different ...).


If you want to re-create content-types you have created in other drupal-installations you can use the features module:

This module allows you to export content-types to code (called features). Those features can be copied to other sites like normal modules and then be activated via drush using

drush en -y feature_name


Integrating Video.js with Google Analytics

I think I answered this after I posted. I was trying to use the ID on the <video> itself, but I instead tried using the ID of the div that contained the video, and that worked without issue. I still need to figure out how to update the code dynamically on a per-page basis so that the correct video is tracked, but it's at least working now.

EDIT: I was able to modify the "inline" code file from above to automatically pick up any videos on a page that the script is loaded on.

(function ($) {
    $('.video-js').each(function() {
        videojs(this.id, {}, function() {
          this.ga(); // "load the plugin, by defaults tracks everything!!"
        });
    })
})(jQuery);


Drop Tables After Backup Migrate Restore

As far as the API goes there's db_drop_table()

db_drop_table('table_name');


Drupal commerce order notification to field in a line item type

What you've encountered here is how Rules deals with multi-value fields. The commerce-line-items field is a multi-value line item reference field using "delta" values represented by those 0, 1, 2, 3, etc. numbers. Without knowing the full details of your situation, the best I can recommend is to add a loop over that commerce-line-items field, passing each line item to a Rules component designed to e-mail the honoree.

If you aren't familiar with Rules components, that's certainly more than we can get into here. Your best bet would be to find the Rules Mastery course on YouTube and get your learnin' on.

Once you have the idea, what you'll need is a Rule component that accepts a Commerce Line Item as a parameter. It should have at least these two conditions:

Entity has field - does the line item have your honoree e-mail field?
Data value is empty (negated) - does the honoree e-mail field have a value?

If so, your actions section can send the necessary e-mail using the value of that field as the e-mail recipient.


Page title unable to overwrite default title

function mytheme_preprocess_page(&$variables) {

  if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'form_id') {
    if (arg(0) == 'node' && arg(2) == 'node-type') {
    drupal_set_title(t('Your title'));
    }
   }
 }

you can use dpm($variables) to find form id. This for changing page title.

For changing header title i.e the title displaying in tab, below code can be used

function mytheme_preprocess_html(&$vars) {
  if (!empty($vars['page']['content']['system_main']['#form_id']) && $vars['page']['content']['system_main']['#form_id'] == 'your_form_id') {
    $vars['head_title'] = t('title');
  }
}


How to implement responsive social sharing button with counters?

Try any one of this following

1) Social Share Counter

  This module is clearly inspired by the share buttons used by Mashable.

  This module gives the share counts for only Facebook,Twitter and more
  which has some excellent features in more elegant manner. If you have
  a website, then you definitely need this module.

2) Social Share statistics

  This module is developed to track the share statistics of social media
  clicks. So when a registered drupal user shares any content to social
  media, this module saves the uid, nid and the share count for
  FB/twitter/GPlus in the database for the record.

  There is a 'Shares' tab on the user profile page where the user can
  get the list of content shared on different social networks (facebook,
  twitter).

  This module only tracks shares that are made using the share buttons
  that the module provides. If you share the nodes with some other
  mechanism (say directly copy paste the link to Facebook, Twitter, etc.
  or use some other module), those actions / shares do not count.


View the page this item is supposed to appear on, Drupal will encounter the item and add it to the translation interface again.


What could be causing drupal to want to reinstall itself after I clear cache?

That occurs because Drupal can't connect to its database

Ensure you have:

settings.php

in your Drupal /sites/default folder.

settings.php must be readable by the webserver user and contain valid database connection string credentials for that server. Make sure the base_url is either default commented out or valid for that domain.

See _drupal_bootstrap_database for the place where the install.php redirect occurs.

Also, make sure you've run update.php and do clear all caches if possible.


I think for your use can you should use workbench
with workbench_moderation

  Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.


Error on views page. Any idea what this means?

You likely need to bump up max_allowed_packet in your MySQL instance.  That query is likey trying to store a large amount of data.  I have never seen this at runtime, though.  I have only had problems with this variable when trying to restore backups.


Share nodes and users across multiple sites

Sharing users can be done by setting up OpenAuth or something like it.

Sharing nodes can be done using views database connector this tool will let you pull data from a table in another database. To make it work for pulling in nodes, create a MYSQL view (https://dev.mysql.com/doc/refman/5.7/en/create-view.html) that holds the node data you need to share out.  The views connector will be able to read in that table allowing you to create views from your other server without having to duplicate the content.  You can filter on any field in the table. This set up works well for a 1 to Many Content server environment where you don't want to have a new copy of every node on every new install.
 https://www.drupal.org/project/views_database_connector

You can also create a module that pulls data from the other database and present it any way you want.

If you are fine duplicating the content you may want to explore Drupal aggregation it's easy to set up and can all be done through the UI.


This is a broad question that it pretty much requires some proficiency with several aspects of Drupal.

In short, first I would recommend you that you find a ready theme which features some kind of pop-up as you require. Alternatively, you would need to theme a pop-up region by yourself.

Then, you need Views module with exposed filters in a block, which you would add to this specific region.


How to increase meta tag description field to 320 characters?

I had to write a hook_page_attachments_alter for this

function mymodule_page_attachments_alter(array &$page) {
  foreach($page['#attached']['html_head] as &$html_head) {
    if($html_head[1] == 'description') {
      $html_head_content = $html_head[0]['#attributes']['content'];
      if(Unicode::strlen($html_head_content) > 320) {
        $html_head[0]['#attributes']['content'] = Unicode::truncate($html_head_content, 320);
      }
    }
  }
}


This does not seem possible.

However, I found that with tabledrag I could do what I wanted. Instead of having two checkboxes, I used the dragging option instead of one and left the other checkbox in the row you can select by dragging upward. This had the added benefit of being able to specify  the order for the items.

The simple table drag example was easy enough to follow and implement.


PrePopulate a Node URL from Previous Node via Rules Link to Add Content Form

You need to have an entity reference field in your form and set it to reference nodes.

Normally, you would then build your link with the current node's Nid to fill the entity reference field on the next page.

http://example.com/node/add/article?field_previous_page=123

However, because you are using rules link, I guess you have to create a redirect to the form based on the current node replacement pattern available.

Or below is a solution if that doesn't work out.

  If you really must use rules link and can't get normal methods to work, then Rules Session Variables
  would be an easy solution. It will give you actions to let you add the
  node's id into $_session.

  Then when you the user saves the form, have another rule that
  checks if $_session exists and if so, take the Nid, fetch the node and then
  set the entity reference field with it.

So yeah, do you need to use rules link?


Create bundles programmatically using ECK (Entity Construction Kit)

I just found a blog article here which gives an example on how to do exactly this:

After creating the entity type with the example code I gave in the question a bundle can be created as simply as this:

$entity_type_bundle = new Bundle();
$entity_type_bundle->name = 'eck_employee';
$entity_type_bundle->entity_type = 'eck_employee';
$entity_type_bundle->save();


You can easily do this using hook_form_alter(&$form, &$form_state, $form_id) Alter

Hook_form_alter is working before your form shown
Use hook_form_alter in Your site theme template.php file.

Like your theme name is bartik,then use this function their

function bartik_form_alter(&$form, &$form_state, $form_id)
{
//Firstly get form id then use below code

if($form_id=='Your_edit_form_id'){
//here print $form and chek which field label you want to change and then alter that field //like

$form['date'][#label]='Date Field(optional)';
}

}

may this will help you.


You might find some information about how to code changing file names in the File (Field) Paths module.


How to set up Drupal Commerce to sell users the ability to create/post custom nodes (ex. classified ads)?

You can do this with Rules pretty easily.

Create a role with the desired permission.
Create a product to sell.
Create a rule for the checkout complete event.

Condition is that the product you created is in the order. (I would probably create my own condition as I'm better with code than with the Rules interface, but you should be able to set this up in the Rules interface.)
Action is to give user that owns the order the selected role.
There is no step 4, you're done.


Relate Content to a Group feature when creating a node outside a group

Well, if I understand your problem correctly, you could just add an entity_reference field to your node type 'userpost' via admin toolbar. Go to Structure->Content types->userpost->Manage fields->Add field->Choose Reference (other)->Select Group and set cardinality to whatever you want.

This would allow you to add group references when you create a new node of content type userpost

Update
What I described adds a reference from a node to one or multiple group(s) via a new field, it does NOT add this node as a group-content to your group(s). It depends what you are trying to achieve? If you want to add your node as a group-content and you want to do this via the node creation form, you need one more extra step. You can implement a hook_ENTITY_TYPE_insert(). From there get the group(s) that you entered to your node field (from $node), $groups = $node->get('field_groups') and add the $node as group_content to each group, similar as done in the answer you linked.


Why do vertical images flip horizontal after upload?

Probably the program looks on your mac to the orientation of the recording itself. Most cameras place information in the photo or it is taken in portrait or landscape. The program that reads the picture can then look at it and put the picture correctly on the screen.


Get the username of a user who is being added to an organic group

I nice and simple way of accomplishing this will be to download the token (http://drupal.org/project/token) module. Once you've downloaded the token module be sure to enable token and token_actions module.

The token module will give you more "tokenize" options besides the default %username.

Now instead of creating a "send email" action create a "send tokenize email" action, this is going to give you a lot more token options to choose from.

The two options we care about are [author-mail] and [mail], in your case author-mail is the group manager email address and [mail] is the email address of the user that's joining the groups.

So add [author-mail] to the recipient option in the action and [mail] to where ever in the body you want to put it.

Now all you have to do is go to the Organic Group trigger page and add the new action we created to the "New user joins a group" trigger. That should do it. If you can't seem to be able to add that option to the trigger check out the triggerunlock module (http://drupal.org/project/triggerunlock) which will fix that problem for you.

Hope this helps.


Anyway to clear cache on Drupal 7 without any extra modules or even going to the performance page?

drush cc all is the safest bet.

Visiting www.example.com/update.php will also clear the caches, but you need to be logged in.  Otherwise, this is a DOS vector.


Try

Backup and Migrate

Migrate

Related projects

Migrate Extras

Migrate Drupal


Is it possible to hide certain content type options?

I assume your logged in as admin (user 1), so you'll always see them, but for other users it depends on the permissions they have and you can also use http://drupal.org/project/override_node_options to toggle this for each role


How to create a chart about the number of nodes by content type?

Let me try to answer this if I am getting you clearly. There are several contributed modules available for creating charts in Drupal. Refer to the comparison of charting modules for more details. You are not specifying the Drupal version, let me assume a use case for 7. Also know that there are various types of licenses (commercial, open source, ...) for each of the charting libraries, so your choices may be limited by your license needs (each module typically requires at least 1 such charting library as its charting engine).

The solution I am giving has a lot to do with the Google Charts API implemented via the Google Chart Tools module. The module provides a simple API that allows you to build your graphs on that.The module ships with an example that gives a nice pointer to writing your own custom module.

A simple module to get the content types.

function example_block_info(){
  //lets display this in a block. You can do a page if you like.
  $blocks['example_chart'] = array(
     'info' => t('Example Line Bar Showing Content Types'),
     'cache' => DRUPAL_CACHE_PER_ROLE //This is a Drupal default.You can set your own.
   );
 return $blocks;
}

function example_block_view($delta = ''){
    //Create a display for the block.
    switch ($delta) {
      case 'example_chart':
       $block['content'] = example_block_contents()
      break;
    }
  return $block;
}

function example_block_contents(){
  //This is a function specific to the block that lets you prepare the content for the chart.
    //Google Chart Tools integration begins here.
    //First empty the array that is to be passed to draw_chart().
    $settings = array();
    //We then populate the array.
    $settings['chart']['Chart for Nodes'] = array(
      //I am using just one content type. You can loop to get the other node types.
      'header' => array('My Node'),
      //This is the array to be presented to draw().
      'rows' => array(array(
                example_node_count(),
               )
           ),
      'chartType' => 'ColumnChart',
      'containerId' => 'example_chart',
      'options' => array(
            'forceIFrame' = FALSE,
            'title' => 'A column chart for nodes',
            'width' => 800,
            'height' => 600
        )
    );
    draw_chart($settings);
    //Return the DIV containing the chart.
    return '

';
}

function example_node_count(){
  //Custom function to count the nodes available.
  //Put to use Entity Field Query.
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_node_type');
    //Count your node type.Introduce a loop to count your other nodes as needed.
    $my_node_type_count = $query->count()->execute();
    return $my_node_type_count;
}

This is just a shell of a working module. Get some education of the charts at Google Visualization API docs. Warning: There might be some typos in there. Just trying to give an alternative.


How to convert a menu tabs in menu links block?

One of the ways is to simply change the menu type from MENU_LOCAL_TASK to MENU CALLBACK, and then simply create a menu item with the path.

Sample Code:
Cherry pick menu tabs and convert:

function MYMODULE_NAME_menu_alter(&$items) {
  $items['node/%node/view']['type'] = MENU_CALLBACK;
  $items['node/%node/edit']['type'] = MENU_CALLBACK;
}

Convert all at once

function MYMODULE_NAME_menu_alter(&$items) {
  foreach ($items as $key => $value) {
    if ($items[$key]['type'] == MENU_LOCAL_TASK) {
      $items[$key]['type'] = MENU_CALLBACK;
    }
  }
}


I feel you're missing .htaccess file. Usually its a hidden file, so make sure to show all files (including hidden files) and copy it and paste it into your local drupal folder.

Also, make sure you local server has mod_rewrite enabled to support clean URLs, if its not enabled then check this answer: How to enable mod_rewrite in Apache?.

Another suggestion is; to turn off Clean URL from settings.php by adding the following code:

$conf['clean_url'] = 0;


Class not found for a new module/service I am building. I am not sure how to debug

And this is my class
/modules/custom/fivewire_commerce/EventSubscriber/fivewire_commerce_orderStateSubscriber.php

Autoloading relies on your classes being in a root /src folder for the module.
So move the file to

/modules/custom/fivewire_commerce/src/EventSubscriber/fivewire_commerce_orderStateSubscriber.php

And PHP will be able to find it.


Shipping amount incorrect when hitting "Go back" on checkout

Check out Per Product Shipping Buggy

Import this rule or a variant of it and adapt it to your use case:

{ "commerce_shipping_service_free_shipping" : {
"LABEL" : "Rate Free shipping",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_shipping" ],
"USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
"DO" : [
{ "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
{ "commerce_shipping_service_rate_order" : {
"shipping_service_name" : "free_shipping",
"commerce_order" : [ "commerce-order" ]
}
}
]
}
}


Customising image in the first row in a views

you can also use hook

function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'your_view_name' && $vars['view']->row_index == 1) {
    // your code
  }
}


Programmatically create a block region in Drupal 7

Edit your theme .info file to add the following line:

regions[youregionname] = Your Region name

Edit your template file (e.g. "page.tpl.php"), and add the following lines:

<?php if(!empty($page['youregionname'])) : ?> <!--check if region enabled-->
  <div class='my-new-region-class' >   <!--add class to my region-->
    <?php print render($page['youregionname']); ?> <!--print the region-->
  </div>
<?php endif; ?>

After editing the files, don't forget to clear the cache.


Replacement for Drupal 6's $form_state['post'] in Drupal 7

$form_state['post'] in Drupal 6 contains the values of the $_POST global, and a quick look at Drupal 7 shows that when accessing a form via the post method, $form_state['input'] will contain that same array.  Side note: if it is accessed via the get method, this will contain $_GET.


Curently is not possible using core to transliterate uploaded filenames (referer to this and this core issues). To solve this you need to use the Transliterate filenames for uploads module. Check the comments from above.


How to change date_popup date format in form?

EDIT: fixed by setting up drupal date format and using datepicker_options:

$form['mymodule_start_date'] = array(
'#type' => 'date_popup',
'#title' => t('Start date'),
'#date_format' => 'd-m-Y',
'#datepicker_options' => array(
    'maxDate' => 0,
    'dateFormat' => date_popup_format_to_popup('d-m-Y'),
    ),
'#date_year_range' => '-3:+0',
'#date_label_position' => 'above',
'#theme_wrappers' => array('date_popup'),
'#required' => TRUE,

);


Drupal 8 Customize CKEditor Format Options

CKEditor's format drop down is intended for block-level elements only. So e.g. for headlines, divs, blockquotes, paragraphs and so on.

Inline-elements as spans, links (in CKEditor inline elements by default, even HTML5 specs state they can wrap block elements), i, b, strong, em and so on will have to use the styles drop down.

The css tag is neither block nor inline element, and you'd have to define it as custom block element first.

You can let CKEditor know about your block-level elements by extending the dtd setting, but this exceeds the scope of the Drupal Answers group, even Drupal 8 is using CKEditor by default. Please refer to the CKEditor docs for more information.

For your very special use case, I do have a suggestion:

In one of our projects, we have been using the GeSHi filter module in conjunction with the codesnippet module and added a text filter module codesnippet_geshifilter that "translates" codesnippet markup to GeSHi filter compatible markup.

The intention was to have JavaScript based syntax highlighting while editing the source code, but render pages with server-side generated GeSHi highlighting.

It works well for code blocks. There are some flaws with inline code however. These require tweaking the available CKEditor styles drop down.


How to push changes from a dev environment to prod

I use a custom script to automatically pull production to backup and update servers (an update server is a sanitized clone of production with updates applied via pm-update, standing by and ready for testing).  You might get some ideas looking at that.  However, I'd say that it would be a bad idea to automatically sync either prod to dev, or dev to prod.  Only publish to production after a human has tested and validated the release you'd like to bring live.  As for automating prod to dev updates, I'd think that the devs would find that very annoying.

One thing that you could pretty easily do is automate the updates of your staging server.  Just pull the database down from production, pull the latest code up from the dev branch of your repository, and run updatedb and your test suite.  A human could then validate the results and publish the code to production if it was ready.


How can I create a select list with all languages?

there is the _locale_get_predefined_list which return you an array.
so you need to do the field yourself.

you also could try language_field, you should be able to use that directly in your form.


Where are features displayed after they are created?

I think its important to know that essentially, Features result in modules that capture site configuration.

Fundamental differences in D7 and D8 with what Features is designed to accomplish with configuration essentially in Core.

However, if you create a feature and "write" as opposed to "download" the UI should show your saved configuration. This section of d.o gives some detail.

You may prefer to try downloading features once they are what you want, and commit them to a git repo.  Much safer and stable working this way in my experience.


You can do it using the Views Data Export module (Most popular)

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

  CSV
  Microsoft XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT
  XML

Example:

Alternatively, you can also do it using the Views Datasource module

  Views Datasource is a set of plugins for Drupal Views for rendering
  content in a number of shareable, reusable formats based on XML, JSON
  and XHTML. These formats allow content in a Drupal site to be easily
  used as data sources for Semantic Web clients and web mash-ups. Views
  Datasource plugins output content from node lists created in the
  Drupal Views interface in a variety of formats - XML data documents
  using schemas like OPML and Atom, RDF data documents using a
  vocabulary like FOAF, JSON data documents in a format like Exhibit
  JSON, and XHTML data documents using a microformat like hCard.


Show node in view based on dropdown in seperated content type

I found a solution.

I followed the following steps:

I have created an entity reference (in the content type sport)
I have created a view with relationship to the entity reference
I have created a contextual filter, content Nid with the relationship I created before to the entity reference field.

Everything works now!


Cant remove description field for new taxonomy terms

The description field is a main field. The equivalent to the body field in a node. If you dont need it you have 2 options.

1) You can just ignore it
2) You can use hook_form_alter to hide it for this (or all vocabularies)

There is no setting 'hide description field). If you want to hide the field from the form altogether let me know and I can explain hook_form_alter if you need me to. Otherwise when I don't need a description field in my taxonomy terms, i just leave it blank.

Edit to include the hook form alter

Information on hook_form_alter can be found here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7

This can go either in your theme's template.php or a custom module, I'm going to assume your theme, and rather than the standard hook_form_alter we'll use hook_form_FORM_ID_alter

/*
* Implementation of hook_form_FORM_ID_alter
*
* Hiding taxonomy term description field
*/

function YOUR_THEME_NAME_form_taxonomy_form_term_alter(&$form, &$form_state) {
  $form['description']['#access'] = FALSE;
}

Just change theme name for module name if your using a module


How do I code to take action when a VBO (bulk action) is finished?

This is how I tackled this scenario in D7.

In my custom VBO code I did a variable_set() and then I use hook_views_pre_render (note that the D8 hook params changed, so don't copy the hook from my code below) and did a variable_get(), if it was not empty, then do your action.

/**
 * Implements hook_views_pre_render().
 */

function bulk_mail_hauliers_auto_emailing_views_pre_render(&$view) {
// check the view name
if ($view->name == 'hauliers_auto_emailing') {

    $store_all_in_one_en = variable_get('bulk_mail_hauliers_auto_emailing_all_in_one_en', 0);

    // check that variable_get is not empty, which means VBO ran.
    if ($store_all_in_one_en != 0) {

      // CUSTOM ACTION GOES HERE

      // delete the variable
      variable_del('bulk_mail_hauliers_auto_emailing_all_in_one_en');

    }

}

So you can basically do this in D8, except use the D8 equivalent of variable_set,get,del.


How can I check, if node has a new (unpublished) revision in node-template?

Maybe this could help you

{% set isNew = node.isNewRevision %}

Otherwise use template_preprocess_node() in your theme to generate needed variable.


How to use official documentation to figure out what namespace to use

I was able to discover the namespace by finding the documentation for the Term class here.

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.1.x

And on that page there's a namespace section that said Drupal\taxonomy\Entity so I used

\Drupal\taxonomy\Entity\Term::create

and that worked.

So I believe in order to find the right namespace to use, you have to find the page for the class that is using the method. In this case Term. And then find the namespace section and put that before the class when you are using a method of it.

(This might be obvious to everyone else, but it took me a bit to figure out)


Adding custom designed product to cart in drupal commerce

I think you can done it using commerce_cart_product_add(). Pass product id and line item as parameters. For details please check here.Hope this will help you..


Is there a good way to determine which database table are associated with each module?

I am unaware of an automated way to check for orphaned tables.  Before the Schema API was rolled out in Drupal 7, people would use the Schema module.  This had a hook_requirements() in it that would do this check and list orphaned tables on the status report.

You could make your own automated test.  The procedure would be something like

Do a SHOW TABLES query to get the list of all of the tables.
Query the {system} table to get a list of all modules, both enabled and disabled
Loop through the modules, and then use drupal_get_schema_unprocessed() to get the module's schema.  From this, build up a list of tables.
Do an array difference between the list you just built and the list from SHOW TABLES.  This should be all tables that aren't owned by a module that is enabled or disabled.

Something like this:

$alltables = db_query('SHOW TABLES')->fetchCol();

$modules = db_query("SELECT name FROM {system} WHERE type = 'module'")->fetchCol();

$accountedfor = array();

foreach ($modules as $module) {
  $schema = drupal_get_schema_unprocessed($module);

  if (!empty($schema)) {
    $accountedfor = array_merge($accountedfor, array_keys($schema));
  }
}

// tables not accounted for by hook_schema() from enabled and disabled modules

$orphaned = array_diff($alltables, $accountedfor);

This ignore the intricacies of table prefixes, multiple catalogs, and sharing catalogs between applications.

Use at your own risk.


Continue saving node under some condition

You can use hook_node_validate() to check your condition.

  Perform node validation before a node is created or updated.

  This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.

  To indicate a validation error, use form_set_error().


How to make a page the home page of another domain

Use Domain Access: https://www.drupal.org/project/domain

Core Drupal + Domain Access can do this, you don't need any code or custom modules. Your Drupal can load different content on each configured domain name.

Point all domains in Apache/Nginx at the same Drupal install
directory.
Install Drupal using your primary domain.
Create your Landing Page nodes using the default Page Content Type.
Install Domain Access.
Add a new Domain at: http://example.com/admin/structure/domain/create
Edit the Domain settings at: http://example.com/admin/structure/domain/view/:id/config and specify the Site frontpage.
Done.

If you want it in code, you can export the entire configuration with the Features module: https://www.drupal.org/project/features


How can I have a view  tag render markup correctly?

with Views UI, in the HEADERsection, add a Global Text area with this Content in Text format = Full HTML:
Ajouter

and it gives something like:


You might want to try a community solution for this like breadcrumbs by path

Your custom function isn't doing anything with the url path itself, it's just using the breadcrumb variable. You can get the path with:

$_SERVER['HTTP_HOST'] . request_uri();

Then you could split by '/' and use drupal_set_breadcrumb to set it.


Adding a library to a module using composer

Using composer update, Composer created the vendor directory, and the autoload.php file, which is necessary to autoload the library. Unfortunately, Drupal doesn't load all the autoload.php files found in each of the directories containing a module.

Instead of adding the dependency of your module in the composer.json file used by Drupal, you should edit its extra/merge-plugin section to include the directory containing the modules you add.  (I added the "modules/*/composer.json" line.)

"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},

In this way, running composer update from the Drupal root directory would  add the required classes in the vendor directory used by Drupal, making them automatically loaded.

If the modules you install are all hosted on drupal.org (i.e., you don't use any custom module), you can instead edit the repositories section to contain the following lines.

"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packagist.drupal-composer.org"
    }
}

In this way, you could add a module hosted on drupal.org running composer require drupal/module-name from the Drupal root directory, and Composer would install its dependencies (declared in the module's composer.json file) in the vendor directory, making the classes automatically loaded.


You need to create a connection between image and node, a reference. You should set the fid. Have a look at this example. Also, in my case it was really helpful this post


Taxonomy menu with a large list of terms

Yes, this error usually is related to a large size of data, so database can't handle such sizes due the given limits and it fails, because the server timed out and closed the connection.

To fix it, you need to increase value of max_allowed_packet in your my.cnf (e.g. ~/.my.cnf) under [mysqld] section, e.g.

[mysqld]
max_allowed_packet=256M

See: B.5.2.9 MySQL server has gone away for more detailed information.

Another thing is that in this particular case it happens in shutdown function (which is after Drupal finished the processing of the site), therefore it could be related to some cron or debugging tasks.


How do I check if a single on/off checkbox is checked?

There's a mix of correct and incorrect details here, so I will try to sort them out. This is for Rules on Drupal 7, and applies to working with a Boolean field.

To make a condition that checks a field's Boolean state (true/false, yes/no, checked/unchecked), first make sure that you can access the field in the data selector. As Bojan mentioned above, and as it mentioned on the admin page itself,

  To make entity fields appear in the data selector, you may have to use
  the condition 'entity has field' (or 'content is of type').

The operator you want to choose is "equals".

For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field.

Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.


CAS module is a nice option, and it is quiet stable in D8 (using it in production site since more than a year). Morerover, SSO looks more confortable for users that don't have to reconnect when they jump from one site to another.

You should know that each D8 site will have its own user table created by the CAS/Externalauth modules'stuff.
If you plan to grant different access permissions based on something (many payments methods), imho, you should store these infos somewhere regardless to drupal (more precisly : anywhere your CAS server can retrieve, i have not tryed cas_server). Those could be retrieved in attributes sent during connection according to CAS protocol (CAS parameters).

Note : Given the fact each of you websites store its user table, and do not necessarily know the existence of an user "x" until its first connection to this site, you just have to pay attention on duplicates. Easiest way is probably to use email as UID but you undestand the idea.


Rewrite a text field in "Manage display" of content type

You have a couple of choice based on your needs:

Overriding the template file (twig) of the specific field
Using form_hook_alter
For complex and clean solution I suggest you to use a custom widget for your field type.


Remove the X-generator header from the response

The simplest method is to remove the header in a custom EventSubscriber:

$response->headers->remove('X-Generator');

See https://drupal.stackexchange.com/a/201297/47547 for an example.


Be aware that the rendering (and therefore the translation) happens at $this->renderer->renderRoot(). I'd create a mail key handler, and build the body inside that handler. I'm not sure, but it may be that drupal switches to the given language at the ->mail function before processing the custom hook.

  $this->mailManager->mail(
    'mymodule',
    'content_update',
    $follower->getEmail(),
    $follower->language()->getId(),
    [
      'node' => $node,
    ]
  );

/mymodule.module

<?php

use Drupal\Core\Url;

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $renderer = Drupal::service('renderer');

  if ($key === 'content_update') {
    $node = $params['node'];
    $renderArray = [
      '#theme' => 'email_notification_content_update',
      '#name' => $node->getOwner()->getDisplayName(),
      '#content_title' => $node->getTitle(),
      '#content_url' => $node->toUrl('canonical', ['absolute' => TRUE])
        ->toString(),
      '#unfollow_url' => Url::fromRoute('flag.field_entry.delete', [
        'flag' => 'flag_name',
        'entity_id' => $node->id(),
      ])->setAbsolute()->toString(),
    ];
    $message['body'] = $renderer->renderRoot($renderArray);
    $message['subject'] = t("Content :title has been updated", [':title' => $node->label()]),
  }
}


How to NOT "Print" a section by using Print module?

In those cases I added a custom print--pdf.tpl.php file to my theme and defined my custom css in the head of the HTML page which is rendered in this file (you find the original template file named "print.tpl.php" in the print modules folder - just copy it to your theme and rename it).

Here you can define any element by CSS and give it a "display: none;" - so it will not be seen in your final PDF.


How to set Cron Job in custom module for specific time in Drupal 7

You can't. Drupal 7 does not provide this functionality. You have two options:

In your mymodule_cron(), test if it is after specified time, and at least arbitrary number of hours after previous run (like, 20?). That way your processing will run almost every day, no earlier than specified hour.
Make your module require Elysia Cron and use it's scheduling capabilities. That way you will get your code executed everyday, at specified time (5 minutes resolution if Elysia is configured as suggested in their documentation).

Important: You cannot assume your task will be executed at specific time. It will be executed at first opportunity after the time you specified, whenever, if ever, such opportunity happens. Elysia Cron is pretty good at it, true, but exact time of execution can't be assumed guaranteed. Highly probable, to some resolution, maybe. But never guaranteed.


In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:

<?php
  // Retrieve all records into an indexed array of stdClass bjects.
  $result->fetchAll();
 // Retrieve all records into an associative array keyed by the field in the result specified.
  $result->fetchAllAssoc($field);

  // Retrieve a 2-column result set as an associative array of field 1 => field 2.
  $result->fetchAllKeyed();
 // You can also specify which two fields to use by specifying the column numbers for each field
  $result->fetchAllKeyed(0,2); // would be field 0 => field 2
  $result->fetchAllKeyed(1,0); // would be field 1 => field 0

  // Retrieve a 1-column result set as one single array.
  $result->fetchCol();
  // Column number can be specified otherwise defaults to first column
  $result->fetchCol($column_index);
 ?>


How to vote for both answers and question using the Answers module?

Instead use Question/Answer module, it have the vote system for both question and answer

  It adds a question/answer section for website. Different from other
  modules, it uses only one node type for question, and the core
  comment.module for answer. This allow reutilisation of CCK, Views..

or

You can try Vote Up/Down module

  Allows votes on some drupal entities and provides the base for
  implementing votes on other entities

or take a look at Rate module

  This module provides flexible voting widgets for nodes and comments.
  Multiple ratings on the same node (i.e. for "comfort", "location",
  "services" etc.)


This is the final solution:

use Drupal\Core\Entity\ContentEntityForm;

$bundle = FALSE;
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityForm) {
  $bundle = $form_object->getEntity()->bundle();
}


Why don't you just use the Superfish module that already integrates Superfish into Drupal. It automatically creates a block to add to any region you wish.


How To Add Button To Commerce POS Command Pane?

Implement the hook hook_commerce_pos_commands().


Create content within the site instead of the Drupal modal popup?

It is, but you'll need a bit of jQuery:

(function($) {
  $(function() {
    $('a[href="/node/add/client-request"]').addClass('overlay-exclude');
  });
})(jQuery);

That will add the overlay-exclude class to any link that goes to the node add form for your content type; all this is does is force the overlay to close when the link is clicked, and forward you on to the right page. It'll also stop any links on non-overlay pages from invoking the overlay for that path.


Why is the login redirecting to the access denied page?

I had the same issue but for Chrome and this was caused by the old cookies since it perfectly worked on the other web browser (Opera). When I've removed old cookies while being on that page, it worked as well.

If this doesn't work on one browser, but not on the other, definitely it's related to the invalid cookies.

If this doesn't work for all web browser, then most likely it's invalid cookie_domain setting in your services.yml file. By default Drupal automatically generates a unique session cookie name based on the full domain name used to access the site and it's sufficient for most cases. However if you're re-using across different subdomains, then you need to set your cookie_domain.


Taxonomy term via Rest API returns 406 Not Acceptable

This works as expected using Drupal 8.3.x using latest Rest UI Mar 28, 2017.

I've done a clean Drupal install
Next created a term visiting  http://drupal.d8/admin/structure/taxonomy/manage/tags/add
Visited the term http://drupal.d8/taxonomy/term/1 to check it's there
Tested for a json response http://drupal.d8/taxonomy/term/1?_format=json
giving the expected {"message":"Not acceptable format: json"} as we have not yet configured Rest
Next enabled Rest UI module
Configured taxonomy term on http://drupal.d8/admin/config/services/rest
Visiting http://drupal.d8/taxonomy/term/1?_format=json again gave me the expected json output like {"tid":[{"value":1}],"uuid":[{"value":"d5e87924-5ccd-4fbe-bf1b-f1790da0d800"}],"langcode":[{"value":"en"}],"vid":[{"target_id":"tags","target_type":"taxonomy_vocabulary","target_uuid":"b1d2d8a9-0f05-49e7-abbc-137aaa9d0f64"}],"name":[{"value":"Term 1"}],"description":[{"value":null,"format":null}],"weight":[{"value":0}],"parent":[],"changed":[{"value":1491899632}],"default_langcode":[{"value":true}],"path":[]}

Note I have tested as admin and anonymous with same results. Enabling HAL and requesting the formats xml and hal_json gave the expected results too.

Disabling cookie request and enable basic_auth give a different response.

  {"message":"The used authentication method is not allowed on this route."}

Hope this helps.


Set the status of the created file to something other than PERMANENT.

So replace

$file->setPermanent();

with

$file->status = 0;

The file field will then set the status to permanent and add the file_usage metadata.


Drupal 7 - Output taxonomy terms on a node?

You don't need php field for this.

On the right side click on Advanced, under RELATIONSHIPS add "Content: Taxonomy terms on node".

On the left side add a new field. Search for taxonomy and you should see a Taxonomy term name field that is now available thanks to the relationship.


Any flexible customizable theme for display configuration via panels?

I still very new to the Panels module and theming in general but I have really enjoyed the Zen base theme.

I think it would have been confusing as a 'first' theme, but if you've been playing with Bartik and other common Drupal themes I think you'll love Zen.

The support, documentation and standardization surrounding the project is very impressive.

I should note though you need to be comfortable designing with CSS.  It's very 'clean' out of the box.


Drupal website only in Arabic on English installation

First you'll need the i18n module to enable your drupal website for a multilingual setup. It should be no affair to have Arabic as the preliminary language, though you may think about having English as the default language due to some string issues. If you want a website with right-to-left text direction, you'll need a theme which supports this.

A good start to see what's also important can be found in this comprehensive tutorial.


Change workbench_moderation_state from select to radio

$form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick.
I just forgot the ['options'] array.


Image styles are not created 404 Not Found

The solution is to add try_files $uri $uri/ @rewrite; at the bottom right after add_header, final snippet with more edits:

location ~* /sites/default/files/.*\.(?:css|js|ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 1w;
    add_header ETag "";
    add_header Cache-Control "max-age=2628000, no-transform, public";
    try_files $uri $uri/ @rewrite;
}

This solves the issue, we use this snipped with AdvAgg module.


Hook into update/install process callback (Update manager) - providing a custom message after installing a module from URL

I think the easiest way would be to extend the ModuleUpdater class to provide your own postInstallTasks() implementation:

class MyModuleUpdater extends ModuleUpdater {

  /**
   * Overrides ModuleUpdater::postInstallTasks().
   */
  public function postInstallTasks() {
    return array(
      l(t('Enable @module module', array('@module' => $this->title)), 'admin/modules/enable/' . $this->name),
      l(t('Install another module'), 'admin/modules/install'),
      l(t('Enable newly added modules'), 'admin/modules'),
      l(t('Administration pages'), 'admin'),
    );
  }

}

And then implement hook_updater_info_alter() to let Drupal know you want to use that class instead of the default:

function MYMODULE_updater_info_alter(&$updaters) {
  $updaters['module']['class'] = 'MyModuleUpdater';
}

You'll also need to add this to your module's .info file so the new class can be autoloaded:

files[] = path/to/MyModuleUpdater.php

Once you clear the caches the change should take effect.


How to programmatically create new revision and publish it?

I think it will work when you explicitly set revision_moderation to FALSE. If moderation is not required, it should be published right away.

$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
$node->revision_moderation = FALSE;
node_save($node);

From the example here: http://drupalprogrammatically.com/anwsers/7/create-node

Poster of above url also sets $node->revision = FALSE;, but that would give me the impression no new revision is saved, which is not what you want.
I hope it helps.


Is it possible to extend Drupal's user_access() function to provide a more complex logic for permissions

Looking at the code there's simply no way to do this without directly hacking the user_access() function.

There are no hooks invoked and the logic is completely self-contained, aside from one call user_role_permissions(). That function just runs a database query though so there's no scope to intercept the process there.

Obviously you could write your own access function and call it from your own code, but there are 152 calls to user_access() in core files (and countless others in contributed modules) which won't be able to take advantage of it unfortunately.


For that, you're going to want a custom template file (.tpl.php in D7, .html.twig in D8).

In Drupal 8, the logo and site name are contained within Bootstrap's block--system-branding-block.html.twig; in Drupal 7, they're set in Bootstrap's page.tpl.php. If you go into that file, you can change how those elements are rendered - just wrap them in the necessary  /  tags and you'll be good to go!


To bootstrap, try adding the following lines of code to the top of your custom-posts.php file:

$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
define('DRUPAL_ROOT', '/var/www/drupal7');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Don't forget to update the path to your Drupal root folder.


Error when activating the View Mode Page module

I don't know about the View Mode Page module specifically, but here's how you can find out yourself.

Check the issue queue for the module.  You can find a link to "all issues" on the module's project page (in this case, here).  In this case, there aren't many issues; if there were a lot, you can use the search function.  If searching, make sure to set the status to all issues, not just open issues, as if you're lucky your issue will already have been reported and fixed.
If step 1 doesn't solve the problem, create a fresh install of Drupal 7 on your local machine or another server and install the Views Mode Page module and its dependencies.  Make sure it works properly by itself when you have no other modules enabled.  (For a small module like View Mode Page which has less than a few hundred installs, this step is especially important; for an extremely common module like Views itself, you can assume that someone has already done this and it's your problem.)
If step 2 doesn't solve the problem, you'll need to start disabling the modules on your site one by one.  Of course, don't do this on your live site-- do it on a backup site.  Just guess which module might be causing the problem, disable it, and then clear the cache.  Then try to enable Views Mode Page.  If it doesn't work, choose another module to disable and repeat.

Yes, this is really painful and frustrating, but sometimes it is necessary if a search of the issue queues on drupal.org doesn't turn up anything.  If you do have to do this and find the source of the problem, please don't forget to create an issue on drupal.org and report what you found!


240sec Registering New Account with Services

This was a server configuration issue as described here: http://www.promediapublishing.com/blog/2012/07/fixing-a-slow-registration-form-post-on-drupal-7


How do I compare a field of a node with all nodes of a content type with rules?

I haven't found a solution using only rules yet, maybe it would be possible with rules and views bulk operations (vbo)? A custom module is what I did to solve it (thanks Oleg for pointing me to EntityFieldQuery). Here is the code:

<?php

/**
 * @file
 * custom_unpublish.module
 *
 * This module compares a field in a node when updated with a field in all
 * nodes of a content type and if match, the matching nodes is unpublished
 */

function custom_unpublish_node_update($node) {
  // Only check nodes of a certain content type
  if ($node->type == 'article') {
    $wrapper = entity_metadata_wrapper('node', $node);

    // Get the wanted field
    $id = $wrapper->field_id->value();

    $query = new EntityFieldQuery();

    // Check only a certain content type (bundle) and make a fieldCondition
    $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'accepted_article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_id', 'value', $id, '=');
    $result = $query->execute();

    if (isset($result['node'])) {
      $result_items_nids = array_keys($result['node']);
      $result_nodes = node_load_multiple($result_items_nids);
      foreach ($result_nodes as $result_node) {
        // Unpublish the node
        $result_node->status = 0;
        node_save($result_node);
        watchdog('custom unpublish', 'Match for ' . $id . '. ' . $result_node->title . ' was unpublished.');
      }
    }
  }
}


How can I add a "weight" functionality to nodes?

You could for example use Nodequeue to create  fixed list of nodes and then show that as the front page (as a view I guess).

Or, you could define your own weight field (for example a simple integer field, or a select with options from -50  to 50) and then create a view of nodes which you sort based on that field.


field_attach_update stopped working - how to debug this?

You can't debug what ain't a bug :)

status is a property, not a field, of the commerce_order entity type - so it isn't affected by running field_attach_update(), which just saves field data, and avoids saving the entity itself.

You'll need to use commerce_order_save(), entity_save(), or manipulate the commerce_order table directly, and then clear the cache using the entity controller.


Tag to show Related Content Type and Term

You could create two separate vocabularies each with the same terms in it, then make one vocabulary available to content A and the other vocabulary available to content B.

An alternative is to use views: https://drupal.org/project/views

With Views you can list items of a Content type with certain tags associated with it on a page.

E.g. I have two content types News & events both are categorized by term group. I only want display all News items so I use Views to only show content type News.


Drupal 7 doesn't allow search in chinese character

This is probably a server configuration issue.  I have successfully used Japanese search on both Drupal 6 and 7.  Try installing a copy of your site on a local development environment (Acquia Dev Desktop, etc.) and see if the problem recurs.


Custom libraries and dependency injection

OK people, I played around with a couple of options, but the bottom line is, if you want to create your own 'services' class, specifically for dependancy injection, it has to be tied to a module.

So - I created a custom module.  The actual module file is empty

<?php

Also created the services definition / config file my_module.services.yml and then critically, your services class files should go in a sub-folder /src.  Since it is a service, you will need an interface and implementation class.


Adding a tab to commons browsing widget with hook_commons_bw_group_widget()

Don't know if this is your module, but this one accomplishes just that:
https://drupal.org/project/commons_bw_ui

It was posted just 2 weeks after your post above.


hook_menu() is the method used by modules to add their own menu items. Most of the menu items you see on Drupal are added by modules with that hook.
The user interface allows you to add extra menu items that are not added by modules.

If you are asking the difference between creating a module that adds menu items with hook_menu(), and adding menu items with the user interface, hook_menu() allows to do things that are not possible with the user interface. For example, the menu that is visible when you hover the gear icon visible for a block is created with menu items added with  hook_menu(). (It requires the Contextual links module, which is a Drupal core module.)

The tabs that you see, for example, on a node page, are created with hook_menu(), or hook_menu_alter(). You could not create them with the user interface.

What you can create with the user interface are links that go:

In a menu block

In the Menu links

In the Secondary links


Create a public profile page for specific roles only

It seems that what you are looking for is to modify the URL structure. In my mind, View is for the layout. Since I assume you have a content type for Profile2 profiles, you can simply install PathAuto and configure it so your URLs have that structure.


which views template controls the field div sections

You should be able to accomplish this through the UI from each field settings form:


Drupal 7 html.tpl.php vs page.tpl.php variables questions/thoughts

Something to keep in mind is that Drupal doesn't work with templates the way a traditional MVC framework will. Ideally you want to have as few templates as possible in your theme, i.e having only one page.tpl.php with some conditionals would be best. If you do need to split things up you can define additional templates with hook_theme() in your theme's template.php and move your header/footer section into there, but in general you'll have better results by not having lots of template variations.


Translation mess up with fields which are not translatable used in views

This is known core bug, see https://www.drupal.org/node/2451657. The patch there should work well.


Try the XML Field module

  Defines an xml field type. Provides an XML widget using CodeMirror (beginning with version 7.x-1.6).Provides XML related API functions for working with XML code. Adds a theme_xml() theme function. Defines a form type called xmltext for use in the Forms API.

Image from project page


How to print anything in a twig template file

better practice is to do that in preprocess functions !

so, fe. in preprocess page, you can access the node (if existing) via the $variables array and so on ..., then you add your own variables for the twig template, like:

$variables['my_fancy_block'] = \Drupal::service('renderer')->renderRoot($whatever);

and access this like:

{{ my_fancy_block }}


You can set permissions for users - Skip comment approval in admin/people/permissions/list#module-comment(in drupal 7). After as admin you can manage your comments here - admin/content/comment you can approve comments, delete them or unpublish.


The input formats can be configured at /admin/settings/filters/list so that you can add the <iframe> tag as an allowed tag to the input format that you are using.

Though, I think for security purposes, you may want to allow tags other than <iframe>.  One option it so use Vimeo's 'old' embed code (the link would be just above the box where you copy the code from).  The old embed code uses the <embed> and <object> tags, which you'll likely still have to add to the filter's allowed HTML tag list.


You need to enable clean URLs. From the documentation:

For Drupal 7:

Navigate to the Clean URLs configuration page (Administer > Configuration > Search and metadata > Clean URLs)
Wait for the automated Clean URLs test to run.
Check or uncheck the Enable clean URLs checkbox
Click "Save configuration"

For Drupal 5/6:

Go to the Clean URL's (Administer > Site configuration > Clean URLs in Drupal 5) section of the administrative interface.
Look for the paragraph that reads as follows:

  This option makes Drupal emit "clean" URLs (i.e. without ?q= in the URL.) Before enabling clean URLs, you must perform a test to determine if your server is properly configured. If you are able to see this page again after clicking the "Run the clean URL test" link, the test has succeeded and the radio buttons above will be available. If instead you are directed to a "Page not found" error, you will need to change the configuration of your server. The handbook page on Clean URLs has additional troubleshooting information. Run the clean URL test.

Click on the Run the clean URL test link at the end of the above paragraph.
If the test is successful, set Clean URLs to "enabled" and save the configuration. If the test is not successful, use the steps below to fix your server configuration and try again.


Randomly show one item from the last x posted

Sort your View by Content: Post date (desc) and set the Pager to Use pager: Display a specified number of items | 5 items

Go to the Advanced Settings in the view and click in the Theme: Information

Search the Style output: section and select a name, in my case was views-view-unformatted--temp.tpl.php

Go to the folder YOUR_SITE/sites/all/modules/views/theme and copy to your theme folder the file views-view-unformatted.tpl.php and rename it to views-view-unformatted--temp.tpl.php

Edit your new file views-view-unformatted--temp.tpl.php and put inside only this code to show only one element:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
 //Selecting one element from your last 5 posted elements
 $element = $rows[rand(0, 4)];
 $rows = array();
 $rows[] = $element;

?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

In the View go to the bottom of the Information window and click Rescan template files and click OK, then save your View.

And go to see your result.

Attention: Remember to repeat these steps if you ever change theme.


How to upload files to the sites/default/files place without going to the Cpanel backend just through admin backend?

If you want to upload files from UI you can use the elFinder file manager module. I've checked this module. Seems it's what you're looking for.
You can upload multiple files from admin UI itself. You can access the URL like follows

http://example.com/elfinder

Features

  Integrated with WYSIWYG API  capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor
  Multiple file upload
  File copying/moving with Drag & Drop support
  Quick file and directory rename
  Image resizing
  Lightbox-preview
  Contect menu with generic file/directory operations
  Inline text file editing
  Favories directory list
  Directory selection history
  Working with archives
  File descriptions

screenshot


You can't use facets on MySQL (for the moment), from the project page:

Search facets
This module provides the ability to create facets on any search executed anywhere in Drupal, be it a search page, a view or any other source. The feature isn't available for all servers, though, since it would be too complex to implement for some service classes. Right now only the Solr servers support this, facet support for the database-based searches might be done in the future.

This means that you can't use facets, but you can still use Search API to search your content.


How to login into Drupal 8 using the REST API?

'Content-Type': 'application/json' needs to be 'Content-Type': 'application/hal+json' in order for it to work.

I recommend you watch these video tutorials

Learn Drupal 8 - REST API Part1

Learn Drupal 8 - REST API Part2

The login is covered in part 2, but part 1 is very informative and part 2 will make more sense if you watch part 1.

Although, the video tutorial uses the Google Chrome Postman add-on, your code needs to do the same.

Have a header with the Content Type and Authorization values

  GET http://{my-host}/user/testing

Your URL to POST, GET, or PATCH shouldn't be your user page, unless you want to work with the user fields. The URL needs to have the entity you are working with.

For example: See the url's used in the video tuts.

You can even use Postman to generate your code

HTTP Generation

PATCH /node/1 HTTP/1.1
Host: forexample.com
Content-Type: application/hal+json
Authorization: Basic Q2FtaWxvOmNvY29saXNa
Cache-Control: no-cache // delete
Postman-Token: 3803eeac-0dc2-5c09-05e1-40d15d5b9820 // delete

{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}

PHPV1 generation

<?php

HttpRequest::methodRegister('PATCH');
$request = new HttpRequest();
$request->setUrl('http://forexample.com/node/1');
$request->setMethod(HttpRequest::HTTP_METH_PATCH);

$request->setHeaders(array(
  'postman-token' => '9656f5e8-13a5-0e2b-23cb-5ac03af59b5b', // remove this line
  'cache-control' => 'no-cache', // remove this line
  'authorization' => 'Basic Q2FtaWxvOmNvY29saXNa',
  'content-type' => 'application/hal+json'
));

$request->setBody('{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

You can also generate for other languages like Python, jQuery, PHP Curl to name a few.


22762 rows in my session table. What does this mean for the site, and what should I do about it?

The long term action is to limit session lifetime.
Look for the following line in your settings.php:

ini_set('session.gc_maxlifetime',   200000);

This parameter sets session life time, after which session is marked as garbage and will be deleted by garbage collector.
Average session life time (not on drupal sites) is much less than 200000 seconds  - something between 15 minutes and half an hour (900-1800).
So, if you don't need long sessions, you can reduce ini_set value and thus get less sessions stored in the sessions table


Using Views as a report in a custom module

views_get_view_result is the API you should use to query an existing View and process the results in your module.


How to add multiple value using autocomplete widget

You need to explode the string inside the autocomplete function.

function autocomplete_callback($string) {
  $explode_str = explode(',', $string);
  $last_str = drupal_strtolower(array_pop($explode_str));
  // use $last_str in the query
  $explode_str[] = $result;
  return implode($explode_str);
}


on submission of form respective form should open

I'd do something like

function donation_donate_form_submit($form, &$form_state) {
  switch ($form_state['values']['donate']) {
    case 'candidate':
      $form_state['redirect'] = 'donate/candidate';
      break;

    case 'organization':
      $form_state['redirect'] = 'donate/organization';
      break;
  }
}

and from this point I can do two things

Solution 1

Create other two menu items with different form for each

Solution 2

your original form would be called if you don't create any extra menu items (drupal falls back to the longest menu item that match the current URL), then change the existing form depending on the argument like this

function donation_donate_form($form, &$form_submit) {
  $form = array();
enter code here
  // No argument ? we must be in the selection phase.
  if (arg(1) == NULL) {
    $form['officials'] = array(
      '#title' => t('OFFICIALS'),
      '#type' => 'radios',
      '#options' => array(
        'candidate' => t('Candidate'),
        'organization' => t('Organization'),
      ),
      '#default_value' => 'candidate',
    );

    $form['name'] = array(
      '#title' => t('NAME'),
      '#type' => 'textfield',
    );

    $form['submit'] = array(
      '#value' => t('PROCEED'),
      '#type' => 'submit',
    );
  }
  elseif (arg(1) == 'organization') {
    // Candidate form stuff.
  }
  elseif (arg(1) == 'candidate') {
    // Organization form stuff.
  }
  return $form;
}

It depends on how you like your code, and what you are trying to do.


Contextual filters exclude option missing

The exclude option is a part of the views_handler_argument_numeric handler that comes with views.  If it's not there, it likely means your filter is operating on something other than a numeric argument.  What you have is "Indexed Node: Node ID".  If you create a filter on "Content: Nid" instead then you should see the option.

Also see https://www.drupal.org/node/733686 .


How to send dynamic content as an attachment file in email?

I have found the answer.
Here is my code.
$content = '<?xml version="1.0"?><root><element>element value</element</root>';
$params['attachments'][] = [
  'filecontent' => $content,
  'filename' => 'data.xml',
  'filemime' => 'application/xml',
];

and then in hook_mail
function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'my_email_key':
      $message['body'][] = $params['body'];
      $message['subject'] = $params['subject'];
      $message['params']['attachments'] = $params['attachments'];
      break;
  }
}

BTW I am using the swift mailer module.
Hope this helps someone.


Ok, these elements do not display an "edit block" option when I am logged in as an admin and mouse hover them, nor do they display any of the HTML class / id properties which are typically associated with a block.  So It had to be somehow injected or modified VIA a template file.

I did however, finally discover that they were in fact being added via a cryptically named block.

This meant that it was likely being acted upon by a "block-" template. Armed with the newly discovered block number, I found that the file "block-block-22.tpl.php" was stripping the edit link and other divs and formatting to prevent the block from having it's own background etc.

The standard "block.tpl.php" file writes all blocks in the sub-theme like:

<div id="block-<?php print $block->module . '-' . $block->delta; ?>" class="<?php print $classes; ?>">

  <?php if ($block->subject): ?>

<?php print $block->subject; ?>

  <?php endif; ?>

    <?php print $block->content; ?>

  <?php print $edit_links; ?>

Whereas "block-block-22.tpl.php" was overriding the default and writing it as such:

<?php print $block->content; ?>

effectively stripping all of the block's formatting so that only the images that it contained would show with no extra margin, padding, background etc.

I had a feeling I was missing something simple...

Furthermore, changing it to:

<?php print $edit_links; ?>
<?php print $block->content; ?>

Enabled the "edit block" link for administrators, so now it can be edited directly from the page.


Place custom block on particular content type pages and home page

You can create two instances of the block on the manage blocks page. One instance can be limited to the content types on which you want it shown, and the other instance can be limited by path, which you will then set to <front>.


Solutions for frontpage that consist of only blocks

The pages are already built from blocks, where the 'main content' block is the page content. These blocks are positioned in regions defined in the template.

I guess you want to reorganize the blocks? Have maybe multiple columns and so? Then you can either use panels or alter the theme with the regions you want. (This basically is what panels does, but at the position of the 'main content block'. Leaving the other blocks intact.)


How can I cast a fivestar vote on a different node

How are you generating your page with the 15 products? I think views can display the widget as a field so that might be an easy way to achieve the desired functionality.


Mediafront Youtube playlist feed playlist problem

this i found useful: https://gdata.youtube.com/demo/index.html

which got me a functioning feed URL for MediaFront and so I still can create a playlist as a MediaFront preset. But its still another problem, yet to be solved, to get that MediaFront YouTube playlist preset to show as a node!!

Because when I add the same URL into an empty preset, its fails, complaining URL is bad!!

good luck and let me know how it goes for you ;-)

Richard


How do I let end users create and manage arbitrary connections between their user account and an entity

With Entity reference, this isn't very easy, because references are fields, and the permission management you need here is hard to do on a field level. You could still do it, but it would require a significant amount of custom work.

Consider using Relation or Flag instead.

You'll most likely get a better "out of the box experience" with the Flag module, but you will get better flexibility with the Relation module.

I've tried to convince one of Flag maintainers that the Flag is a special case of the Relation module and so should be based on it, but he didn't want to add a dependency.


Allowing content access only though aliases and views

Yes, in Drupal 7 this functionality was covered under the Global Redirect module. It has since been merged in the Drupal 8 version of Redirect.

Under the Redirect settings (/admin/config/search/redirect/settings), the Global Redirect section contains options to enable alias, non-clean, & canonical redirecting. This will enable you to redirect any requests from /index.php?q=node/X or /node/X to /my-canonical-content-alias.


dump $variables in theme_preprocess functions

The best way would probably be a breakpoint with xdebug turned on. Which requires configuration efforts though.

What I was normally doing in similar cases was a step-by-step approach. I was printing out $variables keys first and then narrowing my var_dump with a specific key. E.g. var_dump($variables['key']). Slowly but surely.

In the end I think that in terms of efforts it is way better to set up debugger and use breakpoints to inspect variables.


How to create a PHP file that returns a list of nodes as XML?

This is what i did:

I created a view.
Changed the style to XML data document (Need to download the Views Datasource module)
Added the fields I needed and Nodequeue
Added a filter to filter by node type so it looks like this:

then I added a new page with a path:

my end result looks like this:

 <node>
    <node>
        <Description>blablalbla</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>derp</Link>
        <gallery>Gallery1 For flash</gallery>
    </node>
    <node>
        <Description>sdfsdfdf</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>sdfdf</Link>
        <gallery>Gallery2 For flash</gallery>
    </node>
</node>


Adding labels to a Webform multistep form

Just add a fieldset around each step with the labels "step 1-3"


How can a field definiton be imported, either via the admin or in code?

There is nothing in the interface but what you can do is make a temporary content type which uses the field(s) you wish to import, then export/import that content type to the target site.

Your new field(s) will then be available at the target site, make sure you attach them to other content types before you delete the temporary one or the field(s) will disappear.