There wasn't enough space in the comment field, so I'll write a full answer :)

As far as I know, there is no way to do that using existing Drupal modules or functions. If you really want to do something alternative, look into guidelines/recipes for creating own functions for simple templating parsing.

  don't you feel that it is sometimes overkill/tedious just to theme something very simple with hook_theme etc...?

With the same logic, you could argue that you don't need any hook_menu() implementations, and that all you could do is have a .php file in the root of the site from where you would query the database directly :)

It all boils down to conventions because they imply more efficient/simpler maintenance, security, self-explanatory code for other people working on the same project, etc.

However, if you are the only one who is responsible for the site, you're free to do whatever works.

P. S. Toying around and stripping Drupal/turning it into something else can be very good for learning how things work at the higher level. Few years ago I maintained an in-house stripped version of Drupal 5 and 6 for own purposes, with different folder structure, without many modules/features I did not need and some other tweaks. It was a great learning experience.


How can I upgrade from Drupal 8.0.x to Drupal 8.1.x?

Yes, replace the core and vendor directories and run update.php.

Note:

  Also please follow the instructions from upgrade.txt. There are several other necessary instruction so that you can recover from any mishappening.

Drupal treats 8.0.x and 8.1.x as 8.x.x.


How to retrieve a query result in a computed field?

db_query() doesn't return a column, to do this you need to fetch it using fetchField():

$nid = $node->nid;

$result = db_query('SELECT description FROM {taxonomy_term_data} AS ttd
                    LEFT JOIN {taxonomy_index} AS ti ON ti.tid = ttd.tid
                    WHERE ttd.vid = :vid AND ti.nid = :nid',
                  array(':vid' => 16, ':nid' => $nid));

$entity_field[0]['value'] = $result->fetchField();


User Not be Sent to Front Page after Submitting Contact Form

You can use form_state['redirect'] in your form alter,

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == ''contact_us_form) {
      $form_state['redirect'] = array('contact/us');
  }
}


Though view is a powerful module, it can cause a lot of performance problems if certain things are not handled. There a certain steps you can follow to fix this.

There are several things you can do to solve improve this:

Optimizing View:

Try to change left join to inner join using alter.
Enable Cache on views and clear it when order is updated.
Check if Distinct is marked.

Here is a sample views alter code:

/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

Optimizing view is a wider topic, there is a good write up on optimizing views that you can read to understand this better here.

Other than this you should check if your mysql configuration in my.cnf is optimized as per your system resources. For this you could use mysqltuner script or mysql-tuning-primer script.

Above that use of memcached with Drupal can also increase performance to great extend.


How do I override the $message value of the UniqueFieldConstraint class?

The message is hard-coded into UniqueFieldConstraint. It's a public property, so there may be a way to set it that I don't know about. However, another way to go about it is to extend UniqueFieldConstraint, set your own message, and tell the system to use your class instead of the original.

Extend the class:

namespace Drupal\[MODULE]\Plugin\Validation\Constraint;

use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;

class [MODULE]UniqueFieldConstraint extends UniqueFieldConstraint {
  public $message = 'Something about an @entity_type with a @field_name and value of %value.';
}

Implement hook_validation_constraint_alter() to swap out the existing constraint for yours:

function [MODULE]_validation_constraint_alter(array &$definitions) {
  $definitions['UniqueField']['class'] = '\\Drupal\\[MODULE]\\Validator\\Constraints\\[MODULE]UniqueFieldConstraint';
}

Note that [MODULE] should be swapped out with the appropriate value, and the class should be placed in the appropriate folder for the given namespace.

Update: Or, as 4k4 mentioned, you can add @Constraint annotation to the  constraint above, creating a new constraint. This new constraint can then be explicitly attached to whatever it is that needs constraining.

Which method to use will depend on whether you want to override the UniqueFieldConstraint message any time it is called (the original method I outlined) or whether you want to explicitly attach the constraint to specific items (4k4's method).


How do I remove the tabs from the edit field collection form in Drupal 7?

tab tamer has just been ported to D7 a week ago and might be able to remove those tabs as well.


Cannot get values in 3rd level SubFormState

After quite some experimenting I came to a working solution.

  /**
   * {@inheritdoc}
   */
  public function blockValidate($form, FormStateInterface $form_state) {
    if ($form_state->hasValue(['carousel', 'plugin'])) {
      $carousel_plugin = $this->carouselManager->createInstance(
        $form_state->getValue(['carousel', 'plugin']),
        $form_state->getValue(['carousel', 'settings'])
      );

      // We have to do some manual adjustments here since the SubFormState
      // is far from perfect.
      $element = $form['settings']['carousel']['settings'];
      array_shift($element['#parents']);

      $carousel_plugin->validateConfigurationForm(
        $element,
        SubformState::createForSubform($element, $form, $form_state)
      );
    }

So the embedded validation handler has to receive altered form element and the subformstate has to receive the original, intact, form.


How to give class name to no results behavior in views

Can you add a class to the no results token? Like
[token].
Dunno if it works that way. Try that.


How to add js code in the head using a function? For a single page

Please consult function drupal_add_js

  $options: (optional) A string defining the type of JavaScript that is being added in the $data parameter
  ('file'/'setting'/'inline'/'external'), or an associative array.
  JavaScript settings should always pass the string 'setting' only.
  Other types can have the following elements in the array:

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults
  to 'file'.
  scope: The location in which you want to place the script. Possible values are 'header' or 'footer'. If your theme implements
  different regions, you can also use these. Defaults to 'header'.

Note scope option in the text above.

Consult this post: Load JS & CSS Files on Specific Pages in Drupal 7 for direction on using a template preprocess function wherein to add the js.


Check Content Type in Page PreProcess Hook

Instead of looking at the route parameter, you can also do:

$node = $variables['node'];

Here is some example code that I have that is working from preprocess_page:

    $node = $variables['node'];

    if ($node instanceof NodeInterface) {
      $type = $node->getType();

      if ($type == 'listing_page' && trim($node->getTitle()) == 'News') {
        $variables['is_news_page'] = TRUE;
      }
    }

Don't forget your use ... statement if you check node is NodeInterface.

So this is definitely doable - if you are getting any error messages please post them and double check your content type machine names.


The code to print page regions must be in your theme's page.tpl.php file, not in a file in a custom module.

If you want to put your code in a separate file (sidebar.php) you need to make sure it's included in page.tpl.php, like

include './sidebar.php'; // file is in the same folder as page.tpl.php

or

module_load_include('php', 'MYMODULE', 'sidebar'); // file is in a module folder

hope it helps


How to create a rule to conditionally send a notification email, based on field value?

Here is a sample of a rule (in Rules export format), which will send an eMail to the userid selected via the field field_article_reviewer (= a field I added to my "Article" content type that is defined as an entity reference to a 'user'), and this whenever content of content type "Article" is saved:

{ "rules_notify_editor_about_outstanding_review" : {
    "LABEL" : "Notify editor about outstanding review",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-article-reviewer]",
          "subject" : "Article waiting your review",
          "message" : "[node:author] has submitted a new Article post waiting your review.\r\n\r\nYou can review it at: [node:edit-url].",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If (before importing this rule in your environment) in the above exported rule you'd change the field field_article_reviewer to match with your field name of the editor, you should be pretty close to getting it to work.

PS: I'm assuming this question is about D7.


Render node fields in the views-view--[view_machine_name].html.twig

You can call the node field in the view template

 node.field_(your-field).value

This will print the html tags as well, If the node field has the html structure.

node.field_(your-field).value | raw (or) node.field_(your-field).value |render|striptags

This will clean the html structure and useful to print the node value inside the view.template

NOTE: using node. instead of content. , because content. will be used only the node.html.twig


You can do this by creating custom module and creating yourmodule.services.yml

services:
  yourmodule.breadcrumb:
    class: Drupal\yourmodule\FwsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

and creating custom class which should extend BreadcrumbBuilderInterface like this

class FwsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();
    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home One'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }
}

I have also got the above code from http://drupal.stackexchange.com

You can also add new and alter previous breadcrumbs in hook_preprocess_HOOK function like this

function yourmodule_or_yourtheme_preprocess_breadcrumb(&$variables) {
    // Your Logic Here
}


Delay ajax from firing immediately (AJAX links api)

Ok so this was in fact a JS problem and not related to Drupal, I was in the correct place and writing some bad JS.

If you are trying to delay the AJAX clicks on the AJAX Links API module, you need to add a setTimeout and an extra variable to the JS defined in ajax_links_api.js

  $elements.click(function(e) {
    e.preventDefault();
    //This gets altered by setTimeout function, so save now.
    var store = this;
    var selector;
    setTimeout(function(e){
      if(!ajaxLoading) {
        ajaxLoading = true;
        var url = $(store).attr("href");
        var id = $(store).attr("rel");
        if(id) {
          selector = $(store).attr("rel");
        } else {
          selector = Drupal.settings.ajax_links_api.selector;
        }
        ajaxBefore(selector);
        ajaxLink(selector, url);
      }
    },800);
  });


Template suggestions for page on specific node id

You need to do two things before this will work:

Make sure you have a copy of the original node.tpl.php file in your theme folder (the overridden template file will not be picked up otherwise).
Clear Drupal's cache

Other than that everything you're doing is perfect so that should fix the problem.


"attempt to write a readonly database" with BrowserTestBase Functional tests

I don't quite understand why this fixes the problem, but in my case the issue was caused by my executing the core/scripts/run-tests.sh script as root. By running it as www-data instead the issue went away.
I can only assume that the sqlite DB gets created by root and then the script switches itself over to www-data and can't access the DB anymore.


Get the total value of the users vote in Rate module

You need to do custom coding to achieve above functionality. Assigning User Badges on Cron run will be a good option. Below steps will help you to solve the problem.

Create a custom module
Implement hook_cron
Get list of users who doesn't have comment votes badge.
Get above list of users comment score using custom query
Loop through results and check for your condition to assign badge
Assign badge using user-badges API. Look into user badges module where it assigns badge to user to figure out logic to assign badge!

Hope it helps :-)


How to log to console when in a Drupal attach behavior?

Drupal object should be passed as function parameter like below:

(function($, Drupal) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery, Drupal);


How can i add a block below the content of a node?

In the Block UI at admin/structure/block toggle "Show Row Heights"

Set the weights manually to ensure they are correct.


Using Entity Print to generate several PDFs of a Webform submission

You can use the "Webform Entity Print (PDF) Attachment" module included with the Webform module to create different PDF versions of a submission.
This video includes a little more information about attachment elements.


Converting a helper class into an Entity

Why exactly do you want to use an entity?

Entities are about CRUD. Saving, loading and deleting data in the database or somewhere else.

From looking at your code, that doesn't really seem to be what you're after, you just have an API to display some data. That's not what entities are about at all.

You could make a service of your class but that doesn't really seem to match either.

I guess the only thing that would make sense is to define it as a render element. See RenderElement and Render API overview.

So you'd define your class with @RenderElement in an Element namespace, see Link for an example. You give it a name in the annotation, like yourmodule_plot and in your render array, reference it as #type => 'yourmodule_plot' and pass the data to it like that.

A render element class basically consists of a getInfo() method that defines some default properties. In your case, that would be #theme, #attached and so on. if you need to dynamically process your data, you can add a #pre_render callback like shown in the Link example that can then process the merged array of your defaults + data you specify in the controller.


How can I enable/disable programatically added fields from a custom module?

You should try module_disable(array) function.
Here is the documentation for it.
Module Disable Programmatically

You should first check its existence by module_exists and you can also have a look at drupal_uninstall_modules.

I hope this will help you.


Post comment permission by content type and role

These days there is a D7 version of Comment Permissions. Here is a quote about it (from the module's project page):

  ... enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.


Hide an entire View Block when query returns no data

One of the solution is:

Under FIELDS: click each field and in the "No results text" area, check the "hide if empty" box.

This will allow the field not to show if there is nothing actually there to show. But will not affect how the block itself displays on the page.

Another solution for this is :

  Go to the advanced tab of you view
  Add contextual filters
  Select Global: Null
  When the filter value is NOT available: Select 'Hide view'


How to deny access to invalid $_GET parameters

There's no 'catch-all' method for this sort of thing, but on an individual basis you would probably want to perform a manual check in hook_init() in a custom module:

function MYMODULE_init() {
  if (isset($_GET['page'])) {
    if (!is_numeric($_GET['page']) || $_GET['page'] > 9) {
      drupal_access_denied();
    }
  }
}

I imagine you'll need to add further conditions to the above code to make it more contextual to your specific situation.

EDIT

As MPD mentions it might be better to use drupal_not_found() in place of drupal_access_denied()...it's a better semantic representation of what you're actually doing.


duplicate entry on using commerce_product_ui_product_type_save()?

You are getting the error because you are setting $product_type['is_new'] to TRUE, which is saying to the module the product type is new, but that evidently is not true. That is what the error is telling you.

Set $product_type['is_new'] to FALSE, or don't set it at all, and you will not get any error.

If you are programmatically creating new product types, be sure you give to $product_type['type'] a unique value for each of the product types you create.

Reference

commerce_product_ui_product_type_save()


From the Drupal API docs for Url::fromRoute()

  Creates a new Url object for a URL that has a Drupal route.

  This method is for URLs that have Drupal routes (that is, most pages
  generated by Drupal). For non-routed local URIs relative to the base
  path (like robots.txt) use Url::fromUri() with the base: scheme.

For this method, you need to provide the route name as defined in your module's .routing.yml file, along with an array of parameters in your route:

\Drupal\Core\Url::fromRoute('mymodule.my_route', array('route_param' => 'param_value'))->toString();

Alternatively, if you don't have a route to plug into you can use Url::fromUri() as the docs specified:

\Drupal\Core\Url::fromUri('base:/any/number/of/arbitrary/slugs',array('absolute' => TRUE))->toString();


How to onclick-trigger a non-native jQuery plugin's action?

This works.

Adding a targetable class to each slide, so that markup's:

    ...

         ...

         ...

    ...

then, in the init,

    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
                $('#myImg',context).click(function() {
                    $("dt.slide_1").activateSlide();
                });
            }
        };
    })(jQuery);

Now, a click on the img in the #myImg div opens the target slide ... here, 'slide_1', as intended.


It would be a good idea to see this podcast.


FYI: Page Manager is in beta, but that doesn't affect the solution; see below.

You should first check if the node context is available in your Variant. Here is an example screenshot for that:

If that is the case, then you can simply use the following token in the page title field:

  [node:title]

should look like this:

Good luck!


Does drush up do a database backup/dump?

To make gzipped mysql dump with drush:

drush sql-dump --gzip --result-file

Update from the wranvaud's comment:
If you don't specify the result file it will be stored on you home folder under: ~/drush-backups/<db_name>/<timestamp>/<database_file>.sql.gz, otherwise you can specify --result-file='~/Documents/'


Programmatically creating a new instance of a custom content entity that contains a field collection

The bundle of the entity type "field_collection_item" is field_name and the error messages says this is missing:

$variation = FieldCollectionItem::create([
  'field_name' => 'my_field_name',
  ...


How to add extra fields to user profile?

I found the page hard to find, but at /admin/config/people/accounts/fields you can add fields to users.


Views 'Search terms' exposed filter not working as expected

The mistake comes from the WHERE conditions :

AND(( (search_index.type = 'node') AND( (search_index.word = 'australia') ))AND( (search_index.type = 'node') AND( (search_index.word = 'astronomy') ))))

This will always return empty result ! Not convinced?  simply try

    SELECT * FROM `search_index` WHERE `word` = 'Australia' AND `word` = 'Astronomy'

So you'll need a subquery here : for the sake of example, let's say :

SELECT node.title AS node_title, node.nid AS nid
FROM node
LEFT JOIN search_index ON node.nid = search_index.sid
WHERE node.status = '1'
AND  search_index.word = 'Astronomy'
AND sid IN (
    SELECT sid FROM `search_index` WHERE `word` = 'Australia'
)
LIMIT 0 , 30

Now to get it I suggest that you implement hook_views_query_alter(&$view, &$query). First, call Views API :

/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3, //Views 3
    'path' => drupal_get_path('module', 'YOUR_MODULE'),
  );
}

And then the tricky part

function YOUR_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW' && (count($view->YOUR_EXPOSED_FIELD) > 1 ) )  {
    dpm($view); //OR dpm($query);
    //alter your query here ; you'll have to debug and tune the following lines
    //short one
    $query->where ... = ...
    //alternative one
    foreach($query->where as &$condition_group) {
      foreach($condition_group['conditions'] as &$condition) {
        //not sure from here, use `dpm ()` on your own objects
        if($condition['field'] == 'search_index.word') {
          $condition = array(
            'field' => 'search_index.sid',
            'value' => db_query('SELECT sid FROM `search_index` WHERE `word` = '.$view->YOUR_EXPOSED_FIELD),
            'operator' => 'IN',
          );
        }
      }
    }
  }
}

  This hook should be placed in MODULENAME.views.inc and it will be
  auto-loaded. MODULENAME.views.inc must be in the directory specified
  by the 'path' key returned by MODULENAME_views_api(), or the same
  directory as the .module file, if 'path' is unspecified.

EDIT : as per Vincent, used add_where_expression for the subquery and unset the original part of the query related to that search

$query->add_where_expression('3', "sid IN (SELECT sid FROM search_index WHERE search_index.word = '{$search_value}')");
//sthing like
unset($query->where[1]['conditions'][0]);


The code would look something like this:

function MYMODULE_menu() {
  $items['cart/empty'] = array(
    'title' => 'Empty Cart',
    'access arguments' => array('access content'), // or whatever permission you want
    'page callback' => 'MYMODULE_empty_cart',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_empty_cart() {
  global $user;
  // Load the order and empty the cart
  $order = commerce_cart_order_load($user->uid);
  commerce_cart_order_empty($order);

  // As this page won't display anything you need to redirect somewhere
  drupal_goto('some/page');
}


Anybody know how to create the filters to filter the content using views?

When you are creating any filter in views then see the query string in the address bar. It gives you array.
You can use these query strings to create your custom menu links.
Use "AND", "OR" operators in filters.
Then do little custom code.
Also use $_GET to get filter values from filters.


How to extend/override Rest EntityResource Plugin in Drupal 8

To get this working I needed to:

Install the Rest UI module.
Go to /admin/config/services/rest and
enable my new resource.
Also at /admin/config/services/rest, click the edit button next to the new resource and configure it.
Go to /admin/people/permissions and configure the permissions for the new resource (Access GET, Access POST, etc.)

Couple of notes...  Both on the Rest UI config and permissions pages, it was difficult to distinguish between my new resource and the original.  In addition, when I tried to disable the original resource from the Rest UI config page I got the following error:

Fatal error: Call to undefined function Drupal\restui\Controller\drupal_valid_token() in drupal-8.0.0-beta2/modules/contrib/restui/src/Controller/RestUIController.php on line 211

However, even though both resources are configured, the system appears to be using my resource and not the original.


I'm trying to create two content types at once in one form. One is a parent page the other a child page

The Inline entity form module was built for pretty much that exact use case:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.

  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

  Existing entities can also be referenced.


No results behavior in Views not working when referencing another field after cache clear

I replicated your scenario and its working fine for me.

Here is what I did.

In Taxonomy I added a Vocabulary called "Sermons", I added an image
field called "tax image"
I added a term name of "Mega Man" to Sermons, and uploaded a
mega man picture to the "tax image" field.
Created an Article with title of "Enter Shikari is awesome" which has "Article Picture" as a field and I uploaded a picture of the band. Term Ref "Mega Man"
I Created another Article with title "Woooo" this time I did not upload any image to the "Article Picture" field. Term Ref "Mega Man"

Now in Views

In FILTER CRITERIA I added Content Type Is one of Article (so it only shows Article nodes)
In RELATIONSHIP I added Content: Taxonomy terms on node

Check marked "Sermon Series"
Check marked Require this relationship.

In FIELDS and I added the "tax image"

checked exclude from display.

In FIELDS I added "Article Picture"

No Results behaviour I put the token [field_tax_image]

I put a cache of 1 hour.

So here is what my View looks like

I added another Article with title "Kewl its working!!!" with Term Ref "Mega Man" and left the "Article Picture" field empty.
I Cleared the cache (since my view is cached, it won't show "kewl is working!!! until I clear it).

RESULT AS EXPECTED Kewl its working!!! and Wooo do not have Article Pictures, so Mega Man (tax image) shows up.


"Allow users to see own content only", You can achieve this using contextual filter and relationships in advance settings in views module, Given by you already set the contextual filter set filter to login user,

1.) In Advanced settings add field Content:author in relationships.

2.) Then in Contextual Filters add User: Uid and choose provide default value and set Provide default value Type User ID from logged in user.


Accessing the cell phone camera to populate the profile picture field

Agreed this is not purely a Drupal question but not unrelated, a little searching got me a really good answer on HTML5 Rocks taking you through the history and methods.

Specifically go to the section on getUserMedia(), there are even examples on the page that let you test it on your browser.

To my knowledge and from my searching I have not seen any Drupal module making use of this, but there is a discussion thread on drupal.org looking into this.


Route isn't being created for custom rest resource

I'm not sure if there is a different lingering issue, but I was able to solve it
by using the REST UI module.

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

Once I installed it I was able to see my route listed on the configuration page, but it was listed as disabled. After enabling the route from the configuration page it started working.


Store anonymous user selection temporarily until registration

I want to let my first time visitors to first select a city.

okk... so is this selection apart of say their Registration Process, if so you have 0 code to write? or some other random landing page on the site you are funneling new traffic too ... in which case you have to write some code ...

Anyways I would:

Add a field like user_location to their Account Profile fields under Admin -> Account Settings -> Manage Fields ... or use the Profile module to add such a field to a profile. There are "location" contributed modules for location type drupal Fields as well ... not sure what or how you want to store a "city" reference (string, geocode, zip, country + city, whatever).
Then that field will be available everywhere as apart of the $user object.

If, you want this field to be collected before a user has registered (or separate from the registration process -- any fields in a users account settings can be made apart of the registration process). I would:

create a simple module and define a FAPI form with a country list. The list_predefined_options module may help you make this list and manage it in code ...
store the value in the users Cookie session value. Upon login use hook_user_login to look for the cookie value on 1st login to update the account user_location field with the session value.

Good luck.


How to build links compatible with clean and "dirty" URLs?

You should be able to define such Links with the menu_hook

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7

Especially lookt at the Wildcard options i used them recently to define own urls


D8 - Paragraphs - Multilingual - Content Erasing

It turns out the issue was that I had the "Users may translate this field" checkbox checked for the paragraph field types in my content types. Once I unchecked those I was able to replicate the node, change the language, and the paragraph content did not erase.


I recommend the Blame module, it logs all of the form submitted data of any form submitted on your website, whether that be a node form, an admin settings form, etc.


Is it possible to bypass one specific view for authentic users?

Under Advanced>Other>Query Settings, try checking Disable SQL rewriting.


Drupal 7 view to loop through store locations

For the view format instead of using teaser you can select fields. And then add those fields which you want to show. To make the titles clickable, when you will add the title field it will give an option to link it to the content.
Here is the fields format option.

And here is the field which you will need to add. The screenshot will have different fields than yours because I don't know what fields are there in your content type.

And here is the option to link title. So when you will add title field you will get this popup


Views Exposed form in block : how to add a ajax results counter?

Create a folder structure as sites/all/themes/example_theme/templates/views

2.Create a file named views-exposed-form.vars where you use MYTHEME_preprocess_views_exposed_form. Code snippet below:

function example_theme_preprocess_views_exposed_form(&$vars){
  if($vars['form']['#id'] == 'views-exposed-form-exaample-page') {
    $views_rows = views_get_view_result('my_custom_view', 'page');
$count_rows = count($views_rows);
   $vars['count'] = $count_rows;
  }

}

Then you can override the exposed filter tpl. To override the
exposed form template for a particular view, you need to create a
template in the following name pattern,

views-exposed-form--view_name.tpl.php

and print the $count variable wherever you want to place the count.
Once you add the template clear the cache.


Is it possible to create an auto-increment field in a content type?

There is A module called Serial, for drupal 8 it is in development version but can be downloaded and used, This module provides the same functionality as you desire.

You also can write your own module, you can set a configuration value in your module, set it to zero by default, and using hook_ENTITY_TYPE_presave, increase its value and set it to your entity.


What's the best way to insert a user reference field value into the database?

I couldn't make user_reference_autocomplete_validate() work for me so I turned my own code into a function, which now solves my numbers in names problem. I can't see why it would ever fail, but if anyone has a better solution, please let me know.

/**
 * Search for regular expression matches and return the last match.
 */

function extract_id($subject) {
    preg_match_all('!\d+!', $subject, $matches);
    return end($matches[0]);
}


The Field Formatter Conditions module should do the trick. It's currently in beta and doesn't work on excluding fields based on their own value.

However, if you change function ffc_get_condition_fields on line 145 in ffc_conditions_info.inc such that $exclude_current_field is FALSE.

function ffc_get_condition_fields($context, $exclude_current_field = FALSE) {
...
}

it will let you hide field display when it has a certain value.


How to create block with custom embed code in D7?

WYSIWYG editor sees this code as a normal text.You should copy this text in source(There is a source or html button in WYSIWYG toolbar) or disable rich text box and then copy it to your text area.

Also you should use drupal form api to insert forms to your pages.


Why are my custom email messages sent without styling?

I FINALLY found the solution to this problem, commerce kickstart is theming the emails using the mail.css provided for the mime mail module, this file is located in the Omega Kickstart theme that was the one Im using, for some reason my custom messages were not styled using that file, so I did some of research and found this post where they explain how to theme mime mail emails, and they reffer to an issue about using different admin theme than your default theme so they suggest add the mail.css file to all your themes folders...

Well so what I did was to make a subtheme of the commerce kickstart admin theme and the omeka kickstart theme, then I placed the mail.css file in the css/ folder of both, now my custom messages sent with message notify from rules are sent with the correct styling!!

Thank you!


We need university coordinator role, we can create it in People > Permissions > Roles.
Next, we create department coordinator. We do it just like in first step.
University coordinator can make a new user and set a role to it. So we create user DC, set the e-mail dc@example.com and set the password loremipsum. Standalone Drupal has not possibility to generate a random password.

Then, to let department coordinator manage the insitute coordinators you should install Administer Users by Role. One problem - this module don't let you to manage content created by the users.


How do I make the output of field X look like Y?

I usually solve this type of problem by implementing a custom field formatter, which is what controls how a field is rendered.

Below is sample code to implement a basic single delta field formatter. It is used on normal "text" fields, and will simple output todays date, with a single setting for in what format to output the date.

Since this particular example does not actually use the field data, it's important to know that you need the field to have some value, or Drupal will ignore it.

// Declare a new field formatter.
function hook_field_formatter_info() {
  return array(
    'custom_current_date' => array(
      'label' => t('Current date'),
      'field types' => array('text'),
      'settings' => array('date_configuration' => 'm'),
    ),
  );
}

// Form API callback for the formatters settings form
function hook_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'date_configuration' => array(
      '#type' => 'textfield',
      '#title' => t('Date configuration'),
      '#default_value' => $settings['date_configuration']
    ),
  );

  return $element;
}

// Output a message showing what the current field settings are.
function hook_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return 'Date config is ' . $settings['date_configuration'];
}

// Actual field output goes under the #markup key. Add a loop instead of the
// leading 0 to support multi-value fields.
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];

  return array(0 => array('#markup' => date($settings['date_configuration'])));
}


Deploy block and block configuration to production instance

You should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.


How to reset node id to a lower number - Drupal 7

The node id is the primary key of the {node} database table. You need to reset the "auto_increment" property of that table to 1 (or 51 in your case). You can do that with PHPMyAdmin, or other MySQL client.


Why would I provide a composer.json for my modules?

I wrote a blog that gives some case studies about when and why you would include a composer.json with your module: https://www.morpht.com/blog/drupal-and-composer-part-4-composer-drupal-developers

Basically it comes down to four things:

It allows your module to be managed with composer.
It allows your module to have it's Drupal module dependencies managed by composer
It allows your module to have it's 3rd party library dependencies managed through composer
Composer handles autoloading of namespaced classes in libraries it manages, meaning your module can use the 3rd party libraries it depends upon, without having to include any files

If none of the above requirements match your needs, then there is no reason to have a composer.json file in your module.


Trouble with Feeds Import CSV on Localhost

In the case where you manually upload the file and then map to it, try public://feeds/bsif.csv
In the case where you try to upload using your browser, it should be working fine.  It could be that you're unable to upload files in general, not just with the feeds import module.
Check your server's access to upload to /sites/default/files... it could be that only your account has access to place the file there.  Also, Apache/PHP uses a tmp directory for file uploads, so it will need access there as well.


You can use #prefix and #suffix to add any amount of html markup to your form and/or any of its fields.  Tons of information can be found in the Drupal Form API Reference.  I would tend to suggest you stay away from tables and instead investigate css floats and divs, most probably doable without any additional markup, but that's just personal preference.


Best option to upgrade Drupal 6 Video field to Drupal 7

For the video module there is no any direct migrate path even though it is CCK field, so what you have to do is use Migrate module. Just create a Views that output all the videos as XML in D6 site and use that XML input in D7 site to create new video nodes. This may need some additional effort but ultimately this will be really smooth approach.


If you look under your filefield settings you will see a field that called, “File directory” that is self-described as:

  Optional subdirectory within the upload destination where files will
  be stored. Do not include preceding or trailing slashes. This field
  supports tokens.

You can use tokens. Something like. [current-date:short]/[current-page:title]


Are there any modules that can export and import nodes while preserving node id's?

If your backup contains the previously existing users, you could try to recreate your production site locally... Here are the steps I would follow (never tested though):

install a local drupal site with your backup (files should be restored as well) in the production site, via VBO
put your production site in maintenance mode
target all the new / updated nodes since the incident
export them via Node Export
reimport them locally (the nids should be preserved thanks to NodeExport and UUID)
reinstall your local db in production


How to properly perform a patch so that the correct directory is used?

Actually, there is a fairly easy way to generate a patch for a certain path with --relative.

So in your case, just run git diff --relative=docroot/modules/contrib/video_embed_vidyard.


Redirect a user after the node has been saved

Form redirect after node save.  This blog discusses the usually way of redirecting a form, the problem with node forms, and how to solve them for Drupal 6.   I believe it should also work for Drupal 7


struggling with template_preprocess in module

I think it should be  holidayautosxml_preprocess_holidayautosxml_carsearch(&$variables).
Basically the syntax is [yourModuleName|yourThemeName]_preprocess_[themeFunctionName](&$variables).

Also you need to flush your cache after you make the change.


How do I assign variables from BlockBase object?

Via try and error, I found out, that declaring the variables-array in the function mytest_theme() makes it possible, to set the variable in the MytestBlock-Class:

Changes in mytest.module:

function mytest_theme() {
    return array('mytest_block' =>
        array('variables' => array('test' => 'hello', 'test3' => null)));
}

Changes in MytestBlock.php:

class MytestBlock extends BlockBase implements BlockPluginInterface {
  public function build() {
    return array(
        '#theme' => 'mytest_block',
        '#test3' => 'hello3',
    );
  }
}

But I still have no idea how to access the Block-Plugin Instance in mytest.module.


Is it possible to use ajax inside the html output of a computed field?

Well, it's not Crashing with a white screen. You are using ajax_deliver which returns the content of your response as plain text and stops further page rendering.

A Crash would be a WSOD and no output. Check your hook_menu definition and be sure its setup as a non-menu item ... just a callback. You do this by setting the type in the $items array. You may also want to set the delivery callback value to be an ajax response.

Lastly, your link goes to hello_world_link_callback/ajax/, but that is not the URL you have defined in your hook_menu function. It may be a best-fit match for Drupal on a lookup.... but I doubt it.


"_blank" target attribute for links in views

this requires a separate declaration of link path

If you are talking about node title it doesn't require a declaration of link path. Just leave this field empty and link will be made with default link path (e.g. node/NID).

For other fields you need to override link path. The easiest way is to add nid field and exclude it from display. Then you can use node/[nid] as link path. In this case you need not use link formatter in field settings.


If you are doing this by custom method try below code to get published revision id.

$query = db_select('node_revision','nr');
$query->join('node','n','n.nid=nr.nid');
$query->fields('nr',array('vid','status','nid'));
$query->condition('nr.status',1,'=');
$query->condition('nr.nid',$nid,'=');
$result = $query->orderby('vid','DESC')->range(0,1)->execute()->fetchAll();

Pass $nid in condition, here you will get the latest published revision ID.

Then load node as

  entity_revision_load('node', $result->vid)

This will load particular revision id with content type.

Here you will get all node data related to that revision id.

Hope this helps.


Theme Upgrade for an existing D7 site - block and config management

You need to ensure that your new theme has the same regions defined in the info file as the current theme, otherwise the blocks will lose their assignment when the new theme is installed. The blocks are assigned in the database and they will stay assigned to those regions, as long as those regions are available.


Create a validation function for your form.  Here is an example using your form. For instance, say your form code is in a function called my_email:

<?php
function my_email() {
  $form = array();

  $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
  );

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

  return $form;
}

function my_email_validate($form, &$form_state) {
  // YOUR CUSTOM VALIDATION CODE GOES HERE
 if (!valid_email_address($mail)) {
   form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
   }
}

function my_email_submit($form, &$form_state) {
  // YOUR CUSTOM SUBMIT CODE GOES HERE
}
?>

This function will allow you to write custom code to determine if the values entered in your fields are valid or not.  You can also add a custom submit function for your form to execute custom code while the form is being submitted.

Read more about validating forms at Validating Forms, submitting forms at Submitting Forms or read the whole article for a better understanding of the Forms API: Form API Quickstart Guide


insert advertisement block within views list

You can override the format specific template like views-view-unformatted.tpl.php (you can find the right file based on your requirement) and then use some custom code like

  <?php if (($id % 2) == 0): ?>
    Do what-ever you want to do here.
  <?php endif; ?>

This module hosted on github https://github.com/pedroposada/custom_views_nthrow seems to do the same more modularly.

Instructions : http://www.pedroposada.com/blog/insert-whatever-every-nth-row-views.html-0


How to load the current entity object (Profile 2)

I couldn't get menu_get_object to work with profile2 so instead I used a combination of profile2_load_by_user and arg suggested by Clive.

function mymodule_form() {
   //this arg gets the UID from the URL.
    $testarg = arg(1);

  //The UID is then put into a profile2 defined function which locates and opens the
  //correct profile.
    $currentprofile = profile2_load_by_user($testarg);
}


How can I alter ctools access plugin expectancies?

Ok, so here is the answer...

The problem is that we were working on an existing panel page. We made the argument plugin in the middle of working on this page. So we went to "arguments" and switched out the correct argument with Node: Name instead of Node: Id which we had before.

What we didn't do was go through each of our variants and click "Save" on the "Selection Rules" tab. What was up was the old argument was still saved in those slots even though it didn't show up in the drop-down. It took me a while to realize this because I was thinking the "Access" handler settings were being "generated" vs being "stored". I literally worked my way back to the feature I made of the panel page hunting this down, and when I saw it... the UI to Feature translation started clicking in my brain.

In short, the feature I thought I needed isn't needed. All that was needed was to clear the fog of ignorance...

With that said, in an interface such as Views. If a handler such as this was to no longer be available, a "Broken" identifier would then show up. I'm thinking something similar would have clarified a lot here... or at least some kind of validation.

Added a bug report: https://drupal.org/node/2282539


How do I explain the large difference between page execution time and reasonable query execution time?

Here is an easy calculation:

page_execution_time = query_time + php_time;

So basically you seem to do quite a lot of stuff in php.
Same basic stuff you could do

Use some opcode cache, for example apc
Find out what needs a lot of time using xhprof


How to move the edit tab in node.tpl.php

The $tabs variable is set up in template_preprocess_page(); you can add the same var to the node template file by implementing a preprocess hook:

function MYTHEME_preprocess_node(&$vars) {
  $vars['tabs'] = menu_local_tabs();
}


How to overcome "Add new date link" issues in the 7.x-3.4 Calendar?

OK, so I have fixed this with a custom work around. There are many modules that I am using that may be interfering with the permissions to add a new date, and be limiting what can be displayed in the view. No matter, here is how I solved it:

First of all, set up the modules and permissions as following:

Go to admin > modules, and find the PHP Filter module, ensure it is enabled:

Next, go into the permissions and find the following:

Ensure that the last option, "Administrator", is selected.

Next, go to the view where you would like to add the "Create Booking" (or whatever content type it is you are after.) From here, create a new header of type "Global: Text area"

What I chose to do next was create a link to a new view, and on this view I expose the form to add the new date/event. If you want to embed the create form here, then skip the next step, however I find doing it this way leaves the current calendar in it's original state, and by clicking the about to be created "+ Add Event" link, you will be taken to a new view that contains the calendar and the exposed form.

Now, select "Full HTML" as the Text format, and place the following code in the text box. This will create a link to a new view, which we will make next. The two lines below are simply coloured text that I will use as a legend for the calendar.

+ Create Booking

When we next create the view containing the form to add the new date/event, if you chose to use a different path, come back here and change "/calendar/create_booking" to your preferred path.

Now, apply changes and save the view. Go back to your Admin > Structure > Views page, and locate the view of your current calendar. Now, on the "Operations" dropdown, select "Clone View"

Rename the newly created view (I called mine "Create {Your Old View Name Here}"). Now, open up the "Edit" option for this view and create a new Header of type "Global Text Area" as before. This time, we want the Text Format to be "PHP Code" and to place the following code in your text area:

<?php
  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('node_type');
  print drupal_render($node_form);
?>

Remember to change 'node_type' to your desired content type. Save the Header, and return to the last screen. Now simply change your path to what you wish:

And now finally, go back to your original Calendar view, edit the header to contain the correct path in the link we made, and you're finished! The form is now exposed for users to create a new event/date. Ensure that you set the appropriate permissions for users to be able to create this content type, and remember that their view of the create form will be much simpler than yours.

Hope this helped you if you had the same issue as me!


If I understand well your question, an alternative can be edit your image field ("Configure field" options) and select Rewrite results > Rewrite the output of this field. Here you can make lots of things with your image, for example add a link from other previous view field, over your image.

here one example to string included in the rewrite field:

[field_image_test]

in this example [field_test_link] is a text field with the respective web address, and [field_image_test] is the field that comes with the image.

this image comes from Drupal 7, but this steps also are possible in Drupal 6


How do I implement a VIDEO gallery like gallery formatter but with videos?

If you're able to switch to a module other than video_embed_field I'd highly recommend the Media module along with the Media Gallery module.

You'll also want Media Youtube, I've used those three together quite a bit and they're very good.

I'd also recommend installing Colorbox to take advantage of the built-in lightbox features.


Better Exposed filter when shown in pane configuration, then they are all coming as checked

Issue was of BEF version, prev. version was 7.x-3.0beta3, after upgrading to 7.x-3.2, problem gets resolved.


Email field on registration page not working

There you must receive a message with the error. If you don't see it, please, check if your theme have enable the messages.
Check if the mail is not register in the site. Just try to reset the password using that email address and you will see if was registered or not.


How to hide a block in a view when an exposed filter is being applied?

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 for the page with an URL that matches with your view without any filters applied).

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?". If you look at the example included there, just replace its Rules Condition by a Text comparison with Parameter: Text: [site:current-page:path], Matching text: MyViewPath (assuming that /MyViewPath is the path of your view without any filters applied).

Update: looking at your exported rule (in revision 3 of your updated question, so without "UPDATE 2" you added to it ), I noticed that there is a space (blank) at the end of "course ". Not sure why that is there, but I'd first try with removing that space. If that doesn't make a difference, I suggest you try a variation of your rule that looks like so (only the Rules Condition differs from what you have in your updated question):

{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "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" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "courses" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If that also doesn't help, then it's time for Rules debugging. For that, refer to my answer to "How can I display the value of a variable inside a condition?".

PS: This answer applies to D7 ...


In a managed_file upload field, how do I prevent an overflow with long file names?

I would suggest adding a class to the fieldset and adding a class to the css file of your theme.

Add something like this to the fieldset.

'#attributes' => array('class' => array('my-fieldset'));

And then something like this to your css file

.my-fieldset {max-width: 100%;}


Ubercart module, understanding drupal_get_form

Its not related to drupal_get_form, its completely separated events sequentially fired in Drupal.

step 1 - First in menu: argument %something loaded via something_load and passed to page callback as parameters.

step 2 - Second in menu: page arguments will passed to function specified by page callback.

step 3- Third in drupal_get_form: get first argument uc_attribute_form as form ID and use it for build form and get second argument 4 from menu which loaded in step 1. 4 means fifth argument in path 0-admin/1-store/2-products/3-attributes/4-%uc_attribute/5-edit

EDIT:
read more about hook_menu

  Registered paths may also contain special "auto-loader" wildcard
  components in the form of '%mymodule_abc', where the '%' part means
  that this path component is a wildcard, and the 'mymodule_abc' part
  defines the prefix for a load function, which here would be named
  mymodule_abc_load().


Rules token one-time-login-url is showing up empty

The problem was on the "save entity" action, I had to force it to save by checking "force" on the action, because the entity would only get saved after the other actions had been applied.


Why I'm getting theme related error when trying to add external JS to form?

You probably need to add the module/theme name before the attached library:

$form['#attached']['library'][] = 'mm/google.maps';

Otherwise drupal is looking for google as your module/theme name.


ckeditor - Two views with editable fields on the same page

To counter this, I had to clone every field in the second display only to force Drupal to assign different element IDs to each one. Then I deleted the initial fields.

So

views-field views-field-field-e1

changed to

views-field views-field-field-e1-1

letting the Ckeditor to render the rich text editor on every instance.


There are a number of options to resolve this issue:

One option is using the String Overrides module to replace the string used to generate the message.
Another option is to create a custom module that overrides the validation function for a particular form or field, replacing any error messages with the messages of your choosing.
The following link may also help:

Custom Validation Message


Programmatically subscribing all users to Mailchimp list with module

I'm pretty sure the MailChimp module doesn't actually store user subscriptions in the Drupal database, it picks up data from the MailChimp API when required.

What worked for me was to export all my Drupal users and import them into MailChimp through their website.  This is fine for a once-off, and you should be able to handle new and updated users directly through the module.


How to clone a content type and all nodes related

Drupal commerce stores product in a different way than ubercart. You best bet would be to export product in CSV format using something like Views data export and reimport it to Drupal commerce using Feeds and Commerce feeds


function pager_array_splice($data, $limit = 9, $element = 0) {
      global $pager_page_array, $pager_total, $pager_total_items;
      $page = isset($_GET['page']) ? $_GET['page'] : '';

      // Convert comma-separated $page to an array, used by other functions.
      $pager_page_array = explode(',', $page);

      // We calculate the total of pages as ceil(items / limit).
      $pager_total_items[$element] = count($data);
      $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
      $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
      return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
    }

    $output = pager_array_splice($yourarray, 5);

$output = '';
  $your_array = some_method_to_get_array();
  $tree = pager_array_splice($your_array, 5);
  // Do something with the 5 terms
  $output .= theme('pager', array('quantity' => 5));


Send email from non system email address using Drupal API

This happens becouse Gmail seems to block these messages as they are often used for spoofing. Using the SMTP mailer plugin https://www.drupal.org/project/smtp and authenticating using your info.domain@gmail.com should solve the problem.


I'll assume your using Drupal 7, you want to look into hook_node_update() this will allow you to run code whenever a node is saved/created.

From there you'll have full access to the node object in which you can use user_load() to grab the user object and check it's roles. Then you need to add logic based on the role to modify the nodes fivestar rating.


Get node based target id from entity reference

We found the issue, it was both duplicate data issue and syntax errors mentioned by @berramou. The fix to the query was  changing ->condition('status', 1); line to ->condition('status', 1).

We found that the test data included duplicate media entities so when the ->condition('field_document', $linked_document_id, '='); was added, there were no results because the entities we were expecting were not in the table.

Sample test data:

media entity (id=1) name --> foo
media entity (id=2) name --> foo
media entity (id=3) name --> bar
Article->field_document->target_id = 1

I was expecting foo (id=1) to be returned but I was receiving foo (id=2). We have a specific requirement that media entities should be unique so after we merged the duplicate ones, the issue resolved.

function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1)
    ->condition('field_document', $linked_document_id, '=');
  $results = $query->execute();

  // returns results now
  ksm($results);
}


Set custom cache expiration time for a block

There is a real live example of custom cache for drupal 7 in forums:

Asis in Core forum module:

    /**
     * Implements hook_block_view().
     *
     * Generates a block containing the currently active forum topics and the most
     * recently added forum topics.
     */

function forum_block_view($delta = '') {
  $query = db_select('forum_index', 'f')
    ->fields('f')
    ->addTag('node_access');
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
        ->orderBy('f.last_comment_timestamp', 'DESC')
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
        ->orderBy('f.created', 'DESC')
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }

  $block['subject'] = $title;
  // Cache based on the altered query. Enables us to cache with node access enabled.
  $block['content'] = drupal_render_cache_by_query($query, 'forum_block_view');
  $block['content']['#access'] = user_access('access content');
  return $block;
}

Here drupal_render_cache_by_query does caching based on query result.

  Prepares an element for caching based on a query.

  This smart caching strategy saves Drupal from querying and rendering to HTML >when the underlying query is unchanged.

  Expensive queries should use the query builder to create the query and then >call this function. Executing the query and formatting results should happen in >a #pre_render callback.

As in quote query executing and rendering happens in hook_block_pre_render() as in forum.

Another Example:

$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
   'cid' => 'custom_module',
   'bin' => 'cache',
    'expire' => time() + (5 * 60),
  ),
);

The above code is similar to what you did with cache_get, cache_set methods in much similar terms with less code, as drupal_render() function handles this for you setting up cache using drupal_render_cache_set().

You can read more from here: ADVANCED CACHING WITH RENDERABLE CONTENT

As for cache policy when you are caching stuff with custom code in hook_block_info DRUPAL_CACHE_CUSTOM and DRUPAL_NO_CACHE has no difference. However, using DRUPAL_CACHE_CUSTOM for custom caching is better standard.

Check out Block Caching for drupal 7.


Content is not filter with conceptual filter in views

Use all instead of id in any one parameter if you want to consider only one parameter.
e.g. like

http://exp.com/?field_project_catagory_tid=112&field_nd_portfolio_tid=all

or

http://exp.com/?field_project_catagory_tid=all&field_nd_portfolio_tid=112


Show rendered node in jQuery modal through JSON

I can suggest you to check with AjaxResponse, it will return the json response object.

$response = new AjaxResponse();

And use below to open content in modal or as dialog.

$response->addCommand(new OpenModalDialogCommand($title, $content, ['width' => '700'])); // To open a modal window

OR

$response->addCommand(new OpenDialogCommand('#some-element', $title, $content, ['width' => '700'])); // to open a dialog window

$title refers to title of your node and $content refers to content that you want to show in the modal. It is also possible to define some properties like width in it.

And in the end just return it's response like below:

return $response;

Remember to include AjaxResponse in it your controller file.

use Drupal\Core\Ajax\AjaxResponse;

I hope the above will solve your problem.


Rules scheduler reacting on last comment?

To my knowledge, there is nothing in Rules to "overwrite existing scheduled actions" (as in your question). However, by every time attempting to perform an appropriate delete of an already scheduled rule, prior to scheduling a new rule, you achieve a similar result. And such attempt just gets ignored if there was no scheduled rule yet. Read on for more details ...

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" for an illustration about how to delete scheduled tasks, using the "schedule_delete". As explain in that answer: the schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

To make this work (that you actually indicate the exact scheduled task to be deleted), you need to specify an appropriate "identifier", like "[account:name]" in my example. To understand how I know what in my case the identifier is of the task to be deleted, look at the way I specified my (new) scheduled task to be created: it is "identifier" : "[account:name]", which  is what I used as my identifier to schedule a task.

In your case, I think using the node's ID as part of the identifier would be a pretty good choice for such identifier.


Is there anyway to upload a picture to a user image field via services without an FID?

Ok I am going to post what I did to make this work with services. I'll also include a bit of information about my specific use-case because I don't see any list of steps anywhere else on the internet to make this happen, so maybe it'll make it easier for someone along the line.

Here's the optional part of the answer:

I was doing this in PhoneGap. To pass the image data from a mobile device via PhoneGap to a user, I did the following:

navigator.camera.getPicture(saveProfile,
                            function(message) { alert('get picture failed'); },
                            { quality: 50,
                            destinationType: navigator.camera.DestinationType.DATA_URL,
                            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                            );

function saveProfile(image) {
json.image = image;
}

                $.ajax({
                    url: "http://drupal/services_endpoint" + uid,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(json)
                }
                );

And now the actual answer:

After finding this link here: Create file through services

I released I could do something similar:

function MY_MODULE_services_request_preprocess_alter($controller, &$args, $options) {
  switch ($controller['callback']) {
    case '_user_resource_update':
      if (isset($args[1]['image'])) {
        $data = base64_decode(trim($args[1]['image']));
        $finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = uniqid();
        $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
        file_usage_add($file, "user", "user", $args[0]);
        $args[1]['field_picture'] = array(
          'und' => array(
            0 => array(
              'fid' => $file->fid,
            ),
          ),
        );
      }
  }
}

This will generate a random file name. I'm not sure if that'll work perfectly for everyone, but it worked for my use-case.

Anyway, that is a basic way to get image data from a mobile device (iPhone in this case) into a Drupal user in one RESTful call.


It's difficult to answer your question without some concrete specifics. But i went ahead and provided you some common troubleshooting tips when i was in your shoes a moons ago:

Visit the latest readme.txt: It's named that for a reason. I've never read a more helpful readme.txt in terms of contributed modules. Of the best. There's a section relating to site aliases as well. What you have to do for it to work etc.
Review Documentation: First off, please review the Drush documentation which provides great examples of how to create a site aliases.
Copy an example: Also, the maintainers created some awesome examples for a example.aliases.drushrc.php file. In fact, theres a whole folder regarding this that you can copy and paste examples.

Debugging Drush

Additionally, here are some cheap tests to confirm that your site alias is working:

Try running drush status a drush status will show which you which alias file is being read in.
If that's not enough review the drushrc.php file. I would turn on verbose output to figure out how drush is failing.


How do I edit the template files for GLOBAL PHP?

1) Remove Global PHP field from the view

2) Add a new field of type "Global: Custom text"

3) Click on Theme: Information. You will be able to see the suggestion for template file

4)Create the template file with the required name.

5)Invoke the function which was being invoked from your Global: PHP field.


You cannot specify region on your module, but you can custom your page or your block.
Regions are specify into main theme.
First, you need to create a folder on your module root directory :

myModule/templates

Inside, you ll put all your custom template.
For example :

page1.html.twig
page2.html.twig

Then you need to declare all your templates :

In myModule.module :

/**
 * Implements hook_theme().
 */
function myModule_theme() {
  return [
    'page1' => [
      'template' => 'test',
      'variables'=>array('test'=>NULL),
      'render element' => 'children',
    ],

      'page2' => [
          'template' => 'page2',
          'render element' => 'form',
      ],

  ];
}

And after, in your controller or your form :
return $build +  [
  '#theme'=>'page1',
  '#test'=>"its content for my variable inside my template",
];


How to use a RedirectResponse with a # (hash)?

Try url encoding the # fragment. so it becomes %23, e.g:

$event->setResponse(new RedirectResponse(base_path().'mypage%23actions_clicker'));

Update:

Check the browser header to see that the fragment is passed. In my local testing it was ok:

Sample code to append fragment to redirect response.

return new RedirectResponse($redirect_url . '#test', 301);

More info: https://stackoverflow.com/a/2305927/583715


Assigning css class to a particular block

As far as I know, you don't have to add any code to use the class you set on structure/block/configure. The class should be automatically added to $classes array.


pdf.js unable to locate libraries in Drupal 7

Step1: Download from here: https://github.com/mozilla/pdf.js

Step2: Download Windows installer: http://nodejs.org/download

Step3: Download & Install: https://www.drupal.org/project/pdf

Step4: Add the install folder of nodejs, to your PATH variable, so you can call 'node' command from command line

Step5: Through command line, goto /sites/all/libraries/pdf.js. Type 'node make generic'

Note: Make sure that in your library folder you have the pdf.js folder named exactly to "pdf.js". Then inside of that extract the pdf.js files. It should look like this.


In your settings.php add this line ini_set('memory_limit', '128M'); and disable update module.


How to let administrators AND anonymous users create new accounts?

You can always create users as an administrator by going to admin/people/create.

So, in admin/config/people/accounts, in the Who can register accounts? you can choose Visitors and you will be good to go.


Combing View Formatters with Custom Formatter

Custom Formatters module is a (another) good way for this, you can check more samples in official website at: http://customformatters.com.

You probably need to use PHP code for this and get all advantages of powerful Drupal API,  tokens are limited uses for simple outputs without rewrite.

Example for render image fields (do NOT include ):

$output = '';
foreach ($variables['#items'] as $item) {
    $output .= theme('file_link', array('file' => (object) $item));
}
return $output;


How can I hide the active language in the language switcher block?

The links generated by the Language API are alterable via hook_language_switch_links_alter(), so you can do this:

/**
 * Implements hook_language_switch_links_alter().
 */
function MYMODULE_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  unset($links[$language->language]);
}


I think, Role data is not displayed to users other than administrator.
Try with 'Field Permissions' module to edit the field specific permissions.


Render user_pass form in your custom url.
drupal_render(drupal_get_form('user_pass'));

OR

In template.php

function mymodule_theme(){
// custom user-password.tpl.php
    $items['user_pass'] = array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/user-pass',
    );
    return $items;
}

In user-pass.tpl.php:

php global $base_url;

div class="forgotPassword"
Forgot Password

php
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['name']);
    print drupal_render($form['actions']);
?
/div


Is there a way to change Views base table dynamically?

Just use configs overrides services like described here https://www.drupal.org/docs/8/api/configuration-api/configuration-override-system

Example:

if (in_array('views.view.config.name', $names)) {
  $overrides['views.view.config.name'] = ['base_table' => 'your_base_table'];
}


Sometimes these arrays will have a #sorted key that needs to be set to FALSE for the array to be sorted (again) and your weight changes to have an effect. Here it would be at $form['#sorted'].


A Rule component to change author on nodes?

Create a view listing the content that you want to edit.
Add a bulk operation in fields

Select change the author of the content

Go to your view to select the nodes for which you want to change the author

Select the author who should be made the new other for all these content.


Disable caching for a front page path processor

As discussed here, Hide path on frontpage redirect, you need to make caching of route collections domain-specific. Other than the discussed overriding of the core service, since Drupal 8.8 you can use the service method addExtraCacheKeyPart().
Add this code in a request event subscriber:
/src/EventSubscriber/RouteCacheDomainSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RouteCacheDomainSubscriber implements EventSubscriberInterface {

  public function onKernelRequest(GetResponseEvent $event) {
    $routeProvider = \Drupal::service('router.route_provider');
    $domain = \Drupal::request()->getHost();
    $routeProvider->addExtraCacheKeyPart('domain', $domain);
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents() {
    // run before RouterListener (priority 32)
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 33];
    return $events;
  }

}

mymodule.services.yml
services:
  mymodule.route_cache_domain_subscriber:
    class: Drupal\mymodule\EventSubscriber\RouteCacheDomainSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

Also, you need to invalidate the cache tag route_match when book nodes are saved. See Is there a way to partially rebuild the router or invalidate a route cache?


Entity Reference- How do I display more than one view mode?

I solved by using the module entity reference multiple display  which let you to configure different view modes for your field reference. You can split in groups to achieve that.

You install the module and after it is enabled, you go to your content type and in manage display choose rendered entity with different view modes. I have attached a picture

From then you can choose how many groups you would like to display in my case I just need two, the first one I needed to be displayed as view mode teaser and the second one I need no picture in the teaser and just need to display at most two elements in that group.

If anyone has another way to handle this please post your answer here.


How do you load a node inside of another node?

Take a look at the Peekaboo; Ajax field formatter module.

  Provides the ability to load the contents of a field via Ajax.

  Use cases

  Field output that is heavy on resources
  Some fields, such as the *reference fields, can contain a tremendous amount of overhead when formatting the output for the field. This module allows the page output to load without calculating the formatted output of the field, and the field contents can be subsequently loaded into the page with Ajax.
  Field output that takes up too much space
  Peekaboo can be used to initially hide certain fields that take up a lot of space, like maps or images, only to be revealed later at the user's request.
  Fields that reveal more information
  Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.


Is it possible to understand and use Relationships and Contextual Filters without knowing SQL?

By knowing SQL you can have better understanding but it is not necessary.

Relationships give you information about entities that are not listed in the fields b joining current content with other entities. For example detail information about the author of the node is not in the fields, Only it's uid is in there, so by selecting author as relationships you can get the rest of the information.
Contextual filters are similar to regular filters in that you can use mainly the same fields to filter the records on. Where contextual filters differ greatly is that you do not set the filtering value when you create the View, but it is taken from context. Contextual filters are great for when the View needs to display content dynamically depending on various contextual conditions


How do I send data to a template page on form submission?

Form submission handlers (in your case, BM_weather_API_part2_get_weather_report()) don't return any value. See user_login_submit(), and user_register_submit() as examples of form submission handlers.

What I would suggest for your form submission handler is the following:

Set $form_state['rebuild'] to TRUE, and $form_state['BM_weather_API']['weather_result'] to the value obtained from the weather service; this would cause the form builder to be called again.
At this point, the form builder should verify if the content of
$form_state['BM_weather_API']['weather_result'] is not empty, and show the output obtained from the weather service, for example using code similar to the following one.

// First case.
$form['result'] = array(
  '#theme' => 'BM_weather_API_part2',
  '#msg' => $form_state['BM_weather_API_part2']['weather_result'],
);

// Second case.
$form['result'] = array(
  '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
);

In the first case, $form_state['BM_weather_API_part2']['weather_result'] is the value obtained from the weather service, which needs to be passed to the theme function; the code would cause the theme function to be called, and get the value of $form_state['mymodule']['weather_result] as value for the $msg variable used in the template file. In the second case, $form_state['BM_weather_API_part2']['weather_result'] is the value obtained from the theme function, which got the weather service's result.

The code I would write is similar to the following one.

.module

<?php
function BM_weather_API_part2_theme() {
  return array(
    'BM_weather_API_part2' => array(
      'template' => 'BM_weather_API_part2',
      'variables' => array('msg' => NULL),
    ),
  );
}

function BM_weather_API_part2_menu() {
  $items['weather/report'] = array(
    'title' => 'Weather API - Part 2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('BM_weather_API_part2_form'),
    'access arguments' => array('access content'),
    'file' => 'BM_weather_API_part2.pages.inc',
  );

  return $items;
}

.inc

function BM_weather_API_part2_form() {
  $form['location_name'] = array(
    '#title' => 'Location',
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  if (!empty($form_state['BM_weather_API_part2']['weather_result'])) {
    $form['result'] = array(
      '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Get the weather report',
    '#validate' => array('BM_weather_API_part2_form_validate'),
    '#submit' => array('BM_weather_API_part2_form_submit'),
  );

  return $form;
}

function BM_weather_API_part2_form_validate($form, &$form_state) {
  if (BM_weather_API_part2_check_location($form_state['values']['location_name'])) {
    $form_state['BM_weather_API_part2']['weather_result'] = FALSE;
    form_set_error('location_name', t('Please enter a proper location name.'));
  }
}

function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = theme('BM_weather_API_part2', array(
    'msg' => BM_weather_API_part2_get_weather($form_state['values']['location_name']))
  );

  $form_state['rebuild'] = TRUE;
}

function BM_weather_API_part2_get_weather($loc) {
  // ...
}

I will add some notes about your code.

In the implementation of hook_menu(), the array keys are the paths associated with the menu callbacks; in your case, as you use $items['BM_weather_API_part2'], the URL for that menu callback would be http://example.com/BM_weather_API_part2 (replace example.com with the URL of your site). It is preferable a path like weather, or weather/report, which is similar to the paths used from Drupal, such as node/1, user/1/edit.
When defining a menu callback, you can use 'page callback' => 'drupal_get_form' and pass as first argument of "page arguments" the name of the form builder; there isn't the need to define a function such as BM_weather_API_part2_view(), whose only purpose is to call drupal_get_form().
The form submission handlers don't check if the submitted values are correct; that is a task for the form validation handlers. That is why I am using a form validation handler, in my example code.
If the users need to enter a value for a form field, then you can simply use '#required' => TRUE for that form field, as I did.
ctype_digit() returns TRUE when the parameter it gets is a string containing only digits. I am not sure that is what the user should input in your case, as a number is not what I would consider a location name. If the user really needs to enter a number, the description for the "Location" form field should say that, and it should also explain what type of input the form it is expecting (e.g. a zip code).
The first argument of form_set_error() is the form field ID. As you don't have any form field that uses "BM_weather_API_part2_character_required" as ID, form_set_error('BM_weather_API_part2_character_required', t('Please Enter Proper Location Name.')) is not highlighting any form field, which is part of the purpose of form_set_error(). In your case, you should use form_set_error('location_name', t('Error string')), as location_name is the form field ID for the field you are reporting an error.
All functions implemented in a module should be prefixed with the short name of the module (after an underscore, if the function is "private"); in this way, there isn't any collision between different modules, which is what happens if two different modules would define a get_weather_from_google() function.
If the template file just prints the value it gets between its variables, then there isn't the need of a template file, or a theme function; you just use code similar to the following one:

function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = BM_weather_API_part2_get_weather($form_state['values']['location_name']));
  $form_state['rebuild'] = TRUE;
}

I wrote the example code assuming that your template file does more than just printing a variable it gets, and you didn't show all the code for the template file; if the template file does only that, then the template file, and the theme function are not necessary.

As side note, if the short name of your module contains uppercase characters, you will have problems with hook_update_N() being executed. You should always use lower case characters in the short name of your module.


Using the youtube_uploader module, how do I upload the video as private, without hacking the module

hook_form_alter() is what you're looking for. This function, when invoked in any module, will let you modify any form array created/rendered by Drupal's form API. For example, in a module named mymodule you could add the following function in mymodule.module.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //modify youtube_uploader_get_settings_form to add Private to #options array
  if($form_id == 'youtube_uploader_get_settings_form') {
    $form['youtube_uploader_publishing_options']['#options']['private'] = t('Private');
  }
}

function xxxx_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'field_ui_field_edit_form' && isset($form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options'])) {
    $privateOptions = array('public' => t('Public'), 'unlisted' => t('Unlisted'), 'private' => t('Private'));
    $form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options']['#options'] = $privateOptions;
  }
}


How to add an additional class to each element in the menu-local-task.html.twig template?

Create an array, ex:
{%
    set classes = [
      is_active ? 'is-active',
      'my-second-class-name',
    ]
%}

{{ link }}

Currently, the "DefTabs__tabItem--active" class is added to the active
link, but I need to add an additional CSS class "DefTabs__tabItem" to
each DIV element.

By the way, no need to repeat yourself with the naming, do this:
{%
    set classes = [
      'DefTabs__tabItem',
      is_active ? 'active',
    ]
%}

{{ link }}

Then in CSS you can target the active with .DefTabs__tabItem.active { ... }


How can I change a file before save in programmatically?

My best guess is to use hook_field_presave() to alter it before it gets saved, for example:

function hook_file_presave($file) {
  // Change the file timestamp to an hour prior.
  $file->timestamp -= 3600;
}

See also: How do I change the uploaded file name after the node has been saved?


Custom submit handler stops working when checking route

The comment form sets an #action to the comment.reply route, which will rebuild the form and no longer go inside your condition as the route there is differdnt.

Whatever you're trying to do exactly, you need to find a different way to do it.


How do I append something to a node when it's in detail page

If by "detail page" you mean the full node page, you can check the current view mode:

if ($variables['view_mode'] == 'full') {
  // ...
}


How to display an image when hovering over its title in a View?

I post as answer because I have not reach 50 reputation to post as comment.
When you debug .snhover_img a span is the style { position:absolute; display:none; z-index:99; } applied?


Will groups with more number of users cause the page to load slower?

The more modules you add to a site, the more code that likely has to execute, which equates to more overhead per request. Organic Groups particularly can be heavy, depending on what you are trying to achieve. I do not know how much progress they've made in the last few years, but in my experience it was always pretty heavy.

Logged in users also bypass caching, whereas anonymous users see as much cache as possible. This isn't as true for 8.x, but the differences in 7.x can be pretty black and white. Juggling multiple logged in users simultaneously can put a hurt on low end setups or especially if you haven't implemented caching. Or a runaway module could be calling functions every single request per user, adding to that time.

Honestly, the best tools that will help you pin down potential bottlenecks are xhprof and using a service like New Relic. It will give you far more intel about your application than anyone here ever could.

Other things you can do simply comes down to good planning. Are pages made up of lots of Views? Implement Views caching on displays that don't change often. Are you using Panels? Do you need to use Panels? Are you running memcache, does PHP have 256M memory limit, is your server underpowered?

I would start with New Relic, honestly, and xhprof. New Relic is easier to setup than xhprof, depending on your experience. You will need to profile your site before you know what steps to take first.

If you are running Drupal 8, also install the Web Profiler toolbar included with Devel.


How to create custom forms to filter views results in Drupalgap

You could first create a custom form: http://docs.drupalgap.org/7/Forms/Creating_a_Custom_Form

Then in its submit handler build a Views Render Array and inject it into a waiting div placeholder element (markup widget) on the form:

http://docs.drupalgap.org/7/Views/Displaying_a_View/Views_Render_Array
http://docs.drupalgap.org/7/Forms/Form_Elements/Element_Markup

Or have the submit handler go to a page with arguments: http://docs.drupalgap.org/7/Pages/Page_Arguments

Then that's page's page_callback could build a Views Render Array and use the search string as a contextual filter to the View.


dynamic block title for block-view of referencing nodes

Add the content title a second time, but this time set the relationship so that the artist's name is displayed. Set the display of this title to hidden, and make sure it has a label which reads : 'Other albums by'.

Then in the Format section, select settings, and then group by this artist title field you have just added and hidden.

The title will get wrapped in an h3. If you want to wrap it in an h2 then you will have to override the views template, one of the suggestions in the Style Output of the provided theme information.


You'll find "Update URL alias" as one of the choices for bulk operations for nodes under admin/content

This way you can select which specific nodes that needs URL aliases rebuilt instead of deleting and rebuilding all.


How do I get Drupal to use table prefixes so I can install multiple drupal installations in the same database schema?

In the settings.php file, a normal setup might look like

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

The only difference is that you add a 'prefix', like this:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => 'site1_',
  'collation' => 'utf8_general_ci',
);

Make the prefix different in each settings.php site, and you can have as many sites as you want within the same database.


How do I add grouping, programmatically?

Finally found a solution. The grouping is not an Eventhandler in Drupal 8 but a Plugin (Style Plugin) specifically. Here is the code

function utility_views_pre_build(ViewExecutable $view) {
  $view->style_plugin->options['grouping'][0] = array('field' => 'field_category');
}


Commerce File won't let anyone download files

In case anybody else runs into this problem, I managed to solve this issue by applying a patch for the generation of the access token, found here.

In breif, the patch is needed because the latest update to the File Entity module (which Commerce File utilises) changes the way that access tokens are generated and Commerce File has not yet been updated to account for this.


I think there is one more configuration in setting.php for content type mapping with its fields.

In this example i have mapped article content type with cmis type.

$conf['cmis_sync_map'] = array(
 'article' => array(
     'enabled' => TRUE,
     'cmis_sync_cron_enabled' => TRUE,
     'cmis_folderPath' => '/Sites/New/Article',
     'full_sync_next_cron' => TRUE,
     'cmis_sync_nodeapi_enabled' => TRUE,
     'subfolders' => TRUE,
     'cmis_type' => 'alf:article',
     'content_field' => 'body',
   ),
);

$conf['cmis_sync_map']['article']['fields'] = array(
  array('drupal' => 'title', 'cmis' => 'cmis:name', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'body', 'cmis' => 'cm:content', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'field_object_id', 'cmis' => 'cmis:objectId', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
);

I hope it will works for you.


Adding an OR condition to an existing query

Adding new conditions to the query won't overwrite the existing ones, you need to reset the existing array of conditions, build up a new one and add it to the query:

// Get the query args and then the search term
$args = $query->getArguments();
$search = array_shift($args);

// Get a reference to the existing query conditions.
$conditions =& $query->conditions();

// Reset the condition array. It needs a default #conjunction for which AND is fine
$conditions = array('#conjunction' => 'AND');

// Build up your condition
$condition = db_or()
  ->condition('users.name', $search, 'LIKE')
  ->condition('n.field_name_value', $search, 'LIKE');

// Add the new OR condition to the query
$query->condition($condition);

// Join the relevant table
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

I've just tested that to work on a local installation.

There is a slight caveat...for users with the 'administer users' permission the default is to also search through users' email addresses. You can cater for this by adding the following lines immediately before $query->condition($condition);:

if (user_access('administer users')) {
  $condition->condition('mail', $search, 'LIKE');
}

It might also be wise to test the bundle and entity_type columns in the joined field table in case you ever attach the same field to another entity. This way you won't get any false results:

$join = "users.uid = n.entity_id AND n.entity_type = 'user' AND n.bundle = 'user'";
$query->leftJoin('field_data_field_name', 'n', $join);

EDIT

As per Berdir's comment, to maintain as much compatibility as possible with other modules that might also alter this query, you probably want to loop through the conditions, find the one(s) that you need to change and do so on an individual basis.

The above example is pretty rudimentary and works on a 'vanilla' Drupal install, hopefully it'll get you pointed in the right direction.


Obfuscating email addresses displayed by Views?

Spamspan module will help you. It can obfuscate email addresses from email fields along with emails provided inline in text.

For email field - chooses Spamspan formatter in display settings.


Oh, it is really easy with powerful Views module.
There is cool option for contextual filters “Content: Has taxonomy term ID” and “Content: Has taxonomy term ID (with depth)” — Load default filter from node page, that's good for related taxonomy blocks.

Tip: don't forget to exclude node, which is current!


Form submissions aren't dependent on there being a path to view/submit the form at, all you need to do is one of the following:

Name the submit function as FORMNAME_submit() and Drupal will pick it up automatically
Add the handler manually in the form function itself, e.g.

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


If I am correct, you should have a path/url to your Data Export Views (second column, at the top, Data Export Settings > Path). So you just need to create a block with a link to this URL in its body and it will directly launch the export procedure (no filters considered though). You may add CSS/Bootstrap class to your link and here is your nice export button in a block, which you can add anywhere in your website.