Custom redirect for form-edit displayed in Views header

You could to use hook_form_FORM_ID. Something like this:

function mymodule_form_page_node_form_ater(&$form, &$form_state, $form_id){
   if(current_path() == 'page/where/my/view/is'){
     $form_state['redirect'] = 'page/to/redirect';
   }
}

If you don't want to use a hook, you can do something like this:

 $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';

Then,

 function redirect_submit($form, &$form_state){
  $form_state['redirect'] = 'path/to/rediect';
 }

Still it is bad practice to inlcude php in your views header. You should implement a custom area handler.

How to create a view area handler
https://api.drupal.org/api/views/handlers!views_handler_area.inc/group/views_area_handlers/7
https://oliverhuynh.wordpress.com/2011/06/23/custom-views-handler-drupal-7-template/


Use Webform for multiple possible inputs

The Webform Table Element module will allow you to setup your webform in a tabular format.

But I don't think it allows for unlimited number of lines as an excel sheet would. Still it could be a reasonable (quick) solution for your need.


Is the "Start Date" field a date field? Or is it a text (or some other type of field)?

If it's an actual date field, you can configure this behavior through the UI.

Add the field as a filter in the Filters section. Then you should see an Is between operator radio button. Select that and enter your range in the Value section. Screenshot:

You need to activate the date_views module to see the filters appearing in the Views module interface.


creating messages that appear after content is created

This could be done with some code in a custom module:

hook_node_insert($node) {
    if($node->type=='my_content_type') {
        drupal_set_message(t('New content created: :link', array(':link' => l($node->title, 'node/'.$node->nid))));
    }
}


Drupal Search Result Sorting in Desc order

Similar questions here

Use hook_preprocess_search_results and set your criteria there.

Here's the .module file you can use, this sort nodes by their creation time with a descending order. You need to create a .info file to make the module work, also remember to replace [MODULE_NAME] with your own module's name. This is not perfect but at least gives you the data in the order you want.

<?php
/**
 * Implement hook_preprocess_search_results()
 */
function [MODULE_NAME]_preprocess_search_results(&$vars) {
        $results = $vars['results'];// via dsm (Devel module), we can see node creation time is available under the 'results' array
        usort($results, function($v1, $v2) {
          return $v2['node']->created - $v1['node']->created; // sort by created time, DESC order
        });
        $value = '';
        $output = '';
        $output_results = array();
        foreach($results as $item) {
          $value .= theme('search_result', array('result' => $item, 'module' => $vars['module']));
          $output_results[] = $value;
          $value = '';
        } // store all results into an array
        #dsm($output_results);
        $output = implode(" ", $output_results)."
"; // convert array to string
        $vars['search_results'] = $output;
        #dsm($vars);
}

.info file:

name = Search Desc
description = sort default search by creation date in DESC order
core = 7.x

search.tpl.php file, you need to copy this file from modules/search/search-result.tpl.php and put it under your theme dir, do not modify the original.

<?php
$info_split['date'] = date('m/d/Y - H:i', $result['node']->created);// replace update time with created time
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

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

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info_split): ?>

<?php print $info_split['user'].' '.$info_split['date']; ?>

    <?php endif; ?>

Update:
Given Drupal's default search ranking criteria (by content relevance), an additional hook is needed inside the .module file for OP's question. After adding this, you need to go to /admin/config/search/settings and set the Influence for the 'Node Creation Date' field at the bottom of the page, re-index, and run cron.

/**
 * Implement hook_ranking()
 */
function [MODULE_NAME]_ranking() {
  return array(
    'node_created_date' => array(
      'title' => t('Node Creation Date'),
      'score' => 'n.created',
    ),
  );
}


Seems really odd that the maintainer would say that this was impossible and a fringe case.

Seems to me like this is a very normal use case, in fact one that we use on every single Ubercart site we have in production. I actually thought this was a setting in the module config page and was surprised to see that it wasn't.

Anyway, here's what I did. I disabled the included rule because I despise rules and added this code to my module:

/**
 * Implements hook_commerce_checkout_complete().
 */
function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $order_wrapper->commerce_line_items->value();
  if (is_array($line_items)) {
    foreach ($line_items as $line_item) {
      if (in_array($line_item->type, commerce_product_line_item_types())) {
        $product = commerce_product_load_by_sku($line_item->line_item_label);

        // Subtract the sold amount from the available stock level.
        $qty = (int) $line_item->quantity;
        module_load_include('inc', 'commerce_stock', 'commerce_stock.rules');
        commerce_stock_adjust($product, -$qty);

        // Disable the product if we have no stock left
        $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
        if ($product_wrapper->commerce_stock->value() <= 0) {
          $product_wrapper->status->set(0);
          $result = $product_wrapper->save();

          if ($result) {
            watchdog('commerce_stock', 'Product %sku stock level reached 0, status set to 0.', array('%sku' => $product->sku));
          }
          else {
            watchdog('commerce_stock', 'Failed attempt to disable product %sku', array('%sku' => $product->sku), WATCHDOG_ERROR);
          }
        }
      }
    }
  }
}

It's just a copy of the default rule that ships with the module with the extra code for disabling the product added in.

I guess you could leave the default rule active and remove the 3 lines that adjust the stock level in my example, but then I'm not sure what would be called first, the rule or my hook so you would have to test that yourself.


Add a class to a Drupal table cell containing ['data']

After writing out the question in general terms, I've gone back to test again, and have determined that Option 5 in the OP with '#wrapper_attributes' at the same level of the 'data' element does work.  I believe Drupal 8 was aggressively caching the table, because my changes were not showing up even after a drush cr.

The rules for adding classes to tables via backend PHP is:

Table class requires #attributes.
TR row class inside TBODY requires #attributes.
TD cell class inside TBODY requires #wrapper_attributes.
TR row class inside THEAD/TFOOT requires 'class' and 'data' containers.  Neither #attributes nor #wrapper_attributes work here.
TH/TD cell class inside THEAD/TFOOT requires 'class' and 'data' containers.  Neither #attributes nor #wrapper_attributes work here.
There is no way to add a class directly to a
 or
 tag without overriding a twig template.

Here is the most common example for adding classes to the
 &  tags inside the main
, as well as to the main
 tag itself:

$table = [
  '#type' => 'table',
  '#attributes' => [
    'class' => ['table-class'],
  ],
  'row1' => [
    '#attributes' => [
      'class' => ['tr-class'],
    ],
    // Table data cell using 'data' for renderable elements.
    'column1' => [
      'data' => [
        '#type' => 'link', // Or any other renderable thing.
        '#attributes' => [
          'class' => ['link-class'],
        ],
        // Other elements required to render the link go here...
      ],
      '#wrapper_attributes' => [ // Watch out!
        'class' => ['td-class'],
      ],
    ],
    // Table data cell using '#markup'.
    'column2' => [
      '#markup' => '' . $this->t('text') . '',
      '#wrapper_attributes' => [
        'class' => ['td-class'],
      ],
    ],
  ],
];

Note that the 'class' container will accept either a string or an array, but I suggest always using an array.

From here, the story gets more complicated.  If you need to add classes to the TR or TD/TH tags inside a THEAD/TFOOT area, the rules change completely.  Neither #attributes nor #wrapper_attributes work inside #header and #footer sections and trying to use them produces very strange effects.

The bare minimum structure for tables with header/footer data columns in Drupal 8 is this:

$table = [
  '#type' => 'table',
  // Produces

  '#header' => [
    'Header 1',
    'Header 2',
    'Header 3',
  ],
  // Produces

  'row1' => [
    'Body 1',
    'Body 2',
    'Body 3',
  ],
  // Produces

  '#footer' => [
    'Footer 1',
    'Footer 2',
    'Footer 3',
  ],
];

You must change the actual structure of the data and introduce two levels of additional multi-dimensional arrays, in order to leverage the 'class' array index which requires then also introducing the 'data' array index.  This applies both to the row element and the data cell elements, as seen in the following example:

$table = [
  '#type' => 'table',
  // This example works the same way for '#footer'.
  '#header' => [
    // First, introduce an extra level to the array to provide a
    // place to store the class attribute on the
 element inside
    // the
.
    [
      'class' => 'thead-tr-class',
      // Next place the columns inside a 'data' container, so that
      // the 'class' can be used.  '#wrapper_attributes' will not
      // work here.
      'data' => [
        // The following line produces data inside a
        // without any class.
        'Header 1',

        // The following lines produce data inside a
        // with a class: th-class.
        [
           'class' => 'th-class',
           'data' => 'Header 2',
           'colspan' => 2
        ],
      ],
    ],
  ],
];

The above example #header example produces:

      Header 1
      Header 2


The error is related to the location module. Uninstalling that module will remove the errors.


Failed patching both manually and with Git in Ubuntu terminal

The patch you have doesn't apply to the version of the module you have.

You either need to get a version of the module that the patch applies to, or look for/create a patch that applies cleanly to the version of the module you have installed.

Might be worth checking the patch and target files manually, the patch may well have been applied and just not have fixed the problem in the way you were expecting. I can't tell what order you've run commands in/what you've done to clean up after each and so on so it's just a guess, but the "Reversed (or previously applied) patch detected!" message suggests the patch has already been applied at some point.


According to #15 of this Drupal issue

having a duplicate node on the screen is enough to disable the contextual menu functionality. It's a bug.


Detect profile2 save occasion in module and get user

Yes it is possible, you can use the generic hook_entity_presave (or update/insert). There is also a specific hook for profile2 as well, hook_profile2_presave (or update/insert), but it requires the Rules module to be enabled.


How to generate XML feed with nested tags using Xpath Parser?

You need to move your context 1 level back.

context: /rss/channel

title: title

description: description

owner name: owner/owner:name

owner email: owner/owner:email

item title: item/title

item author: item/author


Add a class to the first teaser on /blog page

In the template_preprocess_node hook you can use $vars['id'] to get the array index in the order that the nodes are printed.

You'll need to replace COND_FOR_BLOG with whatever logic you have for checking that.

Example to get you started:

function THEME_OR_MODULE_preprocess_node(&$vars) {
  if (COND_FOR_BLOG && $vars['id'] == 1) {
    $vars['classes_array'][] = 'featured';
  }
}

Edit: Note that $vars['id'] is not zero-based so $vars['id'] == 1 actually gives the first post.


Adding a "title" field to video thumbnails in the Video Module

You can use hook_form_alter(), there is no any built-in option to do that.

You can also use the Field collection module to create a new field collection with a text field, and the video field.

  Provides a field-collection field, to which any number of fields can be attached.

  A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


Please take a look at the views export below, this will give you user values. This will work on editing the task but not when you are initially creating the task (as the field_parent_project does not yet have a value stored against it).

$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_project_team_node']['id'] = 'reverse_field_project_team_node';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['table'] = 'users';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['field'] = 'reverse_field_project_team_node';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['id'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['field'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['relationship'] = 'reverse_field_project_team_node';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'reverse_field_parent_project_node';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Entity Reference */
$handler = $view->new_display('entityreference', 'Entity Reference', 'entityreference_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'entityreference_style';
$handler->display->display_options['style_options']['search_fields'] = array(
  'name' => 'name',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'entityreference_fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;


Drupal 8:How to add tags for custom content types

Go to /admin/structure/types and press on manage fields of your custom content type

Press on the +Add field button, and use Re-use an exiting field (the drop down on the right) to select the existing Entity Referenc: field_tags

Then go to manage form display, for tags change the widget to autocomplete (Tags style)

PS: I suggest you install admin toolbar if you haven't already.


How do I customise individual menu links?

If you just need to add a string after the menu title, you can use the following code.

function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $output = l($element['#title'] . ' ' . t('the string you need to add'), $element['#href'], $element['#localized_options']);

  return '
' . $output . $sub_menu . "
\n";
}

The alternative would be using the following code, which would give to who translate the string more context to translate it.

function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $output = l(t('!title the string you need to add', array('!title' => $element['#title'])), $element['#href'], $element['#localized_options']);

  return '
' . $output . $sub_menu . "
\n";
}

You could also implement a preprocess function to alter the title.

function mytheme_preprocess_menu_link(array $variables) {
  $variables['element']['#title'] = t('!title the string you need to add', array('!title' => $variables['element']['#title']));
}


Calculate shipping cost by weight in Drupal commerce

For Commerce shipping 2.x this is actually pretty simple.

Create a calculation rule.
Set the condition that the weight for the order is above 2 kg (this can be a bit tricky to do in Rules, but there a plenty of guides how to do it. I believe Randy even shows this in the video you linked to.
Select the "add amount to unit price" for a line item and select the shipping line item. You can even select which component to use for this and could create an weight fee price component if you wanted to.

That's it.


First I tried to use the hook_views_pre_execute.

<?php
function hook_views_pre_execute(&$view) {
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
}

But when I tried to use the pager, it had too many bugs. It felt like a hack. So in the end I used:

<?php
/**
 * Returns a page with one not voted poll
 * @return [array] [drupal page array]
 */
function one_poll_page(){

    $page[] = "";
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

        $result = $query->execute();

    foreach ($result as $record) {
      //saves the rendered poll node to the array
      $node = node_load($record->nid);
      $view = node_view($node, 'full');
      $rendered = drupal_render($view);
      $page['#markup'] .= $rendered;
    }

    return $page;
}

Because I can then control exactly what the page does.


How to check if view is added in a feature?

The features export views' code in files like this: my_module.views_default.inc. Every feature module with a file my_module.views_default.inc contains views.

Manually:

Searching against those modules by using the view's machine name as an input, will show whether that view machine name is tracked or not, to any of these modules.

Using drush:

Having all your features updated drush fu-all -y do some changes to a view (save) and drush fl. The feature that will appear with an overridden status contains that view, otherwise the view is not tracked yet. To see which features contains views code do drush fc --exported and select views_view, that will narrow down significantly the searching range.

More Features & Drush


Can't get the author's picture printed onto a node in Drupal 7

Have you tried examining the $user object itself? It should be something like

    <?php
    global $user;
    print $user->picture;
    ?>

Or if that is loading the logged in user(which it will) as opposed to the user(creator of the node) you are viewing try on a node:

<?php
$user_object = user_load($uid));
print $user_object->picture;
?>


You can override the output of theme_form_element() function in your theme's template.php file. Just copy the function from includes/form.inc file and put it in template.php as MYTHEME_form_element(), and you can now change classes for only text fields with something like this before initializing $output variable :

if($element['#type'] == 'textfield'){
  // Add a class specific to textfields
  $attributes['class'][] = 'custom-textfield-class';
}

This code is not tested, but it should work. You should clear drupal cache after implementing the function in template.php.


How do I fix this commerce_auction_node_presave error message?

Change the code below :

 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
    $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];

with

 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price['und'][0]['amount'];
        $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price['und'][0]['currency_code'];


Did you try the Prepopulate module? Entityforms just use Drupal Fields so I imagine it should work. You would then just define the values per field in the URL from your email.

  The Prepopulate module allows fields in most forms to be pre-populated
  from the $_REQUEST variable.

  For example, the following URL,

  http://www.example.com/node/add/blog?edit[title]=this is the title

  will automatically fill the Title field on a new blog post with the
  words "this is the title". Any field can be prepopulated this way,
  including taxonomy and CCK fields. You can prepopulate more than one
  field at a time as well. Prepopulate is excellent for creating
  bookmarklets. For examples on usage for all of these cases, please
  read the USAGE.txt file that comes with the module or you can read the
  online handbook page.


How to join the dots and reduce the dot size in scatter plot using Easychart?

Part of what you're asking for (= "How will I reduce the size of the dots"), is a typical example of how it is like to use a UI (= Easychart), and find out that you need some special option/facility of the Highcharts library, but which you cannot enter via the Easychart UI.

Here are some hints/directions to try to resolve that part of your question anyhow:

As you must have noticed using the Easychart UI, there is nothing (out-of-the-box) that you can use to reduce that size of those dots.
So head over to the Highcharts options reference which outlines the chart configuration options, and the methods and properties of Highcharts objects. Attention: don't get overwhelmed, there are a zillion of options ... in this case, your question boils down to plotOptions.scatter.marker.radius, which is the "radius of the point marker" (don't ask me how I know, I just do ...). It turns out that its defaults is "4". So with that your question becomes like this: How do I overwrite that default value of plotOptions.scatter.marker.radius with (eg) "1"?
To understand where we're going, first have a look at the Feature request Other chart types. It's a request about "Is it possible to use more chart types like Donut, 3d Pie, or any available HighCharts examples". So that is actually way more then just adapting the default value of "radius of the point marker". Nevertheless, comment nr 3 in that feature request contains the actual answer. The crucial part of that comment is that it contains "an example of an interface with more options than those provided by our default set". It takes some effort to digest it (what it is about), but the most important part of that sample is at the end of it, and which looks like so:

{
  "panelTitle": "Advanced Chart options",
  "pane": [
    {
      "title":"Pie/Donut",
      "options": ["plotOptions.pie.innerSize","plotOptions.pie.allowPointSelect","plotOptions.pie.depth","plotOptions.pie.cursor"]
    },
    {
      "title":"3D",
      "options": ["chart.options3d.enabled","chart.options3d.alpha","chart.options3d.beta"]
    }
  ]
}

To understand what this sample is about, have a look at the image in the next comment (nr 4), which looks like so:

As shown in the above image, by adding (near the end) those specifications about "Advanced Chart options", it is perfectly possible to add that panel with title "Advanced Chart options", and with the 2 panes titled "Pie/Donut" and "3D" (each with their related "options" also).


Is there a tool to covert any template to drupal 7 theme?

Nope! :)

There is, however, a nice page full of information to convert Drupal 6 themes to Drupal 7: link


Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away'

99% of the times I've seen that error it is because the website is trying to save more data than the amount expected by MySQL.

It is fixed increasing the value of the mysql variable max_allowed_packet

The value of this variable is given in bytes, and by default it is set to 1048576 (1 Mb).

You can try to modify it to something bigger, like 4194304 (4 Mb) and keep increasing it to a value that do not give you this error.


Views node author relationships with profile2 owner

I managed to get around this by setting up relationships with Content:Author and (author)User:Profiles. Then setting up a Contextual Filter of Content:Author UID, with Raw Data from URL, using Path Component 2, as the Default Value.


Hooks Alter not called in Template.php for

Hooks are only invoked for enabled modules, and the current theme. So code in template.php for theme1 won't be used when theme2 is active (unless theme2 is a subtheme of theme1, thanks @greggles).

The reason is obvious when you think about it: if you've explicitly said you want one theme on a certain page, code from another theme shouldn't be allowed to interfere. It could cause all sorts of problems.

If you have code that should run independently of the theme that's being used to display the page, the proper (and only) place to put it is in a module.


Filter a field based on the content type in a view(Drupal 7)

You can use a preprocess hook to build in some logic to now show the last comment when the content type if of the type is External news. You need to add the content type and exclude it from display. That will make the value available in the preprocess hook.

You could use hook_preprocess_views_fields for this.


It depends on how your node 'products' are setup. In Drupal Commerce, 'products' are a fieldable Entity Type and each bundle of that entity type is a different product with different sets of fields.

One possible solution would be to check out the Migrate and its ecosystem of other modules to see if there would be a way to convert your product Content Type to a Product Type.

Note that in the native Commerce workflow, you also need a Product Display node to act as a container for products to display them to the end user. Think of the Product entity as a single product option [in the example of a t-shirt it could be "X-Large Blue"] and the Product Display node is the wrapper that contains all options to display as a single "product" to the user.


How do you define an arbitrary sort sequence for views?

Views has hook_views_query_alter, which lets you mess with the query object that it maintains.  It gets called before the query object gets converted to SQL.  You can change the sorting that is set in the UI with something like:

function mymodule_views_query_alter (&$view, &$query)
{
  $query->orderby = array('node.nid ASC');
}

Basically, the value you use is what would be after the ORDER BY in a normal query.  You should be able to use an ORDER BY CASE,

function mymodule_views_query_alter (&$view, &$query)
{
  $orderby = "
    CASE
      WHEN node.type = 'page' THEN 1
      WHEN node.type = 'article' THEN 2
    END ASC
  ";
  $query->orderby = array($orderby);
}

You will need to enable previewing the SQL in Views (it's in the main views settings, not with the settings for a particular view) to see the names to use.


Repository-based site deployment -- what to do about sites/default/files?

Ahh the age old question of how to properly deploy Drupal from dev->test->live. If you search around you will find many opinions and answers. There is no one answer and no singular method. The symlink solution is good one and is safe and simple. Another solution would be to use SVN to sync directly back to the same site/directory(s). You could mark certain files so that they are not pushed. If a mistake is made, you just revert. One other file I can think of that you may not want to overwrite is .htaccess. Other than that, settings.php and your files directory are about all that would need to be excluded.


User or Content Type for employee directory

I think you would be dealing with 'users' so using profile fields on user profiles would be your best shot.  As a bonus, Drupal is well thought out and flexible enough to handle whatever kind of userbase you throw at it.  Unless you want to re-invent the wheel in node hooks, I would shoot for profile fields and if you need to code up a custom module (or two), I can highly recommend entity api module to help you deal with profile field data.

The 'red' information you want (I assume) added to new content for example, (or any other possible variable) is easily done in templates. Usually based on conditionals and often (but not always) based on a bool variable of some kind.

For example, consider a 'flag' variable called $is_new. If $is_new isset (or !empty),  either you send a conditional stylesheet, or set up a template to show that background in red text in black. As simple example here is a repost of recommended way to use if's in a template:

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

<?php print $is_new ; ?>

<?php endif; ?>
 // You can use foreach statements for arrays you want to render
<?php foreach ($new_items as $item): ?>

<?php print $item; ?>

<?php endforeach; ?>

As for the different views for different is totally a different matter, but happily is also built in natively via roles, permissions and content-access system.

Good-luck!


I done this before using global text field and html. Add all needed fields into view and exclude them from display. Then create an html layout using field replacement patterns according to your requirement using a Global:Text field. Then generate PDF.

Hope this helps you.


With Drupal 7, Drupal 8, and Drupal 9 you can use user_cookie_save() to store a cookie.
function user_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

The first function parameter is an array. Its keys are the names of the cookies to set; its values are the values to set for those cookies.
user_cookie_save() doesn't allow to set when a cookie expires; cookies created with this function expires after 365 days.
There is just a method in Drupal 8 core class that uses user_cookie_save(): SystemController::compactPage().
public function compactPage($mode) {
  user_cookie_save(['admin_compact_mode' => $mode == 'on']);
  return $this->redirect('<front>');
}

Unfortunately, there isn't an equivalent function to read a cookie. Drupal 8 and Drupal 9, to read the cookie saved from SystemController::compactPage() uses system_admin_compact_mode().
function system_admin_compact_mode() {
  // PHP converts dots into underscores in cookie names to avoid problems with
  // its parser, so we use a converted cookie name.
  return \Drupal::request()->cookies->get('Drupal_visitor_admin_compact_mode', \Drupal::config('system.site')->get('admin_compact_mode'));
}

The other function/method I found that stores cookies in Drupal 8 and Drupal 9 is BigPipeController::setNoJsCookie() (implemented since Drupal 8.1.x) which uses the following code.
if ($request->cookies->has(BigPipeStrategy::NOJS_COOKIE) || !$request->hasSession()) {
  throw new AccessDeniedHttpException();
}
if (!$request->query->has('destination')) {
  throw new HttpException(400, 'The original location is missing.');
}
$response = new LocalRedirectResponse($request->query->get('destination'));

// Set cookie without httpOnly, so that JavaScript can delete it.
$response->headers->setCookie(new Cookie(BigPipeStrategy::NOJS_COOKIE, TRUE, 0, '/', NULL, FALSE, FALSE, FALSE, NULL));
$response->addCacheableDependency((new CacheableMetadata())
  ->addCacheContexts([
    'cookies:' . BigPipeStrategy::NOJS_COOKIE,
    'session.exists',
  ]));
return $response;

Using $response->headers->setCookie() gives more control over the cookie parameters (the parameters Cookie::__construct() accepts).


Not able to print variables of content type

Try this: (D7)

function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('<pre>' . print_r($vars, true) . '</pre>');
}


If you have the ability to write the patch, even if it's not "right", it can often encourage the developer to jump in and help. If you're not as comfortable writing the patch, you can also explicitly offer to test it.

Overall, just be polite, and be prepared to be patient. We're almost all volunteers!


jQuery csv file export fires multiple times

Try this:

(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").once().click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

I added the jQuery.once() method.


Drupal views get field info from node within another field

I assume that you are using the References module to provide a Node Reference field to Photo Gallery nodes which reference Projects, and then provide another Node Reference field, or Term Reference field to Project nodes which reference Categories?

In Views:

Expand the Advanced column
Add a Relationship
In the Add Relationships dialog, select the Photo Gallery: Project Node Reference field from the list
In the Configure Relationship dialog, Click Apply
Add another Relationship
This time in the Add Relationships dialog, select the Project: Category Node/Term Reference field from the list.
In the Configure Relationship dialog, there is a field labelled Relationship with a drop-down menu, which lets you choose other compatible relationships you've added previously, from which you should select the Photo Gallery: Project relationship (I'm not entirely certain what text to expect here). Then click Apply.
Now when you add new Fields to the View, you'll have the option to select a Relationship for each individual field, which allows you to pull data from the entity (Node/Term) that is referenced by the selected Relationship


How can I have different image size for a content type

The Image Style Selector module allows you to select a predefined image style and apply it to the uploaded image. In this way when you create a node (or any other fieldable entity), upload an image, you can choose which image style to apply to that image.


Displaying two Content Types in a single view

In response to Molot:

There are several ways to skin this cat. I believe that the approach I took is the easiest, though there is one remaining issue (more below).

Steps:

Add the References module (other options include using the Entity Reference module and one other similar module)
On Admin->Modules, under Fields, enable References and Node Reference, and click Save Configuration.
For the 'parent' entity type (in my example above, Panel) add a new field of type Node Reference. In the settings for this field, select the content type(s) that can be referenced (for my example above, I chose Presenter).
In the patent entity type, chose Manage Display. For the Referenced Node, you can choose 'Rendered Node' as the Format of the child node (and you can define this to be the default view, the Teaser view, etc.)
For each entity of the parent type, in the newly created reference field, start typing the title of the field to be referenced, then click the proper one.

As noted above, I am still having one problem - see Configuring View output with multiple related nodes for details.

I hope you find this helpful.


use custom tokens on a webform email confirmation

use also the token module, you'll find instructions in its documentation.

basically, you'll need to implement these two hooks:

function my_user_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'user') {
    $user = $object;
    $tokens['name']      = $user->name;
    $tokens['mail']      = $user->mail;
    return $tokens;
  }
}

and

function my_user_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens['user']['name']      = t("The user's name");
    $tokens['user']['mail']      = t("The user's email address");
    return $tokens;
  }
}


Inserting additional AJAX using hook_flag

I'm certain there is a better way to do this, but rather than using hook_flag use JavaScript.

The trick seems to be to use bind('flagGlobalAfterLinkUpdate', function(event, data)

And then catch the specific flag you're using with data.contentId;

(function ($) {
    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
        var fsrnid=data.contentId;
        var fsrpostcard = $(".postcard-" + fsrnid).text();
        var fsrpostcardset = fsrpostcard.indexOf('Yes') >= 0;
        var fsrcalled = $(".flag-customer-called-" + fsrnid).text();
        var fsrcalledset = fsrcalled.indexOf('Yes') >= 0;
        var fsremail = $(".flag-email-sent-" + fsrnid).text();
        var fsremailset = fsremail.indexOf('Yes') >= 0;

        if (fsrpostcardset || fsrcalledset || fsremailset) {
            $(".completed-" + fsrnid).text('Yes');
        } else {
            $(".completed-" + fsrnid).text('No');
        }

    });
}(jQuery));

The Flag API (JavaScript) documentation is a bit dated and doesn't necessarily apply directly to Drupal 7.  It is still very useful in figuring out how the Flag module uses JavaScript though.


Can't use drush site-install to drop tables and reinstall in MAMP

Make sure nothing breaks Drush calls; attempt a drush cc all to see if the error still appears, and debug if it does.

To avoid dropping the database, the simple "hacked" answer is:

Edit site's settings.php file to use another database scheme (make sure it exists though).

$databases = array (
  'example1' =>
  array (
    'example1' => array (
      'database' => 'example2', // Changed from "example1".
      'username' => 'user',
      'password' => 'pass',
    ),
  ),
);

Use site-instal . This will drop "Example2" and install the site there, without hurting the original database.
Edit the site's configuration file back to original database scheme.

You need to use backquotes on the "drush sqlc" part:``drush sql-connect`` < path/to/file.sql.


They see a blank 403 page with this message specifying that their IP address has been banned:

The block is done at the application level. Drupal inserts a record into the blocked_ips table which is referenced upon bootstrapping; if a match is found the above page is shown.

I've not heard a module that does this at the OS level. Considering the variety of environments it would have to accommodate, and the potential harm of giving an application OS-level blocking (e.g. Drupal blocking you could lock you out of your own server), it's likely it doesn't exist.


Problem with restricted download links (hook_file_download)

Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The performance hit from using the private file system is minimal.

IMHO, using the private file system to control download access to files is the only sane way to do this when using Drupal.

  What am I doing wrong?

You err in not using the private file system .

When you hand the direct link to the browser, it goes directly to that link.  It does not even see the PHP/JavaScript you've put in place to restrict download access.

To prevent unauthorised downloads, you must enforce that the downloads are managed by Drupal, and that this access control cannot be bypassed by requesting direct links served by the browser. This is what the private file system (aka private download method) does.

This download method stores the files attached to a node in a directory that is not accessible by the browser (preferably above the web-root). The only way to get to these files, are then through Drupal.


I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

Then, in your module's .info file, add the file containing this class (in this example, 'custom_handler_filter_countries.inc') to the .info file's files array (files[] = includes/custom_handler_filter_countries.inc).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in hook_views_pre_view(), I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.

This discussion may also have a possible solution:

Custom Options Value of Views Grouped Filter?


What is the best way to calculate the price from selected line item field (a select line item field)

The only reason I used following solution, was because we didn't need to make a product type for variety of options we had, and we had a lot of options which didn't make sense to make it as individual product.

I used rules, if any one find better solution let me know, hope it will help someone.

1) defined an action function to multiply the price to a coefficient

2) checked to see what option has been selected and proper coefficient has been applied

/**
 * Rules action: multiply the unit price by some amount.
 */
function modulename_unit_price_multiply($line_item, $amount, $component_name, $round_mode) {
  if (is_numeric($amount)) {
    // Coefficient variable
    $cf = '1';
    if(isset($line_item->field_color[LANGUAGE_NONE][0]['value'])){
        $selected_color = $line_item->field_color[LANGUAGE_NONE][0]['value'];
        switch ($selected_color){
            case 'red':
                $cf *= 2;
                break;
            case 'black':
                $cf *= 3;
                break;
           case 'blue':
                $cf *= 4;
                break;
            }
    } else {
        $cf *= '1';
    }
    $wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

    // Calculate the updated amount and create a price array representing the
    // difference between it and the current amount.
    $current_amount = $unit_price['amount'];
    $updated_amount = commerce_round($round_mode, $current_amount * $amount * $cf);

    $difference = array(
      'amount' => $updated_amount - $current_amount,
      'currency_code' => $unit_price['currency_code'],
      'data' => array(),
    );

    // Set the amount of the unit price and add the difference as a component.
    $wrapper->commerce_unit_price->amount = $updated_amount;

    $wrapper->commerce_unit_price->data = commerce_price_component_add(
      $wrapper->commerce_unit_price->value(),
      $component_name,
      $difference,
      TRUE
    );
  }
}


Rendering plain text instead of formatted data

I believe you can use check_markup to render the text in the specified format. In your example, you'd want to also save the format, something like:

$query = db_insert('my_table')
  ->fields(array(
   'full_detail_text' => $form_state->getValue('english_copy_text')[value],
   'full_detail_format' => $form_state->getValue('english_copy_text')[format],
   'date' => REQUEST_TIME,
  ))
 ->execute();

Then when you go to render it in the hook_views_pre_render

$rendered_markup  = check_markup($full_detail_text, $full_detail_format),

For more info,
 see:
 https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check_markup/8.3.x


Drupal 7- "Users who bought this also bought that" module

There are two modules available for Ubercart; the first one is Ubercart Products Recommender which provides a View for:

  Users who ordered this product also ordered.

The second is easyrec for ubercart, which provides a block called:

  other users also bought

Either one should be fine for what you want, and both have a stable Drupal 7 version available.


How to find/download latest drupal version via bash?

For all your command line and script needs there is Drush. To download the latest Drupal 7 with it, you simply do

drush pm-download drupal


Altering database tables belonging to core modules

Yes, I'm not sure altering core tables is a good idea.

I don't see any problem with it, as long as you just add fields.

But I remember having seen some code here and there that cycles through all the fields in a table, so even this might cause problems.

It's a bit personal and question of belief, but as far as I can, I try to make my code as something that can work with core's code and structure. I've seen too many devs going in implementation hell with decisions like that.

Also, having to alter what's already been designed by big teams and/or big guys like core devs is very often due to a bad analysis of the use case.

My general advice for anybody who's lower than core dev level (including me, of course) would be : don't do it.


What's the advantage of using Git submodules for Drupal core and contrib?

At our workplace we avoid git submodules as they add unneccessary complexity to the system.

We run one git repo for each site, and we have drupal core as an upstream remote. This makes merging in 7.12 for example as easy as:

git fetch upstream
git merge 7.12

As for contrib, drush is king

drush dl views
git add -A
git commit -m 'bumps views to next stable'

Hope this helps


Translate Drupal's built-in English to another kind of English

You can do this with the Locale module, which is provided by core.  Steps are for Drupal 7.  This assumes you want to completely replace the built-in English with your own custom version of English (which will still show the strings for the built-in English unless you have translated/edited them).

Enable the locale module.
Go to languages admin (/admin/config/regional/language).
Click edit for the English (built-in) language.  Add en as the Path prefix (this will allow you to add your own language without a path prefix.)  Save.
Click "Add a language"
Choose "Custom language", set a language code, set both language names to English,  leave Path prefix and Language domain blank, and choose Left to right for the Direction.
Go back to the language list (/admin/config/regional/language) and set your new English as the default language.  Then uncheck Enabled for the built-in English.
Translate all the strings you want to modify on the translation screen (/admin/config/regional/translate/translate).


Is there a module provides UI to create field index?

Because views does not create tables but rather builds queries, you cannot add indexes to views but what you can do is insert Mysql Index hints via the Views Index Hint module.

If this module is not flexible enough for you, you can manually add the index hint after the sql query is constructed by using the hook_views_query_alter hook.


Why does advancing/retreating the month remove all events from the calendar in FullCalendar?

Looking at your calendar now it looks like you have it fixed.  I was gonna' offer the solution that I was told:  Make your site's short date format to use "2014-5-19 17:30"  Unfortunately it had to be in military time, not 12 hour or it didn't work.  That is only an issue when looking at the "upcoming events" that I have listed at the bottom of my calendar in another block.  I was going to go the ajax method if I can get 12 hour time to work with ajax, using the fix offered for Ajax at the drupal posts on this issue; haven't tried it yet.

So what solution did you get to work for you?

Dave N


what is drupal 6's version of hook_user_cancel for drupal7?

hook_user() has an operation for delete, it does however lack an option for ban or block. In this case you should use the rules module and implement a custom action that gets called when a user is banned, the action being in your custom code. There's a few Drupalcon presentations on Rules, Conditions and Actions available on Drupal.org.


Displaying Ubercart order history for customers in their "my account" page

So after long last, by accident, I found the option. In Drupal 7 go to Home » Administration » People and select the permissions tab. Once there navigate down the "Orders section" within that section you will be given the option to allow users to view certain order information. Select the relevant information and you are good to go. Be careful not to give them access to things they should not be able to see (these options are also available there as well).


Found index.php in files folder and all its subfolders? Anyone know what type of exploit is this?

Just an additional note, this looks like it could have been caused by the FCKEditor / CKEditor arbitrary file upload bug.

If using one of those WYSIWYGs, check this advisory:

http://drupal.org/node/1482528

and upgrade to latest


How to copy select list value from a webform submisison into select list field new node?

Well, finally i figure it out how to solve it.

I'm using Webform Rules module

Just need to add an Execute custom PHP code action and set the value like this

// $new_question is my new node.
// $data['components']['category'] is my webform listbox component.
// $new_question->field_category is my taxonomy reference field select list.

$tid = substr($data['components']['category']['value'][0],4,2);
$new_question->field_category['und'][0]['tid'] = $tid;


Error on module admin configuration page

This is because the page rendering stopped when an error occurred. By default, Drupal does not display such kind of errors.

Enable your error reporting by temporarily editing your index.php file (normally located in your root directory) directly after the first opening PHP tag to add the following:

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

After you edited the file, run your site and see what error came out.

WSOD is not directly related to this question, but it may be useful for you to tackle down your problem. It will help you to find out invisible errors.


If the views are working but you cannot edit, then could something wrong with the views_ui module.

There are two differend modules:

Views: for views functionality
Views_ui: for changing views with the web browser at admin section.

Views do not need the Views-ui module activated. This is only for changing existing views. Therefore you can try to deactivate views_ui module and reinstall it.

(Cache clearing is always a good idea, but I think this have you done.)


Just try

drush config-export --destination="<folder-path>"

Path should be some writable folder


prevent drupal from redirecting to created nodes

You can use rules to achieve this easily, here:

Add a new rule and give it a name.

Event:

After saving new content

Conditions:

Content is of type - and chose your content type you want this rule to react on.

Actions:

Page redirect - and enter your destination.

here is an export of a rule that will redirect to homepage after insert a new node of type article.

{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "\u003Cfront\u003E" } } ]
  }
}


Does having too many cck fields negatively affect site speed and performance?

Yes. The more fields you have, the more load you should expect on your database server; that's a given.

What it means in real terms depends on your hardware, configuration and usage - you'll need to benchmark your site in that actual environment to come to any meaningful conclusion. If you get one request a day, for example, your pages are cached, and you have a brand new shiny server, then you probably won't need to think about changing anything.

If you get thousands of requests per second, all your pages are non-cacheable, and your server isn't great, then you might have to think about re-structuring that data so it's more performant (e.g. creating custom field types to combine data from multiple other field types into a single table).

In short, there's no general answer to what you're asking. You need to see what problems your application develops under load, if any, and deal with them then. Premature optimisation is rarely a good idea.

All of that said, Drupal's main defence against this kind of thing is caching. There's a great post here: How do you improve Drupal performance?


Nealv, the preprocess function can only be implemented for the base name, not for the additional suggestions you used for creating your tpl.php file.
The suggestions for alternate template files are added in the preprocess functions themselves.

See https://drupal.org/node/223440 - These naming suggestions are set from preprocess functions.

So call THEMENAME_preprocess_webform_form and check if it's the right form to alter within the function itself.


Autcache + Varnish modules installed but cache tables growing

Varnish should not ideally affect your cache tables, not sure about auth_cache. You should try the reverse approach to figure out what is wrong, check which of your cache tables is growing abnormally and then do bit of digging around to find what module/s is responsible for stashing cache data in those tables.

There is a well-known issue with cache_form table in D7, it can grow abnormally for some live sites. Check this issue, Cache Form table size is enormous.

If you find your cache_form also huge you can use one these modules to help you to periodically clear it, https://www.drupal.org/project/optimizedb or https://www.drupal.org/project/safe_cache_form_clear.

Hope this helps.


How to get a node object/id from theme functions when the form is ajaxified?

You can try to store the node->nid in a hidden field on page load. When your ajax call is executed, you can load the node from the hidden field instead of the menu_get_object.


Add class to Bootstrap login form button

Checkout hook_form_alter. You can add and change (I would suggest only adding unless you are sure it will only affect the forms you want it to) classes with #attributes


jquery slide toggle - affects all on the page

You'll need to make use of the this keyword inside your click function:

 Drupal.behaviors.myToggle = {
   attach: function(context, settings) {
     $('.views-row').find('.views-field-field-mp3').hide();

     $('.mp3-toggle', context).click(function() {
       $(this).parents('.views-row').find('.views-field-field-mp3').slideToggle();
     });
   }
 };


Is it possible to search a view of views?

Under Advanced (located on the right side), for Relationships add Content Authored

Then in Filter (located on the left side) add Content Type and expose the filter.


What is the nature of list variables provided by "Fetch content flagged by user"?

The action 'Fetch content flagged by user' definitely only returns node type content.  I just tested it out and sent the items provided by that action to a rule component which checked the content type.  It only sent nodes, not terms, though my user definitely had flagged terms...

Here's what I did to look into it.

Create a rule component: /admin/config/workflow/rules/components/
Make sure it's a rule or rule set component
I have mine accept 'any entity' as a parameter, because I want my original rule to supply it with the 'Fetch content flagged by user' list_item, which this component can check
Eventually, you can have it accept a second parameter, which could be a list for it to add to, if the supplied entity is determined to be a type 'taxonomy term'... no need to do this yet, because we'll find out that none of the content passed is of this type.  :-(
Once you've set the parameters, continue to your rule, and add a condition "entity is of type".  Set this to 'taxonomy term' and then in an later iteration to 'node' to compare the results of each of these settings
I set the action based on the above test to be 'Show a message on the site' for now.  This could have been something like 'add item to list' if the above test actually ever was true for terms.
Save the rule component, and go back to your original rule where you loop through the content tagged by the user.  Add an action IN your loop, in which you call the above component (components appear at the very end of the list) and provide your current list item as the component's parameter.
You'll see that only flagged nodes are ever sent to the component, and never terms.

It seems that though flagging of terms was recently introduced in the Flag 2.0 module, the integration of that piece with rules is a little behind.  :-(

Anyway, I hope the above helps shed some light in your situation.  Let us know if you find a way around this.  I've played around with it some more, and couldn't find a round-about way to get to what you need yet.


Only ask for a shipping address if a real product is ordered

you could use hook_commerce_checkout_pane_info_alter and do

unset($checkout_pane['customer_profile_shipping']);

only if all line_items contains physical products:

function mymodule_commerce_checkout_pane_info_alter(&$checkout_pane) {
  global $user;

  foreach ($checkout_pane as $pane_name => & $pane_data) {
    if ($pane_name == 'customer_profile_shipping') {
      $order = commerce_cart_order_load($user->uid);
     if ($order) {
       $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
       $lines = $order_wrapper->commerce_line_items->value();

       $ask_shipping = FALSE;
       foreach ($lines as $line) {
         if ($line->type == 'product') {
           $line_wrapper = entity_metadata_wrapper('commerce_line_item', $line);
           $product = $line_wrapper->commerce_product->value();
           if ($product->type == '---> you physical product type <---') {
             $ask_shipping = TRUE;
           }
         }
       }

       if (!$ask_shipping) {
         unset($checkout_pane['customer_profile_shipping']);
       }
     }
   }
 }
}


How to get Media image values (alt and title) in Views?

alt and title are stored in field_media_image of the media type Image. To access the values in Views add this field to FIELDS and select/configure a field formatter to display the values.

To output the raw values outside of a formatted image rewrite the field and use the replacement patterns:

{{ field_media_image__title }}
{{ field_media_image__alt }}


Advantage of including file in .info file and also in hook_theme()

The Elements module is using that slightly incorrectly; files[] is used to inform Drupal's autoloader of files that contain classes, so that they can be used without manually including the file they're declared in.

As elements.theme.inc doesn't contain any classes, listing it in files[] actually does nothing at all. Though it doesn't cause any problems, such is the nature of autoloading.

So to directly answer the question, there can't really be an advantage of using one method over another, as they're used for different things. If elements.theme.inc contained a class as well as the theme functions, it would be perfectly valid to have both declarations.

As an aside, I've seen this plenty of times before - there was a bit of confusion when D7 first came out as to what files[] was for, and quite a few people chose to list all of, or the 'main' files of, their module.


product vs product type vs product display in drupal commerce

Product types is like node types. The main thing about is that you can tell them apart and you can put different fields on them. A product type could be books, but if your books and board games are essential the same (they need the same data) they could be the same product type, where as t-sheets would need to be a different product type, since you probably want to add data for color, size, model which doesn't make any sense for books and games.

A product is an instance of a product type, meaning it could be a green medium sized t-shirt for men, or 'The Definitive Guide to Drupal 7', along with price etc.

Product displays is the main way of displaying your products to the end user, since out of the box products can't be displayed. For this commerce has built the product reference field and the add to cart form and such features to do the trick. Meaning that you can display your products on other entities. Most often you want to use nodes for this, but in theory you can use Profile 2 with the profile entity, to allow users to sell stuff on their profile with a product reference field.

You could also use Views to display products to the end user, this is what I did with my first Commerce site, where Commerce wasn't matured yet. I wouldn't recommend this, as you loose the ability to combine products with the add to cart widget. But if you are selling antique furniture, where every product is unique, this could work out well for you, as you only would need to create products and not product displays as well.


Does Drupal Disqus Commenting have a Server Side rending for SEO indexing?

Disqus itself does support this (see this post for example) but I do not believe that the Disqus Drupal module supports this. It would probably be a worthwhile contribution to that module (or perhaps a companion module).


Make sure content of every view is published

Why not just set a filter in the View configuration and set Status as Published?


Ok, I figured it out. This is my code:

<?php
    $term = field_get_items('node', $node, 'field_taxonomy_term');
    $parent = current(taxonomy_get_parents($field[0]['target_id']));
    print l($parent->name, 'taxonomy/term/'. $parent->tid);
?>


Results in view page with search api having multiple duplicate result

I solved my issue.
Turns out the filter TEMPLATE_views_pre_render function I programmed in was working, the problem was in the template it's self. I had tried to solve this problem on the template before trying this issue.
Before I was trying to only allow $row 1 to return, which didn't solve my problem.
I then tried the _views_pre_render function, and saw that it was filtering but my view was not showing any data.
That is because only one row was being returned due to the _views_pre_render function, but the only row being returned was row #0, and in the template below I was specifying to only show row 1.

So, in conclusion, if you have views with search api and find that

        <?php $lastItem = 0;?>
            <?php foreach ($rows as $row_number => $columns): ?>
                <?php if($row_number == 1):?>
                <?php $array = array();?>
                <?php foreach ($columns as $column_number => $item): ?>

                    <?php if($item != null && $item != "" && strlen($item) != $lastItem):?>

                                <?php print $item?>

                        <?php $lastItem = strlen($item) ?>
                    <?php endif ?>

                <?php endforeach; ?>
                <?php endif ?>
            <?php endforeach; ?>

So, in conclusion, if you have views with search api and find that the solution listed here,
Does not work for you, then your data returned to the _views_pre_render function is probably different due to your search api, and you should follow my BootstrapBlocks_views_pre_render function above, and you should be filtering out the duplicates.


What you're asking about is usually referred to as "theming", and it is a huge subject.

I suggest you read up on "starter themes", which are Drupal theme projects that are specifically designed for the type of flexibility you want.

As you can see, there are several of these. One that is both popular, well-documented and well-supported is Zen.  Getting a grip on Zen takes some effort (it seems both useless and bone-ugly out of the box).  But Zen, together with one of the avialable grid frameworks (Zen Grids, 960.gs, Gridset App) gives tremendous flexibility.  It is well worth the effort to get to grips with.


global variable/array unset when hook_field_presave() is being called

This will never work - global variables only exist in the context of a single page request. Since the form build and presave happen in different requests, you can't use globals in the way you're trying to.

Use a session var instead, that will persist


How to find where Drush is installed to include a file in my module?

A temporary solution that I found is define the same constants in the drush_help.module file.

/**
 * Constants defined by drush in the includes/bootstrap.inc file.
 *
 * To see why we need to do this please read:
 * https://drupal.stackexchange.com/q/250786/28275
 */
define('DRUSH_BOOTSTRAP_NONE', -1);
define('DRUSH_BOOTSTRAP_MAX', -2);
define('DRUSH_BOOTSTRAP_DRUSH', 0);
define('DRUSH_BOOTSTRAP_DRUPAL_ROOT', 1);
define('DRUSH_BOOTSTRAP_DRUPAL_SITE', 2);
define('DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION', 3);
define('DRUSH_BOOTSTRAP_DRUPAL_DATABASE', 4);
define('DRUSH_BOOTSTRAP_DRUPAL_FULL', 5);
define('DRUSH_BOOTSTRAP_DRUPAL_LOGIN', 6);


How to navigate URL after moving drupal site from one server to other server?

These kinds of problems (after transfer to a new host) might be caused by some type of permission problems. Some of the extra comments from the OPer in the question makes me believe that is the case here also.

So I'd verify that the userid of your webserver has appropriate file permissions.

Another option is to verify the various items mentioned in the community documentation about Migrating a site. One of the typical issues is (as mentioned in this link):

  Attempt to log on to the new site. You will probably find that you are locked out by a combination of site maintenance mode and the non-clean URLs. In that case navigate to newsite/?q=user to login, then turn on clean URLs.


When does drupal settings.php become read-only?

Towards the end of the installation process, when the install scripts have finished writing all they need to write to the file.

  Why does it happen?

Because leaving that file writeable represents a security risk.

  How can I find the error causing this issue?

It's not an error, so there's no cause to find.


How to set up Drupal behind a proxy correctly?

The problem has to do with how cookies are associated with domains. After you log into a Drupal site, Drupal sends a cookie to the browser that it uses in future requests to show it has been authenticated. Drupal associates that cookie with the domain that the login occurred on. Since your proxy sends requests to your Drupal site using the hiddendomain.be domain, that is the domain that Drupal associates the cookie with. However, the visitor's browser sends requests to publicdomain.be, and so considers the cookie it received from your Drupal site to belong to that domain. It is this discrepancy that is causing the problem.

To fix this, you need to configure Drupal to associate its cookies with the publicdomain.be domain. In your settings.php add, or update, the following line: $cookie_domain='publicdomain.be';

If your public and private domains share a root, then you can use the domain root as the cookie_domain. For example, if the public domain was www.example.com, and the private domain was private.example.com, then in settings.php you would have $cookie_domain='.example.com'; (note that there is a dot before the domain).


Rewriting the pager of Views in Drupal 7

I found a way, by using the template_pager function in the template.php ( sites/all/themes/mytheme ) and modifying the core behaviour to this:

function template_pager($variables) {
    $tags = $variables['tags'];
    $element = $variables['element'];
    // next line is modified
    //$parameters = $variables['parameters'];
    $parameters = process_post();
    ...
 } // function template_pager

 function process_post(){
    // specific function
    $parameters = array();
    $parameters_sent = array("param1", "param2");
    foreach($parameters_sent as $key => $value){
    if(isset($_POST[$value]) ){
        if($_POST[$value] != ""){
            $parameters[$value] = $_POST[$value];
        }else{
            $parameters[$value] = 'all';
        } // if
    } // if
  } // if
  if(count($parameters) > 0){
    return $parameters;
  }else{
    return NULL;
  } // if
} // function process_post


How to programmatically hide field from display?

Solution is pretty damn simple. I forgot about field_update_instance function.

To get data for passing to this function there is a need of debug: field_ui_display_overview_form_submit

where all Manage Display forms are submitted.

I end up using custom drush command after all custom modules are installed


Pager Gone when I edit query in "views_pre_execute"

I found the solution of the problem.

Indeed I manipulate the code in wrong function.

I switched to hook_views_query_alter and modify my codes in that function.

now everything works fine with no problem.

my function is

function modify_view_query_views_query_alter(&$view, &$query){ }

and I modify the query parts by changing the array values.

$query->where[0]["clauses"] and $query->where[0]["args"]


I think this is what you want Rules action with node.js  module

In order to do this, you have to install the node.js on your server. They have a tutorial video for that Installation of Node.js integration module for Drupal


How to Write Browser Tests on Custom Theme?

I Would recommend reading
https://www.previousnext.com.au/blog/introducing-drupal-testing-traits-drupal-extension-testing-existing-sites
in this article it explains using https://gitlab.com/weitzman/drupal-test-traits
in this way you can do...
use weitzman\DrupalTestTraits\ExistingSiteBase;

/**
 * Test webform on theme
 */
class WebformValidationTest extends ExistingSiteBase
{
    public function testThemeFormPage()
    {
        $this->drupalGet('/page-that-displays-form');
        // Assert stuff here.
    }
}


To do this in a template,
1. create a file inside your /sites/all/themes/YOURTHEME folder, called node--CONTENT_TYPE.tpl.php.
2. copy the contents of node.tpl.php into that file.
3. add something like the following to the template file, where you want to print the image:

<img src="http://example.com/<?php
    print $node->YOUR_FIELD_1[$node->language][0]['value'] .
    '.' .
    $node->YOUR_FIELD_2[$node->language][0]['value'];
    ?>
 alt="..." ... >

Another possibility (probably better), would be to use the filefield sources module, and let the users upload the image to your drupal site by pasting the url.


Build a dynamic form based on user input

If I understand well, one user need to enter informations for X persons who has to attend to your future meeting right?

To do it, I think the better way is to create a content type and use CCK with multiple field. If you need a group of fields, you can install CCK 3.X that include multiple_group module. It's a module very useful that allow you create a group of fields and the user can multiple it at infinite or as you wish.


webform: redirect to modified result page

You have do some customization for this, use hook_form_alter().

Create a custom module.
Create a result page in that module.
Alter the webform.
Do the calculation.
Sent the data to result page and show.

Example:

function  MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_') === 0) {
    // webform_client_form_ (change this id with your form id)

   $form['#submit'][] = 'changeform_form_submit';

  }
}

function changeform_form_submit($form, &$form_state) {
  ... your submission logic ...
}


Require v8 only contrib module with v9 patch

You've got the right idea but you don't need to fork Drupal's repository. You can set up composer to read Drupal's git repo instead of using packagist for the naughty modules like this:
    {
        "type": "package",
        "package": {
            "name": "drupal/cache_control_override",
            "type": "drupal-module",
            "version": "1.0.0",
            "source": {
                "type": "git",
                "url": "https://git.drupalcode.org/project/cache_control_override.git",
                "reference": "8db91684a427366d8f9c51f60cbac10c2d586d95"
            }
        },
        {
          "type": "composer",
          "url": "https://packages.drupal.org/8"
        }
    },

Note the 'reference' is a commit hash, though it looks like you can also use tags. Also note that the custom git type: package repo must be before Drupal's default type: composer repo in your composer file.
And then patch as normal using composer:
"drupal/cache_control_override": {
    "Drupal 9 Compatibility (3132036)": "https://www.drupal.org/files/issues/2020-04-29/Drupal-9-readiness-3132036-2.patch"
},

Thanks @miststudent2011 for pointing out that this doesn't automatically install dependencies which I can confirm. You will need to require those yourself!
(Shamelessly stolen from @acbramley on Drupal Slack because wider dissemination of this knowledge is worthwhile)


Drupal 7: Duplicated and Extended values on hook_preprocess by Drupal

This bit is the problem:

$variables['members'] = $variables;

When you declare named variables in your theme function they are passed in as named keys of the $variables array. So when you call your theme function:

// Note the array wrapping the passed variable and also the 'members' key of the array. This is required in Drupal 7.
print theme('team_members', array('members' => $members));

This is what you'll get in your preprocess function:

$members = $variables['members']; // This contains the original member array passed to the theme function as the named variable 'members'.

What you're doing at the moment is overwriting $variables['members'] with the $variables array itself, so all you're really doing is adding an extra array around the variables array.

Try putting the members that are passed into the preprocess function into a different variable:

$variables['custom_variable'] = do_something_to($variables['members']);

and outputting that one in your template file:

print $custom_variable;

I think that's what you're trying to do, have a look at hook_theme() for more information :)


Is it possible to use the "Save & Edit" module with Rules?

Just a simple concept:
I could imagine using the Rules Forms module with the following Form API conditions:

Form ID: form_id == YOUR_CONTENT_TYPE_node_form
Clicked button: $form_state['clicked_button']['#id'] !== 'edit-save-edit'


For colorbox to work on your new posts, you need to edit the content type(s) of your new posts

Home » Administration » Structure » Content types » YourContentType

Click on "Manage Display". Here, you can choose the format "Colorbox" for the image field (and click that modal to customize, etc). It will be applied to all nodes of that content type.

Of course, you'll first have to install the colorbox module and library.

The same principle applies to other modules.

About posts/nodes and content types:

Typically, there are only very few content types configured in Drupal - by default there are "article" and "basic page", but you can create more as you need them.

You would import your old post into drupal using one or very few different content types.

The changes need to be done for the content type, meaning they'll get applied to all nodes (posts) in that content type.

You need to look which content type to imported your nodes (posts) into. When you go to http://www.example.com/admin/content, you see a list of your nodes, and in the "Type" column the content type.

Then you go to http://example.com/admin/structure/types/manage/yourcontenttype/display and manage the display as outlined in my answer.

For the article content type, this would be:
http://example.com/admin/structure/types/manage/article/display

Of course, you need to change example.com to your url.


Automatically Subscribing Nodes to Organic Groups based on Taxonomy Term

Custom module will help. I would use node_insert() and node_update() although we have used submit handlers for this in the past also.

Code to add a node to a group is:

$form['group_audience'][LANGUAGE_NONE]['#default_value'] = $group_audience;

I have read that og_group() can set a node type entity as group content, but the api looked like it changed to us.

The taxonomy_access module might provide another way of thinking of this that suits your needs.


How to add the Organic Group list in the user profile

This question is slightly vague, however, I am going to answer in the two methods that I take away from it.

You want a list of all OG groups on a user page: Create a View for all of the different content you have related to groups (i.e. you have a content type called "Groups" that is an Organic Group).
You want a list of all OG groups that a user is a member of: Create a View (with a contextual link and/or relationship) between the UID in the current URL and get their appropriate group memberships.

You can create either of these Views as a block and place that on the /user page.


Enable new content types to use as newsletter

The main options are the defaults.  So when you edit a content type all the options you turn on/off are the defaults for newly created content.  Any content that has already been created will need to be edited and re-saved with that option selected.  If you have a lot, I suggest using VBO.


How to create one entity and assign the same entity as field to new entity programatically

Once you have the ID of the new entities, it's as simple as:

$new_entity->field_foo[LANGUAGE_NONE][0]['target_id'] = $other_entity_id;
$new_entity->field_foo[LANGUAGE_NONE][1]['target_id'] = $yet_another_entity_id;

I've assumed the field type is Entity Reference, YMMV for other types.


I never did it I have a small though...

Write a customer formatter (module /custom_formatters) for this field which outputs for the length of the field &nsbp;

Another option is maybe to add custom tokens which a writing blank spaces and set the initial value to this token.


There is no such an attribute in block_view function, but you can always use something like that (assuming that you have already implemented hook_block_info() and you have defined your own MYBLOCKDELTA):

function MYMODULENAME_block_view($delta = '') {
  switch ($delta) {
    case 'MYBLOCKDELTA':
      $block['subject'] = t('This is my block');
      module_load_include('inc', 'MYMODULENAME', 'my_inc_file');
      $block['content'] = myblock_contents($delta);
      break;
  }
  return $block;
}

Then define function myblock_contents($delta) in your my_inc_file.inc in MYMODULENAME module folder.


Renaming file entity in Drupal 8 can be achieved like this:

    $file = File::load($file_target_id);
    $new_filename = "filename.png";
    $stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
    $new_filename_uri = "{$stream_wrapper}://{$new_filename}";
    file_move($file, $new_filename_uri);

As you can see in this example Drupal file_move function is used here which takes care of everything. You only need to know file target_id which is the file fid.


Load a custom block and render with subset of data

One way to do this is with a new view mode for blocks. You can add one at /admin/structure/display-modes/view/add (Manage > Structure > Display Modes > View Modes > Add new view mode). Then, you have two options, 1. go to your custom block type and configure this view mode display to only have the fields you want, or 2. create a template file with a name like block--BLOCK-TYPE--MY-NEW-VIEW-MODE.html.twig, then remove the fields you don't want to print like you were trying to do in the node template. (Replace BLOCK-TYPE with your block type's machine name, and MY-NEW-VIEW-MODE with the machine name of the new view mode you created. Convert all underscores in these machine names to dashes.) After you've done this you can update your preprocess hook's view() call like ->view($my_block, 'MY_NEW_VIEW_MODE')(keep the underscores in the machine name of your view mode here). This will make your preprocess hook look like:

function my_preprocess_node(&$variables) {
  $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
  $variables['my_block'] = \Drupal::entityManager()
    ->getViewBuilder('block')
    ->view($my_block, 'MY_NEW_VIEW_MODE);
}

Lastly, because you add your block to the variables array with the my_block key, update your node's twig template to simply be:

{{ my_block }}


You can do many things to fix this.

Delete the /var/www/html directory. Create a symlink from your SSD to the location.

$ rm -rf /var/www/html && ln -s /media/ssd/document_root /var/www/html
Modify your web servers configuration to use the SSD as the document root.
Create a virtual host for your webserver and point it at the SSD. Edit. I just saw youur previous question. Copy your 000-default.conf to 25-example.com.conf and alter the document root and directory durectives. Don't forget to restart apache.

Are you using stock Apache? What version of Ubuntu?


How to print CCK field on a custom node template? Drupal 7, Omega Theme base

Go to you content type's manage display fields tab and check weather field is visible or not?


Cached rendering depending on a parameter

Add the cache context url.query_args in preprocess:

function themename_preprocess_page(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args';

Or more specific:

  $variables['#cache']['contexts'][] = 'url.query_args:step';


Print field content as div attribute in views template

The code you linked is for normal data fields like text or number.

{{ row._entity.field_field_text.value }}

An image is a reference field, which has no value property, but a target entity. This has it's own set of fields. In case of an image the target is a file entity with the field uri, from which you can get the url with file_url().

{{ file_url(row._entity.field_image.entity.uri.value) }}

Or use Twig Tweak to generate an image style url:

{{ row._entity.field_image.entity.uri.value | image_style('thumbnail') }}


How to automatically generate a random url for a views rss feed?

Just configure the menu path for the page/feed display of your view to include a "random" token. You can set them to be whatever you want.

Users will require the token to trigger the menu item and therefore view. You can rotate the token by simply updating the view (though it's a manual process).

If you need to automate rotating the token, you could build a module that hook_menu_alter's  access callbacks (yourmodule_access) onto the desired paths that checks the token (variable_get) that a hook_cron periodically updates (variable_set) and mails out to appropriate admins (users with some role). This has added benefit that it's not limited to use with Views. Though that's a bit complex for providing obscurity.

Also, many RSS readers support HTTP basic auth (via adding username:password@hostname to the feed URL), so you could install a contrib module that adds support for logging in via HTTP Basic.


How to send message using Organic Groups Invite?

Not sure if it is an option you're willing to consider, but the OG Invite People module might be used as a possible alternative for send such invitation to a group. Here is a quote from its project page:

... adds the missing email invite functionality for OG 7.x-2.x.
When you click on "Invite user" a user is created and invited to the group right after. No registration process is needed. Invitee receives an email with one-time login link.


Token to show all the comments including comment body for a node

To solve your issue you can create custom token which contain needed info. Basically you create a module that implements hook_tokens and hook_token_info. For more details see the documentation: http://api.drupal.org/api/drupal/includes--token.inc/7.

Additional, where you can find examples:
https://www.drupal.org/node/1308488 and
How to programmatically create a custom token in a module


The simplest way: Add a block at admin/structure/block/add. Add the html for your images directly into Block body. Make sure the text format is Full HTML. Assign your block to Header region.

Before this, you need to upload the images on your server. You can either upload them directly to your theme folder or create an image content type with image field and use that to upload your images.


How do you allow users to create own menus?

Menu Admin Per Menu Module comes to solve this purpose!!

  The Drupal 7 Menu Admin Per Menu module is a simple module that allows
  you to grant permissions for users to administer specific Drupal menus
  based on their role.

  This module for instance would allow you to allow one role to modify
  the Main menu, while not allowing the role to modify a separate menu
  on your Drupal 7 website.

Watch this Screencast to learn about it : How to allow a specific role to administer the user menu on a Drupal site without giving them access to modify the Main menu


Could drush require significantly more memory than same action in Drupal

Probably not - but remember that in PHP 5, the command line or client interface for PHP was separated out and has its own ini file. if you search for your php.ini file, you'll probably see two versions, something like this

/etc/php5/cli/php.ini
/etc/php5/apache/php.ini

and you just need to match the memory limit in the (cli)ent ini file with what you have for Apache (or your web server).


How to make submit button work in form themes

You don't want to run your drupal_get_form from inside your template, you want to render it from your page callback. You'll instead declare the theme for your form with $form['#theme'] = 'students' in order to use your template.

function agents_form() {
  $form = drupal_get_form('students_form');
  return render($form);
}

function students_form($form, &$form_state){
  $form = array();
  $form['efname'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
  );

  $form['#theme'] = 'students';

  return $form;
}

You also had a '#submit' attribute on your submit button element but it would need to be set as an array rather than a string '#submit' => array('agents_myForm_submit'), However I didn't see that submit function defined so I removed it.

Then your customTemplate.tpl.php can be as simple as:

  <?php print render($form['efname']); ?>
  <?php print render($form['elname']); ?>

  <?php print render($form['submit_btn']); ?>

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


Drupal 7 Webform Components Related To Individual Nodes

I'm not sure what UX you want, but with Fieldgroups webforms can be multi-paged. As of webform 4.x Conditional Fields (on the same page, or across pages) is supported by webform. You can have hidden fields already in webform if you need a simple storage mechanism not seen by users ...

I imagine you could then use webform rules and upon final submission of the webform to examine whatever values have been submitted and use a custom rule to populate an available list of NIDs based on the submitted criteria.

You could maybe use Entity List and nodequeues to solve this:

if component is selected on submission use Entity List X, which references a smart nodequeue to nodes of a certain content type ... etc.


The buttons on the toolbar are automatically added when the module is enabled, as long as the menu items defined from the module with hook_menu() are sub-menus of the admin menu defined from the System module.

The function that renders the toolbar is toolbar_view(), which contains the following code.

  // Retrieve the admin menu from the database.
  $links = toolbar_menu_navigation_links(toolbar_get_menu_tree());
  $build['toolbar_menu'] = array(
    '#theme' => 'links__toolbar_menu',
    '#links' => $links,
    '#attributes' => array('id' => 'toolbar-menu'),
    '#heading' => array(
      'text' => t('Administrative toolbar'),
      'level' => 'h2',
      'class' => 'element-invisible',
    ),
  );

toolbar_menu_navigation_links() excludes the hidden menu items, and the ones to which the user doesn't have access.

toolbar_view() is called from toolbar_pre_render(), which is the pre-render function added from toolbar_page_build() to $page['page_top']['toolbar']. Once the module is disabled, the menu items should not be anymore visible on the toolbar. The Toolbar module doesn't use any cache; I would expect the change to be immediately visible.

To appear on the toolbar, the menu item needs to be a direct sub-menu of admin. Differently, as in your case, it will not appear in the toolbar.

To test it, I added the following code in a module I use to test code.

/**
 * Implements hook_menu().
 */
function code_testing_menu() {
  $items['admin/mysite_form'] = array(
    'title' => 'My site form',
    'description' => 'Set custom settings for a site',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('code_testing_mysite_form'),
    'access callback' => 'code_testing_mysite_access',
  );

  return $items;
}

function code_testing_mysite_form($form, &$form_state) {
  $form['code_testing_switch_lights'] = array(
    '#type' => 'checkbox',
    '#title' => t('Switch lights on.'),
    '#default_value' => variable_get('code_testing_switch_lights', TRUE),
  );

  return $form;
}

function code_testing_mysite_access() {
  return user_access('administer site');
}

What I obtained is visible in the following screenshots.

Once the module is disabled, the toolbar doesn't contain anymore the menu.

I would rather not put a menu item directly, under admin, if not in particular cases. If the menu item just shows a form for a module's settings, I would not show it in the toolbar. If, vice versa, the module would show a page of links like the Advanced help does, then I could consider adding the menu item directly under admin.

In the other cases, I would consider adding links through the Shortcut module. This would mean adding code in hook_enable() that:

Creates a new shortcut set to use for the users with a specific role
Sets the new shortcut set as default for those users

In hook_disable(), the code should:

Change back to the old shortcut set

Once the module is uninstalled, it should remove the shortcut set it created.

As alternative, the module could add a new link to the shortcut set used from user with a specific role.

The functions that such code would use are the following ones:

shortcut_default_set()
shortcut_set_save()
shortcut_set_load()
shortcut_set_assign_user()

Playing with the Shortcut module, and manually adding a link to a menu item defined in hook_menu() from a module that I then disable, I noticed the link is automatically removed from the shortcut set once the module is disabled. Even after re-enabling the module, the link is not anymore shown as part of the shortcut set.

The second screenshot shows the shortcut content after the module is disabled.

After I re-enable the module (which defines the "My site form" menu callback I shown before), this is what appears as content of the shortcut set. I didn't save the shortcut set, since the other screenshot.


force block module to load admin panel theme

If what you are asking is if, when you go to admin/build/block, is there a way to make drupal use your admin theme instead of your custom theme, then the answer to that question is no, because it needs your theme to figure out what regions are available and what blocks are in them.  But it will allow you to pick different active themes so you can put different blocks in different regions in different themes if desired once your custom theme has the needed regions and other logic required to work with the block admin pages.


You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:ComponentFieldName-value-raw] (and with a data type which equals the data type of your Webform component). Looks like you need 2 variables though: 1 for the username, one for the eMail ID.
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).


Is it possible to restrict the site search module to specific nodes?

You can use one of these 2 modules, Custom search Or Search restrict. Both these modules allow you to restrict the search on specific content types


Altering the page title on a /node/add/ page from a custom module

The node/add/... page is a form, so you could do it with a hook_form_alter().


How to make possible to flag only one node

You're looking for the Flag trim action, which you can implement with Rules.

If you make a rule that is activated on the event "Node is flagged" with "Trim the flag" for the relevant user to "1", then the other flags will be cancelled and only the most recent flag will remain.


JS script in theme is ignored for anonymous users

Worked it out! I post an answer myself in case anyone else has the same issue. Hopes it helps somebody.

I had to add the jquery.cookie library in my template.php

drupal_add_library('system','jquery.cookie');

And it seems you were right to add only one library at a time, Namari, it didn't work until I tried that. Thanks!