Custom php in rules how to check users' geolocation lat lon field and return only users in certain area

How about using javascript? You could submit it with ajax and write it to the db.

Here is a good example of a javascript geolocation function to get long and altitude:

window.onload = function(){
    if(navigator.geolocation)
        navigator.geolocation.getCurrentPosition(handleGetCurrentPosition, onError);
}

function handleGetCurrentPosition(location){

    location.coords.latitude;
    location.coords.longitude;
}
function onError(){...}

More complete demo:
http://od-eon.com/labs/geolocation/

For the calculation of the distance with php:
http://www.dzone.com/snippets/distance-calculation-using-1


How to make all webform types collapsed by default?

Firstly, let me recommend you use Weform 7.x-4.0-alpha6. It has conditionals built into it. Webform Conditional is a great module but I had problems with it.

Options, for select components, take the following format:

mr|Mr
ms|Miss
mrs|Mrs
doc|Doc

The in-built webforms conditionals are very simple and intuitive. Just add a condition and it will display an interface enabling you to hide/show a component when another component is/is-not a certain value.


Try this module to import node data from CSV file. Content Import


How to create a page on which users can upload files?

To create page 'downloads' you can use Views module and create page that contain listing of nodes of your content type.

To create 'Upload page' you can just add link to node/add/YOUR-CONTENT-TYPE to main menu.


ubercart 2 views - filter by order total weight

My solution was to add custom php filter and add:

$ord_weight = db_result(db_query("SELECT SUM(qty * weight) FROM {uc_order_products} WHERE order_id = '$row->order_id'"));


How do I add a Site Information variable and make it multilingual?

So I managed to solve this after searching through Drupal's code and the Variable module. Turns out if you add a call to hook_variable_info, it will add it into the multilingual variables list, and then if you check that off, it makes it translatable like the rest of the Site Information.

/**
 * Implements hook_variable_info().
 */
function omm_variable_info($options) {
  // Site configuration, site information
  $variables['site_pretitle'] = array(
    'type' => 'text',
    'title' => t('Site Pre-Title', array(), $options),
    'default' => '',
    'description' => t("This will appear above the website name on all pages.", array(), $options),
    'group' => 'site_information',
  );

  return $variables;
}

After adding this, go to admin/config/regional/i18n/variable and click on the Site information group.  Click the checkmark beside your variable (site_pretitle for mine), and hit Save configuration. Once that's done, return to the Site Information area (admin/config/system/site-information) and you should see it appear and say This is a multilingual variable. in bold.


How can I add items to the Admin Toolbar?

You can add items to the admin toolbar in two ways:

As content:

In ui /admin/structure/menu/manage/admin

or in code:

$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'internal:/<front>'],
  'title' => 'Front Page',
  'menu_name' => 'admin',
]);
$item->save();

Or in static configuration files:

system.admin:
  title: Administration
  route_name: system.admin
  weight: 9
  menu_name: admin
system.admin_content:
  title: Content
  description: 'Find and manage content.'
  route_name: system.admin_content
  parent: system.admin
  weight: -10
system.admin_structure:
  route_name: system.admin_structure
  parent: system.admin
  description: 'Administer blocks, content types, menus, etc.'
  title: Structure
  weight: -8
system.themes_page:
  route_name: system.themes_page
  title: Appearance
  description: 'Select and configure themes.'
  parent: system.admin
  weight: -6

This is the start of system.links.menu.yml, which defines the admin menu as we know it from D8. You can add your own entries in mymodule.links.menu.yml.

Edit:

To add an item to the top row, use the hook mymodule_toolbar(). This is an example from the tour module:

/**
 * Implements hook_toolbar().
 */
function tour_toolbar() {
  $items = [];
  $items['tour'] = [
    '#cache' => [
      'contexts' => [
        'user.permissions',
      ],
    ],
  ];

  if (!\Drupal::currentUser()->hasPermission('access tour')) {
    return $items;
  }

  $items['tour'] += array(
    '#type' => 'toolbar_item',
    'tab' => array(
      '#type' => 'html_tag',
      '#tag' => 'button',
      '#value' => t('Tour'),
      '#attributes' => array(
        'class' => array('toolbar-icon', 'toolbar-icon-help'),
        'aria-pressed' => 'false',
      ),
    ),
    '#wrapper_attributes' => array(
      'class' => array('tour-toolbar-tab', 'hidden'),
      'id' => 'toolbar-tab-tour',
    ),
    '#attached' => array(
      'library' => array(
        'tour/tour',
      ),
    ),
  );
 return $items;
}


manage multiple sites with a single login

Sounds like you might be looking for the Domain Access module

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


This is quite a complex task your planning – and it's hard to answer in just a few lines of text. I can basically just recommend you have a closer look at the mighty Rules module in combination with the Flag and the Entity reference module.

Here's just a vague suggestion / outline of how this could probably be done by combining the above modules:

Put a flag 'participate' on content type event users of role 'B' can use
Define a new content type 'participation' with checkbox/flag 'confirmed / dismissed' and reference the event and the user to it, editable by 'A' users
Make a rule that generates a new node of content type 'participation' and alerts users of role 'A' of a new request
Extend your profile pages' view with the referenced items of content type 'participation'

There is probably different ways to do this – most likely also easier ways than the one described above. And then there is also a more specific module 'Rules link event' that might fit your demands.


Is there a way to use wildcards in block restrictions first?

You can use the Rules block visibility module for this. Here is a quote from its project page:

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

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

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

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

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown on those pages that have a path ending with "/blog").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

{ "rules_block_visibility_show_on_selected_blog_pages" : {
    "LABEL" : "Show block on selected blog pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/blog",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}


You can make your script file with following statements:

<?php
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); // Define the DRUPAL_ROOT constant which is used in many places.
$base_url = 'http://'.$_SERVER['HTTP_HOST']; // Again, this is used in many places.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Include the boostrap file.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); // Start things up to whatever level you need.
//drupal_set_message('custom script');
print db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => 1))->fetchColumn();
?>

But it is not a good practice to handle form submit or whatever.


This is not the right way to integrate a .css file inside a twig file in drupal8. You should use the standard procedure as I mentioned below.

 {{ attach_library('bartik/messages') }}

SO now for minifying the .css  you can use the 3rd party site- https://cssminifier.com/

So the after minifying the .css file, crate the library

messages:
  css:
    theme:
      css/components/my-minify.css: {}

Then attach the library in the twig by using the below sysntax

{{ attach_library('your-theme-name/messages') }}

Hope this will help you. If any doubt please don't hesitate to mention.


drupal multisite and symbolic links with various subdomains

I am not sure what the symbolic links are for. Normally, you would add another web server virtual host for dev1.example.com pointing to the same Drupal root directory as dev.example.com.


Payment Gateway integration on selecting user profiles

Drupal Commerce would probably be a better choice. I've used it on two non-standard ecommerce systems and it works well. It's very flexible and the rules integration would allow you to do things like comfirm and email applicant on order completion.


Change the URL of a node based on parent path

The routing system is probably not the right place for this, you would need to rebuild the routing table whenever the content is changed, which is very slow.

PathProcessor is the right tool. By the way, path aliases are also implemented in a PathProcessor, the aliases are coming from a lookup table. You can change the path in and outbound dynamically or with your own lookup table if you need it for performance reasons.

Better for SEO would be a redirect to avoid duplicate content, but this changes the url in the browser, what you don't want.

Example for the symmetrical inbound/outbound (asked in the comments):

  public function processInbound($path, Request $request) {
    if (strpos($path, '/foo/') === 0) {
      $path = preg_replace('#^/foo#', '', $path);
    }
    return $path;
  }

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    $path = '/foo' . $path;
    return $path;
  }

This will add /foo to all paths.

One way to approach this could be, you get the child node node/x in the outbound processor as input, the parent node id from the current route. Then you get the title from each of both nodes and put the path together.

For inbound I suggest a third fix path parameter, so that you can identify this kind of path right away and scrap all but the title from the child node, query the node id and you are back where you started at /node/x.


Slight design problem with Roles, Rules and Profile2 on my site

Here's a fairly straightforward way to do it.

Create a field (boolean) on the user account manage fields page.  Assign it useful label such as "I want to run a store" etc.
Create a rule to add the role as follows:

Event After saving user account AND After updating an existing user account

Conditions Data comparison (user account field value) == yes AND User has role (store) NOT

Actions
Add user role (store)

And create another rule to remove the role:

Event After updating an existing user account

Conditions Data comparison (user account field value) account-unchanged == yes AND data comparison (user account field value) account == yes

Actions Remove user role (store)

This should let the users check the box and then the role will automatically be toggled on or off.


No Drupal Site Found when clearing cache

I figured out that you will need a mysql server installed and included in path, even if you are using mysql from AWS RDS.


What's the purpose of subfolders inside a theme's templates folder?

These folders are arbitrary. As long as the template is in the [THEME ROOT]/templates folder, it will be picked up. Using folders is simply the developer being well organized.


Adding more variables to menu for use in menu.html.twig

Here is an example from a real project I had done:
mytheme.theme:
/**
 * Implements hook_theme_registry_alter().
 * @param $theme_registry
 */
function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu']['variables']['top_parent'] = [];
}

/**
 * Implements hook_preprocess_block__menu_block().
 * @param $variables
 */
function mytheme_preprocess_block__menu_block(&$variables) {
  // set the top parent on the left nav
  if ($variables['elements']['#id'] == 'left_navigation' && !empty($variables['elements']['content']['#items'])) {
    // code removed

    $variables['content']['#top_parent'] = [
      'title' => $menu_content->getTitle(),
      'url' => $menu_content->getUrlObject(),
      'is_current' => ($current_path == $item_path)
    ];
  }

  // code removed
  }
}

In Twig:
  {% if menu_level == 0 %}
    <li class="left-nav__item active-trail is-active {% if top_parent.is_current %}is-current{% endif %}">
      {{ link(top_parent.title, top_parent.url) }}
    </li>
  {% endif %}

You are likely missing the part where you add test_var key to the content array:
$variables['content']['#test_var'] = "whatever";
With exception to flagging is-current, it looks like you're trying to do the same thing I did. You should strive to use the link function in Twig instead of a hard coded anchor unless there is no way around it.


Custom prefix for each value of a multi-value field

You can use form_alter function to do it:

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_number'][LANGUAGE_NONE][0]['value']['#prefix'] = '$';
    $form['field_number'][LANGUAGE_NONE][1]['value']['#prefix'] = '€';
  }
}


Several things to consider.

*.php only looks in the folder itself. **/*.php also looks in subdirectories recursively. This seems ok in this case, but I want to mention it for other visitors.

The files[] = .. always requires clearing the cache.
If you have problems with this, drush rr (Registry Rebuild) is useful.

The core class registry with files[] = .. does not work for classes in namespaces.
xautoload does not change this.

The Registry Autoload module makes namespaced classes work with the core registry. But I don't know how well it works with the *.php-style wildcards.

Or, you can use hook_xautoload() to register additional namespace directories.


View content based on if a new session is created

On Drupal, when a new user logs in, a new session is started; when the session expires, the user must log in again. You just need to use the hook that Drupal uses when a user logs in, which is hook_user_login(). Take system_user_login() as code example.

function system_user_login(&$edit, $account) {
  // If the user has a NULL time zone, notify them to set a time zone.
  if (!$account->timezone && variable_get('configurable_timezones', 1) && variable_get('empty_timezone_message', 0)) {
    drupal_set_message(t('Configure your account time zone setting.', array('@user-edit' => url("user/$account->uid/edit", array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone')))));
  }
}

Keep in mind that PHP variables don't persist between sessions. If, for example, you need to show the content only once for users, you need to use code similar to the following one.

function mymodule_user_login(&$edit, $account) {
  if (variable_get("mymodule_show_message_{$account->uid}", 1)) {
    // Show the message.
    variable_set("mymodule_show_message_{$account->uid}", 0);
  }
}

For anonymous users, you cannot count on the session being saved between two different page requests. Drupal, at the end of a page request, destroys the session for anonymous users, if it is empty. See drupal_session_commit().

  if (empty($user->uid) && empty($_SESSION)) {
    // There is no session data to store, destroy the session if it was
    // previously started.
    if (drupal_session_started()) {
      session_destroy();
    }
  }

For a solution that works for both the anonymous users and authenticated users, I would rather implement hook_page_build(), although this has the side effect of always creating the session for anonymous users, with all the consequences.

function mymodule_page_build(&$page) {
  if (empty($_SESSION['mymodule_page_disclaimer_shown'])) {
    // This is a new session. Show the disclaimer.
    $page['page_top']['disclaimer'] = array(
      '#markup' => t('Acme, Inc. is not responsible for the contents of this sample code.'),
      '#weight' => 0,
    );
    $_SESSION['mymodule_page_disclaimer_shown'] = TRUE;
  }
}

In this way, since the session is not empty, it won't be destroyed from Drupal after serving the page. The second time the anonymous users visit the site using the same computer/browser, the disclaimer will not be shown.


Although Workbench is good I use to build a custom admin with:

admin menu and admin menu source to build a custom admin menu per editor.

Also is good to have menu per role to choose what menus can edit editors.

With views and views bulk operations you can build a better administration interfaces.

With this you must built it, but I think you will get a better options that Workbench.

Also you can use dashboard to help user to see their options.


How to sort product displays by price using search api sorts?

my solution is:

Fields Tab: in Related Fields section add Product-Price multi field
Field sTab: check field_product:commerce_price:amount_decimal for index (integer)
Filters Tab: enable aggregated fields.
Filters Tab: add aggregated field: name - your custom label, type of aggregation - first, Contained fields - Price > Amount (decimal)
Fields Tab: check your new aggregated field for index (integer)
Sorts Tab: now your custom aggregated field available for sort

Be sure you are using latest dev version of the Search API sorts because of the https://drupal.org/node/2202093 issue.


How do I convert AddressField "Administrative Area" abbreviation to full name

As mentioned earlier, there's no function in addressfield that does this, it's hard coded and not re-usable.  Instead, there's a function in addressfield_tokens module which DOES do this.

Using this function isn't really good practice because it's not an official hook (so it could change at anytime without notice), but as long as you're aware of what's going on and you use the proper checks that the module exists, it's the most flexible way to make this happen.  Here's how to use it:

First, ensure that addressfield_tokens.module is installed.  Then you can use this function from line 338 in the .module file:

_addressfield_tokens_state($country, $state)

You need the $country because abbreviations are sometimes the same for different countries.  So, if we wanted to find the full name of California, we would do this:

$california_fullname = _addressfield_tokens_state('US', 'CA')
return $california_fullname;


Should I use Entity Views Attach module to solve my problem

I suspect you might get a better answer if you were to say more about what you are trying to achieve than how you are doing so.

For example, reading between the lines of your question I wonder if you are working on some sort of faceted search? In which case I'd recommend you look at Search API. And this may be of interest: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels


How to convert a webform into an ordered list?

Install Theme Developer and look for theming function name.


Modal Popup in IE submit button does not work

Have a look at http://drupal.org/node/1549934 for a potential fix.


I always run with a Dev mirror copy of the Live site and test all modules here before updating the live site with those modules, do this and test the site thoroughly. Make sure the dev and live environments are identical or as close to identical as possible.


How can I unset / remove a paragraph component from within template_preprocess_node?

Pretty easily it seems. Something like the following does the job for removing the first component, for example:

function THEME_preprocess_node(&$variables) {
    unset($variables['content']['field_landing_page_components'][0]);
  }


How do I modify the "view" link in a view?

In the 'Add fields' on your View, you can select 'Content: Link', which generates a simple link to your content. When configuring this 'field' you can set the 'Text to display' property and under 'Style settings' specify any CSS classes you want (see screenshot below).


Update views result after unset() in views_pre_render

You may want to look at doing this in Views' hook_views_post_execute():

  This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.

as the paging happens in the handler phase, and hook_views_pre_render()

  This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.

All about the various Views hooks is available here:

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7

Also, some interesting conversation about this process and potential alternate suggestions is available here in a drupal.org issue queue "update pager count after chaning results in hook_views_pre_render" as well.


Printing a content pane with Printer, Email and PDF versions Module

Example code taken from Programmatically display panels page

$node = node_load(array('type' => 'panel', 'title' =>'Your Node Page Title'));
$panel_node=node_view($node, FALSE, TRUE, FALSE);
print($panel_node);


Javascript only runs when logged in as admin

I switched to the views_accordion module, which works perfect:
embedded views wrapped by views_accordion


How to save session data in prod server?

Don't use procedural code. Session is now a Symfony object:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

Source: https://www.drupal.org/node/2380327

Edit:

What you need to do for debugging depends on your dev environment. If for example you have disabled caching you are not able to debug caching issues. In this case enable caching in dev and see what happens if you add cache metadata to the returned result:

    return [
      '#markup' => $value,
      '#cache' => ['max-age' => 0],
    ];

Cache max-age = 0, because the result in this example changes on each request and is not worth caching.

When this is working the next step is to optimize production performance. Put the code in a #lazy_builder callback or in a block, which is built lazily by default. In both cases this is then auto-placeholdered for certain cache condition like cache max-age = 0, so that the rest of the page can still be cached.


In checkout is a stage when someone adds something to the cart but does not go through the checkout process. It has nothing to do with the way your site functions. Just the user didn't want to checkout.

This problem (most likely) is Shopping Cart Abandonment (Google it).

UC Followup is a module that helps users push through "Adondoned Carts".
http://www.drupalmodules.com/module/ubercart-followup


#ajax on a managed_file custom form field is not working

I don't think you can attach multiple ajax callbacks to a form element. But you could override the callback by extending the core element:
/src/Element/MyManagedFile.php
<?php

namespace Drupal\mymodule\Element;

use Drupal\file\Element\ManagedFile;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * My Managed File Element.
 *
 * @FormElement("my_managed_file")
 */
class MyManagedFile extends ManagedFile {

 /**
 * {@inheritdoc}
 */
 public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    $response = parent::uploadAjaxCallback($form, $form_state, $request);
    $response->addCommand(new AlertCommand('Hello!!!'));
    return $response;
  }

}

And then use it in the custom form:
 $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'my_managed_file',


I would make a view with your base settings, and then make two displays: one with the exposed filter, and then one without.  Then use your normal access control methods to show the proper display at the proper setting.

For example, if you use views-as-blocks, add visibility rules.  If you use panels, use a new page variant w/ access settings, or add access settings to the content pane.

Otherwise, your best option is to implement the view hooks and experiment.  See what $view looks like with the exposed filter and without.  Add your logic, and make the one look like the other.  Unfortunately, what you can do in view hooks is rather sparsely documented; I always tackle this through trial and error.


Create token with translatable variable in pathauto

There are issues open about making patterns translatable.

And patterns actually can be per-language, so you can have multiple patterns, one for each language.

You could also implement the token yourself but be aware that for example during bulk generation, pathauto might create aliases for different languages in the same request, so you can't rely on the current language.


How to make uploaded file permanent to node without node submit

You could try the autosave module, which allows automatic saving of the node form via ajax while the user is editing the form.

If it doesn't do exactly what you are after it would be a great place to look for ideas on how to code it yourself.

Probably if it doesn't do exactly what you want the easiest path might be to make a patch for that module to add what you need, instead of writing something from scratch.


Use nested foreach like below.

$terms = taxonomy_get_children(1);
foreach ($terms as $term) {
  $items[] = $term->name;
  $child_term = taxonomy_get_children($term->tid);
  if (!empty($child_term)) {
    foreach ($child_term as $child) {
      $items[] = $child->name;
    }

  }
}
return theme('item_list', array('items' => $items));


Views theming: How to grab the contextual filter?

You can achieve this functionality in views itself

In footer add a global text area
Select PHP code in the text format select box
Enter the following code

$view = views_get_current_view();
/* $view->args will contain all the argument values in the order */

However make sure to include php opening and closing tags and read this one if you have multiple views in same page.


Put a meta refresh tag in the header of your mobile splash page template:

<meta http-equiv="refresh" content="3;url=http://WHEREYOUREALLYWANTTOGO">

This will display the splash page for 3 seconds before moving on to the page you want them to see next.


Submitting a form, when using the same form with different ID are on a page

You need to call your form like this:

$form = new Drupal\mypoll\Form\PollForm($nid);
$poll_form = \Drupal::formBuilder()->getForm($form);

Then add this methods to your form class:

protected $nid;

public function __construct($nid)
{
  $this->nid = $nid;
}

public function getFormId()
{
  return 'my_form-' . $this->nid;
}

And you need to make sure that $nid is different each time the form is on the page.


Want to modify drupal default pager functionality

I worked on it and found a result... actually Drupal core pager is user friendly enough but in case you need to alter it's functionality you need to edit variables in theme_pager() in your theme's template file.

To obtain the above functionality I altered some variables which are as follows...

$pager_first = (floor($pager_current / $quantity) * $quantity) + 1;

$pager_last = $pager_first + $quantity - 1;

if( $pager_current % $quantity == 0){
  $pager_first = $pager_current - $quantity +1;
  $pager_last = $pager_first + $quantity - 1;
}

I neglected $page_middle variable since I did not needed it...

Warning: Do this when its absolutely necessary...


How to grant edit access for specific nodes to 1 or more selected users?

The Group module is what you should be looking at ... It's not °overkill° (as in your question), instead it's the only stable contributed D8 module available today that will also address your needs.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Note:

Let me address (part of) your additional comment below this answer also, which is like so:

  I will need to have quite a few Groups in my case - one for each course taught by more than 1 teacher.

If I was to configure the Group module for your case, I would use an approach like so:

Create a Group type = Courses.
Create Group roles =  Teacher and Student.
Create exactly 1 Group for each possible Course, labeled (say) C1, C2, C3, ....
Only grant the Group Permission to "edit" a node of content type "Course" to users who have been granted the "Group role" Teacher. And as per your "I want all nodes to still be publicly viewable by anyone (even anonymous users)", you want to grant "View" access to "Outsiders" and "Anonymous", and probably also to "Students".
If only teacher (user) T1 is teaching Course C1, then only T1 is granted the Group role "Teacher" for (group) C1.
If teachers (users) T2 and T3 are teaching Course C2, then only T2 and T3 are granted the Group role "Teacher" for (group) C2.
When creating nodes of type "Course", assign them to 1 (and only one) Group (so either C1, C2, or C3, or ...). And decide about which teacher(s) (user(s)) Tx the newly created Course will be granted the Group role "Teacher".

Done ...

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How do I add a taxonomy vocabulary to more than one menus with the taxonomy menu module?

Try this: https://www.drupal.org/project/taxonomy_menu_block

Otherwise, you can use views to create blocks with links from a taxonomy vocabulary.


Trying to get IMCE with Filefield Sources working (no Upload button in popup)

Ah! Like, Filefield Sources no longer lets IMCE do anything except browse your files and select one of them (for security reasons i think). That's what the situation seems to be, though i can't find anywhere that says that explicitly.

Luckily there's a patch which reinstates the missing functionality...

http://drupal.org/node/877452#comment-4499144

The maintainer of Filefield Sources links to that patch from the module's project page, so it's a recommended patch.

All functioning now :) Can i have my Sunday back now please?

++Thanks to ufku for providing the patch.


Use ajax to render a view - pagination not working

The problem here is that the Drupal.settings does not have the proper views key it needs to attach the behaviors if you are loading a view via views/ajax.

There is no good documentation on this, spend alot of time trying to figure it out, but this ended up working. I had to set the views key in the settings manually:

success: function (response) {
    if (response[1] !== undefined) {
        $('.store-locator-view-wrap').html(response[1].data);

        // Set views key based on response data.
        Drupal.settings.views = response[0].settings.views;
        Drupal.attachBehaviors();
    }
}

I also had to make sure the Views js files had been added to my page:

$views_path = drupal_get_path('module', 'views');
drupal_add_js(
    $views_path . '/js/base.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);
drupal_add_js(
    $views_path . '/js/ajax_view.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);


related content types - "top 10 best movies" functionality

It looks like you need to build functionality to allow users to see movies under different categories where diff categories are top 10, top 9 ....

Assuming we do not have any criteria to put movies under diff categories instead this is being handled while adding them through a content type.

I am not sure if this will be good solution but might help you,

Create a vocab as movie rating add terms to it as within top 10,within top 9,within top 8... and so far upto top 1st.
Add this vocab as term reference to content type responsible for
   generating movie nodes.
Now every time you add a movie opt the appropriate taoxonomy
   field.
Create a view for the same content type and keep the movie
   rating vocab as exposed filter as type links for this view, which
   will allow users to select the appropriate category as shared in the
   image in question.so this filter will automatically filter down the
   nodes as per the rating added while creating them.
Allow your view to use ajax for better user experience.


if this is strictly a css question, I believe it's off-topic here, but...

I've never worked with that module, so this may or may not be an option:

If you output your View as a table, you can modify how fields are represented. Unless the module overwrites the default image formatter, you should be able to choose the Image formatter instead for that field and bypass the module.


How to repair "Mismatched entity and/or field definition" when "drush entity-updates" fails?

Although this question is quite old and no longer relevant for Drupal 8 as drush no longer has entity-updates, I believe people would still be landing on this page with Pending Entity Updates messages in the Status Report. I ran into the same scenario and wanted to address that issue.

The message is shown when the definition of the entity in the database is different from the definition of the entity in the file because of deleting or adding a field in the entity. That is something that is going to happen a lot when you are developing the module and the entity definition keeps evolving.

Uninstalling and installing the module will solve the problem because you are recreating the entity again.

I ran into this same problem and thought I should get to the bottom of this as it was not possible to keep uninstalling and installing the module.

Drush used to have entity-updates as a feature that would allow entity definitions to be updated on the fly. However this was removed from Drupal core in 8.7.0 (Support for entity updates removed from core)

The work around is to install Devel Entity Updates module and run the dentup alternative

If you are using composer

composer require --dev drupal/devel_entity_updates

drush en devel_entity_updates

drush dentup

That should address this problem. The devel entity updates module is to be used in develpment environments only and in higher environments you are expected to push changes to your entities through hook_updates


Create a new template view for a specific vocabulary name

I ended up using the Taxonomy Views Switcher module which allowed me to create a new views page. It's not the best solution, but for me it works.


Try out Image Annotator module.

  The module allows you to annotate images, and works in combination with field_collection. The module defines a new field called 'Image Annotator' that can be linked to an image field, so you can add multiple markers to an image.


How do I display some no results text in a view if the views results are aggregated?

I figured it out. Instead of configuring the no results display on the UID field, I had to configure it in the no results display of the view itself.


Best Way to share content across a UK and USA website

We have successfully done this with a multi site installation and the domain module.


Ajax error while uploading or removing file through managed file

MaxRequestLen sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.

See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:

<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

Or try switching from FastCGI to mod_php or php-fpm (if you're using FastCGI).


Easy peasy, all I did was disabling the PHP Code module, editing the block and reactivating the module again.


Multilingual- can non-English languages be used without a prefix if they are the main language of the site?

Yes, just go to 'admin/config/regional/language', click the edit link of your main language (Spanish), delete the prefix and save your changes.

If you have issues (like links still having the old prefix in them) then clear the caches ('admin/config/development/performance').


Visit index.php?q=admin/config/regional/settings to configure whether users are able to set their own timezone.


How to notify user using ->messenger() and ajax?

This works for me:
$element = NULL;
if (!empty($triggering_element['#ajax']['element'])) {
  $element = \Drupal\Component\Utility\NestedArray::getValue($form, $triggering_element['#ajax']['element']);
}
// Element not specified or not found. Show messages on top of the form.
if (!$element) {
  $element = $form;
}
$response = new \Drupal\Core\Ajax\AjaxResponse();
$response->addCommand(new \Drupal\Core\Ajax\ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
$response->addCommand(new \Drupal\Core\Ajax\PrependCommand('[data-drupal-selector="' . $element['#attributes']['data-drupal-selector'] . '"]', ['#type' => 'status_messages']));
return $response;


This sounds a lot like a php runtime issue. PHP has a configuration called max_input_vars, which you can use to set a limit on the number of input vars php will accept. This will affect the number of $_POST and $_GET variables that can be fed into php. The default is 1000, and I suspect, if you have lots and lots of user type, you're hitting up against this ceiling.


How to add large self hosted videos to Drual 7?

To answer your question: Use the contributed Drupal 7 Video module.

You will likely need to configure your server to allow for large file/video uploads.

I currently allowing video uploads that are up to 1GB using only the Video module, FFMPEG and a few helper modules to manage the 'video processing' workflow.

Most likely you will need to modify your PHP.INI file to allow large uploads.  Specifically max post size and max upload size.

As for a widget that allows you to select a file uploaded via FTP, I see several issues in the Video modules issue queue that look relevant, but no solutions seem to be offered.

This question was also un-answered months ago.  If FTP is a requirement you may need to write a custom module or contact the Video modules maintainers for a status update.


How to prevent programmatically created blocks from caching

The bug is in your code. max_age should actually be max-age.

See the documentation page for more information: https://www.drupal.org/docs/8/api/cache-api/cache-max-age

You could also set the max age in Jdrupal's answer.


How to show blocks by url, when nodes have multiple paths?

Try setting the baseball menu to show on baseball/* and baseball/*/*. Likewise for the basketball menu, then set the Everything Else menu not to show on all four paths.


In a Drupal query, ? should never be used. Drupal uses placeholders, which are listed in db_query(), and that allow to

type casting to a integer the value passed for the %d placeholder
escape the string passed as value for the %s placeholder
convert the value to a floating point value for the %f placeholder
convert and escape the value passed for the %b placeholder

This means that, for example, db_query("SELECT * FROM {table} WHERE value = %f", "12") would convert the string "12" in the floating point value 12.0, and db_query("SELECT * FROM {table} WHERE string = '%s'", "It's an example") will change the string passed as argument to "It\'s an example".

The query is wrong, in a way, as taxonomy_schema() doesn't define pid (nor classid) as fields of the {term_data} table. The following part of the function will never be executed:

if ($row['pid'] > 0) {
  $term = term_parent($row['pid']);
  $row['classid'] = $term['tid'] . '^' . $row['classid'];
  $row['classname'] = $term['name'] . '^' . $row['name'];
}

The {term_hierarchy} table define a parent field, which is the ID of the parent taxonomy term, but the reported code is not making a join between the tables, and it could not find the ID of the parent taxonomy term, which then is not stored in the pid field.


You can do this using hook_preprocess_node() either in your theme's template.php file, or a custom module file. You'll want to use API functions to get the data from the node rather than accessing the arrays directly, so you don't need to worry about language codes etc.

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}

You can obviously change the output to whatever HTML you need, but the above will produce an unordered list of image filenames, available in the $filenames variable in your node.tpl.php file.


Linking content of one field to content of another

There are several ways to achieve this. I think the following one may be one of the easiest:

Assuming you have two fields outputted in views: "Image" and "File" make sure to display them in the following order:

Image
File

Edit image field and mark "exclude from display"
Edit file field and mark "rewrite output".
You'll see you can use the image field as replacement patterns so you can print the previous field [image] and link it to the file by writing a bit of html code such as this one: [image].


How do I implement "enable" or "disable feature" similar to Drupal Gardens?

What you see on that page is a Drupal form where the form fields have been heavily themed to appear differently from how you would normally see that type of form field on a Drupal site.

Looking at the HTML source of that page, it is clear those selectors are simply checkboxes rendered with a custom theme function.

 &nbsp;<input type="checkbox" name="features[28711]" id="edit-features-28711" value="1"   class="gardens-feature-checkbox" />Follow us
Gain a following. Provide links to your (or your users') profile on Twitter, Facebook or other social networks.

There is also custom JavaScript code that changes the appearance of the form field.

When I turn off a feature, I see a CSS class being added to a tag, and another tag value being changed. The value associated with the checkbox is not changed; it is 1 when the feature is enabled, and it is still 1 when the feature is disabled.


how to preserve interface language for a multilingual website?

Your best bet might be the Administration Language module. It allows you to set the general and user specific administration language. The module doesn't seem to be maintained currently/anymore though and there's only a dev version for the Drupal 7.x branch so you may want to check the bug reports and test it first. I've used it on a few sites without running into any major issues so it should be worth a shot still.


SQL query to display a particular content type?

List all content types

To build a list of all your content types in a Drupal 6 site, use an SQL query like so:

SELECT * FROM `node_type`

The values in the type column in the results you get, corresponds to the machine name for each of the content types you have in your site.

List all nodes of a particular content type

Here is an SQL query to display a list of nodes of content type story in a Drupal 6 site:

SELECT *  FROM `node` WHERE `type` = 'story'

Change story to the machine name of your particular content type (= any of the values in the type column from the first SQL above).


How to allow node authors to mark the best comment and to promote this comment on the top of list

As discussed in the comments above, you can create a global Flag, say Best price, for comments. In order to reorder the comments, you can create a comment View which displays all comments of a certain node with the flagged ones on top. Afterwards, display the associated block on the node's page.

Maybe there is an easier way to reorder the comments, but this should at least work and illustrate the strength of the Views module. Underneath is my exported View, which you can easily import and adapt to your needs if necessary:

$view = new view();
$view->name = 'reordered_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Reordered comments';
$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['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access comments';
$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'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Flags: best_price */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'comment';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_price';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['label'] = '';
$handler->display->display_options['fields']['comment_body']['element_label_colon'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Flags: Flagged */
$handler->display->display_options['sorts']['flagged']['id'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['table'] = 'flagging';
$handler->display->display_options['sorts']['flagged']['field'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['sorts']['flagged']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$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: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$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: Block */
$handler = $view->new_display('block', 'Block', 'block_1');


Openid account validation without password reset

If you want your users to be able to setup their own password, check out LoginToboggan. It adds password fields on the front-end user registration page and optionally links non-verified accounts to a "temporary" role on the site, if you want to limit their behavior/actions until they confirm the email.
It also features a lot of other goodies and tweaks, which make the registration/login process much easier.

Another option is Email Verification, which checks if the domain or host of the email address exist, and tries to validate the account by sending HELO/MAIL FROM/RCPT TO to the host's SMTP server.


Fixed, I added all of the required fields from product list to teaser, then modified the css accordingly.


How to disable 'Path prefix language code' for admin panel?

Have you tried to use the GlobalRedirect module? You may be able to set the option 'Language Path Checking' to true in the module configuration page and add the paths for admin pages in there.


How do I allow user to select table column they want in Drupal View?

Give a look at Views Dynamic Fields module. I have used it in the past to create selectable table columns to display for views.

  The Views Dynamic Fields module provides a filter for use with Views
  module. This filter allows the user to pick and choose which fields to
  display for a rendered instance of a view for that user. This provides
  a customized view instance for each user.

  Features

  Users can dynamically choose the fields to view in their rendered view instance
  Default fields to show when no filtering is applied, can be configured
  Possible to always keep certain fields to display to the user
  An exclusion mode to allow reverse selection of fields when there are too many
  Great for creating and exporting reports from the view
  Works great with Fields Embed Views module


I did something similar and used the Views Bootstrap Module. I am not sure if you are using also a Bootstrap Subtheme, but  here is what i did:

Installed the Bootstrap Theme and created a Subtheme.
Installed JQuery Update. (Most recent Bootstrap need JQuery 1.9)
Installed Views Bootstrap.
Created a Views Block for my Slides. I did it with articles which have an imagegallery field.
Added a contextual filter, so for each article a carousel of images can be added in form of a block.
In the Views Block under Format i choosed Bootstrap Carousel.

Then i had a Carousel Block to put in any region i want. You can configure your view to serve your personal needs.


How to link a Radio Button choice to a taxonomy term or tag

You can achieve that by creating a term reference field for your content type(structure > content types > your content type > manage fields) or users(configuration > people > account settings > manage fields). Just pick radio/checkboxes widget with only 1 value.


You can create custom breadcrumb by adding this code :

<?php
global $base_url;
$breadcrumb[] = l('Home', null);
$breadcrumb[] .= l('Product Category', 'prod_category');
$breadcrumb[] .= l(drupal_get_title(), $base_url.$_SERVER['REQUEST_URI']);
drupal_set_breadcrumb($breadcrumb);
?>

Refer to LINK1, LINK2 & LINK3


you should boot drupal on your file so that your file be aware of drupal functions,you can do this by :
YOUR_DRUPAL_ROOT= root of your drupal,here my drupal root was crawler.alexa.com. and
require bootstrap.inc of your drupal.
and then boot drupal compeletly.
here is my example :

define('DRUPAL_ROOT', '../crawler.alexa.com');
require_once '../crawler.alexa.com/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Nodes containing simple field collection not displaying properly

I think I have found the answer, but not really the solution. I deleted the following code in my node.tpl which caused the malfunctioning of field collection:

<?php if (!empty($content['links'])): ?>
<nav class="links node-links clearfix"><?php print render($content['links']); ?></nav>
<?php endif; ?>

But I do not understand why.


Go to your View. In Contextual filter configuration >> More >> Check "Allow multiple values". So if selected this, users can enter multiple values in the form of 1+2+3


How can I serve different view blocks based on media queries?

You can try Browsecap and Browsecap Block modules to show blocks only on mobile devices.


Filter taxonomy terms in common to nodes related to the viewed node

To show a list of season terms on the ingredient nodes related to the recipe node:

Create a view of taxonomy terms of type season.
Add a relationship: Taxonomy term: Content with term
Add a relationship: Entity Reference: Referencing entity (A bridge to the entity that is referencing Content via field_recipe_uses_ingredient) via the relationship created in step 2.
Check "require this relationship".
Save.


find all users of a certain role and return that list

The name of the role is in the role table so just join that in as well:

function mymodule_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', 'administrator');
}

Note that you want inner joins here, not left, otherwise you'll just get whether they have the admin role or not. You don't need an and as you only have one condition.

The hashed password is added by user_load, not your query, so you'd have to address that separately. I'm not sure there's an easy way to exclude a property from an entity load, it would make for a good follow-up question.


Do you have a specific template for your front page?  Is your front page pointing at a node?  Or just a list of recent updates?


Improving UX with views exposed filters: automatically selecting certain options based on a profile value

As a huge fan of direct approach and writing own helper modules, I would make it happen mostly with jQuery.

Outputting user's age or age category in a hidden <div> is easy. You can append it to view's form with hook_form_alter, or simply output it as a block that will never really be seen.
Attach your JS library to views form (or again - simply load it and make it see if form is on page)
In behavior, read user's age from <div> created in 1. and based on that check checkboxes. Invoke click() on them for full emulation of user interaction (i.e. to reload what would get reloaded if it was user who selected it).


How to change wrong English sentences in contributed module?

Another approach is to use GIT for such contributed modules to actually change such sentences or words. E.g. with the master branch corresponding to the official version of such module, and a branch containing all the changes.

In doing so, it is straight forward to also create a PATCH each time such changes are needed, which you can then also attach to an issue in the issue queue to report about such changes. Bonus: you're contributing to Drupal! ... Which should also show up in your D.O profile ... By creating such "issue" (in the module's issue queue, the module maintainers will get notified automatically (unless they turned of such notifications for their modules). So that's "a" way to contact the maintainer/contributor. Refer to comment #1 in issue # 2327917 for a contributed patch containing only a 1 character typo correction (remove an "s" that was not appropriate), and which I committed afterwards.

If you're not able or willing to create such patch, then at least "report" about it in the issue queue, even if it is only some small issue (in the format of a few lines or text about the typo to be corected). Such issues should get picked up soon by the module maintainers (who will transform that in a patch, etc).

And next time the module gets updated, you use GIT to also update the master branch of that module in your own site. After doing so, you then also use GIT to re-apply all relevant changes that are needed for the new version again. For patches that got accepted in the official version of the module, you won't need to reapply their changes anymore of course.

With this approach, you've reduced your issue to something like maintaining a custom version of a module, and at the same time you're contributing to a permanent solution to reduce the need for such changes in the future.


what is the hook name in order to alter theme function of specific element

You can use hook_theme() function to use custom item list.

Hook theme:

function mymodule_theme($existing, $type, $theme, $path)
{
  if ($type == 'module')
  {
    return array(
      'custom_item_list' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'custom-item-list',
      ),
    );
  }
  return array(); //will raise fatal error if void
}

Call it as usual:

theme('custom_item_list', array('var_name' => mymodule_variable()));


How to unflag all messages when a users visits the Message page?

This sounds like a job for Javascript

Flags has an option to allow the link to use AJAX. So I would dig into the Javascript that the flags modules uses and then create your own script that walks over and triggers each link when the page is loaded.


Attach an #ajax callback to a field when the form is reloading from previous ajax request

#attached Will not be processed properly on elements that was loaded with AJAX. Maybe it could, but it never worked for me. on the other hand, using #ajax worked for me without a fault. what I would try (obviously a guess because you didn't provide full SSCCE) would be:

$field['#ajax'] => array(
  'wrapper' => 'module_form',
  'callback' => 'module_form_ajax_callback',
  'event' => 'change',
);

If this element is created with an AJAX call from another element, it's AJAX will work.


Drupal Commerce, Search API DB and Views | How to display the product variation accordingly to the attribute being applied as filter?

Feature request here

This is not the ideal solution but will do for now. There are 2 steps to it:

At Views UI:

Add all the fields you need into your view and Exclude them from display.
At last add a Global Custom Text field for building your row display. This is my example:

[field_image]

[title]

[field_old_price][commerce_price]

[add_to_cart_form]

In your template.php file:

.

/**
 * Implements THEME_views_view_field__VIEWID__DISPLAY__FIELD().
 */
function mytheme_views_view_field__myview__page__nothing($vars) {
  $nid = $vars['row']->entity;
  $size_attibute_tid = myvalue;
  $row_product_id = $vars['row']->_entity_properties['field_product_reference:entity object']->product_id;

  $query = db_select('commerce_product', 'p');
  $query->join('field_data_field_size_attribute', 't', 't.entity_id = p.product_id');
  $query->join('field_data_field_product_reference', 'pr', 'pr.field_product_reference_product_id = p.product_id');

  $query
    ->fields('p', array('product_id'))
    ->condition('field_size_attribute', $size_attibute_tid)
    ->condition('pr.entity_type', 'node')
    ->condition('pr.entity_id', $nid);
  $query = $query->execute()->fetchAssoc();

  $query_product_id = $query['product_id'];
  if (isset($query_product_id) &&
      $query_product_id != $row_product_id) {

    $node_title = $vars['row']->_entity_properties['entity object']->title;
    $node_url = $vars['row']->_entity_properties['url'];
    $product = commerce_product_load($query_product_id);

    $line_item = commerce_product_line_item_new($product, 1, 0, array(), $product->type);
    $line_item->data = array(
      'context' => array(
        'product_ids' => array($query_product_id),
      ),
    );
    $add_to_cart_form = drupal_get_form("commerce_cart_add_to_cart_form_$query_product_id", $line_item);
    $add_to_cart_form = drupal_render($add_to_cart_form);

    $price = commerce_currency_format($product->commerce_price['und'][0]['amount'], $product->commerce_price['und'][0]['currency_code']);
    $old_price = commerce_currency_format($product->field_old_price['und'][0]['amount'], $product->field_old_price['und'][0]['currency_code']);

    $image_variables = $product->field_image['und'][0]['image_dimensions'] += array(
      'style_name' => 'my-image-style',
      'path' => $product->field_image['und'][0]['uri'],
    );
    $image = theme_image_style($image_variables);
    // You should install https://www.drupal.org/project/commerce_product_urls module
    $image = "$image";

    $vars['output'] = "
$image

$node_title

        $old_price$price

$add_to_cart_form
";
  }

  return $vars['output'];
}


Some menus not showing in Menu Settings drop down when editing page

Go to admin/structure/types/ and click the edit link next to your content type. In the Menu settings tab select the menus you want to be available in the content creation page.


Drupal Multisite (subdomain) Not Working

If you want to run several sub-domains on the same code base you need to make sure that either both the sub-domains resolve to the same IP address as your main domain, or that your main domain supports wildcard DNS. You also might consider giving Subdomain module and Domain Access module a try.


Shawn Conn's answer is what I needed. Going forward, I will now make it part of my routine to take snapshots of my configuration with drush cex and commit the changes. My mistake was believing that the views would be saved in the database.


Comments and Testimonials on Profile 2 Profiles

There is a module called reply, that is intended as a solution for fieldable comments on non-node entities and should work with any entities created via the Entity API module, which includes profile2 entities.


You are trying to store state values into a protected variable in the class. That will not work. You will have to store state values into the form.

So instead of using

$this->step

and other class properties to store values use

$form_state->set('step', $value);

to persist values between submissions.


How to set root of programmatically rendered menu

Try the following:

$parameters->setRoot('menu_link_content:818bf040-f12a-4915-835f-b9339eb7c828');


Prevent anonymous to input a registered email during commerce checkout through Rules?

With @RyanSzrama's suggestion, I pursue a form validation solution. What I finally use is to implement a hook_commerce_checkout_pane_info_alter. The following is a simplified code snippet for that.

/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  if(isset($checkout_panes['account'])){
    $checkout_panes['account']['callbacks']['checkout_form_validate'] = 'MYMODULE_form_validate';
  }
}

function MYMODULE_form_validate($form, &$form_state, $checkout_pane, $order) {
  if (!user_is_logged_in()) {
    $mail = $form['account']['login']['mail']['#value'];
    $query = sprintf("SELECT COUNT(*) FROM {users} WHERE mail = '%s';", $mail);
    if (db_query($query)->fetchField()) {
      $msg = t('The email address is registered to an account!');
      form_set_error('[account][login][mail]', $msg);
      return FALSE;
    }
  }
  return TRUE;
}

Hope that also provides some hint or help to others. For form validation, please refer to Adding validation to commerce pane form.


How to show multiple Series of line charts in Views with the Charts module?

The way to get this to work (to put those charts together), is to work with what's called  "parent charts" and "child charts", as explained within Steps to create charts using the views UI. More specifically what's detailed within the paragraph "Creating Multiple Series and Combo Charts in the UI". Here is a quote from it:

... you can combine multiple charts on top of each other. The "parent" chart provides the global information, such as the height, width, title, and other properties. Charts that are "children" provide only data and (optionally) a secondary axis. After you've assembled the first series of data in your chart according to the instructions in the Creating Charts using the Views UI section, add a new display to the same view of the type "Chart Add-on". The "Chart Add-on" type is added the same way you would add a new Page or Block display, from the "+ Add" menu at the top of the view configuration.
After this new display has been added, find the setting for "Combine with parent chart" and change this value to point at the parent chart you have already assembled. Then adjust the settings for the child chart to pull in different data (often by overriding the filter settings). Now you can go back to your parent display, and see that the results from the child chart have been merged into the results from the parent chart. You can even use this approach to combine different types of charts, such as a line chart over the top of a column chart. Note that not all chart types can be combined together and invalid combinations may cause your chart to throw errors.

Refer to "Combination chart without aggregation" for an online demo of such chart. Here is a quote from it:

The chart below (created using the "charts" module) shows a
combination chart about all nodes of content type "Article", which has
these fields with these "machine names" (+ values):

"field_optionlist" (with some select list values, such as the "year")
"field_free_format_text" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
"field_free_format_nr" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.

This online demo consists of a combination of 2 "Area charts". If you only change the "settings" for each of the 2 charts to "Line chart" (within "format" of each view), you'd get a similar set of combined charts but shown as line charts instead. Here is the view (in views export format) that created that chart (using "Line chart" as the format for both charts):
$view = new view();
$view->name = 'combination_chart_without_using_aggregation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Combination chart without using aggregation';
$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'] = 'Combination chart without aggregation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'body';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'body' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'body' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'The chart below (created using the "charts" module) shows a combination chart about all nodes of content type "Article", which has these fields with these "machine names" (+ values):

- "field_optionlist" (with some select list values, such as the "year")
- "field_free_format_text" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
- "field_free_format_nr" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
/* Field: Content: Free Format Text */
$handler->display->display_options['fields']['field_free_format_text']['id'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['field'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['label'] = 'Products';
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$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;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: Content: OptionList (field_optionlist) */
$handler->display->display_options['filters']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['filters']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['value'] = array(
  13 => '13',
  14 => '14',
  15 => '15',
);

/* Display: Chart */
$handler = $view->new_display('page', 'Chart', 'page');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['xaxis_title'] = 'Year';
$handler->display->display_options['style_options']['yaxis_title'] = 'Nr of Products';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_free_format_text' => '#7b0d49',
  'field_optionlist' => '#8bbc21',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['path'] = 'combinatuion_chart_with_no_aggregation';

/* Display: Chart add-on */
$handler = $view->new_display('chart', 'Chart add-on', 'chart_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart_extension';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_nr' => 'field_free_format_nr',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_optionlist' => '#2f7ed8',
  'field_free_format_nr' => '#006d1a',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Field: Content: Free Format Nr */
$handler->display->display_options['fields']['field_free_format_nr']['id'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['table'] = 'field_data_field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['field'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['label'] = 'Enduser Price';
$handler->display->display_options['fields']['field_free_format_nr']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
$handler->display->display_options['parent_display'] = 'page';
$handler->display->display_options['inherit_yaxis'] = '0';


Search query for node content join taxonomy term

Finally I managed to get results by using this code
db_query("SELECT faq_questions.question, faq_questions.nid,taxonomy_index.tid
FROM faq_questions
JOIN taxonomy_index ON faq_questions.nid = taxonomy_index.nid
JOIN taxonomy_term_data ON taxonomy_index.tid =taxonomy_term_data.tid
WHERE question LIKE '%$keys%' AND taxonomy_term_data.tid='$tid'");


You can attach the reset function in this way:

function submission_list($form, &$form_state){
  $form = array();
  $form['name'] = array(
    '#title' => 'Name',
    '#type' => 'textfield',
  );
  $form['surname'] = array(
    '#title' => 'Surname',
    '#type' => 'textfield',
  );
  $form['actions'] = array(
    '#type' => 'actions',
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#attributes' => array(
        'class' => array('my-submit-button-class')
      ),
      '#submit' => array('your_submit_function')
    ),
    'reset' => array(
      '#type' => 'submit',
      '#attributes' => array('class' => array('my-reset-button-class')),
      '#value' => t('Reset form'),
      '#submit' => array('submission_list_reset')
    )
  );
  return $form;
}

function submission_list_reset($form, &$form_state) {
  $form_state['values']['name'] = '';
  $form_state['values']['surname'] = '';
}

function your_submit_function($form, &$form_state) {
  drupal_set_message('The form has been submitted');
}

But please consider to use ajax callback for this reset function, it would be better do not reloading the page only because of resetting. More info - Ajax forms in Drupal 7


How can I programmatically bulk delete redirect entities based on their status code?

If I understand your question correctly, you want to delete all redirects with a status code of 301. That could be done like this:
$ids = \Drupal::entityQuery('redirect')
   ->condition('status_code', '301')
   ->execute();

$entities = Redirect::loadMultiple($ids);

\Drupal::entityTypeManager()->getStorage('redirect')->delete($entities);

If you only want to delete redirects that have a certain source URL, you should be able to add
->condition('redirect_source__path', $sources, 'IN')

to your query.


Yes, under Advacned Options for the View there is a No Results option. You can set a global text result as an example and say "sorry no values found." Then under the Table format Settings there is a checkbox to show No Results text in Table. That will replace the empty row with your message -- while still showing the table headers.


Should the relationship not go via the taxonomy reference rather than direct profile to node? Or have I misunderstood what you've tried/want to achieve?


Is it possible to add a new variable?

YES

  Is it possible to use a function like array_unique()?

Yes, as long as you have an array to pass as a parameter.

PS: You shouldn't be using Views PHP to begin with; you should create a template file for your view and add the PHP code there.

What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?


How to change the HTML output of link to image file?

Install the devel themer module. After enabling it you can point to whatever you want to change. It will tell you which theme method is actually called what options you have to implement your own one.


There are couple of modules for this.

1)Menu Position

Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1
Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog
blog/category1
blog/category1/article1

Note: I'm not sure about(didn't use) Menu Trail By Path module. but I used Menu Position module and works great for me.


Enabling Clean URLs on website-in-progress

You can use relative css as long as you are pointing to files within your theme. That will work like this. url('img/image.jpg'); So no need for full url's here.

More explanation here: http://css-tricks.com/quick-reminder-about-file-paths/

At template level you might want to use drupal_get_path to point to the various modules and or themes.


how to retrieve password from within hook_user_presave()

It us not advised not to use the user's password as a raw value, however if you still want to access the password field value in unencrypted form than try the following:

<?php
/**
 * Implements hook_form_alter().
 * Alters user_register_form.
 */
function MyModule_form_alter(&$form, $form_state, $form_id) {
  // Add the additional validation callback for the user registration form.
  if ($form_id == 'user_register_form') {
    $form['#validate'][] = 'MyModule_user_register_form_validate';
  }
}

// Callback function for Validation handler of user_register_form.
function MyModule_user_register_form_validate($form, &$form_state) {
  if (isset($form_state['values']['pass'])) {
    // Here you will get the value of password.
    $password = $form_state['values']['pass'];
  }
}
?>


Autocomplete several fields with values based on the selected value of an user reference field

I just found the solution to my problem: Every AJAX command runs and replaces the defined element. The trick is to predefine the values for all fields I need to update, within the callback. Then, these values remain in tact within the array of the newly rendered fields using the AJAX commands. Here is my updated callback:

function my_ajax_callback(&$form, &$form_state) {
    if (user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']) != FALSE) {
        $user_obj = user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']);
        $user_id = $user_obj->uid;
        // and another user attribute:
        $user_whatever_userfield = $user_obj->whatever;

        $form['dependant_field1'][LANGUAGE_NONE][0]['value']['#value'] = $user_id;
        $form['dependant_field2'][LANGUAGE_NONE][0]['value']['#value'] = $user_whatever_userfield;

        $commands = array();
        $commands[] = ajax_command_replace("#dependant_field1_wrapper", render($form['dependant_field1']));
        $commands[] = ajax_command_replace("#dependant_field2_wrapper", render($form['dependant_field2']));
        return array('#type' => 'ajax', '#commands' => $commands);
    }
}

Also, I changed the position of my wrapper to have a wider range, in order to include all the fields I want to ajax-update. As every AJAX command will be recreating each form element, if the form element lives within a wrapper (added in form_alter), the wrapper will also be rendered and that causes an HTML mess. So having one hidden field above & another hidden field below my fields makes life easy. The new wrapper encloses these hidden fields and leaves all other fields clean when regenerated from the callback.


Importing multiple images from Dropbox with Feeds

I hope you can read the images's urls inside the Excel table – or actually let your D7 install read them? Once you have that and can actually also access the files on dropbox, it should be possible to load them into your D7 install.

I had a similar, though probably more trivial problem. I had the images' urls and all related info nicely wrapped in a simgle xml file. Looking for a way to actually import the images I came across the Media Feeds module which basically let's you 'import' media files into as an image or file field into an entity (e.g. a node).

The module's project page (https://www.drupal.org/project/media_feeds) has also a link to a screencast – should not be too complicated once you can read the Excel table / get access to the images' urls.


This is as simple as reloading the entity.  The entity is loaded with the current fields, if new fields are added to the content type, the entity won't update on its own.

In my presave hook I check to see if new fields have been added at that time.  If so I wait til the media update hook is fired to reload.


Keeping development database in sync with production database

It really depends on what you're changing in the development environment. If you're adding/removing modules, content types, custom fields, etc.. I can't think of a really good way to do this in any sort of trustworthy automated way.

Also I am SURE there must be modules for exporting Drupal content.  A quick search turned this up: http://drupal.org/project/node_export


How to override code of module in custom module?

You can use  hook_field_attach_form(). function much like it has been done in content_taxonomy_autocomplete module and replace the validate function to the one you want.

function MODULENAME_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
 // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'YOUR_NEW_VALIDATOR_NAME';
      }
    }
  }

}

// add your validater function here


How to add .active class in to the menu item?

You can achieve your goal without jQuery. Just use theme_menu_link() function, or (my suggestion) theme_menu_link__your_menu()

Place this function in your template.php file:

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

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);

    // if link class is active, make li class as active too
    if(strpos($output,"active")>0){
        $element['#attributes']['class'][] = "active";
    }
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You can use this function only for menus displayed as a block.
If you're theming main menu:

go to admin/appearance/settings/yourtheme and turn the main menu off.
go to admin/structure/block and place main menu block in header region
customize ul with theme_menu_tree() and li elements with theme_menu_link()


How can I unpublish the content profile node when users update their user account?

You can use the "Set data"-action to set the profile node's status to 0: status=1 means published, status=0 means unpublished.


Adding a class to current taxonomy term link

The only thing to think about here is the page you end up on (the term page), so don't worry about links that appear on any other pages.

So what you want to do is on taxonomy/term/% pages, add a class to links that match that page.

Seeing as we are adding a class to an a tag, we want to be altering/overriding the markup output of an a tag.

So then you just have to find the best way to do that.

There are a lot of places that a link might come from in drupal, so to try to cover the most you possibly can, you want to be as general as possible, which in this case means theme_link(), which as the name indicates, handles the themeing of a link.

For more information on overriding themeable output see About overriding themable output. There are also many other examples across the internet.

In this case you will want to do something like this...

In your theme's template.php file add this:

/**
 * Theme a link tag.
 */
function YOURTHEMENAME_link($variables) {
  // If we are on a term page.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) {
    // The easiest way to check all possibilities, like absolute & relative
    // paths and path aliases and real paths is to compare via the url function,
    // which will normalise all this stuff.
    if (url($variables['path'], array('absolute' => TRUE)) == url($_GET['q'], array('absolute' => TRUE)) {
      // Add the class to the link definition so that it will be
      // added to the rendered link.
      $variables['options']['attributes']['class'][] = 'your-class-goes-here';
    }
  }

  // Print the link as usual.
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

After adding this function to your template.php you will have to clear the drupal cache for it to take effect.

Note that if your theme or any modules print links without using the l() function or theme('link') or similar then it won't be affected by this.

If you have user entered content that has these links in them then they will also not be affected by default.
The easiest way to make it so they are also handled is to enable and configure the pathologic module.

The other option is javascript, but that is not ideal as it isn't really necessary in this case and doesn't work for users that don't have javascript.

In that case you need to include your script on the taxonomy/term/% pages only (see drupal_add_js()), then in the script check for the current page matching any link hrefs and add the class.


Where to start looking up if there's something wrong with cck field variables?

to test if the value of your CCK field is inside node content, I think that you can use  print_r($node); in your custom node.tpl.php (in your case node-events.tpl.php) file of your theme directory, to see the list of the CCK fields (or if you use Devel module, is best use dsm($node);)

For example, I have a CCK field called field_test_text, see this screenshot using dsm($node);

And this is the way to test the specific value of the test field:

  <div class="content clear-block">
    <?php print $content;
    dsm($node->field_test_text['0']['value']); //dsm way
    echo $node->field_test_text['0']['value']; //echo way
     ?>
  </div>

I hope information be useful.


Which are the most effective methods of optimizing a drupal 7 site?

Boost module is the best option for performance issues, even it will works great in shared hosting. It will not hit the server for every request, instead it cache the pages and deliver them and Boost will cache & gzip compress html, xml, ajax, css, & javascript. Boosts cache expiration logic is very advanced; it's fairly simple to have different cache lifetimes for different parts of your site.

  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic. For shared hosting this is your best option
  in terms of improving performance.


How can I override JavaScript settings used by a contributed module?

As those strings are passed to t() the faster way to rewrite those strings is to overwrite then in the settings.php file, using something similar to the following code (write only the code for the Drupal version you are using):

// Drupal 6.
$conf['locale_custom_strings_en'] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);

// Drupal 7.
$conf['locale_custom_strings_en'][''] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);


The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.

  This module does not directly integrate with Paypal's APIs.
  This module allows a site user to generate a Paypal 'Buy Now', 'Add to
  Cart' or 'Donate' button and replace their form's submit button with
  that button.
  You can manually keep track of the payment status on individual
  submissions.


Command to install Drupal 9 with Composer

create-project can take a version number, and recommended-project has some tags in for 9.x, so for example:

composer create-project drupal/recommended-project mynewproject "9.0-beta1"

Or if you just want the bleeding edge to play with:

composer create-project drupal/recommended-project mynewproject "^9.0" --stability=dev --prefer-dist


Can somebody tell my, what these attacks are about?

They're requests from bots fishing for vulnerabilities in your website.

  Was there a bug in Drupal making it vulnerable for those attacks?

Vulnerable to the specific attempts you've listed? Looking at the exact nature of the URLs, probably not. But there was, of course, Drupalgeddon once upon a time, so maybe.

  Is somebody else experiencing those attacks?

It's highly likely that they are. These attacks are usually orchestrated against as many potential victims as possible, and not built to target a single site. If the attacks you're experiencing were tailored, you would probably expect to see less generic and more Drupal-focused approaches.

You may wish to consider installing and configuring something like Fail2Ban to help with keeping the bots out.


You could add the file usage by implementing hook_node_insert which gives you all node fields besides what you are looking for nid and the fid using file_load in that case you could add file usage


How do I iterate through images using file_create_url()?

You're probably looking for a for loop, but Drupal has a specific function for this, field_get_items():

if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
    $uri = $item['uri'];
  }
}


Cannot re-order the blocks of Drupal 7 site

If there's no javascript error in the console, and you have a lot of blocks, and are using the Suhosin extension, you may be hitting a Suhosin limit. If that's the case, you will need to increase the relevant values there. There may be more information in your server error log.

More info: http://www.hardened-php.net/suhosin/configuration.html#suhosin.post.max_vars


Basic Drupal site architecture based on taxonomy

You'll need to use Fields and some modules to do this but it looks like you already have the understanding on how to get started.

Fields are basically properties that can be used to extend Drupal entities. You can add Fields to your Content Types and your Taxonomy Vocabularies to include extra properties not available out of the box.

Any Fields that you want associated with your Node, add them to the Node Type. Any Fields you want associated with a Taxonomy Vocabulary, add them to the Taxonomy Vocabulary. And in the end, make sure everything is rendered correctly in your theme.

As soon as you associate a Node with a Taxonomy Term, Drupal already provides a way to display all Nodes associated with a specific Taxonomy Term. If you navigate to /taxonomy/term/TERM_ID you'll see what I mean.

If you want to modify that page, I would start looking into Views and Panels which are arguably the building blocks of any Drupal site. It is important to note though that Views and Panels are usually not used to create new content but rather to query and display, respectively, existing content.

For the URL structure you mentioned, look into the Path and PathAuto modules. They provide a way to generate URLs based on a pattern.

So, for your example, if you want a URL /BMW to show all Nodes tagged with the BMW Taxonomy Term, those two modules will get the job done for you.

So what's the best approach? It depends on your site's content. From your question:

Index Page: Classic use case for a view that takes an argument from a
URL. In this case, a Taxonomy Term. You can choose to filter on
specific Node Types, Taxonomy Terms, etc.
Model Page: Simple Node. Create a field on it's Node Type to
associate it with the appropriate Taxonomy Vocabulary. You can also use Views to pull      related content, which from your description is what you need here. There are also a lot of modules that can help with this.
Article Page: Same as above.

Good Luck!


Get field content of all instances of a field

If i understand correctly you have field_call_to_action_link in node, paragraph, block entities. And you would like to get values from this field from all entities which contain this field.

I would use EntityQuery and condition to check if field exists in given Entity.

$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('field_call_to_action_link', 'NULL', 'IS NOT NULL')
->execute();

this should give you all published nodes which contain field_call_to_action_link. You can obtain 'block' Entity the same way only change 'node' to 'block'.

Useful links:

Condition exists DOC link
EntityQuery DOC link


How to remove link of username in comment submission form

Simple solution is to use CSS. Just add a css rule to your theme's stylesheet.

#some .rule {display: none;}

Alternatively you can use hook_form_alter to modify the form and remove the link or change it to something else.

How to do it depends on your Drupal verion, see the API docs for reference or see altering form with hook_form_FORM_ID_Alter for usage on hook_form_FORM_ID_alter which is a specialized version of hook_form_alter.