Define fields created through the UI as non-revisionable on a revisionable entity

By default, all the entity fields created from the user interface are set as revisionable, and the user interface doesn't allow to set a field as not revisionable. That information is added from field_entity_field_storage_info(), which contains the following code.
$ids = \Drupal::entityQuery('field_storage_config')
  ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
  ->execute();

// Fetch all fields and key them by field name.
$field_storages = FieldStorageConfig::loadMultiple($ids);
$result = [];
foreach ($field_storages as $field_storage) {
  $result[$field_storage->getName()] = $field_storage;
}
return $result;

FieldStorageConfig::isRevisionable() always returns TRUE.
public function isRevisionable() {
  // All configurable fields are revisionable.
  return TRUE;
}

To make a configurable field not revisionable, a module should implement hook_entity_field_storage_info_alter() and alter the $field_storage values returned from field_entity_field_storage_info().
  function mymodule_entity_field_storage_info_alter(&$fields, $entity_type) {
    $ids = \Drupal::entityQuery('field_storage_config')->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
      ->execute();

    // Fetch all fields and key them by field name.
    $field_storages = FieldStorageConfig::loadMultiple($ids);
    $result = [];
    foreach ($field_storages as $field_storage) {
      $result[$field_storage->getName()] = // Replace $field_storage with an object implementing FieldStorageDefinitionInterface and returning the value you want with isRevisionable().
    }
    return $result;
  }


How to create optgroups from taxonomy terms?

Is this what you are looking for:
http://drupal.org/node/76500#comment-2193734

I posted the code used in the comment.  All props go to Nate Anderson from drupal.org

<?php
if (isset($form['taxonomy'][$vid])) {
  $tree = taxonomy_get_tree($vid);
  $parent = "";
  $options = array();
  foreach ($tree as $term) {
    if ($term->depth == 0) {
      $parent = $term->name;
    }
    else {
      if ($term->depth > 1) {
        $options[$parent][$term->tid] = _modulename_spaces($term->depth, '-') . ' ' . $term->name;
      }
      else {
        $options[$parent][$term->tid] = $term->name;
      }
    }
  }
  $form['taxonomy'][$vid]['#options'] = $options;
}

function _modulename_spaces($number, $char = ' ') {
  $output = '';
  for ($i = 0; $i < $number; $i++) {
    $output .= $char;
  }

  return $output;
}
?>


The correct command for setting site in development mode is

drupal site:mode dev

Check here for more details - Debugging compiled Twig templates


How to hide webform block after submission for anonymous users?

When a visitor submit a form, cookie with a name "webform-123" (123 - webform ID) save in his browser. In the block visibility settings use the cookie existence check with PHP:

<?php
$match = FALSE;
if(!isset($_COOKIE['webform-123'])) {
$match = TRUE;
}
return $match;
?>

If the cookie does not exist, the condition will return the TRUE and the block will be displayed.


Create rule to e-mail only someone who has combined roles

Two solutions come to my mind:

Write a module that provides the action you require. See the Developer Documentation for Rules for how this is done.
Write a module that adds users to the role "Marketing Publisher" whenever he as both the role "Marketing" and "Publisher". The module would only have to implement hook_user($op = 'update') and hook_user($op = 'insert').


In my mind, the big advantage of using Panels is so that you can extend/alter sites like this in the future, without needing a lot of rework.  In a lot of ways, Panels provides a framework for futureproofing sites.

While I am not sure if I have used Domain CTools,that is the first approach I would take.  I essentially use a similar approach using Mobile Tools in combination with Domain Access for providing split desktop/mobile sites that share some, but not all, content and features.

The access rules that Domain CTools provides will show up in the visibility and selection rules inside Panels.

For the node pages, I would enable the default node override page inside Panels, and then make variants for each of my content types.  I would then assign access rules to each, based on the domain.

For the home page, I would make a new custom page and set it as the home page.  I would then make two variants, and make a selection rule based on the domain for each.

The other thing to think about is how nodes get used in places other than the node view page.  For example, if you should double check your views and add access controls as needed.  Assuming the approach outline above, you could also use the Domain CTools access rules.  Depending on what other uses there are, you may need to investigate whether you need a custom hook_node_access() for your site.


How to programmatically create a custom token in a module

In Drupal 7 the code for handling tokens is part of the Drupal core module.

The hooks the token modules need to implement are:

hook_token_info() is the hook that provides information about the tokens implemented by a module.
hook_tokens() is the hook that needs to be implemented to provide the actual values that replace the tokens.

Other modules can alter the token implementation provided from a module using hook_token_info_alter() and hook_tokens_alter().

Differently from the Token module, the code in Drupal core allows to create the content of a token only when strictly necessary.
In Drupal 6, the Token module would ask to the modules implementing tokens all the values for their token using hook_token_values(); this means that a module can compute the value for a token which is then not required for the tokens being replaced. In Drupal 7, the implementation of hook_tokens() receives $tokens, an array of tokens to be replaced, as argument; the module is then able to compute the value of a token, knowing it will be used.

The function that in Drupal 7 is used to replace the tokens with their value is token_replace(), which is the only function used to replace the tokens with their values.

Other difference between the Token module for Drupal 6 and the code in Drupal 7 are:

In Drupal 7, [node:author] returns the name of the author; [node:author:mail] returns the email address associated with the author of a node, and [node:author:url] returns the URL of the user profile for the node author. In other words, it is possible to use [node:author:xyz], where "xyz" is one of the tokens returned for a user object.
In Drupal 7, there are not raw tokens; the implementation of hook_tokens() get a parameter that tells to the hook when the content of the token needs to be sanitized; when the token value doesn't need to be sanitized, the content is not passed to the functions check_plain() or filter_xss().
In Drupal 7, there isn't any function that show the list of the available tokens. If a module needs to show the list of available tokens, it must build the list of the tokens itself and show it in the description of a form field; alternatively, it can use the theme function still available in the Token module.


Look at the module  Fuzzy Search , this may solve your problem.

  This module provides drupal sites with a fuzzy search engine to allow
  for broader keyword matches including partial or misspelled keywords.

  Fuzzy matching is implemented by using ngrams. Each word in a node is
  split into 3 (default) letter lengths, so 'apple' gets indexed with 3
  smaller strings 'app', 'ppl', 'ple'. The effect of this is that as
  long as your search matches X percentage (administerable in the admin
  settings) of the word the node will be pulled up in the results.


Images placed in blocks do not show up on certain pages

Add "/sandbox/" before sites like below
(src="/sandbox/sites/default/files/buttons/fbicon.png")

Or add "/" before sites as src="/sites/default/files/buttons/fbicon.png" and set your base url to http://www.thebeat99.com/sandbox


How to display all when input argument is wrong

For contextual filters, the Views UI allows you to specify two different cases:
Case 1: If the filter value is not passed to the URL
In the contextual filter configuration, in the "When the filter value is not in the URL" section, you need to set the "Display all results for the specified field" option.
Case 2: If the filter value is wrong
In the contextual filter configuration, in the "When the filter value IS in the URL or a default is provided" section, you need to check the "Specify validation criteria" checkbox. Then, you can set the "Action to take if filter value does not validate" to "Display all results for the specified field".
You can see more details in the Views documentation: https://www.drupal.org/node/1578574
Hope it helps,


Auto-create Nodes based on Content in current node?

You can do this kind of stuff with Rules. You could also look into hook_node_presave() yourself and do logic when nodes of TypeA are being saved.


Theming: Is this a valid way to go about it

You certainly could do it that way, however, that would require you to know all of the php necessary to make a fully functional Drupal page.tpl.  What I would recommend, and how I started themeing (outside of reading a bunch!) was taking a page.tpl.php from a theme similar to what I was looking for and modifying it until I was happy with it.  After doing this several times and experimenting a lot (and reading!) I became quite familiar with the templating system used in Drupal and the php code needed in the most common template files.


Looking to change the header from a color to an image

Add this CSS:

<style>
  #header {
    background: url('critic-banner-image.png');
  }
  #logo {
    margin: 0 15px 5px 15px;
  }
</style>

Add this background image
(use better ones that your client provides)

Replace your old logo with this:

(use better ones that your client provides)


Exposing Individual Fields on Output for Styling

This is a complex but ultimately pretty easy thing to do once you understand how this "haphazard" array is built :)

In Drupal 6....

If you go into views, look under Style Setting at Theme Information.  There, it will tell you all the templates it uses to create its output.  The one here you are interested in is Row Style Output, because it is the template that is building the $rows that are ultimately passed to jcarousel-view.tpl.php.

What you want to do is make a copy of this template in your theme directory that overrides the default one, and in this case, the easiest is the first one that incorporates your view name into it.  Doing a quick test here, with a view named jc-test, that would be views-view-fields--jc-test.tpl.php.

Rescan the templates files to make sure it's selected and edit that bad boy.  What you want to do now is change how it creates the individual row.  Normally, views just passes the information given to it along, but you want to work on it programatically, eg, turn the content of a field into some html based upon it.

So, if you don't have devel set up on your machine, a quick:

<?php drupal_set_message('
' . print_r('field id: ' . $id . ' field raw: ' . $field->raw,true) . '
'); ?>

right after the first foreach() will tell you want's inside here you have to work with.  Let's say for ease of discussion, the field you have that you want to use for the color is named field_color.  For ease, it should be the first field passed to the row, which is easily set up in views.

So, inside here, you'd do something like this:

<?php if ($id=='field_color'): ?>
  <?php print '
raw . '">'; ?>
<?php else: ?>

  -- ALL THE REST OF THE CODE BEFORE THE ENDFOREACH GOES IN HERE
  -- BECAUSE YOU DON'T WANT TO PRINT OUT THIS FIELD
  -- BUT YOU DO WANT TO PRINT EVERY OTHER FIELD

<?php endif; ?>

Now....that OPENS the DIV.  You need to close it at the end of the row, so just put:

<?php print '
'; ?>

after all the php in the template (after the last endforeach).

So, now, barring any typos of mine above, you've wrapped a row in a div classed with the content of the first field of the row :)  Use CSS to make it pretty.

You do have to make sure your data is sane, though,  $field->raw isn't friendly at all, so you may need/want to check_plain() it if it's user input etc etc.

Anyways, hope this helps out!


So, if you create a new .tpl.php for your content type, you can simply print the divs as html, and echo the vars as php.

example:

<?php print $title; ?>

<?php echo render($content['some_field']); ?>

See https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field for a starting point on pulling specific custom fields, for separation, if needed.

be sure to have a copy of your original node.tpl.php in your theme folder as well, or your node--my-content-type.tpl.php wont work! Again, see https://www.drupal.org/node/17565.


I guess that, as the creator and maintainer of the Drupal commerce shipping, I should bid in.

The short answer is that right now, this is actually possible without creating the functionality yourself from scratch. The issue was raised in the Drupal commerce shipping queue (by yourself?). Anyways as stated there, this is something that should be handled by commerce core, which right now is lacking a way to apply taxes to line items which aren't the product line items.

I have a chat with Ryan about the problem, where we agreed that the product line item is a special case, since a lot of price handling is tied to the product, where all other line items, shouldn't have a relationship like that. The issue has been raised on the Drupal commerce issue queue, which I believe you are aware of.

If you don't have the ability to create the code for this yourself, your best bet is to wait for some one to fix it, or buy it.

Update:
This is now built in the Commerce shipping module, by exposing an event in rules that can be used to add taxes on shipping line items.


why i can't write anything to a custom cache table?

You don't need to create your own table to use the internal cache. Just use cache_set() and cache_get() as documented. This will store the $my_data in the default 'cache' table:

// Store $my_data in cache.
cache_set($data_id, $my_data);

// Get $my_data from cache.
$data = cache_get($data_id);

Your code snippet should look something like this:

$cid = some_calcuated_cid();
$cache = cache_get($cid);

if (!$cache){
  $data = some_calcuated_data();
  cache_set($cid, $data);
}

Documentation:

cache_set()

cache_get()


How does Strongarm decide which variables need to be included in a feature

Strongarm provides a component to features where you can manually select the relevant variables to export with that feature.

Some variables may be included by default, e.g node_type variables when exporting a node type, others may need to be manually checked and exported with the feature module.


Different view page based on taxonomy depth?

if you know the depth of the category in advance you could create different view page for each depth of the category.

For example for the main category the path would be category/%
and for the subcategory the path would be category/%/%

this way when there is 1 argument after category the view page for the main category would be displayed. If there are two arguments the view page for the sub category would be displayed.


How to disable text format options in CKEditor

The simplify module will allow you to hide text format selection, and a lot of other bling too: https://drupal.org/project/simplify

The simplify module allows you to hide the text format selection globally on all content types, as in the attached screen. Alternately, you can disable text format selection for each content type individually.

I've really only used it one one site so far, but haven't had any trouble.


How do i set limit query into url from views output

Ccreate a custom module and implement hook_views_pre_build.

To create the module follow these steps:

In sites/all/modules create a new folder with the name of your module. As you are not contributing this module back to Drupal and it is specific to your project just give it the name of your project and other code tweaks can also live in there.

Let's assume you called your project custom_project and it is at sites/all/modules/custom_project.

Add a file called custom_project.info to it with this content:

name = Custom Project Module
description = This module is for project related tweaks
core = 7.x

Add a file called custom_project.module with this content:

<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    if (isset($view->args[0]) && is_numeric($view->args[0])) {
      $view->set_items_per_page($view->args[0]);
    }
  }
}

Now install this module (and in future if you add any hooks then clear the cache)

You call this on a friendly url ("http://example.com/serve/all-articles/10").

If you wish to add a query parameter to the url as in "http://example.com/serve/all-articles?limit=10" then your function will need to inspect drupal_get_query_parameters for that parameter instead of pulling it out of $view->args[0].

ie.:

<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    $query_params = drupal_get_query_parameters();
    if (isset($query_params['limit']) && is_numeric($query_params['limit'])) {
      $view->set_items_per_page($query_params['limit']);
    }
  }
}

You need to replace NAMEOFVIEW with your views name. You get it like this:

Note that a view has a name, but also a display id. The display id in this case is page. If you add a block it will get a block display id. So the above code will work for all displays that you add to this view, even for blocks etc. To limit it to just the page you will change the one line to this:

if ($view->name == "all_content_of_article" && $view->current_display == "page") {


What is the advantage of the APC module?

Using APC with PHP and the APC module are two totally different things.

APC for PHP caches the opcode for files.  Essentially, when PHP executes a page, it compiles all of the code into opcode.  APC caches this, so the next time a file gets used, it can skip the compilation step.  This can cause tremendous speed increases in a complex PHP application like Drupal.  Running Drupal without APC enabled is a bad idea.

The APC Module is an alternative cache backend for Drupal.  Out of the box, Drupal caches data in the database.  The APC Module lets Drupal cache the data in the APC user cache.  As with everything, tuning APC is essential to getting this to work well.


Is there any way to dynamically add a CSS class selector to a view with submitted exposed filters?

You can do this with View's pre_render hook, eg, something along the lines of this:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAME_OF_YOUR_VIEW') {
    drupal_set_message('<pre>' . $view->exposed_data . '</pre>'); // to see what you have to work with
    if (!empty($view->exposed_data['type'])) {
      $view->display_handler->set_option('css_class', 'view-has-been-filtered');
    }
  }

}

The above is based on a node type exposed filter, you will need to look at your View to see what filter names are involved, but the logic is that the exposed_data filter arrays will be empty until you have applied the filter.  For example, here, this looks like this when you first go to the View:

Array
(
    [type] => Array
        (
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

and this is what it looks like after selecting 'foo' as a type in the exposed filter:

Array
(
    [type] => Array
        (
            [foo] => foo
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

ADDITION:

If this works for you, and per your comment, I suppose the following would work for any/all Views, but I haven't battle tested it...

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key) && !empty($key)) {
        $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

...with the logic here being the only arrays in $view->exposed_data are filters, and if they aren't empty, the View has been filtered.

EEEK ADDITION:

My logic is somewhat flawed in that my initial tests were for filters that allowed multiple selections, and, of course, Views used arrays to capture them in $view->exposed_data.  If your filters are just single value fields, Views will do something like this first:

Array
(
    [multiple_value_allowed_type] => Array
        (
        )

    [field_single_value_field] => All
    [submit] => Apply
    [form_build_id] => form-f601bde36c625db96bad7a84bf4fa210
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

so I guess the following dull ax approach would work:

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key)) {
        if (!empty($key)) {
          $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
        }
      } else {
        switch ($k) {
          case 'submit':
          case 'form_build_id':
          case 'form_token':
          case 'form_id':
            break;
          default:
            if (!empty($k) && $key != 'All')  {
              $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
            }
        }
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

DOUBLE D'OH ADDITION:

Of course, this quick and dirty logic also works:

function YOURMODULE_views_pre_render(&$view) {

  if (!empty($view->exposed_data) && count($_GET) > 1) {
    $view->display_handler->set_option('css_class', 'view-has-been-filtered');
  }

}

ADDITION DUE TO COMMENTARY:

If you are setting css classes via the UI that you want to preserve, you can do this:

$view->display_handler->set_option('css_class', $view->display_handler->get_option('css_class') . ' view-has-been-filtered');

which gets that UI option and then adds the view-has-been-filtered class to it.  Please note the required space in front in the code :)


Show  on user page if user page belongs to current user

To do this right you will need to use this combination of tests.

Is the user logged in {% if logged_in %} ?

Does the user have the permission needed to edit their profile with {% if user.hasPermission('depends on your site setup') %}?

Is the owner of the node the same as the current user?  {% if node.ownerId  == user.id %}

NOTE: The snippets above are not tested.  You may have to tweak to get the correct info (e.g. getOwnerId SHOULD equal node.ownerId.. but twig may have a different opinion).


Reverting the taxonomy view back to its original state, and then rebuilding the changes again made the errors disappear from watchdog, but the management menu and admin menu were still completely messed up.

To fix this, I installed Devel module, and the ran a SQL query to delete all menu rows added by system.

mysql> delete from menu_links where module='system';

I then navigated to /devel/menu/reset

This successfully re-built the management menu, and everything went back to normal.

Note: I also used backup and migrate to quickly clone the website onto a local server and test the changes before making the changes on the production environment.


Building a simple render array and rendering it

I believe "children" needs to have a "#" ... You could also try using #value instead of children


Specify language of Comment using Entity Translation?

Drupal natural way would be to show comments for different languages separately.

For example If you have a node in English and Spanish. Drupal natural way would be to show comments for en/es translation separately (attached to en/es content).

If you are looking for language field you can use Language field module...

  This module creates a Language Field that combines Drupal 7's Field
  list options and Internal language list.

  This is used to simply collect language data.


Should I add a div class to a fields TPL file or just change my CSS file?

You should be able to set a custom css class for each field, but otherwise your technique of drilling down using css classes is fairly common practice.


How to hide webform block for users who submitted the form already?

Have a look at the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you may have a possible solution for your question, provided you can think of an appropriate rule to be used for it. Using the Webform integration with Rules, you should be able to catch (=Rules Event) the submission of a form by a user. And combine this with some type of Rules Action so that the form is no longer visible to that user.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".


LESS could not create a directory in public:

Your drupal site files directory has to be writable by your webserver.


After upgrade from OG6 to OG7 directly to ver. 2.x: Is there any possibility to use OG migrate (available only in OG 1.5)?

For OG 7.x-2.2, the migrate functionality is now coming with the OG module itself. No additional module is needed. Documentation can be found here:

Migrate: Contributed module support: Organic Groups

Which means the functionality is no longer in migrate_og (where it was for OG 6.x-1.x) and also no longer in migrate_extras (where it was, I think, for OG 7.x-1.x).


Problem with form submit handler using system_settings_form for module admin

Not quite...$form_state is defined (or at least will be if you have a standard installation of Drupal).

The problem is the submitted values are in $form_state['values'], not $form_state. Also, Unless you have #tree set to TRUE on $form['fieldset_1'] the values will be collapsed, and the hierarchy you're expecting won't be there.

This should work:

$file = file_load($form_state['values']['pic_1']);


Getting an fatal error message when trying to render custom blocks on my node twig template

You can print blocks directly using Twig Tweak

  {# No need to configure this block on "admin/structure/block" page. #}

Block:

{{ drupal_block('system_branding_block', {label: 'Branding', use_site_name: false}) }}

  {# Bypass block.html.twig theming. #}

Block (without wrapper):

{{ drupal_block('system_branding_block', wrapper=false) }}

Source: Cheat sheet

Do not use the block's machine name, enable the devel and in block configuration click on Devel tab to get the Plugin ID.

For example, the Site Branding Block has machine name of sitebranding, but the plugin ID is system_branding_block


How can I adjust the css within fusion theme based on the size of the screen?

You might find this post on media queries and width attributes useful.


Is there a significant performance difference between the Computed Field module and writing code?

"Significant" really depends on too many things - how often such nodes are created, how many users (anon/auth) does your website have, which other modules you have installed, what's your workflow setup (e.g. Rules, moderation modules, etc.) and so on.

While doing this through your code is definitely going to be faster, I doubt you will really notice performance improvements. Doing things in code will in most cases have lower overhead than installing a module to do the same.
If you're really wondering about exact performance differences, you will have to benchmark it with Devel and xdebug for example.

However, you already mentioned another important point - it's generally not a good practice to have raw PHP code entered anywhere in admin. Sometimes it's faster to do it (e.g. in Rules, Views or other contrib modules), but over time you should look to migrate those changes to code. Not to mention that you will reduce the number of modules on your website, which is generally a good thing.


Why does aggregator report "There is new syndicated content" but still 0 items for this feed?

I have just been experimenting with the aggregator and come across the same issue. The only workaround that I have been able to find in order to pull content from the RSS feed in issue has been to use the Feeds module. If you are still having this issue then this is a possible solution.

EDIT: Just found a far simpler solution for the problem. By default the aggregator deletes items older than 3 months and 3 weeks from the feed. If the youtube feed you are subscribing to has not had new content added in that time then you may get the situation you describe. If that is not the case then go with the first option I suggested. Otherwise you can change how long Drupal keeps the feed items in the Aggregator settings tab.


You could do a partial configuration import and then a cache rebuild

drush cim --partial --source=modules/custom/MY_MIGRATION_MODULE/config/install -y
drush cr


How do I get the public file URI for a media file from jsonapi?

Here's the correct path:
http://mysite.com/jsonapi/node/MY_CONTENT_TYPE?include=field_ref_media_audio.field_media_audio_file&fields[file--file]=uri,url

This results in a value for uri such as:
"value": "public:/sites/default/files/coolstuff/audio/apples-bananas-pears.mp3",


Allowed types for DataDefinition::create()

The types are defined as DataType plugins. You could also implement additional ones, but that's not necessary very often, since all the basic scalar data types exist already.


How can I edit the contents of the printable invoice for Ubercart order?

Try Ubercart Register Invoice, this will allow you to define new email templates for invoice emails ... these same templates should also be visible/useable by your sites Theme.

  Registers invoice templates with Ubercart so they appear on and can be
  selected for the Ubercart "E-mail an order invoice" Rules action.

  Registers invoice templates with Drupal so they can be used to theme
  the invoice data.

  Provides extensive instructions and feedback on how to configure
  invoice templates.

See the README. You name your template: uc-order--*.tpl.php and it will be seen by the system. Also see the built-in help (prior and after creating a template) at http://mysite.com/admin/help#uc_register_invoice


How to add a option in wysiwyg editor so that blocks can be selected as images?

Seems you will need to write your own plugin. There are dozens of manuals, like Creating a CKEditor Plugin with a Custom Dialog Window - this one seems to be good for you, as you might want to have dialog window to allow user select a block.

You will need tips from this Drupal.org thread to

get list of blocks you will feed to the editor
make block data avaliable in node.tpl.php via preprocess function
render the block in a node, probably using custom created, block enabled text filter.

Don't forget to consider security issues when deciding who should be able to add what.

Last but not least, publish your module on Drupal.org for future developers.


Separating User Picture from Submitted by date in Node

Use the Display Suite Module

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

Watch the screencasts to see it all in action!


Relationships between nodes and display in a special order

I solved this with the modules: entity reference and corresponding entity reference, setting up a relationship between the "team member" and "office" content type.

Then I created a view and added A Contextual Filter choosing the reference field from the "team member" content type as a contextual filter. Then I added: "Provide default value" "Content ID from URL" in the "When the filter value is no available" option.

After that I chose "Content: Function" field as a sort criteria so that the team members will be displayed according to the taxonomy order. Finally I added the block, which I created with the view, to the office page content type under manage display.


Drush command 'omega-wizard' could not be found

Add -d option so that command looks drush -d omega-wizard. You will see debugging information showing what causes problems.


How can I display Drupal comments on a separate page from hook_node_view()?

The Talk module shows the comments for a node in a tab added to the node page.

  The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.

  When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.

If you need to do something similar, but on a completely different page, you can look at the code of the module to write similar code.
In short, apart from implementing hook_node_view(), the module implements hook_node_load() to set $node->comment to 0 (after saving its value in another node property). Then it calls comment_node_view() after temporary setting the values of the Drupal variables used from that function.

  global $conf;
  $clone = clone($node);
  $clone->comment = _talk_node_comment_value($clone);
  $recover = FALSE;
  if (array_key_exists('comment_form_location_' . $node->type, $conf)) {
    $original_setting = $conf['comment_form_location_' . $node->type];
    $recover = TRUE;
  }
  $conf['comment_form_location_' . $node->type] = COMMENT_FORM_SEPARATE_PAGE;
  comment_node_view($clone, $view_mode, $langcode);
  if ($recover) {
    $conf['comment_form_location_' . $node->type] = $original_setting;
  }
  else {
    unset($conf['comment_form_location_' . $node->type]);
  }

  // Display comment summary
  $addcmnt = ((_talk_node_comment_value($node) == COMMENT_NODE_OPEN) && (($view_mode != "teaser") || variable_get('talk_addcmnt_teaser', TRUE)));
  if ($addcmnt) {
    $links = $clone->content['links']['comment']['#links'];
    $node->content['links']['comment'] = array(
      '#theme' => 'links__node__comment__talk',
      '#attributes' => array(
        'class' => array('links', 'inline'),
      ),
    );

    foreach ($links as $link) {
      if(talk_activated($node->type)) {
        if (isset($link['href']) && $link['href'] == 'node/' . $node->nid) {
          $link['href'] .= '/talk';
        }
      }
      $node->content['links']['comment']['#links'][] = $link;
    }
  }
  // Add the Talk link if user has access and it's not blank
  if (_talk_access($node) && strlen(variable_get('talk_link', '')) > 0) {
    $node->content['links']['comment']['#links'][] = array(
      'href' => 'node/' . $node->nid . '/talk',
      'title' => talk_title($node, 'link'),
    );
  }


Difference between Minimum cache lifetime and Expiration of cached pages

I have made following observations after spending a few hours. If there are any gaps or mistakes, do let me know. I will be happy to make editions.

First observer that none of the Options under the CACHING are interdependent. If they were you would have seen them under different field sets(or as dependent fields). Make a note of this observation and we will revisit that later.

Let us begin with the first option Cache Pages for anonymous users.

When you check this option you are basically telling Drupal

Hey Beast listen, when an anonymous user visits my site,

Store the generated HTML in the cache table
So that I can display the same result to all users as my pages
remain same for all anonymous users.
And don't clear the page caches until I say clear
all caches.

Also even when you don't enable the Cache Pages for anonymous users  the page can still be cached by external cache systems. Eg : Boost

Now lets move to the next options which you would end up using generally.

Expiration of cached pages

Note that this setting has nothing to do with the Drupal Database or
cache tables.
Read the description The maximum time an external cache can use an
old version of a page. As Molot pointed out the keyword is
external.
So what this option basically does is it sets the header Cache Control to public and the max-age value in the header to the specified value(1 day in this case).
This header tells the external Caching systems not to make a call
to the server for this page until the max age, as they can show this
page from their own cache. After the max-age the Caching system
should check back with the Drupal server to see if the content has
changed.
If its a Varnish server, it doesn't make a call to Apache and
returns the page from its cache. So assume that Varnish has cached a
page and thousand different users made a request to that page. So it
means that 1000 requests have been processed without hitting the
Apache Server even once.

Minimum Cache Life Time

If your site doesn't have a huge traffic or if you are not sure what this value is, it better to leave this value as none.

This value applies not just for the pages. But all the cache objects.
What this value tells is "Its ok to serve cache objects which are stale"
In our case the value is set to 5 mins.
If you have a page that lists the five latest blogs on your home
page. What the above values means is that, if a new blog is created
its ok for the blog not to appear on the listing for the five
minutes.
When this value is set, for the cache to be updated/recreated minimum
this much time must have passed and a cache clearing action must be
run[A cache clearing function should be run].


How to get the value of a custom field in hook_node_presave?

You can't get the value in the hook_node_presave() because this is not a node field, as you says is a custom field that you create altering the form.

In this case you need to add a custom submit handler to use the value, something like this inside the hook implementation:

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
// ...
  if (isset($form['actions']['save_continue']['#submit'])) {
    array_unshift($form['actions']['save_continue']['#submit'], '_node_revision_delete_form_node_type_submit');
  }
// ...
}

And in the function you can access to the value and perform your actions

function _node_revision_delete_form_node_type_submit(array &$form, FormStateInterface $form_state) {
// Getting the form values.
  $field_after_lecture_tmp = $form_state->getValue('field_after_lecture_tmp');
}


Have you tried running your update.php file?

(https://www.drupal.org/upgrade/running-update-php)

II. Run update.php
In your web browser navigate to the directory where Drupal is installed:

http://www.example.com/update.php

or

http://www.example.com/test_site/update.php  (if you are upgrading a test site)
The update script should only be run once. It will complete all the updates at once. If prompted for which version, choose the closest starting version that makes sense for you.

This will update the default Drupal and contributed module database tables automatically (versions prior to 4.7 will require manual upgrade of the contributed modules). Once the script has stopped loading, be sure to scroll to the bottom to look for errors.


You can add classes you need directly to your form with #attributes. This is example directly from the official documentation:

$form['#attributes'] = array('class' => array('search-form'));

If it's not your code that creates form, you can add this with hook_form_alter(). Just be careful not to overwrite any attributes or classes that might be already in place:

$form['#attributes']['class'][] = 'search-form';


Using drupal to run a download website with about 10K files

It depends on how do you want to manage/upload your files. You can put your files in sites/default/files but create a new vhost (with or without the same web server with your primary site) at files.example.com to give access to this folder. Also, it depends on whether you want access control to your files. If you don't want public access to those files, you should use the vhost, but use something like X-Sendfile header to reduce server load.


Configuration page in Modal Forms not working

In Drupal 7, the installer tests for compatibility with Clean URLs as a part of the installation process. If the environment is tested as compatible with Clean URLs, it will be enabled as part of the installation process and no further action is required to enable Clean URLs.

If you need to enable Clean URLs post installation, Drupal will run the clean URL test automatically when you navigate to the Clean URLs configuration page;

Administer > Configuration > Search and metadata > Clean URLs, show the results, and allow you to save configuration.

You can enable or disable it at a later time by following these steps:

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".

Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server.

If your clean url is not working enable rewrite_module from server.


There is an option in Field configuration to Create a label. It's usually just at the top of the options.

You have to tick it to enable it. Once you tick it an input field appears where you can enter a different label for your field.

To get to the field configuration just click on the desired field under Fields area in your Views.


Serving the CSS and JavaScript files of the Bootstrap theme locally

You need Bootstrap Library module.

Quote:

  Download Boostrap files on /libraries/bootstrap (you`ll have to
  create "libraries" folder in Dr8 install directory).
  Then go to
  example.com/admin/config/development/bootstrap_library
  -configure on which pages you want to load the libraries (by default everything but admin/*).
  Configure on which themes you want to load the libraries.
  Drink some champagne coffee.


Find current layout name for a Panels Node?

The function panels_get_current_page_display() is what you're looking for:

$panel = panels_get_current_page_display();
$layout = $panel->layout;


How do I translate a views field to lowercase and with spaces replaced with dashes but not make it a link?

You want link all output with studio/my-studio .First convert My studio to lowercase then rewrite as link  custom text.

Think My studio is [field_studio_name_1] .Convert this to lowercase. Then rewrite as link custom text like this .


This is untested but I would try implementing a template_preprocess_panels_pane():

function mytheme_preprocess_panels_pane(&$vars) {
  $content = &$vars['content'];

  $title = !empty($content->title) ? $content->title : '';
  $title = preg_replace("/\*\*(.*?)\*\*/", "$1", $title);
  $title = preg_replace("/\*(.*?)\*/", "$1", $title);

  $vars['title'] = $title;
}

Adapted from this answer, and would allow some simple markdown in the titles.


Add some extra text(html+content) before start view. (Within the div from the view)

In the header add the type Global: Unfiltered text and enter your HTML there.

A more Drupalish way would be

Mark "Kermit the Frog" as Sticky at top of lists in it's Publishing options on it's node edit form.
Alter the Sort criteria your View to have two criteria: Content: Sticky (DESC) followed by Content: Post date (DESC).


When removing a file it still is present on the machine

Permanent files have a status FILE_STATUS_PERMANENT.

  Indicates that the file is permanent and should not be deleted.

  Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be
  removed during cron runs, but permanent files will not be removed
  during the file garbage collection process.

When you remove a file from a node, the file_managed record may simply be marked as status = 0 or anything other than FILE_PERMANENT, in which case, it's deleted during system_cron (if no entry in the file_usage table).

Basically, if you have cron running, it should be fine.


How to dynamic select options each webforms seperately?

I don't entirely understand your question, but I believe that you want to customize a webform based on the user currently logged in.

To do this you can use hook_form_alter.

All webform have an ID that starts webform_client_form_ so you check check for this, and then make any modification as necessary.

E.g:

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

    //drupal_set_message("Form ID is : " . $form_id);

    if(substr($form_id, 0, 20)=='webform_client_form_') {

        global $user;

        // make changes to form here

    }
}


Get config variable value in hook_block_list_alter

Assuming you've set the variable using the variable_set() function, you can get the value using the variable_get() function.
From the docs:

Returns a persistent variable.
Case-sensitivity of the variable_* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.

In your case the foreach loop would become :
foreach ($blocks as $key => $block) {
  $enable_conectivity = variable_get('enable_conectivity', TRUE); // Default value of `TRUE` is returned if the variable is not set.
  if($enable_conectivity) {
    $blocks[$key]->visibility = BLOCK_CUSTOM_DISABLED;
  }
}


Render Array for hook_field_formatter_view not displaying

To add markup that's already been prepared to a render array, you would indeed use #markup. There's nothing wrong with using it where appropriate.

However, since you're preparing the markup in the same function anyway, you may as well use the render array version of the call to theme(), e.g.

$element[$delta] = array(
  '#theme' => 'mymodule_formatter',
  '#image' => $image,
  '#another_var' => 'foo',
);

It provides better structure, makes it easier for other modules to alter if necessary, and is better for caching.


Any working techniques or examples for a multistep AJAX enabled node form

I think trying to use multistep, ajax and the core node form may be quite tricky. I am not going to say impossible, but I think it would be a lot of work.

I would think using a custom form and saving the node as you suggest may be easier, what you'll loose with this is the flexibility of having it integrated, so if you add a new field to the node, you will need to change your form.


For text fields you can use

$value = $node->field_my_field_name['und'][0]['value'];

or, if you want sanitized value, use ['safe_value'].


How to improve search results filtering on taxonomy

Use Custom Search module.

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box

Or, the other best solution is to use create a view with exposed filters. Here is article about it


Views: show only one node per select box value

I thing it's difficult to make just with the views UI (the aggregation will not work)
If you don't want the solution of Anil Sagar, i have another solution with some theming.

Go to format => setting : In Grouping field Nr.1 select your field type (left)
Now your result will by group by type (dog, cat and others) You can see an extrat of the output. (right)

Go to Advanced setting => Other => Theme information

Copy / Paste views-view-list.tpl.php in your new template and make some modification

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

<?php print $title; ?>

 <?php endif; ?>
 <?php print $list_type_prefix; ?>
 //Add this
 <?php $x = 0; ?>
 <?php foreach ($rows as $id => $row): ?>
    <?php if($x < 1): ?>
    <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

    <?php $x++; ?>
  <?php endif ?>
<?php endforeach; ?>
<?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

And you'll have what you wanted:


Copy the images to the public folder after form submit with PLupload in a custom module

I finally manage to do what I want...

I didn't understand how to use file_copy ans its $destination argument. We can put a file path, not only a folder path. So, I can save my file.jpg correctly.

My code :

$values = $form_state['values']['create'];
$photos_count = count($values['photos']);
for ($i = 0; $i < $photos_count; $i++) {
    $path = $values['photos'][$i]['tmppath'];
    $name = $values['photos'][$i]['name'];
    // set file datas as an object to pass it in file_copy()
    $file = (object)array(
        'uid' => 0,
        'uri' => $path,
        'filemime' => file_get_mimetype($path),
        'status' => 1
    );
    // copy the file in the correct folder
    if ($file = file_copy($file, $filepath . '/' . $name)) {
        drupal_set_message('Success');
    } else {
        drupal_set_message('Error', 'error');
    }
    // set the field datas for saving the node with an array
    $node->field_album_photos[$node->language][$i] = (array)$file;
}

Have a nice day !


Set value of List field of a node with multiple values

You can replace the complete content of a field by assigning an array:

$node->field_multivalue = [
  ['value' => '1'],
  ['value' => '2'],
  ['value' => '3'],
];

If you want add another value to the field you can use the field like a php array:

$node->field_multivalue[] = ['value' => '4'];

You can omit the main property of a field:

$node->field_multivalue[] = '5';

Now you have 5 values in the field.


How can I populate multiple blocks on a paginated page?

I think building this functionality using custom code would be the way to go as views isn't really capable of this sort of thing.

If it was me I'd make a custom block to replicate this giving you alot more control.

But if you really want to use views you could maybe just have the 1 block and make it show 11 item per page. Then create a views template for the view and add some bits in there e.g. if you're using unformatted list you could copy views-view-unformatted.html.twig and save as views-view-unformatted--VIEWNAME--block-1.html.twig and then do something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>

    {% if loop.index == 1 %}
     //use elements from $row to build display 1
    {% endif %}

    {% if loop.index == 2 %}
      //use elements from $row to build display 2
    {% endif %}
    ....
    ....
  </div>
{% endfor %}

Downsides of this you can't easily use different image styles or amount of text per row without using some contrib modules and other bits (I haven't actually attempted this but know there are modules to let you do more in twig, as mentioned custom block would be better though)


You don't need to use custom code to delete the preview button.  On the Content Type administration page at admin/structure/types/manage/your_content_type, you can selection Disabled for Preview before submitting under Submission form settings.  This will remove the preview button for that content type.


How to add static content before the feed on the front page?

there are multiple ways to do this:

1. Use the default block system

Create a new block admin/structure/block/add and insert your headline (or none) and the body text. Under Visibility settings select Only the listed pages and insert <front>. Select under region the region where the block shall be shown, or do this at admin/structure/block after saving the block.

2. Use panels + page manager (ctools)

Create a new panel page and make this page your frontpage, put the feed you want to be displayed inside of the main area, add a custom content pane before that feed/ view.

3. page.tpl.php

inside of your templates page.tpl.php you can add a codeblock for your custom content, drupal_is_front_page will help your here:

<?php
if (drupal_is_front_page()) {
  //your custom code
}
?>

reference for bartik: page.tpl.php with bartik you could use the $is_front variable as well for detection.


Option 1:

Think of one form as Node Form with more fields that you can reuse on user entity as well.

Now on node save you have flexible node api to hook in and create user. As an example

hook_node_presave($node)
hook_node_insert($node)
hook_node_update($node)

You can use any of the above, most suitable would be node_insert I think as you would like to create user only when new nodes is created. Inside the hook you will get the user submitted values inside $node object, all you have to do is create user programmatically from it.
Which basically is building a user object and mapping of fields and finally do a user_save() on your user object.

Here is an example of how you can create user programmatically

http://codekarate.com/blog/create-user-account-drupal-7-programmatically

Option 2:

Form does not need to be node form, you can have a custom form as well using form api, in that case you will not need any of the node hooks instead process would be just like user_save() you will do node_save(). So inside your custom form submit handler you will be creating a node(how to create node programmatically) and a user(how to create user programmatically)


How to prevent CKEditor from replacing spaces with  ?

I solve this with a text filter

/**
 * Implements hook_filter_info().
 */
function MYMODULE_filter_info() {
  $filters = array();

  $filters['kill_nbsp'] = array(
    'title' => t('Kill Non-Breaking Spaces'),
    'description' => t('Remove non-breaking spaces.'),
    'process callback' => '_MYMODULE_filters_kill_nbsp',
    'tips callback' => '_MYMODULE_filters_kill_nbsp_tips',
  );

  return $filters;
}

/**
 * Filter callbacks.
 */
function _MYMODULE_filters_kill_nbsp($text, $filter) {
  return preg_replace('/&nbsp;/', ' ', $text);
}

/**
 * Filter tips.
 */
function _MYMODULE_filters_kill_nbsp_tips($filter, $format, $long = FALSE) {
  if (!$long) {
    // This string will be shown in the content add/edit form.
    return t('Don\'t use non-breaking spaces.  Ever.');
  }
  else {
    // And this one on the "Filter Tips" page.
    return t('Non-breaking spaces are evil and will be eradicated.');
  }
}

The code simply searches for non-breaking spaces and replaces them with normal spaces.

Stuff this in a custom module, and then assign the filter to the input formats that have WYSIWYG enabled.  This does assume that you never want actual non-breaking spaces in your output, which is good for my sites.


This works for me in Drush 5.

In a drushrc.php file (I tested with my ~/.drush/drushrc.php you could do this per-project as well).

I simply added:

$options['v'] = TRUE; somewhere in the file. Then try issueing drush commands.

This works because of how drush_parse_args executes.


I can see one empty line in beginning. This might be due to a empty line in any one of your modules. In PHP blank lines before <?php tag causes a lot of problems remove it and check again. have a look at other site XML (Source Code) for proper format.


The first level is an array. The keys are the plugin id's. You can list them:

$defs = Drupal::service('plugin.manager.field.field_type')->getDefinitions();
foreach ( $defs as $key => $value ) {
   echo $key, "\n";
}

This is the result:

comment
datetime
file
image
link
list_string
list_float
list_integer
path
text_with_summary
text
text_long
email
boolean
created
changed
timestamp
string_long
language
decimal
uri
float
password
string
integer
entity_reference
uuid
map
taxonomy_term_reference

You can pick one and dump the plugin definition.

var_dump($defs['comment']);

If you are interested in a special object, you can digg deeper with the help of api.drupal.org. But it will be easier, if you search for the plugin in the core directory.

To access an object, locate it in the var_dump and use a method:

$defs['comment']['description']->render();

In this case it is the object TranslatableMarkup, which has the method render to access the translated string.


How to modify comment-wrapper.tpl.php to change the comment form layout?

The best solution:

This is the default comment-wrapper.tpl.php:

  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

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

If you want to modify the form elements by overriding the template file, here is the best known way:

  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

    <?php
    // 1. Create a custom markup
    $form_custom_markup = '';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($content['comment_form']['author']);
    $form_custom_markup .= '
';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($content['comment_form']['comment_body']);
    $form_custom_markup .= '
';

    // 2. Attach the custom markup to the form
    $content['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
    ?>

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

In this example we make the Author field appear in red background and the comment body in blue background!

You could simply modify the sample above to re-arrange any form element in your form.

Why the normal way didn't work?

To understand this solution and other solutions first we need to understand why forms behave differently than other render arrays.

To start let us have a look at the function that renders a form:

<?php
// form.inc

function theme_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  // Anonymous DIV to satisfy XHTML compliance.
  return '<form' . drupal_attributes($element['#attributes']) . '>
' . $element['#children'] . '
</form>';
}

As you see, when you render($form) it wraps it with ''. It means that any elements that have been rendered before will be out of <form>. That was why when you render render($form['actions']) before render($form) even buttons stop working, because they are out of the <form> element!

What are other solutions?

Using HOOK_preprocess_hook()

As you could see we modified $content['comment_form']. You could do the same thing by using the template preprocess function:

/**
 * Implements HOOK_preprocess_hook()
 * Preprocess variables for comment-wrapper.tpl.php
 */
function THEME_preprocess_comment_wrapper(&$vars) {
  if ($vars['node']->type == 'article') {

    $form_custom_markup = '';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($vars['content']['comment_form']['author']);
    $form_custom_markup .= '
';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($vars['content']['comment_form']['comment_body']);
    $form_custom_markup .= '
';

    // Attach the custom markup to the form
    $vars['content']['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
  }
}

This example overrides form elements of comment form on article pages.

Tip: You should replace THEME with your theme name and put this function in template.php in you theme folder.

Using HOOK_preprocess_hook()

If you trace where the element is actually generated you will get to this lines in comment.module:

$build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));
$additions['comment_form'] = $build;

We can see this is a form with the form_id of comment_node_NODE_TYPE_form. So we could use hook_form_alter to alter form elements:

/**
 * Implements hook_form_alter()
 */
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_article_form') {
    // Play around with $form
  }
}

In this example we are altering the comment form for article nodes.

Tip: Generally using form_alter to change the display of the form is not recommended because it also affects the form_submit() and form_validate() and may cause unwanted issues in future or conflict with other modules.


In node-article.tpl.php  add this code at the beginning

// loop through node properties
foreach ($node as $k => $v) {
  // ensure this property is a field
  if (substr($k,0,6) == 'field_') {
    // use the CCK function to get the field data for this field
    $fieldData = content_fields($k, $node->type);

    // add the label to the array
    $fieldLabels[$k] = $fieldData['widget']['label'];
  }
}

Than you can print labels like this:

<?php if ($node->field_YourField[0]['view']){ ?>

    <?php print $fieldLabels['field_YourField']; ?> // prints label (add div/span wrapper if you need it)

    <?php print $node->field_YourField[0]['view'] ?> // prints field value (add div/span wrpaer if you need it)

<?php } ?>

This is tested in Drupal 6.
Hope it helps.


How to find the list of 'paths' on my site?

To get all the paths you can use, you can use the following code to get all the paths defined from modules:

$items = module_invoke_all('menu');
drupal_alter('menu', $items);
foreach ($items as $path => $info) {
  print preg_replace('/%([a-z0-9_]*)/i', '*', $path);
}

The code will show the path as you enter in the block settings; this means it will change node/%node in node/*, and node/%node/edit in node/*/edit.

About your specific issue, the block could not appear because the block has not been assigned to any theme section, the theme doesn't define the section where the block should appear, or the block is empty. In most cases, modules don't output empty blocks.


In Drupal 7, moving the comment form above the comments

I think you should copy modules/comment/comment-wrapper.tpl.php to your theme and change it there. The file is pretty much self explanatory. Hope it's helpful.


In Drupal 7 there was the Views Reference Filter.

Basically, what you're after is filtering one view with another (if you have to go through the interface and not code a custom solution). Those database queries can be quite slow so you're advised to use caching.

Views Field View has the D8 version. The strategy is to create two Views displays, one listing Users, the other Views listing only one node sorted by Value descending and with a contextual filter for UID. Then you insert the second view into the first one (as an additional field).

This way you get the one node that has the highest value for the particular user.


How to show a Views attachment in other region or create a block acting as attachment?

At moment I fixed with contextual filter query by disabling the ajax and get query from URL. This way I can use separated block for the map.


How to filter view results by currently logged-in user's (NOT AUTHOR'S) role?

In Filter criteria, you can choose current user, with the help of which you can filter view with current logged in user.


How to alter an existing breadcrumb link programmatically?

Turns outs you can't edit the existing breadcrumbs. However you can fetch them using the getter function, modify them and then call the Breadcrumb builder class.
<?php
/**
 * Implements hook_system_breadcrumb_alter().
 */
function MODULE_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Add new link
  $breadcrumb->addLink($link);
  // Saving the original links and caching
  $original_links = $breadcrumb->getLinks();
  $cacheability = CacheableMetadata::createFromObject($breadcrumb);
  // Remove the old value of the array.
  array_shift($original_links);
  $home_link = array_pop($original_links);
  array_unshift($original_links, $home_link);
  // Finally generating the new link.
  $breadcrumb = new Breadcrumb();
  $breadcrumb->setLinks($original_links);
  $breadcrumb->addCacheableDependency($cacheability);
}


How to send HTML/Rich text email from /contact

You have two solutions one is

https://www.drupal.org/project/htmlmail - html mail module especially for html mails
you have to customize the drupal_mail function to accept html

https://www.drupal.org/node/900794

https://www.drupal.org/node/224333#email-html

below is the sample:

Since Drupal 7 automatically converts all HTML emails to plain text before sending them (http://drupal.org/node/224333#email-html), you must now write your own implementation of MailSystemInterface and set a variable telling Drupal to use it in order to send HTML emails. Here is the class which needs to go in your module:

<?php
/**
 * Modify the drupal mail system to send HTML emails.
 */
class ExampleMailSystem implements MailSystemInterface {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

  /**
   * Send an e-mail message, using Drupal variables and default settings.
   *
   * @see http://php.net/manual/en/function.mail.php
   * @see drupal_mail()
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   * @return
   *   TRUE if the mail was successfully accepted, otherwise FALSE.
   */
  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}
?>

Rename the class for your module (i.e. ForwardMailSystem). Then, you need to set the mail_system variable:

<?php
variable_set('mail_system', array('default-system' => 'ExampleMailSystem'));
?>

If you wish to have only emails from your module be sent in HTML but leave all others untouched, use this code:

<?php
variable_set('mail_system', array('default-system' => 'DefaultMailSystem', 'example' => 'ExampleMailSystem'));
?>

That code can go in your module's install file in hook_install to set that variable as soon as your module is enabled. Make sure to also set the variable back to the default in hook_uninstall.


Where can I find an exhaustive reference of the Views module

This is an excellent tutorial: http://nodeone.se/blogg/taming-the-beast-learn-views-with-nodeone-0


Question regarding rendering fields in node.tpl.php

That should be print render($content['field_service_summary']); (notice the $ sign prefixing the variable name).
It's technically OK, but unless you've customised the preprocess workflow to a large degree, what you'll find at $content['field_service_summary'] is actually the result of a call to field_view_value() anyway, so you're just duplicating logic. If you find that method to be the way forward for whatever reason, at least move it into a preprocess function so it's not cluttering up the template file.
When nodes are loaded, they get field data attached to them. That data is in a certain format. When a field is viewed (e.g. with field_view_field()) that data is restructured into a render array, suitable to be run through render()/drupal_render(). The arrays might well contain the same data in some places, but they're formatted differently for their various different purposes.
It's a reference to the node object. It might be used by a theme/render function, or it might not. Core puts it there by convention. Remember it's just a reference to the object, it's not a duplicate.


How can I filter entity titles in an autocomplete form and use the title as context for a View page?

Here's how I solved my problem:

Added an ID field (the ID from the source I'm pulling/validating player names) to my variation.  On creation of a variation, I store the ID in the field when the user selects the player name during product creation, e.g. "Barry Bonds" is ID 35456 in my source.
I'm using a regular autocomplete route in my form instead of an entity_autocomplete.  My autocomplete handler does an entity query on cards (product variations) that are active and match the player name.
After the player is selected from the autocomplete, on form validation, I re-select the player to get the ID.
On form submit I pass the ID with the URL to my views page as a contextual filter, where it expects it as a field value in the URL, e.g. "/player-card-search/35456".

Creating the new ID field in my product variation feels redundant, but it got me to the solution.


Commerce Email: HTML Mail not reading template

It's not enough to leave the theme selection entry as Current theme; you must explicitly state that you want to use the theme you are already using. Now everything works.


Minimizing the time taken for entity_load while using for apachesolr indexing

You could very well form an array of the nodes to be indexed after the query execute and do a single entity_load instead of doing a entity_load for each and every node separately and I hope that will reduce the time and below is the patch that could help you

Index: apachesolr/apachesolr.index.inc

--- apachesolr/apachesolr.index.inc     (revision 9348)
+++ apachesolr/apachesolr.index.inc     (working copy)
@@ -636,9 +636,21 @@
     $query->condition('aie.entity_type', $entity_type);
   }
   $query->range(0, $limit);
-  $records = $query->execute();
-  $status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
+  $records = $query->execute()->fetchAll();
+  foreach ($records as $node_record) {
+    $entities[] = $node_record->entity_id;
+  }
+  $arr_entity = entity_load($entity_type, $entities);
+  foreach ($records as $record) {
+    $record->status = $record->status && $arr_entity[$record->entity_id]->status;
+    $rows[] = $record;
+  }
+  // Commenting as we have already used the entity_load
+  /*$status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
   foreach ($records as $record) {
     // Check status and status callbacks before sending to the index
     if (is_array($status_callbacks)) {
@@ -651,7 +663,7 @@
       }
     }
     $rows[] = $record;
-  }
+  }*/
   return $rows;
 }

As you have said most of your fields are taxonomy term it is idle that you check the term_load method and also whether the term_data table is properly indexed.


Rest full web service API url is changed in d8

From the related issue:

  Drupal core no longer uses accept headers for routing but rather rely on a _format query parameter, because browser, (reverse) proxy and CDN support is very poor, and hence could lead to severe bugs. See See #2364011: [meta] External caches mix up response formats on URLs where content negotiation is in use for more background.

So it was a conscious decision, to help prevent common bugs out in the wild. I wouldn't advise trying to find a workaround, the motivation for changing it is sound. But if you want/need to, perhaps just a simple rewrite rule that would take requests for *.json and forward them on to *?_format=json would suffice.


How to get rid of a duplicate title on the front page?

It sounds like you have node as your front page which lists summaries of content that is promoted to the front page by default. That's the way Drupal comes configured out of the box. If I understand correctly, what you're looking for though is a single node to be displayed in full on the front page.

You can change it from node (which shows a list) to your specific Node at admin/config/system/site-information or Configuration -> Site Information under the "Front Page" section. Simply change "node" to "node/[node-id]" where [node-id] = the nid of the node you want to appear on the front page:


Associate Every Displayed User Name With Corresponding users.data Table Row

It sounds like you should start with what you don't want.

Drupal::currentUser()->id() will retrieve the current user's UID. From there, you can use the UserStorage::loadByProperties() method you referenced to pull the UID by user name. The last step is add code to check Drupal::currentUser()->id() doesn't match the UID found from UserStorage::loadByProperties()


Building something like an affiliate shop?

You've tagged this with ubercart and you're using Drupal 6 so this should be fine - http://drupal.org/project/ubercart_marketplace

If you're not processing payments directly and have some 3rd party integration you're probably best off implementing a custom payment gateway and method using the hooks provided by ubercart than trying to track down a contrib module.


Charts Module not working for one site - No messages in the log

As the Charts maintainer, I am happy to help. My first recommendation is to update to the latest version of Charts (beta1). This has improved handling of fields within Views and a new default in place for Charts Attachments that prevents some issues that users have faced previously. The next thing, and what I think is most likely, is that the libraries did not install properly. Please try disaggregating your JS (from the Admin > Config > Development > Performance page) and then on the page where the chart should be displaying, try inspecting the code and looking for the library's .js file (e.g. highcharts.js). If you're using Chrome, the console tab may tell you something about what is happening.

This also seems silly to say, but be sure your View has results, that it has a field for a title and a field for data, and that those are set in the format settings. This should help for most issues you would experience, but if you are still having trouble please add more information to this post so that your issue can be better diagnosed. Good luck!


How to switch language on pages containing charts created using Forena?

As per the "uncaught TypeError: $(...).dataTable is not a function" you mentioned, it sounds to me that what your language problem is actually not a language problem, but some installation issue related to what's required to Enable Data Tables support. I'd recommend you to first try to resolve that error (as explained in the documentation in the mink I mentioned before, which you can also find in your own site located at /reports/help.setup#datatables.

You may also want to look at my answer to the question about "How to translate the title, axis labels and legend of a chart?" for the typical steps required to correctly translate a chart create with Forena (just to make sure such translation exist for each of your languages, and that the URL for each translation of the report is correct, and does exist).

If neither of this helps to sort out what's happening, then please further enhance your question by including your report/chart specifications (= what's called the "frx"-source in Forena). After doing so, I'd be happy to try to further enhance my answer also.

Disclosure: I'm a co-maintainer of Forena Reports.


If you use a special layout only here, maybe the display suite module is enough for you.
The main part of the solution is you have to create a view mode for the node, that you will use to display a media/description in the views.
You have to set the proper layout here, so something 50/50 and the two fields. If you are done with this new view mode, you have to go into the views. In the Format section you will see the Show line there you have to change from Field to Content. If you set the Content you will see a second column which is listing the available view modes for your content, here you need to select the recently created view mode.


I had this same problem recently, and it took me forever to figure out. What you have to do is make sure the database at your new location is empty. You have to have a database, and it has to be an empty database. Of course, do still make sure your settings.php info is correct, as you did the first time around. Then run install.php and go through the normal steps. Once that is complete, then import all of the tables from the old database into the new database.

The reason for this is that Drupal caches the database connection information, so if you change that in settings.php, it will continue using the old information until you run install.php. And you can only run install.php if you’re pointing the site at a fresh database.

EDIT: Sorry, I missed part of your post. You need to also make sure that your base_url settings in settings.php are set up for the live domain.


How to create a Views based chart with time intervals and using Highcharts?

The example in your question looks like a variation of this chart:

The above is a screenprint of a chart created with the Charts module, for which Highcharts is one of the supported charting engines (apart from Google Charts). So consider this module as a possible alternative to create such chart(s).

Head over to the Community documentation Create charts using Views for details about how to use the Charts module in combination with Views.

Disclosure: I'm a co-maintainer of Charts.


theme_preprocess_node function not getting executed from template file

For using this hook, u will have to replace MYTHEME with your theme name, like if your theme name is bartik, then your function will be

bartik_preprocess_node(&$variables, $hook)

After that clear your cache, by going to Configuration >> Development >> Performance

or just write in url admin/config/development/perfromance


Views, add field value as class to list element

The question is a bit old, but i was looking for the same.
The answer is for drupal 7 / views 3.5, and works fine on Drupal Views 8 || 9 as well..
You can use some field replacement patterns when specifying the classname for the row (in the view edit : Format / Settings / Row Class )
To do so, on the same settings page you may have to check the box 'force using fields'
You then have to make sure the field you want to use is added to the fields section of the view edit
To know what pattern you can use, click on the field in the fields section and go to 'rewrite results' / 'rewrite the output of this field', there is a 'replacement patterns' block that will show you the available patterns.
hope that help, I'm still stuck though by the fact that the string you will get is not class friendly and may contain spaces.


Pulling Possible Select Values From A Field (Drupal 7)

Ok, I did some digger on google. ychaugule made a nice function for this problem. Here is the post.
Also, reference to the information here:

"But the above code will only work for select list, not for node reference or other types of references. _field_allowed_values() function is a custom function which returns allowed values of reference type field. The function returns allowed values for node reference and term reference field and can be extended to get allowed values of other reference fields as well. - See more at: http://yogeshchaugule.com/blog/2013/get-allowed-values-select-list-field#sthash.xnf89Cgn.dpuf"

<?php
function _field_allowed_values($field_name) {
      // retrieve field configurations from DB.
  $allowed_values = array();
  $query = db_select('field_config');
  $query->condition('field_name',$field_name)
  ->fields('field_config',array('type', 'data'));

  $result = $query->execute()->fetchAssoc();

// Allowed references type
  $ref_type = array(
    'node_reference',
    'taxonomy_term_reference',
    );

  $field_config = unserialize($result['data']);
  if (in_array($result['type'], $ref_type)) {
    if ($result['type'] == 'node_reference') {
      $node_types = array_filter($field_config['settings']['referenceable_types']);

      $query = db_select('node');
      $query->condition('type', $node_types, 'in')
      ->condition('status', 1)
      ->fields('node', array('nid', 'title'));
      $allowed_values = $query->execute()->fetchAllKeyed(0, 1);
    }
    elseif ($result['type'] == 'taxonomy_term_reference') {
      $allowed_values = taxonomy_allowed_values($field_config);
    }
  }
  else {
    $allowed_values_raw = unserialize($result['data']);
    $allowed_values = (!empty($allowed_values_raw['settings']['allowed_values']) ? $allowed_values_raw['settings']['allowed_values'] : array());
  }
  return

  $allowed_values;
}

$field = _field_allowed_values('FIELD_NAME');


The way I did it was I implemented my own menu item for 'cart' and embedded the cart view on the page where I wanted it, while implementing other things I needed on the page. Definitely not for the faint of heart, though.

In this approach, your page callback is building the elements to be rendered, so you could use views_embed_view with the appropriate args if needed, pass them as variables, and render your page template where you want them.

Note: this is for Drupal Commerce in Drupal 7.


Using CCK or Taxonomy with Custom Fields in Drupal 7

My idea: make CCK fields of all personal data you want to collect about the athletes. (length, weight, ...) These are different for every athlete.

When you have items that are similar, you should use taxonomy. (Type: Soccer player, Golfer, ...)

Using both taxonomy and CCK makes a complex but great system!

*An example:

I'm making a "travel" website about Spain. A website with many pages.

On my website about Spain I have a regio related page. This page shows content about cities, golf tracks, parks, ... It has an image on top (CCK field), a "tag" (taxonomy term to link pages - show list with simmilar content), a "regio tag" (also taxonomy list of all regio's) and two text fields: positive / negative (CCK fields to enter good and bad things about this city / track / park and so on.

The image and positive/negative fields are for all pages different. The "regio tag" can be the same for some pages (same with the tag).

This way you easily make a view with similar pages people can visit!*


View output a custom designed teaser then full post separate design

Sure it is possible.For that you need to add custom field in your content type called featured image.
While creating the views use that field first and you can have to add

float: left;

In Image field css class to align it left

For exmaple you can see my site www.techiestuffs.com which is exactly what you mentioned.The teaser has image aligned left and when you click either image or title it will leads to original content.
see the below css code i used to achieve this

  .view-recentarticles .views-field-field-image {
float: left;
padding: 3px;
border: 1px solid #C9C9C9;
white-space: nowrap;
margin-right:10px;
margin-bottom:5px;
}
.view-recentarticles {
padding:5px;
border:1px solid #ccc;
background-color:#ffffff;
}

.view-recentarticles .views-field-title {
  margin-bottom: 10px;
  padding-left:10px;
  font-size: 18px;
  line-height: 1.4;
  font-weight:bold;
  background-color:#f4f4f4;
  }
  .view-recentarticles .views-field-title a {
  transition: all 0.2s;
  -moz-transition: all 0.2s;
  -webkit-transition: all 0.2s;
  -o-transition: all 0.2s;
 }
 .view-recentarticles .views-field-title a:hover {
  color: #181818;
 -webkit-transition: all 0.2s;
  text-decoration: none;
  background-color: #f6ecdd;
 }
  .view-recentarticles .views-field-body {
  padding-bottom:5px;
  border-bottom:2px solid #f4f4f4;
  }
    .view-recentarticles .views-field-field-blog-author {
    font-size:10px;
    font-weight:bold;
  padding:5px 2px 5px 2px;
  background-color:#f4f4f4;
  }


it also needs the field name I think, check CommentDefaultFormatter::viewElements

https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21Plugin%21Field%21FieldFormatter%21CommentDefaultFormatter.php/class/CommentDefaultFormatter/8

It uses a lazy builder so it can be built after render caching

$output['comment_form'] = [ '#lazy_builder' => ['comment.lazy_builders:renderForm', [ $entity->getEntityTypeId(), $entity->id(), $field_name, $this->getFieldSetting('comment_type'), ]], '#create_placeholder' => TRUE, ];


While updating the user id is not recommended, for arguments sake, you could reset the user id column in the database.

This is with the caveat that you must also update all referencing tables that use that user id so that those tables also use the new user id value - to maintain "referential integrity". Otherwise, if you do not update all the related user ids, you will corrupt and mixup private user data

For example, the users_roles, file_managed, node, node_revision and other tables...

To match the users with the new uid, you could make an export first of user id to email address. Then you can make another export later and cross-reference the uid from the mail address - to check the new user id match. Keep in mind email address isn't strictly unique in drupal by default.

SELECT uid, mail FROM users;

Backup the users table first.

Then you could do something terrible like:

ALTER TABLE users DROP COLUMN uid;
ALTER TABLE users ADD uid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

That will obliterate and regenerate the users uid column.

UPDATE: As clarified by Berdir, curiously the user id field is not an autoincrement field in Drupal 7 by default. So, you may need to remove the autoincrement property after the UID sequence is recreated and convert to normal int with:

ALTER TABLE users MODIFY uid int(10) unsigned;

Note: you will need to regenerate the anonymous user account with:

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
UPDATE users SET uid = 0 WHERE name = '';

If you just want to hide the uid field value, you could instead try a user alias module like:

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


I don't know if you mean adaptive theme as the theme on drupals repository or adaptive theme as a general behavior. Either way, you don't need a module to handle it. You just need the proper media queries, regardless if they're served by AdaptiveThemes or you insert them directly into your CSS files, somewhere at the end.

Once again, displaying three elements as a grid doesnt require a grid regulation. Is just a view, could be unformatted or html list or whatever. You need to declare responsive widths in your CSS for each row of the view, like so:

  Consider using .gridimg as your row class in unformatted format for
  example

HTML

CSS

            .gridimg {
                width: 33.333333%;
                float: left;
            }

Then the media query where needed

            @media all and (max-width: 600px) {
                gridimg {
                    width: 100%;
                    float: none;
                    margin-bottom: 10px;
                }
            }

Do not display elements for the sake of your media queries, display elements for the sake of your content. Replace 600px with whatever resolution you want your rows to adjust.

Your classes could be named differently. Also the wrapper of your three generated rows should be set to 100%. Rows within should be position: relative;. They're like this by default, unless specified in a different manner.

Maybe your image element should have some css applied to them, for responsive purposes, if they're not set already:

            .gridimg img {
                width: 100%;
                height: auto;
                display: block;
            }


Latest update to 8.7 with Commerce caused Edit buttons to appear in place of shipping/billing information

It looks like you have Commerce AutoSKU installed. The authors of the module modify one of Drupal's validation constraints which checks if fields are empty or not. This causes the addressbook form element to break, which what you're seeing, on top of other problems.

The issue is reported here, https://www.drupal.org/project/commerce_autosku/issues/3086828

The solution is to either uninstall the commerce_autosku module or apply the patch in comment #3: https://www.drupal.org/files/issues/2019-10-18/3086828-3.patch


How can I assign the Commerce Product SKU as the Path Alias?

Pathauto should give you enough flexibility to do that.

Once your "product" content type has a commerce_product_reference field linked to it (let's call it "field_product"), all fields attached to your "product variation type" should be available as tokens like this:

[node:field-product:product-id] or if you created a specific field to store the value [node:field-product:field-sku].

You probably know it but patterns can be configured from here : admin/config/search/path/patterns.


With respect to all of the commentary given to the question, if you really want to do this, you can look at $_SERVER['REQUEST_URI'] in any number of places and based upon its content, do things differently.

For example, if you go to:

www.example.com/path/to/hidden/content

$_SERVER['REQUEST_URI'] will be /path/to/hidden/content

yet if you go to

www.example.com/node/###

$_SERVER['REQUEST_URI'] will be /node/###

but the same content will be displayed while the url in the browser will be different.

So, if you want to obfuscate your nodes based up that, you could delete their content in a preprocess hook, or cobble together something in hook_init to do a 404 but just also be very wary of the caching of pages for anonymous users as well, so hook_boot would be needed instead, and do you want to do this for logged in users and any of numerous other what ifs.........

Plus, if you have global redirect or another similar module installed, the above won't work as it will have already redirected you to the alias.


Content organization for complex website

Taxonomy is the way designed just for this. You can override taxonomy term pages with Views, and in view settings you can easily add your own content. Or use any other approach. Nodereference feels awkward to me, but would work.

If you want to go taxonomy way, just do what feels natural for your kind of data. Make things as simple as possible, and not simpler! That said, if one tree is a subtree of another, yes, keep it as one hierarchical vocabulary. It makes sense and will allow you to filter more effectively in the future.


Best method of importing a large csv file with fields containing multiple values and sub-fields like paragraphs and field collections

You could try using Field Collection Feeds

  Provide feeds integration for field collection module.


Users that can add other users in drupal 7

There's a module for that: Administer Users by Role.

  This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

  To use this module:

  Create a role for the users who you'd like to be able to create/edit/delete other users
  Give that new role the 'administer users' permission and give it the desired Administer Users by Role permissions

I'm using it exactly for the same purpose you described.


Possible to require custom module dependancy on a specific dev version?

Here is the info.
Writing .info files (Drupal 7.x)

dependencies[] = exampleapi (1.x)

The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)

The dependencies[] property in the .info file can also optionally specify operators:

= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to


Page visible for authenticated user, not custom role

When declaring items in hook_menu(), you can specify a custom access callback property. This should be a function that returns TRUE if the user has access to the page.

In this function you can have a look at the global $user object (ie. the currently logged-in user) and determine whether to grant access or not:

/**
 * Implementation of hook_menu()
 */
function hook_menu() {
  $items['user/%/custom-page'] = array(
    'title' => 'Custom Page',
    'type' => MENU_CALLBACK,
    'page callback' => 'your_page_callback',
    'access callback' => 'custom_page_access',
    'access arguments' => array(1),
  );

  return $items;
}

/**
 * Access callback for /user/%/custom-page

 * @param  {[type]} $account [description]
 * @return {[type]}          [description]
 */
function custom_page_access($account) {
  // how do you want to handle role restrictions? if looking at the user
  // whose custom-page is being loaded, use $account, otherwise the global
  // $user object:

  global $user;

  // check that role id 3 IS set, and role id 5 is NOT
  if (isset($user->roles[3]) && !isset($user->roles[5])) {
    return TRUE;
  }

  return FALSE;
}

Don't forget to clear the site's cache (to rebuild the menu registry) after making these changes.


Drupal Commerce Paypal: Order information at Paypal

The only way to change that is through an alter hook documented in the module commece_paypal_wps.


I finally altered the title link by using a preprocess hook and a custom field template file (and a custom view mode for my entity, done with hook_entity_info_alter()):

  function hook_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];
  $uri = entity_uri('taxonomy_term', $term);
  // Edits are here:
  $variables['term_url'] = url($uri['path'], $uri['options']);
  $variables['term_name'] = check_plain($term->name);
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  $variables['term_id'] = drupal_html_id($term->name);
  // Flatten the term object's member fields.
  $variables = array_merge((array) $term, $variables);
  // Helpful $content variable for templates.
  $variables['content'] = array();
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);

  // Gather classes, and clean up name so there are no underscores.
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;

  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
}

My taxonomy-term.tpl.php:

<div<?php print $attributes; ?>>
  <?php if (!$page && ($view_mode != 'subcategory_anchor')): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <?php if (!$page && ($view_mode == 'subcategory_anchor')): ?>
    <h2 id="<?php print $term_id ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <div<?php print $content_attributes; ?>>
    <?php print render($content); ?>


Choosing sub-term after choose term when user post article

Hierarchical Select is exactly for that purpose.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


I think you have issue with hook_suggestions that we need to configure correctly for a template to work.

Its already answered here

drupal 7 template suggestions based on path alias

Hope it will help!


How to programatically change file user owner

I don't know of a module built to handle this, but you could build something easily enough to do it:

the DB table file_managed handles files, and includes a uid field which is the user ID of the file 'owner'

This could be modified in a custom module, but a MAJOR WARNING that I don't know what potential damage this could cause to other elements of the site, perhaps someone with more experience with the DB could add some advice in this regard


There is a module in drupal called Form Block . This module will allow you to present many forms through blocks . Advanced Form Block is another module with same goal .

if these modules couldn't help you can do it by yourself .
create a module , create your own form , your form callback can be User save , export your form as a block .