Pathauto tokens for taxonomy terms except root

The default tokens won't allow you to do this, but the only thing you're missing I think is an array token that removes the first element, I'd call it "tail". See token_token_info(), which defines for example a 'reversed and other array tokens:

$info['tokens']['array']['reversed'] = array(
  'name' => t('Reversed'),
  'description' => t('The array reversed.'),
'type' => 'array',
);

And the implementation for that is in token_tokens():

// [array:reversed:*] chained tokens.
if ($reversed_tokens = \Drupal::token()->findWithPrefix($tokens, 'reversed')) {
  $replacements += \Drupal::token()->generate('array', $reversed_tokens, array('array' => array_reverse($array, TRUE)), array('array sort' => FALSE) + $options, $bubbleable_metadata);
}

Instead of array_reverse(), you'd call array_shift() on the array first and then pass that along.

Might also be a useful standard token to have in the token.module, if someone wants to provide a patch.

Your token would then look like this:

[node:field_product_category:entity:parents:tail:join-path]


Can't delete content type that I created?

Ensure you are user/1 and try navigating to this page

/admin/structure/types/manage/<content-type-name>/delete

replace <content-type-name> with the actual name of the content type


How to display selectable variations without attributes?

if i understand you question correctly, you accomplish this by going to your order item type, choose manager form display then you have the field available called Purchased entity ... you want to change the default widget from product variation attributes to Product variation title.


How Can I do a content type with a 1:n field inside?

It seems Field collection/tabular data solution is what you're after.

In Drupal 7 the popular module for that was Field collection.

In Drupal 8 Paragraphs seems to be popular, although its description is pointing heavily to the current fad of designing content pages with separate sections, it is still a solution that allows for a more structured group of references. Then you reference the Paragraph you constructed for this particular purpose from within your nodes.

A more abstract solution similar to Paragraphs but more flexible is Bricks. Although its description is pointing to Layout integration you don't have to be distracted by that, it's still a great entity reference grouping mechanism you can use to construct your node structure.

I think Bricks might be better suited for your particular case since you'll always be using the same platform/date structure, but investigate both and see which fits you best.

In short, you need references from your nodes to the platform, and date, and they need to be grouped in pairs. You can do that by creating the abstract reference (brick) from your node, that in itself holds two other references (to platform and date). Platform items (entity reference) can be Taxonomy terms, Date can also be Taxonomy or Date fields, it all depends on your details, what type of data it is, how you're expected to manipulate it, etc.


Is it possible to export all block's region settings to Features?

We abandoned managing the blocks through the normal Structure->Blocks page a long time ago. Now we use it simply to set block titles, and the individual block's settings.
For assignment onto pages we use Context module:

Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

This module lets you assign blocks to regions using criteria based on more than just page paths, such as taxonomy term of the content, type of content etc. And also it allows you to react with more than just blocks as well. Also one block can be assigned to different regions using more than just 1 context.
Overall the most important thing to this question regarding Context module is, the context rules are exportable via features!


How to properly specify context for Drupal behaviours

Just stop using context in this case.  I've been playing around with jQuery Masonry and I've not needed to use it.

(function ($){
  Drupal.behaviors.myModule ={
    attach: function(context, settings) {
      $('.view-SPECIFICVIEW .view-content').masonry({
        columnWidth : 300,
        gutterWidth : 20
      })
    }
  }
})(jQuery);

FYI, I'd also take a look at the Masonry recommendation to use the imagesLoaded plugin if there are images in your view.  It takes a LOT of future frustration out.


You can use single title callback by passing two arguments :

'title arguments' => array(3, 4),

and use same callback for both function :

function fr_form_view_submission_page_title($id, $type = 'view') {
  $type = ucfirst($type);
  return t('@type submission ID: @id', array('@type' => $type, '@id' => $id));
}


tableselect showing empty message instead of options

Apparently, something is/was cached because clearing the cache solved it. So there weren't any problems with the code.


How do I pre-configure a block's settings in my module in Drupal 7?

If you want to set the standard block options, you can do that in hook_block_info

e.g:

/**
 * Implements hook_block_info
 */
function MODULE_block_info() {

  $blocks = array();

  // Assign block to front page, sidebar_first region by default
  $blocks['my_front_page_block'] = array(
    'info' => t('Front page block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>'
  );

  return $blocks;

}


Drupal 7 - Dynamic Allowed Values Field Widget

You might get it to work like so:

Use the Select (or other) module, and
Integrate it in a form or module using a Forms API element.

More details below ...

About this module

Here is an excerpt about the Select (or other) module from its project page.

  Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few options (Option 1, Option 2, Option 3), and whenever somebody needs another one (not in the list yet), they just enter "Option 4". Here is a sample about it:

Integration in a form or module

By only using the module as delivered, you wouldn't have a different set of options yet for each author. But the Select (or other) module can be integrated in any form or module, as shown also in the usage example within the Community Documentation of this module.

By enhancing that usage example to make the values for value_1, value_2, value_3 depend on each user, you should get it to work.


Where are the field variables in a block template?

They're in the content variable, e.g.

<div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content.field_foo }}
    {{ content|without('field_bar') }}
    {{ content.field_bar }}
  {% endblock %}
</div>

For reference, these are the default core variables you have available (from the core template:

  plugin_id: The ID of the block implementation.
  label: The configured label of the block if visible.
  configuration: A list of the block's configuration values.
  label: The configured label for the block.
  label_display: The display settings for the label.
  provider: The module or other provider that provided this block plugin.
  Block plugin specific settings will also be stored here.
  content: The content of this block.
  attributes: array of HTML attributes populated by modules, intended to be added to the main container tag of this template.
  id: A valid HTML ID and guaranteed unique.
  title_attributes: Same as attributes, except applied to the main title tag that appears in the template.
  title_prefix: Additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.
  title_suffix: Additional output populated by modules, intended to be displayed after the main title tag that appears in the template.


Change the body field widget to Long text and summary


Views Rewrite return html string instead of rendering them

I think it could be because of the .... tags part, if you take that out, does it render? Seems like views uses Filter HTML, and only popular html tags are allowed on Custom Fields or Re-Write boxes.

You should be able to achieve your goal by creating a template file.

views-view-fields--[view-name]--[machine-name].html.twig

{{ fields.totalcount.content }}


DDEV php/twig error "Unknown "link_attributes" filter."

It was an module identification problem. I thought it was the link_attributes modules but the error is from twig_link_attributes. That one didn't download cause it's a git submodule or something... Anyway that folder is empty.


You need to check your node and page level twig templates to make sure it is not outputting the submitted by information, despite what the setting is here. There could also be a Views block outputting this information in one of the regions, which would ignore the setting as well.


You are almost there, here is a rewritten version of your code that should work:

<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

$client_ip = $request->getClientIP();
$headers = $request->server->getHeaders();
$referer_url = isset($headers['HTTP_REFERER']) ? $headers['HTTP_REFERER'] : '';

\Drupal::logger('sitelog')->notice($referer_url . '::' . $client_ip);

The main idea of the rewrite is to keep a reference to the HttpFoundation\Request from the very beginning and use if to get access to the parameters you want.

P.S.: Loading Symfony's components as well as booting Drupal's kernel may be an overkill for getting the client's IP and referer url, a simple php script could do that for you and write logs in a file.


Where is the code that filter web and email addresses into links?

This answer is for Drupal 7

You can see where the default filters are defined in /modules/filter/filter.module line 1147. There we see that _filter_url() (line 1358) is the function used to transform text into links.

You shouldn't modify this code directly. Instead you can implement hook_filter_info_alter() to change the process callback for url filter to your own function (you can copy _filter_url() and make the few changes you need)

function YOURMODULE_filter_info_alter(&$info) {
  $info['filter_url']['process callback'] = 'YOURMODULE_filter_url';
}

Keep in mind that these changes will be reflected everywhere the URL Filter is used. If you need something not so "all inclusive", you can implement a new filter that you can apply to a seperate input format.


Drush has a php-script argument which will allow you to run a PHP file with any code in it. Since Drush performs a bootstrap and includes the usual files required at Drupal runtime before running your script, you have all of the Drupal API available to you in your custom script.

If you need to submit any arbitrary form you can pre-populate a $form_state array and then submit the values using drupal_execute (see its API documentation). Getting to know what values to pre-populate in $form_state can be tricky, but this line can help you out:

drupal_set_message('<pre>' . print_r($form_state, TRUE) . '</pre>';

Place this in the submit handler function for to the form you'd like to programatically submit and then run through the form once in your browser. Upon submitting that form, you should get a print out the $form_state structure that you would need to mimic. Be weary on live sites though, users will be able to see that debug message too!

If you're just needing to submitting nodes then you could even use node_save() directly which is a bit simpler. How to do this is detailed on another question, How to create nodes using node_save?


Drupal 7, Looking for a module that can geo-locate a user and feed them specific data?

Smart IP module (https://drupal.org/project/smart_ip) will do the job. It will locate the visitor based on his/her IP address. Anything better than that (e.g. street address) requires Device Geolocation, which comes as a submodule of Smart IP.


how to filter nodes that match url of current node or particular field of current node

Ok managed to create a working view:

Under contextual filter:
-Content: Has taxonomy term ID

Configured:

Provide default value - Type:

Taxonomy term from url - load default filter from term page (checked)

Specify validation criteria (checked)

Validator: taxonomy term (selected)

Check term in vocabulary list

Filter type: term name converted to term id (selected)


How can I restore author and post information for nodes?

Regarding both date and author info:
If you are not comfortable updating the Post date directly in the database, then I suggest you take a look at Views bulk operations, which is capable of performing mass manipulation of your sites content.

If the data doesn't show up as expected, it's always a good idea to switch to stark, to see if it's a theme issue.


How do I compare a shipping address with a profile address field?

You could make a custom module and add in there a custom rules condition that checks exactly what you need
The tiny book of rules contains great examples how to implement custom conditions www.drupal.org/files/tiny-book-of-rules.pdf

Also you could try do the same thing with the default rules condition (e.g. entity has field and entity field has value) but i think is much more hard to get relationships this way

If you choose to go with a custom condition function I suggest you set the default argument as an order type and the use functions like this one http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!customer!commerce_customer.module/function/commerce_customer_profile_load_multiple/7 to get the shipping profile and then the address you want to compare. You may load the current user simply by using global $user; . The devel module and the dpm() function is a great help to see what is available during development in an object.


If the fields differ markedly, that's a case for a different content type.

e.g "Vehicle" and "House" would be two distinct content types with their own fields - much easier in the long run.


Provide contents of file field at node URL

Its not a good idea to provide contents of file field at node URL.

Instead use File Aliases module which will let you use node properties in the resulting file url.

  The File Aliases module allows you to use token customizable aliases
  for your uploaded files, giving you the ability to keep your file
  system organized as per usual while providing clean looking paths
  (i.e., no more '/sites/default/files/').


Why is this block found but not installed?

In general, that can have many possible causes. But it's very likely some sort of syntax or other error that leads to an exception or a fatal error.

Open the Place block link in a new tab to see the response, check the network tab and/or check your apache or drupal logs.

That should give you a hint about the problem. In this specific example, it was a trailing space after the closing PHP tag, as suggested by @kiamlaluno, that's why Drupal coding standard says that they should be left out.


How to show or hide some content on a node view using Page Manager based on the url destination?

It appears that there is a visibility rule that you can set on a particular content using the String: URL path.

Step 1:

take only the destination parameter: e.g. *?destination=no-edit-permission where the (*) asterisk is the wild card and represents whatever comes in front of that string.

Step 2:

In the Configure visibility rule for New custom content

set the option to:

  Allow access on the following pages

and tick the box:

  Reverse (NOT)

That should hide that content block based on the destination parameter. Yay!


Executing a view programmatically with input filters

I don't think that you need to execute the view programmatically. Because it's meaningless. Views just fetches data from the tables which you show and display it, it's all it does.
I think you need to alter Exposed Filter form and add your additional submit callback which on submission writes the searched strings into your custom table. And then you can query those table (from which table views fetch data.) with saved string as condition..
All of this logic must be run on cron job..

EDIT:
I don't know this can help you or not, but here is a very poor example. Not very performance friendly :). OPTIMIZE IT.

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
   if ($form['#id'] == 'MY_EX_FORM_ID') {
      if(user_is_logged_in()) {
         $form['actions'] = array(
            '#type' => 'actions',
         );

         $form['actions']['submit'] = $form['submit'];
         $form['actions']['subscribe'] = array(
            '#type' => 'submit',
            '#value' => 'Subscribe',
            '#submit' => array('my_ex_form_subscribe_submit'),
         );
         unset($form['submit']);
      }
   }
}

function my_ex_form_subscribe_submit($form, &$form_state) {
   global $user;
   $account = clone $user;

   $input_val = $form_state['values']['field_adv_price_first']['min']; //Find your input field value and change this..

   db_insert('MY_SUBSCRIBE_TABLE')
      ->fields(array(
         'uid' => $account->uid,
         'email' => $account->init,
         'input_val' => $input_val,
      ))
      ->execute();
}

function MY_MODULE_cron() {
   $subscribed_query = db_select('MY_SUBSCRIBE_TABLE', 'mst');
   $subscribed_query
      ->fields('mst', array('uid', 'email', 'input_val'))
      ->execute()
      ->fetchAllAssoc('id'/* id - is the primary key of MY_SUBSCRIBE_TABLE */);

   // Supposing that your view is querying for the node table to fetch jobs, by title field
   if(!empty($subscribed_query)) {
      foreach($subscribed_query as $key => $val) {
         $nids = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('title', '%' . db_like($subscribed_query[$key]['input_val']) . '%', 'LIKE')
            ->execute()
            ->fetchCol();

         if(!empty($nids)) {
            foreach($nids as $nid) {
               $node_url = url('node/' . $nid, array('absolute' => TRUE));
               $template = 'New job is found in our site and blablabla... BLABLABLA';

               // Suppose that you are using SwiftMail library.. You can use drupal's mail system as well. It's up to you
               $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
                  ->setUsername('MYGMAILUSERNAME')
                  ->setPassword('MYGMAILPASS');

               $mailer = Swift_Mailer::newInstance($transport);

               $message = Swift_Message::newInstance()
                  ->setFrom(array('no-reply@'.$_SERVER['SERVER_NAME'] => 'MY-SITE.com'))
                  ->setTo(array($subscribed_query[$key]['email']))
                  ->setBody($template, 'text/html');
               $mailer->send($message);
            }
         }
      }
   }
}


its better to use Facebook realtime update https://developers.facebook.com/docs/graph-api/real-time-updates/v2.2

create your callback to handle this and register it with real time updates

do the following in your callback

1- load user from facebook ID you get it in the posted from facebook

2- get the new image from facebook

3- replace it with the current image

4- save user

or you can forget about real time update and replace the image whenever user login

here the code you can use

1- Make your action by Implementing hook_fboauth_actions().

2- use hook_user_login to call the action you create which grab the photo and update it

Thats all


Alter menu link lists dynamically in regards to user's role?

The best way to do it would be simply to restrict access to those pages to only the roles you wish to be able to see them. The menu system will automatically not print out links for pages the user cannot access.

How to do this depends on what you're linking to. If it's nodes, perhaps the core per-content-type permissions are enough. If not, there is a variety of node access modules you can use to implement more fine-grained node access, using taxonomy or other methods. If those pages are Views, you can set a View to only be available for certain roles.


Is the database table "field_revision_body" used in a core module or can I just drop it?

Both tables (field_data_* and field_revision_*) are added and used by the field SQL storage module in core. The existence of both tables make it possible to store revisions of field data. There's no way to use that storage system without both data_* and revision_* tables.

So don't delete it :)

There are modules out there defining alternative storage systems without using revision tables (e.g. Field SQL norevisions) but I'm not sure how difficult it would be to convert an existing database to use that system.


The version of core you're running - 7.30 - is extremely vulnerable.  As long as you're running any version of core prior to 7.32, your site will remain vulnerable.  The vulnerability will allow changing modules (which can be discovered with the Hacked! module), putting executable PHP in the database (which can not be discovered with Hacked!), and injecting malicious shell scripts (which can not be discovered with Hacked!).

Simply replacing Drupal core and modules with non-hacked versions will not remove backdoors.

Just going through the changed modules and reinstalling them will not do.  At this point, even if you replace everything, the intruder have probably infected your database with exploits, as well as having installed several well-hidden backdoors to your site at shell level.

The best recourse is to delete your entire site an rebuild it from scratch on a clean vhost, then restore its contents from a backup made prior to Oct. 15, 2014.

Read this SA to understand the severity of this vulnerability: https://www.drupal.org/SA-CORE-2014-005. Also read:

https://www.drupal.org/node/2357241
http://www.linuxjournal.com/content/drupageddon-sql-injection-database-abstraction-and-hundreds-thousands-web-sites

If you're unable to delete the site and restore from backup, read this about recovering: Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?.

After you have cleaned up your site, to be alerted if this happens again, consider installing File integrity check. This module will monitor the integrity of almost all files on your site and send you an email if it detects that file integrity is breached.


How do I change a theme based on the URL?

Considering that the change is for a limited period of time, and that implementing such code is not difficulT, I would suggest to implement a custom module that changes the theme being used for specific pages.

It is enough to implement hook_custom_theme() as follows:

function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'the theme to use for that page';
  }
}

If you would need to change the theme only for http://example.com/event2011, but not for http://example.com/event2011/node/123, then the code should be changed to

function mymodule_custom_theme() {
  if (arg(0) == 'event2011' && !arg(1)) {
    return 'the theme to use for that page';
  }
}

As for using the theme callbacks in the definition of a menu callback, the documentation says:

  As a general rule, the use of theme callback functions should be limited to pages whose functionality is very closely tied to a particular theme, since they can only be overridden by modules which specifically target those pages in hook_menu_alter(). Modules implementing more generic theme switching functionality (for example, a module which allows the theme to be set dynamically based on the current user's role) should use hook_custom_theme() instead.


Load published nodes of certain content type

To load a bunch of nodes based on custom parameters, you have to use EntityFieldQuery. It replaces the $conditions array noad_load_multiple used.


How to alter the title of a views exposed form block with code

function hook_block_view_alter(&$data, $block) {
  if ($block->bid == $id) {
    $block->title = $title;
  }
}

Where hook is the name of your module, $id is the numeric ID of the block and $title is the desired title.

You can find the ID with the Devel module by putting dpm($block); inside the hook_block_view_alter() function and then looking at the output for each block to see which one matches. It'll have a delta attribute on the $block object something like -exp-your_view_name-display where your_view_name is obviously the name of the view, and display is the type of display, e.g. page or block. Or you can just pattern-match the delta value instead of selecting by ID, up to you.


Enable twig debugging by copying default.services.yml to services.yml and following instructions in the twig.config section. The debugging comments will display template file name hints in HTML comments in the page output.


Drupal version 8.5.3 Local dev with Aquia Dev Desktop.

I've tried all combinations with .htaccess (root, in /files and in styles) with no success.

Also tried with:

$config['image.settings']['suppress_itok_output'] = TRUE;
$config['image.settings']['allow_insecure_derivatives'] = TRUE;

No results.

Even though I had a settings.local.php solution was to uncommment this line in settings.php:

$settings['file_public_path'] = 'sites/default/files';


Open Atrium: How to change Task assignment from users to groups?

Edit the Task content-type, add a new Entity Reference field for oa_group_ref.
Edit the Task List view and set a contextual filter on the added field, and provide the default value for the filter with the OG groups of the current user, and allow multiple values in More options.
In query settings set the Distinct to make it work with multiple assignment.


Drush hangs when trying to bootstrap Drupal

In this particular case, the issue was with an incorrectly configured memcache server settings, the Drupal environment in question was attempting to communicate with a memcache instance that had a firewall dropping all connections.

The fix was to configure memcache servers in the Drupal settings file. Hope this helps someone else.


Chart & graph as content type? is it possible with any module

As mentioned in the previous answer, charts is indeed a module that might be considered. In response to the comment in it about "not using views" you need to know that using views for creating charts is only one of the available use cases for the charts module, as explained in the charts community documentation. Here is the relevant quote of it:

  Various options are available to actually create charts via the charts module:

  Use the charts module directly e.g. to create a chart as part of the body of a node (using data that are hard-coded in such node).
  It can be used as a views style (views integration).
  Take advantage of the charts API to integrate it into your module, using a single function as the point of contact: charts_chart();.
  Visualize data stored in a database table (more dynamically), as explained in Chart some data stored in a database table (dynamically).

So from the above options, I believe that option "1." could perfectly address the original question. All you'd need is to enable the PHP filter (input format), and then add the relevant PHP code related to the charts render array (which is used to specify any of the desired options supported by the Charts API). As a variation of such "content type", you may also use a custom block (in which you include the same PHP code related to the charts render array).

To create charts in Drupal, there are actually dozens of modules to pick from (really!). Consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the charts module mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Recently I extended the above mentioned comparison with Maintenance Scorecards for all Native Charting Modules. These Maintenance Scorecards should help to further narrow down the available charting options if you're concerned about how well some module is maintained (or not).

Disclosure: I'm a maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison (+ some charting modules mentioned on my profile). I hope this does not violate the site's policy on self-promotion.


How to change fieldset which is made via #theme_wrapper Drupal 7

I had to do this today on a Backdrop CMS site, but the problem and solution are exactly the same:

The problem is that most theme wrappers only add markup around the outside of something else. But a fieldset also has a process function, and process functions are not automatically added for #theme_wrappers.

The process function needs to run on the fieldset in order to take the #collapsible and #collapsed settings you add in the Form API to turn into the addition of the necessary CSS classes and JS library.

That means that not only do you need to set the values for #collapsible and #collapsed, but you also need to add the #process function. See below for an example.

/**
 * Implementation of hook_form_BASE_FORM_alter().
 * - Limits access to legacy fields.
 * - Collapses legacy fieldset.
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (isset($form['field_images_inline'])) {
    $form['field_images_inline']['#access'] = user_access('administer nodes');

    // Add the collapsible and collapsed attributes.
    $lang = $form['langcode']['#value'];
    $form['field_images_inline'][$lang]['#collapsible'] = TRUE;
    $form['field_images_inline'][$lang]['#collapsed'] = TRUE;

    // Add the fieldset process function.
    $form['field_images_inline'][$lang]['#process'] = array('form_process_fieldset');
  }
}


Programatically create nodes, taxonomies and relationships via exisiting database

http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7 - only thing to note is making sure the taxonomy terms don't exist before you add them, which you can easily do with a function like this (recently wrote this for a project)

function taxonomy_import_add_or_get_term($term, $vocabulary) {
  $tid = taxonomy_get_term_by_name($term, $vocabulary->title);
  if (count($tid) > 0) {
    $tid = array_shift(array_keys($tid));
  }
  else {
    $term_object = new stdClass();
    $term_object->name = ucwords(strtolower($term));
    $term_object->vid = $vocabulary->vid;
    taxonomy_term_save($term_object);
    $tid = $term_object->tid;
  }
  return $tid;
}


Custom 'Who's Online' View - How to filter User View by whether logged in

please check the dev version for drupal 7

  Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics include if the user is on or offline.

https://drupal.org/project/user_stats


Image field is not showing up in view/block

check admin/user/permissions page. if you use imagecache check view imagecache permission and set it. and set view image field permission.


Display Views results in a specific order?

You can set arbitratry order on Views using the various ordering modules listed here.

Draggable Views is probably the most popular.


Using a vocabulary term as a panel wildcard

You can set a validation rule to convert your term name into a term id within your view as a contextual filter, and then pass the term name through the page.


Place tag before input text field in search-block-form

The "input" type you are referring to, is actually the element defined inside the array $form['search_block_form'],  of #type 'textfield'. That's the element that provides the input field when rendered.

In order to add a <li> tag in front and back of this input field, try using the properties   #prefix and #suffix. Also I would suggest creating a custom module for this, avoid using it inside the template.php file. Try the following (haven't tested it myself, though).

function myModule_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     $form['search_block_form']['#prefix'] = '<li>';
     $form['search_block_form']['#suffix'] = '</li>';
   }
}


Varnish and Pressflow are two different things.. Pressflow uses varnish to improve performance.. More details goes below..

Pressflow is “a derivative of Drupal core providing enhanced performance, scalability, and data integrity”. Basically, some really smart guys at Four Kitchens and elsewhere back-ported a bunch of Drupal 7 performance enhancements to the Drupal 6 (and even Drupal 5!) code base.

Pressflow adds the following features to Drupal.

Support for database replication
Support for Squid and Varnish reverse proxy caching
Optimization for MySQL
Optimization for PHP 5

What:
Varnish is an HTTP accelerator and caching reverse proxy. Varnish is all about speed. It stores as much content as it can in the fastest place possible – RAM in this case – and bypasses the expensive process of making a request to Apache.

Why:
Pressflow structures the Drupal content to be more cache-friendly, but we still need something to actually cache the content.

How:
Varnish sits in front of Apache, accepts incoming connections from browsers and, if possible, fulfills the requests from its cache. If it can’t, it passes the request on to the underlying Apache/PHP stack. It then takes the response from Apache and forwards it on to the requesting browser. If the response from Apache is cacheable, Varnish stores it in RAM for fulfilling future requests.


Copy content of one node into different content type

You may be interested in Node Convert module:

  Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

Of course this does not clone, but you can use node clone to create a clone of the A content type, and then convert said clone to content type B.


Have you checked title field's settings section in views.
There is a option for "Style settings" you can check the option for restrict or add new html tags.


Node Reference to include an "Apply Now " link

I opened a discussion on this here http://drupal.org/node/1204554. There are a couple of approaches/solution that you may find helpful.

iRex


Front-end page to add content for a specific content type

You can simply go to achieve
Using the 'Admin Menu': Configuration > Site Information.

Under the Front Page section, change FRONT PAGE to content add information.

I think you should look into

Form Block module.

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Advanced Form Block module.

  Create any number of blocks with a particular node edit form.

  Create any number of blocks with a particular node add form of a content
  type.

  Create as many blocks as you like of each kind.


Fatal error: Class 'Drush\Log\Logger' not found

I had the exact same problem after updating core with drush (installed with composer). This is not something you should do if drupal is installed in the root directory, I've now learned. Reinstalling drush fixed the issue for me.

composer require drush/drush

Next step, I guess if we want to avoid this in the future, is to either move drupal to a subdirectory (as a dependency) or uninstall drush as a composer package and install it globally instead (the old fashioned way).


As far as a pre-built solution goes, you can try the Background process module, which would theoretically allow you to do something like:

$handle = background_process_start('drupal_mail', $module, $key, $to, ...);

Beyond that Drupal has nothing to help, so If you don’t use that module, just approach this as a general PHP task. The options and difficulties for async/background processing in PHP are very well documented around the web.


How do I install Drupal with a custom language?

Seems this works fine:

$ drush si standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' \
    --account-name=joe --account-pass=mom \
    --site-name=Example \
    --site-mail=noreply@example.com \
    --locale=it


How to load some selected files in Media Browser

This is little bit tricky. Media browser generally opens all the files. So, when we present the file field in the front end, we need to pass file type (Even we can pass fids too, after uploading the files).

On the views side either using views_query_alter or a filter in the views we need to filter them out.

Using this scenario we can alter media browser files options.


If these titles are on nodes, and you have the Auto Node Title module installed, you should be able to use [yyyy] for the current year in the replacement patterns section.  However, drupal won't automagically go and redo the title for you, but rather, you will have to resave it "next year" for it to take effect.


How to print date in format «long» on node.html.twig template?

you are not using the actual timestamp. Here's what you should do:

{% set date = node.createdtime|format_date('long') %}

See? You only need to replace created with createdtime.
Hope this helps.


Which modules should be listed as dependency of my module?

The Drupal.org .info file documentation does not define a dependency in itself other than stating a module cannot be enabled if a dependency is not present.

I guess you have to decide for yourself what you would consider a dependency. Personally, if a user needs to use Views in order to use your module than you would want to make sure it is installed.

If you don't want to make a module a dependency because it only supports secondary functionality in your module, you can use module_exists() to make sure your module doesn't die if the function it is calling is not there.


First, this is a poorly worded question, so I'm answering the questions you asked, probably not what you really want though..

Both 3-legged and 2 legged work in Services with the OAuth module and the Services_oauth module enabled. I wrote a lengthy article on how to set this up here, and documentation here

But that doesn't really answer your question in terms of If I can help you get started with your flow. I suggest you ask a new question with the problems you're currently having rather than asking if we can help you get started on a solution we know nothing about.

This may help you understand why this is an extremely tough question to answer. Asking smart questions


Subscribing the new user to a mailing list as a part of registration

The email address is already a standard user property. Using fields you can ask for permission about the mailing list.

You can use rules module (http://drupal.org/project/rules) to get notified of new registrations and find or implement the action for a mailing list registration.

Another option would be the simple news module: http://drupal.org/project/simplenews


Use part of Date field for grouping / sorting in View

Go to your view and add an extra date field, but hide it from display. Use that as the grouping field. Then create a views template for that field. You can look at the template name suggestions, something like views-view-field--field-date-1.tpl.php would work

The default content of that file would be

<?php print $output; ?>

But you need to replace that with

<?php print date('F Y', strtotime($row->node_data_field_date_field_date_value)); ?>

Where 'F Y' is the PHP date string format http://php.net/manual/en/function.date.php


You can use the Views Calc module for that. Here is an excerpt about it from the module's project page:

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).


There might be some problem with redirects. To overcome this problem, follow below steps:

Go to URL: admin/config/search/path/delete_bulk

Select option to delete all aliases.

Go to URL : admin/config/search/path

See if there are no aliases left, if any left delete them too.

If you have redirect module installed, go to URL: admin/config/search/redirect and delete all redirects if any.

Recreated all URL aliases, go to URL: admin/config/search/path/update_bulk and select desired URL aliases to be created.
See if problem is fixed. If you still have issues comment below.


Feasability of module or submodule for user picture migration

I hadn't realized that the dev versions of migrate and migrate_d2d now support migrating user pictures.

The UI asks for the location for files in the installation one is migrating from. In my case, pictures were stored under files/pictures but I only had to specify "...files". I don't know if it would work if user pictures are stored in a directory with a different name.

In any case, once I switched to the dev versions, it seemed to work.


How do I set a specific image header for each page?

After some many headache...
I believe I got what I wanted, thanks to Ivan.

  SubheaderBlock.php

<?php
/**
 * Provides a 'Subheader' Block
 *
 * @Block(
 *   id = "slssubheader",
 *   admin_label = @Translation("slssubheader"),
 * )
 */

namespace Drupal\subheader\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

   // get the node id if exist
   $node = \Drupal::routeMatch()->getParameter('node');
   $nid = $node ? $node->id() : 0 ;

   $outpout['id'] = array(
           '#markup' => $nid,
           '#cache'=>[
                 'contexts' => ['url:pager_id' ],
                 ]

       );

    return $outpout;
  }
}
?>

I get the id in twig with

{{ content.id }}

I checked with a a random number rand(1,100) it works perfect. There is one different cache per nid.

althought it works, I am not sure about the best practice for #markup and url:pager_id


How do I avoid a template get rendered from a preprocess function?

Why preprocess?

Blocks have language visibility. Just configure that block to be shown only in a specific language.


How can I restrict user access to view nodes based on field value?

You could use a programmatically solution using hook_node_access(), in this example the field_YOURFIELD is a checkbox.

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  $access = new \Drupal\Core\Access\AccessResultNeutral();
  if ($node->hasField('field_YOURFIELD')) {
    $field = $node->get('field_YOURFIELD')->getString();
    if (empty($field) && $account->id() != $node->getOwnerId()) {
      $access = new \Drupal\Core\Access\AccessResultForbidden();
    }
  }
  $access->addCacheableDependency($field);
  $access->addCacheableDependency($node);
  return $access;
}


I can't tell from the examples provided ... but if a View has no results from the database, then tokens are not replaced.


Users are getting spontaneously logged out

OK, I think I've got this figured out:

As part of the siteI need to be able to programmatically set user field values -- what used to be called "profile values" in Drupal 6. I looked around for some ways of doing that, and found a possible solution at http://drupal.org/node/1047600#comment-4094988, which recommends something like this:

$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($existing, $edit);

The instrumentation I did showed user_save was the guy calling _password_crypt(). My belief is that, somewhere along the way (either the method itself or the way I was using it), my call to user_save() was trashing/regenerating user->pass, leaving me in my unfortunate state.

So: I'm now doing the field-saving stuff in a way that doesn't involve user_save (some day I'll figure out this new entities stuff, but, in the meantime, I'm just bashing values into the database) and, so far, I'm staying logged in.  Hopefully this will solve the problem; thanks to all for your attention.


How to change a node add form without changing the node edit form

node_object_prepare(), which is called from node_form() (the form builder for the node editing form), executes the following snippet to verify if a node is being added, or edited:

  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

In your case, you could use code similar to the following one:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "rating_node_form") {
    $node = $form_state['node'];
    if (!isset($node->nid) || isset($node->is_new)) {
      // The node is new.
    }
  }
}


theme function not available, not called?

From the looks of it you've forgotten to register your theme function with the system using hook_theme()

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'cmis_browser_content_propertiesnewtest' => array(
      'variables' => array('cmis_object' => NULL)
    )
  );
}

After you clear the caches your theme function should be registered with the system and start working as expected.


How can I make teasers refresh when they are flagged?

Step 1 (PHP part):

You need to implement, hook_flag_javascript_info_alter() function, and pass in the refreshed teaset html, so that you can use this in js file.

function yourmodulename_flag_javascript_info_alter(&$info) {
  $content_id = $info['contentId'];
  $node = node_load($content_id);
  $view = node_view($node, 'teaser');
  $rendered = drupal_render($view);
  $info['rendered_node'] = $rendered;
}

Step 2 (JS) Part:

Now upon flagging, you will have the refreshed node html as data.rendered_node. So employing your js code you wrote above:

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  var node_id = data.contentId;
  var rendered_teaser = data.rendered_node;
  //here you have to check the logic, find the selector that is to be
  //replaced, and then replace that with the 'rendered_node' variable we declared above.

});

Please note that my intention here was to give you a direction and the general logic and not the exact code, so most probably you have to modify the above code to make it work.

UPDATE:

In the step 2 code, you see I got a variable node_id. That is the nid of the content that was flagged. In the html,  you must be having some class using that nid, may be "node-765"..where this 765 is the id. look for such a class. Once you have the class name, and say that class is of the form "node-nid-765". So we will check for that like this:

$('node-nid'+node_id).replace(rendered_teaser);

Again please note the class names are not exact and have been provided to give you an example.


Well, answering myself. Turns out pure Rules are rather not enough.
But together with Path Rules (https://drupal.org/project/pathrules) it works without a problem. So, question answered, issue solved. Maybe it will help someone.


How do I find if a taxonomy term is used?

If you have the term name, you can use the following code.

$nodes = array();

if ($term = taxonomy_get_term_by_name($term_name)) {
  $result = taxonomy_select_nodes(array($term->tid), 'or', 0, FALSE, 'n.sticky DESC, n.created DESC');
  while ($row = db_fetch_object($result)) {
    $nodes[] = $row->nid;
  }
}

if (!empty($nodes)) {
  // The taxonomy term is used from at least a node.
}


Retrieving users from Database on to forms

You have to use hook_webform_select_options_info() in your custom module.

I made my first module with that hook because i needed to achieve a similar thing but with people who were linked thanks to module relation. I show you what i did (i change the query to retrieve all users from the site, i'm not an expert in query). It was my first code, so it's not very optimize but it's work.

function my_module_webform_select_options_info() {
  $items['membres'] = array(
  'title' => t('Membres'),
  'options callback' => 'webform_membres_options',
  );
return $items;
}

function webform_membres_options($node)  {
  global $user;
  $store = array();

  $result = db_query("SELECT users.name AS users_name, users.uid AS uid, users.mail AS  users_mail
                      FROM {users} users
                      WHERE (( (users.status <> '0') ))");

 //Store mail|username in an array (good format for select options)
 foreach ($result as $row) {
   $store[$row -> users_mail] = $row -> users_name;
 }
 //All users don't have relationship so we have to check the length of array
 if (count($store > 0)) {
   return $store;
 }
     else {
   return false;
 }
 }

You'll see your list in Load a pre-built option list when you'll build your webform (after selecting "select options") Don't forget to put a default value for the select list.
After you'll see your list in the webform :


Not without code, but its fairly easy.

You could add a reference field to contact forms to your node type, and "view" the contact form. contact_storage provides a view builder that will display the form then. That doesn't work for your additional mail requirement, however.

To be able to do that, you need custom code to display the form, something like this in hook_node_view(). field_node_reference is an entity reference field that points back to the node. that will allow you to easily see for which node it was submitted and also use it later on to change the recipient:

  $message = \Drupal::entityManager()->getStorage('contact_message')
    ->create(array(
      'contact_form' => 'YOUR_FORM_ID',
      'field_node_reference' => $node,
      // You can generate a default subject or even hide it completely
      // and always use this value.
      'subject' => t('Contact about "@title".', ['@title' => $node->label()]),
    ));
  $form = \Drupal::getContainer()->get('entity.form_builder')->getForm($message);
  $build['yourmodule_contact_form'] = array(
    '#type' => 'details',
    '#open' => TRUE,
    '#title' => t('Contact the business'),
  );
  $build['yourmodule_contact_form']['form'] = $form;

yourmodule_contact_form can be defined as an extra field (hook_entity_extra_field_info), then you can conditionally display it using if ($component = $display->getComponent('yourmodule_contact_form')) { and you can configure the place and if it should be displayed per view mode.

The final piece is then to override the mail recipient of the sent mail using a hook_mail_alter():

function yourmodule_mail_alter(&$message) {
  if (!empty($message['params']['contact_form']) && !empty($message['params']['contact_message'])) {
    /** @var \Drupal\contact\Entity\ContactForm $contact_form */
    $contact_form = $message['params']['contact_form'];
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_form->id() == 'YOUR_FORM_ID' && $contact_message->hasField('field_node_reference')) {
      /** @var \Drupal\node\NodeInterface $node */
      $node = $contact_message->field_node_reference->entity;
      if ($node && $email = $node->field_email->value) {
        $message['to'] = $email;
      }
    }
  }

This could possibly be built in a generic way but it would require configuration for the mail and reference fields.


As you are looking to edit/override node template, it is suggested to place your changes into node.tpl.php where you will get $nid as out of the box. page.tpl.php will not give you node variables by default.

If you still you want to get your code on page.tpl.php you can get $nid from url like arg(1).

Let me know if I miss anything!


How to create field instance with display none programmatically

your question is not very clear.

What do you mean "display none"?

Make your field in the .install file.
Add a CSS file to your module info filefiles[]=mymodule.css
in the CSS file of your module .field-myfield {display:none;}.
clear your drupal cache

EDIT

I think you probably want to look at Field Permissions module.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


First you need to define region in your_theme.info https://drupal.org/node/171205#regions

for example

regions[search_bar]         = Top Search bar

then you probably want to output that region in your page.tpl.php:

<?php print render($page['search_bar']); ?>

to make it height = 50 px and width=200 px you need to write some css. You can also add some wrapping div with id:

<?php if ($page['search_bar']): ?>
<div id="search-bar">
    <?php print render($page['search_bar']); ?>
</div>
<?php endif; ?>


Delay in code changes on custom pages in drupal 8 in a docker environment

Your image is based on drupal:8.4.3-apache, which sets an opcache revalidate frequency of 60 seconds:

# set recommended PHP.ini settings
# see https://secure.php.net/manual/en/opcache.installation.php
RUN { \
        echo 'opcache.memory_consumption=128'; \
        echo 'opcache.interned_strings_buffer=8'; \
        echo 'opcache.max_accelerated_files=4000'; \
        echo 'opcache.revalidate_freq=60'; \
        echo 'opcache.fast_shutdown=1'; \
        echo 'opcache.enable_cli=1'; \
    } > /usr/local/etc/php/conf.d/opcache-recommended.ini

This means that if you access the same file within 60 seconds, it will be served from RAM instead.


Taxonomy view representative node contextual filter leads to incorrect results

First off do NOT put PHP code in the fixed value. This gets stored in the db which is a bad idea. Instead use taxonomy term ID from URL for the default value.

If that does not work as is use a hook. I would probably use hook_views_pre_view in this case. You can use the same code you have in your example to change your $args or $view->args can't remember which off the top of my head.


There is actually a bug in Search API 7.x-1.8.

The full-text views' filters handler is able to use only one exposed filter (the last one in stack, the previous instances are overwritten).

While it was a LOT of hacking in the Search API module, the simple answer is: you can use only one exposed Search filter in Views with Search API 7.x-1.8 without extensive PHP coding.


OK. Its not hard.

To achieve the same thing in angular (being served by drupal), have to:

get angular and bootstrap ui working.
create the  element in my view
add a function to the controller $scope to access $http ($http needs to be injected as a dependancy into the controller).

In my FAPI form I had a autocomplete_path defined:

 '#autocomplete_path' => 'agc/ac/contact/_',

So to access the same call back, in my Angular template:

Model: {{result | json}}

  <input type="text" ng-model="result"
   typeahead="suggestion for suggestion in cities($viewValue)">

The controller:

angular.module('contactFindControllers', []).controller('contactFindCtrl',
  ['$scope', '$http', function($scope, $http) {
    $scope.cities = function(cityName) {
    var path = '/agc/ac/contact/_/' + cityName;
    return $http.get(path)
    .then(function(response){
      // see note below regarding "_.values()"
      return _.values(response.data);
        });
  };

}]);

FYI: I used this as a starting point.

Note: my callback returns a JSON object (because I have non-numeric keys) not the array I needed, so I need to extract the values with _.values().
You many not need to use _.values at all (or if facing the same issue just
grab the values from the object or modify your call back to
return a json array)


How to setup external CSS and JS to prevent render-blocking from Google PageSpeed?

Defer for JavaScript is how to do js. CSS is a lot harder. You need to generate critical css and inline it and then still load the CSS in a deferred way. This explains how to do so with the 7.x version of AdvAgg; the 8.x version shouldn't be that far off.

https://groups.drupal.org/node/517292

Font's are their own special thing, the advagg relocate sub module handles the browser cache part, the advagg font module makes font loading async.

This is the easiest site to use to generate critical css
https://www.sitelocity.com/critical-path-css-generator but it might not give the best results.


How to get view name and display ID in template_preprocess_node function

I'm assuming you're using a view page to display your content type:

$route = \Drupal::routeMatch()->getRouteObject();
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');


Issue resolved. This was a combination of issues with file compression, max width dimensions and ram allocated to it.


How and where would I be able to enable/disable gzip compression?

Personally, I do not like the way Drupal handles output compression; I take care of this outside of Drupal.

On the Drupal site, I add

$conf['page_compression'] = FALSE;
$conf['css_gzip_compression'] = FALSE;
$conf['js_gzip_compression'] = FALSE;

to settings.php, and this to a custom module to show that this is disabled:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}

This is to also prevent accidental double output compression, which can be very hard to diagnose if you don't know about the symptoms.

Then, in my Apache config, I do

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>

</IfModule>

This lets Apache do the output compression by MIME type, and also make sure all text based output gets compressed.  This is adapted from an older version of the HTML5 Boilerplate project's .htaccess file, which now lives in a separate project.  I also add in their directives for cache control, and a few other things.  I keep all of this in an individual file, that I then Include in my virtual hosts.

The downside of this is that the server compresses each request, but it works well for my sites and my clients.


Display only taxonomy parents from an entity reference field

Create a custom view mode for taxonomy terms and display the taxonomy term as "rendered entity", using your customized view mode.

Then create a Twig template for that special view mode: Assuming your newly created view mode is onlyparents, create a template taxonomy-term--onlyparents.html.twig

There is no field like "parents", so there also is no pre-built field formatter for this. To get the parents, you will need to do some manual preprocessing like

function mymodule_preprocess_taxonomy_term(&$variables) {
  $term = $variables['elements'];
  $parents = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadAllParents($term->id());
  $variables['parents'] = $parents;
}

In Twig you can do something like

{% for parent in parents %}
  {{ parent.label }}
{% endfor %}


Replace node add/edit form with a custom form

Try the pathauto module. You can use the Url Aliases page to add an alias for all of your custom node edit links.


The line

if ($page_new[$element] == ($pager_total[$element] - 1)) {

Will never fire because of the earlier line:

if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {

So if the current page is equal to (or higher) then the last page it will skip the whole code.

Try removing that line (and the corresponding closing bracket }).
I hovever don't know if it will keep working then because the following function seems to be assuming it can never load a pager higher then the current page. So prepare for some unexpected behavior.

$page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);


Aha! I guess I posted this question a little too quickly! The path to the drush command can be altered through editing the .bash_profile file.


Can't get drush to work after moving to Acquia Dev Desktop

Use the console coming with ADD - launch the console from the ADD client. Using that console everything is correct setup. You might of course get everything to work inside your "Bash" (which it think you are using since you talk about the "which" command), but it kind of removes the whole point of using ADD - that everything is working out the box.

PS! I use Git Bash for my Git work and the ADD (cmd) console for Drush work. Then I don't have to think ;-)


How to implement custom theme functions (theme_textfield, theme_form_element) for some forms only?

Those theme functions don't get a reference to the form where the element is used. Therefore, they cannot be used to alter an element for a single form.

Every form element accepts #theme, so you can alter the #theme function used for those form fields in a single form. This is what Drupal does in node_filter_form().

  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );

theme_exposed_filters() then does its job.

  $form = $variables['form'];
  $output = '';

  if (isset($form['current'])) {
    $items = array();
    foreach (element_children($form['current']) as $key) {
      $items[] = drupal_render($form['current'][$key]);
    }
    $output .= theme('item_list', array('items' => $items, 'attributes' => array('class' => array('clearfix', 'current-filters'))));
  }

  $output .= drupal_render_children($form);

  return '
' . $output . '
';

Unfortunately, this doesn't work with theme_form_element() or theme_form_element_label().


System settings form data access validation

It looks like the Field Permissions module is the answer to your case.

UPDATE: You could also use '#access' in your field definition, see this post


How to add another navigation bar/block at the top of your site?

The layered navigation that you're asking about (where you always see primary menu items, but the secondary items are related to a particular primary item and they only show when their parent is active) is called Primary and Secondary menu in Drupal.

Drupal 7 Menu settings Primary and Secondary navigation

In Drupal 7 and older there was a Menu setting where you could choose which menu to use as Primary and Secondary level of navigation:

You could use separate Menus for Primary and Secondary levels, but it makes more sense to create one Menu with two or more levels (depths):

Then you would choose the same Menu under both Menu settings and Drupal would automatically only use the first level for Main links and lower levels for the Secondary links.

When you have that set up, and if you have the Main and Secondary links available and enabled in your theme:

you will see the Secondary items related to the parent item when you visit the parent page. Secondary items will appear in the place where the theme predicted it. In Bartik it's at the top right corner of the Header:

Check out this question: How can I make my menu children display horizontally below my main menu?

Drupal 8 Menu blocks configuration

Drupal 8 made changes to this system: Global menus (primary links, secondary links) have been converted into blocks.

This means that in Drupal 8 you still create a Menu with more than one level for your navigation, but the theme won't have a setting to display them or not (under Appearance). Instead, you will go straight to Blocks and place two of the same Main navigation blocks in regions of your choice. You can even include it twice in the same region which can be useful in your case where you want them one below the other.

Then configure each Menu block differently. The first one should always be visible and only show one level (image from D8 Docs: Menu Configuration):

The second one should only show when the parent from first level becomes active:

Although there are no theme settings anymore to turn on special areas that are styled specially as primary and secondary links, themes can still provide this through special regions. Bartik in Drupal 8 has regions called Primary menu and Secondary menu that look very similar to what they looked like in Drupal 7:

If you're creating your own custom theme you might want to create a special region for the two menus that would be displayed on top of the page.


How can I create a view that displays the most popular nodes based on an outgoing link?

yes it can be done in a number of ways... some options:

1) add a JS onclick="" to the link which goes to a function that causes an ajax call to the server. The server would then take in node information and using something like the Flag Module:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

to trigger a counter which can then be easily used in Views.

2) adjust the link direction to an internal proxy page:

<a href="/mymodule/proxy?url=<?php echo $node->field_download_link['und'][0]['value']; ?>">

The proxy page would have a callback function that again uses Flag or similar to track the click and then redirect the page to the provided url.

Option 2 is probably the better of the two, but it depends on the set up, and whether or not you want a redirect, etc.

I can give more specific guidance if you decide to go with one of these.


What about a taxonomy vocabulary for the ingredients list, and then just reference those taxonomy terms in your meal node?
You could try the Insert View module, create a view with whatever other nodes you want, and then display it at the right place in your node
If you want something a bit more complex, you could relate the meal node with the ingredient nodes, and collect them with a view, and then use Insert Views.

As a general note though, Views sounds like what you want to use -- it's perfect for that collecting of different information from other nodes and displaying it.


Changing which content appears at which parts of site

There is many ways to do this:
- you might use the arg() values and act based on that

        if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'YOUR-CONTENT-TYPE') {
               // do something
         }

or you can use template_preprocess_node function in your theme, and act based on the node values.


How do I add tags to the taxonomy data via node and the fields?

In drupal 7, Taxonomy terms are attached as regular fields. So $node->taxonomy is no longer a standard property that Taxonomy module picks up.

If your field name is field_beaches_tags, assign tags to the node as below.

$node->field_beaches_tags[$node->language][]['tid'] = 23;

Note that the 23 above is the term ID of the taxonomy term.
If you have an array of terms, you can assign all of them like below:

$terms = array(23, 45, 678, 1212);
foreach ($terms as $tid) {
  $node->field_beaches_tags[$node->language][]['tid'] = $tid;
}

Keys in the $node->field_beaches_tags[$node->language] array will be used as delta values of the field.

Create a new taxonomy term

$term = new stdClass();
$term->name = ‘My New Term Name’;
$term->vid = 'vocabulary_id';
taxonomy_term_save($term);

Now, $term->tid will be populated with the new term ID that you can use.
See taxonomy_term_save() for the API doc.

taxonomy_get_term_by_name() can be used to load terms by a given name.

$term = taxonomy_get_term_by_name('my existing term name', 'beach_terms');
// $term->tid will now be in place.

Your overall code can be like the following.

$terms_given = array('Miami', 'Colombo', 'Pizza');
$node = new stdClass();
$node->language = LANGUAGE_NONE;
$node->promote = 0;
$node->uid = 1;
$node->type = 'content_type';

foreach ($terms_given as $term_name) {
  $terms_matched = taxonomy_get_term_by_name($term_name, 'beach_terms'); // "beach_terms" is the machine name of vid 1.
  if ($terms_matched) {
    //We blindly use the first match. Not very elegant.
    $first_term = current($terms_matched);
    $node->field_beaches_tags[$node->language][] = (array) $first_term;
  }
  else {
    $term = new stdClass();
    $term->name = term_name;
    $term->vid = 1; // Vid from the question.
    taxonomy_term_save($term);
    $node->field_beaches_tags[$node->language][] = (array) $term;
  }
}


How to create an RTL CSS file (style-rtl.css) for Drupal modules

Solution

Create the flipped rtl css (for example, based on the structure I've described above) and then go to your theme's or module's folder, and there go to the libraries file (like libraries.yml) and create a reference in the end of the library ---> To your new file. Here is an example from the libraries file of one of my modules (admin toolbar):

Note:

The file might not work correctly if you will indent your syntax using the tab key or the space key. If there is a problem try the other of these two indenting options (some files can't work well when you pick a specific method for indenting them - It has to do with the structure of the file types themselves).


Creating a list of child taxonomy terms with Views

I may be wrong but I guess you have created a View of type 'content' while your intention is to list 'taxonomy terms' (I understand that Child # are taxonomy terms). The type of a View is indicated by the label within parenthesis, above the top of the admin lightbox. If my assumption is right, you would want to create a new View of type 'taxonomy term'.


The hook_mail headers need to be like this:

$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';


Create A Block To Add Field Collection Item

Have you tried the Views module yet? You can easily create blocks and add whatever field items you want through it. It's a very powerful and at times complex module so you can refer to the nodeOne video tutorials. Good luck!


You can use Blockexport

Functionality List

It will import all system specific block into a feature.
Import all custom blocks within a feature.
Import all system blocks associated with content type
Import all block roles
No configuration is required.
This module not create any table in your database to minimise the performance issue as much as possible.


Adding a #suffix to a Drupal Product Form Payment Method Radio

The issue here could be the type of element $form['commerce_payment']['payment_method']['#options']['paypal_commerce_payment_paypal_wpp'] is.

Is paypal_commerce_payment_paypal_wpp the key of one your options?

Have you tried #description?


Views filter group "or" operator not working

I got this working — I had to check "distinct" under Advanced > Query Settings, uncheck "reduce duplicates" for the Primary Feature filter, check "reduce duplicates" for the Secondary Feature filter (set up as a single filter using the "is one of" operator with all three values selected), and clear the cache. Now it's working fine.


Getting $content of content type in template.php

I'm not sure, if this is what you are looking. But if you want to embed a node-add form you could use the following code.

<?php
$node = new stdClass();
$node->type = 'machine_name_of_your_content_type';
module_load_include('inc', 'node', 'node.pages');
$output = drupal_get_form('machine_name_of_your_content_type_node_form', $node);
print $output;
?>


A page to display various membership types to choose from?

You will need to create a custom module to do it exactly as you desire, and you probably won't find anyone here to do it for you, so you need to do more research if you go that approach.

A simpler approach does not require a custom module:

create a block with the three "tables" as images (to be prettier in my opinion)
add that block to the content-top of whichever theme you have
restrict the content to only show on the user/register page
under admin/config/people/accounts/fields add a new field of type list(text) that includes the three types of account, required at registration
if desired - set a Rule to act on new account registration to take care of role changes or other account differences based on the value of the drop-down selection

This will show the three options at registration and require the user to choose one of them - the Rules will then act on that choice to change the account as desired


Drilldown search with Search API and Facets

I use CER,  "Corresponding Entity References" to achieve similar results, but not with Search_API.. for that, I just tell the search-page to render the "teaser", and modify the teaser display to include the entity_reference list of associated entities as links, that way, if you search for a "Kustomer", it will show you a list of Kustomers and each project will also appear as a list of links underneath the title, or visaversa, you can also use Facets to filter by taxonomy etc.. handy!


That's quite tricky because the taxonomy system doesn't seem to like looking for children.  You might need to use Page Manager and the ctools context system to achieve this.

Create a 'page' (url) at /categories/%term-id that has the term currently being viewed as a context
Create a view pane that requires a context of parent term id which shows all nodes that have the taxonomy term subordinate to the parent term
use the view pane in your 'page' and set the context to the term being viewed

There's a rather good example of a similar use case here (watch the whole series, it's really good).


How to sum vote values from a single field?

Solved it by removing the sort criteria. Stupid mistake... :)


How do you theme a pager in a specific View?

each view has own class like .view-id-name
so this class or id you can use to CSS your pager for each view


Create jump menu with more options using programmatically

See below code !

$form = ctools_jump_menu(array(), $form_state, array($url => t('Jump!') , 'http://www.google.com' => 'Go to google'), array());

OR

$options = array();
$options[$url1] = $label1;
$options[$url2] = $label2;
$form = ctools_jump_menu(array(), $form_state, $options, array());

Third argument of ctools_jump_menu is $select which is

  An array suitable for use as the #options. The keys will be the direct
  URLs that will be jumped to, so you absolutely must encode these using
  url() in order for them to work reliably.


Commerce Kickstart Product: URI links to admin

Please see my answer at https://www.drupal.org/node/1970482#comment-9252269 and try to avoid posting the same support request in multiple support forums.


How do "Order Types" and "Order Item Types" work?

What rules does Drupal use to decide which Order Type it's dealing with?

That's determined by order type resolvers (implementing OrderTypeResolverInterface in this case). Such resolvers are given an order item, and must use that to determine the type of order.
Out of the box, the default resolver (DefaultOrderTypeResolver) uses the bundle of the given order item, which will be an order item type ID, to load that item type entity, and get the associated order type ID from it.

At what point in the is this decision made?

There are probably multiple places that decision is made (creating orders in the admin UI for example), but in terms of the cart, it happens when the cart is created, which in turn happens when an item is first added to it via the standard AddToCartForm submission.
So I think it's fair to say that the type of an order that originated from a cart will always be the type associated with the first item that was added to it.


Visit admin/config/regional/language and select an admin language
Visit admin/config/regional/language/admin_language and enable Use administration language for the core toolbar


How can I migrate URL fields to link fields?

Have to create solution based on https://www.drupal.org/docs/8/api/migrate-api/writing-migrations-for-contributed-and-custom-modules#field-migrations

<?php

namespace Drupal\custom_url_migrate\plugin\migrate\field;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;

/**
 * @MigrateField(
 * id = "url",
 * core = {7},
 * type_map = {
 * "url" = "link"
 * },
 * source_module = "url",
 * destination_module = "link"
 * )
 */
class url extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function getFieldWidgetMap() {
    return [
      'url' => 'link',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldFormatterMap() {
    return [
     //'default' => 'link',
      //'url' => 'link',
      'url_external' => 'link',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function processFieldValues(MigrationInterface $migration, $field_name, $data) {
    $process = [
      'plugin' => 'sub_process',
      'source' => $field_name,
      'process' => [
        'uri' => 'value',
      ],
    ];
    $migration->setProcessOfProperty($field_name, $process);
  }

}


How can I prevent the display of CAPTCHA for other forms except the login form?

The message "CAPTCHA: no challenge enabled" indicates, that the form in question is not protected by a captcha.

This message is shown to site administrators and users with the "Administer CAPTCHA settings" permission only. It is intended to ease administering captchas on the form. You could, e.g. click the message to open a link that allows you to enable a captcha for this form.

If you don't require these administrative links, you can disable them within the captcha module settings. In your administrative back-end navigate to Configuration > People > CAPTCHA.

Locate the option "Add CAPTCHA administration links to forms", uncheck it and save the settings. The administration links should be gone.


use hook_view_pre_render and in this, you need to check for that value in if condition...


DatabaseSchemaObjectExistsException: Table products already exists

From your previous questions it looks like you're using Drupal 7, but the above code is partly for Drupal 6.

You don't need to add/remove the schema manually any more in Drupal 7; implementing hook_schema() is enough. Drupal installs the schema for you, and then when you it hits your implementation hook_install(), the table does already exists so it throws an error.

Just remove the calls to drupal_install_schema() and drupal_uninstall_schema(), uninstall the module and try again - it should work fine.


How do I log in as a different user when there isn't a login link on the front page?

Click logout - usually in the top right corner (but may vary depending on theme); /user/logout is the address.

Then log back in (from /user) with your administrator credentials.


Rules with Commerce Discount for a certain type of product.

You have a rule that reacts on "Calculating the sell price of an item" and a condition of "is of type BookDisplay (whatever the real display is called)". Then in actions you just apply the discount.

I have this working on a site.


drupal store and retrieve variable from $_POST array

you should use print_r($_POST['variable_name']); to get the post values you sent form the form.

and add

if(isset($_POST['variable_name']) && !empty($_POST['variable_name'])){
    $values_post = $_POST['variable_name'];
}

to avoid unwanted notices.


How can I define a selection rule to use for Panels variants in code?

You can add Panels selection rules.

However, in your case, have you tried just calling a module function instead in your PHP code for the selection rule?

e.g, call a function defined in a module:

return my_module_selection_rule('foo');

instead of all the raw code there.

That way, it can be updated once in the module codebase.

I use that technique a lot for views php contextual filter handling code.

If so inclined, see

panels/plugins/task_handlers/panel_context.inc

for the default selection rules plugin definition. and

ctools_context_handler_edit_criteria

for the default form builder function for the selection rules.


How to add field content as class in Twig?

item.content works only in the items loop, but don't try to put rendered output in a class name. Use the field value instead, which you can get through the field object #items stored in a field template inside of the variable element:

{{ element['#items'].value }}

or from a different field of the parent entity:

{{ element['#object'].field_example.value }}

Depending on the field type replace .value with a different property, for example for a reference field to get the target id or the label of the target with .target_id or .entity.label.

When you have found the field value build your class name:

{%
  set classes = [
    ...
    'icon-' ~ element['#items'].value|clean_class,
  ]
%}


Why this callback doesn't show all node form?

The following line in your code is wrong.

$new_node->type = 'signup_node_form'

What you are setting as node type is really the form ID, not the content type ID. If you look at the code of node_add(), you will notice the executed code is the following one.

  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

$type is the parameter the function gets.
If you look at the content type IDs used in Drupal, none of them contains the string "_node_form"; differently, node_add() would call drupal_get_form() passing something similar to "story_node_form_node_form" as form ID. As the modules that add fields to the node edit form check the content type of the node, it is probable they don't add fields for a content type they don't know. That is plausible, as differently it would mean that a taxonomy term field, for example, would be added to nodes for which it was not supposed to be added.


How to conditionally load javascript file on view page

This should work:

/**
 * Implements template_preprocess_views_view().
 */
function themename_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'view_name') {
    // Standardize the output for rows.
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/js_name.min.js', array('scope' => 'footer'));
  }
}


So this is an important question for Drupal Commerce: What is the best practice way of creating a related products block per content type?

Fortunately, there's a simple answer. Just add an entity reference field that references the product displays:

Add an entity reference field called "Related Products" on your blog content type.
Configure this field to only show the product displays (not product entities).
Hide this field on the "Manage Display" tab.
Create a view block that targets your blog content type.

Edit the view and add a contextual filter for "Node ID" and provide the default value to come from the URL. This will allow the block to bring in the node you are viewing if you are viewing your blog post.
Add a relationship on the "Related Products" field you added to your blog content type and rename it "Related Products" and require that relationship.
Add a field, it should be your product reference field for your product display. For me, it's called "Product" but it could be called something different depending on your setup. NOTE Make sure you set it up to use your new relationship.
Modify the title to use your new relationship.
Set the View Block to display in a sidebar or some region that is available on blog posts.

And BAM! there you have it! A step-by-step to show off related projects in a block on your blog posts.


Using Flags to remember not only the node, but also its attributes

You could try some Rules trickery and save the attributes data to the users profile upon the flag action. However, I really think you will be best going down the custom module route because it is rather specific.

A very basic outline of the module would be something like the below:

Create your .info file to provide Drupal the details of your custom module
Create a .install file to create a db schema to contain the additional data, ensure you include a fcid row (to reference to the flag "flag_content" table).
Create your .module file with function which hooks into the flag actions with appropriate if statements to refine the scope to these products. In this function you will want to save the additional "attributes" data to your new db table with a reference to the fcid to tie them up.
While in your .module file, if flag exists you will also want to perform a hook_form_alter on the products to change the default values to that which has been stored in the database.

I know my answer is very brief with regards to build the module but that is a bit beyond the scope of an answer here and I think that highlights the Drupal Way for what you will need.


Translation showing up in backend but not on display or user registration

do you also use the i18n module ?

tmgmt is not enough !! this module is meant to help the translators and to use external translations servives.

probably you need to enable more translation modules from i18n like field translations, entity translation (seperate module) etc.


compare terms from userterm and node term

Found the solution after seaching around.
node term id:

$node_tid = field_extract_value('node', $node, 'field_your_taxonomy_reference_field', 0, array('key' => 'tid'));

user term id:

//load current user
$user_info = user_load($user->uid);
$user_term_id = $user_your_taxonomy_reference_field['und'][0]['tid'];

now set logic
    if  ($node_tid == $user_term_id) {
    print "show link";
     }


How to clean up multiple Drush Composer installs?

composer global remove drush/drush will get rid of either the ~/.composer or the ~/.config copy, depending on your current configuration.  However, if you are no longer using the components that you installed via composer global, you can just use rm -rf to delete the directories you don't need, which is vendor and bin in ~/.composer and ~/.config.


Is Git now the only way to install Drush?

Drush moved to GitHub a few weeks ago.  The official home is now: https://github.com/drush-ops/drush

The current preferred method is to install with composer:

composer global require drush/drush:6.*

If you are working with Drupal 8, or need a patch that hasn't been backported, then you can work with the latest version:

composer global require drush/drush:dev-master

You can also use composer to install a particular version.

You can install it manually; and normal GitHub retrievals apply.  You can download the master (link is on the main page), or clone the repo locally.  When you clone locally, you can checkout any tag you want.

I have it installed in my home directory, eg

cd ~
git clone https://github.com/drush-ops/drush.git drush

After, you need to run composer

cd ~/drush
composer install

I then put ~/drush/ in my $PATH:

export PS1=$PATH:~/drush/

Everything should work as normal.

Sidenote.  Even if you don't want to contribute back, tracking your whole site with git is a great way to handle dev/live, and for backing out oopsies.


Caching, caching, and caching.

Some suggestions I have previously given to a similar question on d.o.

Putting Varnish or another reverse-proxy in front of your http-deamon is probably the single best thing you can do.
During DrupalCon Copehagen, Rasmus stated that using a php opcode cache, such as APC, is one of the best things you can do to speed up PHP in general. Performance improves with newer versions of PHP. There is also additional benefits to upgrading PHP when you upgrade Drupal. From 6 to 8, Drupal will go through a major shift towards object orientation, which is also were most performance improvements happens in the newer PHP versions.
Memcache is a popular choice for speeding up cache, by putting the cache into memory instead of disc.
Panels + Caching combined with Cache actions can increase performance significantly, even for logged in users, as it supports quite complex logic.
The Entity Cache is a nice and zero-conf speed boost for anyone using Drupal 7.
Write-heavy sites have fewer "well established" solutions. Some options include.

Moving frequent writes entirely, for example statistics, somewhere else, such as google analytics.
Caching frequent write operations with a custom solution in something like NodeJS that will write to DB once every Xth second.
Sacrifice the sacred ACID, and use a database like MongoDB. (See Berdir's comment below)
Cluster your SQL-database. Do reads from one database, writes to another. This is native to D7 and Pressflow can help with that in D6.


Custom form not being validated on submission

Is this because the form is being submitted to an external URL?

Yes, the submit handler for a form in your website won't be executed unless that form is submitted back to your website.

  If that's the case, how to I validate a form before submission?

If you mean server-side (non-JS) validation, and you want the user to continue on to the remote URL as if they'd submitted the form as normal, you can't. There's simply no way to do that.

If you don't need the user to be forwarded on to the remote URL after submission, and the remote website allows it, you could just send a POST request from the submit handler with the data you've received from the Drupal form submission.

If you're even luckier, they'll have an API you can use instead.


How to link up a view created page using hook_menu

hook_menu() is not required. We can set the tab, or link, in the view itself under page settings -> Menu.

I have used the menu options of the view to add the item in my user navigation.


Simply you can do this by using Blind Carbon Copy module.

  The BCC module injects a BCC header in all e-mails sent by Drupal,
  which allows you to receive copies of all e-mails sent by your
  website.


Probably you put the preset values in the default values of form elements. They are at this point only in $form.

The values in $form_state are filled after the form is submitted, as a result of a GET/POST request.

But then your code, that calls the formBuilder, has no longer control. This will be handled by the submit method you have defined for the form.


Caching decrease your page load time and speed up your site. It is used especially when you have images, maps, videos and audio on your page. We can use drupal internal cache or integrate other caching tools like APC, Mem Cache, Varnish with our drupal site.

Why we clear cache?
 When we made some new changes in our theme or code, so to test them we clear old cache so that old data will be removed from cache and new data will be loaded to be displayed changes.


HTML inside mini-pager navigation control labels

I just spent the last 2 hours trying to solve the same problem, using many different approaches, but I finally managed to get it right.

You just have to override the theme_pager_link function in your theme by copying the code content to template.php and change the return (last line), removing the check_plain() function of the $text variable, leaving it like:

return '<a' . drupal_attributes($attributes) . '>' . $text . '</a>';


Hide/disable EDIT & DELETE links in menu-customize form

You can create a small custom module and implement hook_form_FORM_ID_alter().  Below is a quick example for Drupal 6:

.module file

<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_menu_overview_form_alter(&$form, &$form_state) {
  GLOBAL $user;

  // Check if user has a certain role or not and menu is primary links
  // Change ROLEID to the role id you want operations hidden from
  if (!array_key_exists(ROLEID, $user->roles) && arg(3) == 'primary-links') {

    // Hide edit/delete menu operations
    foreach ($form as $key => $ele) {
      if (substr($key, 0, 5) == 'mlid:') {
        unset($form[$key]['operations']);
      }
    }

  }
}

Change YOURMODULE to the name of the module you are creating.  For assistance creating custom modules, see the Module developer's guide.

To work in Drupal 7, I believe all you would need to do is change arg(3) to arg(4) due to the path changes.