How to always show Save as ... when download a image file in Webform result?

This is technically not a drupal specific issue it is just how browsers deal with certain file types on the web in general.

Also note that you can right click a link to save the file always, so if this is an admin only feature then maybe that is sufficient?

If you are using Drupal's public file system for the images then it is possible to change your .htaccess file to change the behaviour of certain file types.

For more info on that see: Force files to download instead of showing up in the browser.

The .htaccess method should be the best performing and most reliable method, however if there is any reason you don't want to do it the .htaccess way there are a couple of drupal module that can help.

The File Force and Download File modules will allow you to configure file downloading however if you are making custom links to your files (for example if you are entering links directly into a text field or in custom code) you have to use a different url for the images to make sure that the links use the module's functionality, so be sure to read the documentation for whichever module you are using.

The modules are quite similar so use whichever you prefer.

[Edit]
I just remembered you are interested in webform related links.
Unfortunately since the current version of webform doesn't use Drupal's normal fields it won't work properly with these file downloading modules out of the box.
A feature request for the modules will be needed to add webform support.

Alternatively you could modify your webform links to use the special formatting the download module you are using supports.

For example, overriding the themeing of the webform file display like this would work if you are using the file force module:

/**
 * Format the output of text data for this component
 */
function THEMENAME_webform_display_file($variables) {
  $element = $variables['element'];

  $file = $element['#value'];
  $url = (!empty($file) && !empty($file->uri)) ? webform_file_url($file->uri) : t('no upload');
  return (!empty($file) && !empty($file->uri)) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('query' => array('download' => '1')))) : ' ';
}

It would be a similar process with the download file module.


Views Block Caching issue for not logged in User

I have found out the issue. Views Query caching and Render Caching are not related. If we set render caching higher than query caching then Drupal will always fetch from Render cache and hence the result will remains. So its recommended to set both as same values. I modified the same to 15mins Query caching and 15mins Render caching.


What is the convention for naming routes?

By design, the route name should NOT mirror the path.  You want to be able to change the path without breaking the route name, which is why other code in the system should refer to the route name only, not the path.  Having a route name that maps directly to the path is akin to a CSS class named .left-align-blue :-)

Some of these conventions are still shaking out.  However, for the typical case the recommended pattern is $module_name.$something_meaningful.  So in your mymodule module, you'd have routes like:

mymodule.settings
mymodule.advanced_settings
mymodule.status_page

And so on.  Note those tell you little about the path.  That's by design, as above.

For entities it's a little bit trickier since core has the advantage that most entities are the same name as the module.  Contrib doesn't always have that.  I would recommend either $entityname.$operation or $module_name.$entityname_$operation.  (I don't think core has any double-period route names at present, but I could be wrong.)

So if I were writing a module with a new entity called "nerd" (it's a candy site), I'd have:

nerd.view (for the page that lets you view a nerd)
nerd.edit (for the edit page)
nerd.delete (for the delete confirmation page)

And so on.  Make sense?


Re-write the output of taxonomy_term_page() without hacking core

You can do it with preprocess page something like this:

function themename_preprocess_page(&$vars) {
  if  (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    unset($vars['page']['content']['system_main']['term_heading']['#prefix']);
    unset($vars['page']['content']['system_main']['term_heading']['#suffix']);
  }
}

in your theme's template.php

I believe system_main could be called something else, depending on your site setup.


I found 2 solutions to this:

Solution one

Use hook_custom_theme(): see hook_custom_theme()

function mymodule_custom_theme() {
 $use_admin = workout_when_you_want_to_use_admin(); //true or false
 if ($use_admin)
   return variable_get('admin_theme');
}

Solution 2 (preferred)

Ensure that the user account has the permission View the administration theme attached to their role.


Unable to retrieve checkbox values from a template file

Checkbox values are preprocessed so only checked ones you can get in your twig:
I think you need to preprocess your field by implementing hook_preprocess_HOOK to add unchecked ones to your variables something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == "field_room_category") {
    // Node object.
    $node = $element['#object'];
    // All allowed values in the field.
    $allowed_values = $node->field_room_category->getFieldDefinition()
      ->getSetting('allowed_values');

    // Checked values.
    $checked_values = array_filter($element, function ($key) {
      return is_int($key);
    }, ARRAY_FILTER_USE_KEY);

    for ($i = 0; $i < count($allowed_values); $i++) {
      // If the checkbox already checked add is_selected as true.
      if (isset($checked_values[$i])) {
        $variables['element'][$i]['is_selected'] = TRUE;
      }
      else {
        // If the checkbox not checked add the item with is_selected as false.
        $variables['element'][$i] = [
          '#markup'       => current(array_slice($allowed_values, $i-1, 1, FALSE)),
          '#allowed_tags' => [],
          'is_selected'   => FALSE,
        ];
      }
    }
  }
}

now in your twig you can do something like:

  {% for key, item in element if key|first != '#' %}

       {% if item.is_selected %}
           {{ item }}
       {% else %}
           {{ item }}
       {% endif %}

   {% endfor %}


How can I pass parameters to allowed_values_function for a field?

It's undocumented because it's not possible with core classes.

The options.api.php file refers to that callback as follows:

  That function will be called:

  either in the context of a specific entity, which is then provided as the $entity parameter,
  or for the field generally without the context of any specific entity or entity bundle (typically, Views needing a list of values for an exposed filter), in which case the $entity parameter is NULL.

There's no mention of being able to pass arbitrary parameters along to it. Indeed if you look at the invocation in options_allowed_values

$function = $definition->getSetting('allowed_values_function');
...
$values = $function($definition, $entity, $cacheable);

You can see that there's no scope for passing extra params at all.

Hopefully you'll be able to get the required context from the entity, otherwise you'll need to find another way to make it available to your callback function.


Using a node editing form on a page that not a node edit page

'file path' => drupal_get_path('module','node'),
      'file' => 'node.pages.inc',

needs to be added to the array.


Add Nid as field,
Set Label to Operation (or anything you want ),
 in Rewrite results section

check Override the output of this field with custom text  and
enter Edit text.
check Output this field as a custom link and in the input box
enter  admin/mymodule/[nid] .

save the field and enjoy the power of views rewriting.


What is the Correct UID path whilst using Ubercart Affiliate in Custom DB

I resolved this by using the ME Alias module which allow the insertion of the said UID into the path I required for all users.


Custom formatting of tokens for date fields

The Token module added direct support for datetime and daterange fields in December 2016. See https://www.drupal.org/project/token/issues/2786181.

You should be able to use something like [node:field_datetime:date:custom:Y]


Exposed filter - based on first three number in Zipcode?

Please check this link

Is has an example how to implement query alter having exposed filters.

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->id() == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}


How do I get the node ID from the view's URL?

If the view uses fields, you can add a field labeled Content: Nid - and either build the link in the template by yourself or try to Rewrite the field in the Views admin UI. If the View uses display views, such as Teaser, you should be able to use the $node variable in the teaser (in this case) tpl file.


enable jquery ui effects in theme .info file

No, it's not possible to add a Drupal library through a module or theme's .info file. You can add single CSS/JS files, but not a defined library.

That means it's physically possible to download separate copies of system libraries and include them statically in your theme, but you should not do this. It's not the 'Drupal' way, and it makes things very difficult to maintain.

You're right in thinking the logic shouldn't be in your page.tpl.php file, it should rather be inside your theme's hook_preprocess_page function in the template.php file.

That way the library will be added in time to be included in the page, you maintain a nice level of separation between logic and display, and your theme will be protected in the case that core updates need to be applied to the libraries you're using.


Twig find if a css class exists in a tag

You could use hasClass to find the CSS class in a specific tag
eg. {% if body.attributes.hasClass('new-class') %}


Views exposed filter autocomplete weird function() code

I do not think it is a major problem.  I had a similar problem a while back ( I don't remember how I cleaned it up :( ).  I would recommend you do check on another browser, but also try running update in the URL  (example.com/update.php) this script makes certain that all DB updates of  modules are completed.  If it persists, you may want to visit the Views issues site at Drupal.org.

Please post back on this page with what worked.


Adding column in Views for completed submission plus several days

I have solved my own problem. Using Views PhP module.
Add field Global:PHP,
in the output code box:

<?php
$correctdate = $row->completed;
$correctdate1 =strtotime("+7 days", $correctdate);
$cdate = date("j/n/Y - g:i a", $correctdate1);
echo ($cdate);
?>


Drupal 7 views - Contextual filter content: Nid content id from url

Let assume that you are using "Content: Nid" exposed filter.

Edit settings of your exposed filter and expand "More" section. If you choose "Exclude" check-box then it will show all nodes except current one.

Please see screenshot - how it used to be.


Trigger Emails/Handlers on Webform submissions update

The below code is untested but should point you in the right direction.

// Get a handler.
$webform_submission = WebformSubmission::load(WEBFORM_ID)
$handlers = $webform_submission->getWebform()->getHandlers();
$handler = $handlers[HANDLER_ID];

// Invoke submit form.
@see \Drupal\webform\Plugin\WebformHandlerInterface::submitForm
$form = []; // Might need to get the $form.
$form_state = new FormState(); // Might need to be build the form state.
$handler->submitForm($form, $form_state, $webform_submission);

@see \Drupal\webform\Entity\Webform::invokeHandlers

@see \Drupal\webform\Entity\WebformSubmission::invokeWebformHandlers


How to troubleshoot Rules when a required variable for an event is not provided?

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Note: maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?"


Why are cck fields included in body when getting a node?

CCK fields, by default, are rendered into $content.  The order depends on their order on the Manage Fields tab.

To not do this, edit the content type, and goto the Display Fields (or goto /admin/content/node-type/my-content-type/display).

Then set the fields/labels as Hidden or Excluded.  I am spacing on the exact difference (too long since I set this up in Drupal 6), but I normally just use Hidden.


Is there a hook or sth after file is uploaded via file field?

hook_node_insert() and/or hook_node_update() would probably be the right place to do this. Your code might look something like this:

function MYMODULE_node_insert($node) {
  // See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);

    // Load the file object from the cache/database
    $file = file_load($file_item['fid']);

    // The path to the file is in $file->uri
    do_something_with($file->uri);
  }
}


Cannot login to my drupal site because of php version 5.6

So finally I found that the problem is with php version 5.6 and workaround is:

function aikidolm_user_login(&$edit, $account) {
  $_SESSION['aikidolm']['ulogged'] = 1;
}

https://www.drupal.org/node/2363219#comment-9366567


Instead of attempting to create your datatype module from scratch, use the Features module to store your content type settings in a feature generated module.  This is faster, but may not cover all of the options that you need (field order, field groups or autotitle.)


theme ALL form elements in a tpl through hook_preprocess_HOOK

I am not sure if this is what you are trying to do. But from the question I feel that you just want to re arrange the form in an order of your choice.

The best place to do that is with in a hook_form_alter function. Rather than the preprocess_HOOK.

Every form element has a property called #weight This could be used to arrange the forms in order the one with higher weight would go down.


In drupal 7, what does make a menu link a stale item?

Is it related to Stale menu link static caches? https://www.drupal.org/node/2425261


Q: "How risky is use non stable modules in Drupal 7?"
A: "Depends."

Without wanting to be obtuse, in late 2011 this is a question only you can answer, based on your abilities, needs and experience.
The simple answer is: Betas are usually fine, Alphas should usually be avoided, RCs are almost certainly OK.
If you're happy to hit a bug and help fix it or apply patches, you'll be mostly fine and able to really help the Drupal community. If not, the risk for you is higher and could become a show-stopper.
If you're using one of the 'biggies' with tens of thousands of users (CTools, Panels, Views etc) you can probably use alphas/betas without hitting many major issues -- or you'll be one of thousands with the same problem which means it'll get fixed quicker... But if you're using less common (but still complex) modules, or it's critical you have complete reliability in your site, then you'll need to think twice - and maybe stick with D6 for a while.
A safer approach if you're worried and don't have the expertise to get your hands dirty in code or patches is probably: use Drupal 6 but choose your modules carefully so there's always a D7 upgrade path. Upgrade when you're happy it's right for you.
Ultimately you might have to use Drupal 7 because it provides certain features you cannot get in D6.
To close I would say that, for the most part, Drupal 7 and its ecosystem of modules is ready for most people/sites/projects. But things are changing by the day, so if you don't feel comfortable now you might in do a month or two.
Do your research and if you have doubts or hit snags, Drupal 6 is generally still an excellent choice and will be for many more months.
Good luck!


Unable to login into website after installing and setting up itweak_login

After reviewing that module's code, I have to agree with @Aboodred1 in his comment you can disable the module from the database for several reasons (which I'll address on the module's drupal.org page rather than this site because I don't think this site is the appropriate place to do so). This is not the preferred or recommended way to do things, but it seems like you might have no other choice if you've already installed it.

Method 1

BACK UP YOUR DATABASE
If you don't feel comfortable directly accessing your database, you should be able to log in to your web server and delete the itweak_login module directory (usually located inside sites/all/modules) and everything inside it. This should at least give you access back into your site. If that doesn't work, or if you do feel comfortable accessing/modifying your database directly, here's an elaboration on the aforementioned comment:

Method 2

BACK UP YOUR DATABASE
Log in to your web server and open the settings.php file for your Drupal installation (usually located at sites/default/settings.php)
Find the line that looks like this:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'mydrupal7database',
      'username' => 'mydatabaseusername',
      'password' => 'mydatabasepassword',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

If the prefix line is empty (as it is in the example above), continue on to number 5

If it's not empty, e.g. if it looks something like this: 'prefix' => 'drupal7_', then replace the word system in step 7 with drupal7_system (in other words, add the prefix to the the word system)

Log in to your database if you're not already there
Select the database used for this particular Drupal installation (using the example above, you'd select the database called mydrupal7database)
Run the following SQL statement:

UPDATE `system` SET `status` = 0 WHERE `name` = 'itweak_login';

Note: after you disable the module in the database, you should be able to access your site again. At this point, I'd highly recommend uninstalling it by visiting the module uninstall page (admin/modules/uninstall), and then after it has been uninstalled, remove it from your server altogether (using Method 1 above).

Hope that helps...

:)


The correct way to fix this issue is to is to attach a JavaScript watch to the button and have the trigger make a confirm dialog pop up and then make a JavaScript request from the user's browser back to a URL with a parameter of the element to be deleted at the end of it, then fade out the rows from the HTML table and make sure the zebra striping is correct, then secure that second URL to have the same permissions as the original page, then receive the parameter at the called URL and process the callback you had originally intended to run:

PHP:

onclick="Drupal.dccAdmissions_confirm_delete('$rec->pi_firstname $rec->pi_lastname', '$rec->pi_id . ', '$rec->pi_id', jQuery(this) );

JavaScript:

( function($) {
  Drupal.dccAdmissions_confirm_delete = function( in_name, id, object ) {
    if ( confirm( 'Do you want to delete the application for ' + in_name + '?' ) ) {
      $.ajax({
        type: 'GET',
        url: '/admissions/application/delete/' + id,
        success: function(data) {
          if ( data == 'DELETED' ) {
            // Remove the specific row
            $(object).parents('tr').fadeOut( 1000 );
            $(object).parents('tr').remove();
            $('#dccadmissions-application-management-form tr:nth-child(odd)').addClass( 'odd' );
            $('#dccadmissions-application-management-form tr:nth-child(odd)').removeClass( 'even' );
            $('#dccadmissions-application-management-form tr:nth-child(even)').addClass( 'even' );
            $('#dccadmissions-application-management-form tr:nth-child(even)').removeClass( 'odd' );
          } else {
            alert( 'Delete failure: ' + data );
          }
        }
      });
    }
  }
  Drupal.dccAdmissions_confirm_reset = function( in_name ) {
    return confirm( 'Do you want to reset the application for ' + in_name + '?' );
  }
})(jQuery);

Make a menu hook:

function dccAdmissions_menu() {
  $items['admissions/application_management'] = array (
    'title' => t("Admissions Online Application Management"),
    'page callback' => 'dccAdmissions_application_management_content',
    'type' => MENU_CALLBACK,
    'access callback' => 'dccInGroup',
    'access arguments' => array( 'Admissions' ),
  );

Check your cases:

/*
 * Page callback for application management pages.
 */
function dccAdmissions_application_management_content( $arg1 = 'new', $arg2 = 0, $arg3 = '' ) {
  include_once "application-management.data.inc";

  $module_path = drupal_get_path( 'module', 'dccAdmissions' );
  $output = array(
    '#attached' => array(
      'css' => array( $module_path . '/css/application-management.css', ),
      'js'  => array( $module_path . '/js/application-management.js', ),
    ),
  );

  switch( $arg1 ) {
    case 'delete':
      $message = _dccAdmissions_application_management_delete( $arg2 );
      return drupal_json_output( $message );
      break;

Then delete your data:

function _dccAdmissions_application_management_delete( $id ) {
//... your delete code here...


The right way to validate fields via hook_node_validate

field_get_items() is the one you're looking for:

$items = field_get_items('node', $node, 'field_FIELD_NAME');
$first_value = $items[0]['value'];

It also takes care of language selection for you, so no need to worry about that one any more.


For people that want to have a separate form, here is my own solution:

I deinstalled Password Separate Form and, instead, installed Password Reset Landing Page (PRLP)
It does the redirect, the separate form and make sure people don't forget to actually set the new password.


Adding multiple checkbox in drupal using cck

A Boolean field/value can only store True or False. What you need is a List (text) field with Check boxes/radio buttons widget.

Then put

Plane
Train
Bus
Ship

in the Allowed Values list.

You can set Number of Values to 4 but I'd set it to Unlimited just in case you add more allowed values and forget to update the number of values.


Can a large amount of CSS using  tags in a template file slow page load time?

Significantly? depends on how much is your definition huge.

It's best practice to have your style's in CSS file because the browser can cache it. Therefore, on subsequent page loads it doesn't have to download your CSS file again.

The browser doesn't cache your HTML, so it would have to download your huge HTML each and every time.

Caching off

Caching On


The problem was that theme_token_tree($variables) was being passed only a subset of available tokens.  Just a gotcha to look out for if you haven't done work with the token tree before.

$variables = array('token_types' => array('nodes','comments'), 'global_types' => FALSE);
theme_token_tree($variables);

I needed to add additional token types to the token types array, like so:

$variables = array('token_types' => array('nodes','comments','bean'), 'global_types' => FALSE);
theme_token_tree($variables);

You can also go to /admin/help/token to get a list of all available tokens.  Be warned though, unless you have enough memory allocated to MySQL it could consume all of it and give you a "MySQL gone away" error.  I received that error and I upped mine to 500MB locally and it was fine after that.


It's because you're using the MENU_NORMAL_ITEM type, which will add the item to a menu, and haven't set a menu_name. From the docs:

  "menu_name": Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

If you want to add the link to a different menu try something like this:

$items['test1'] = array(
  'title callback'   => 'test_callback1',
  'page callback'    => 'test_output1',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu'
);

If you don't want the link to be added to a menu automatically at all, change MENU_NORMAL_ITEM to MENU_CALLBACK.

Remember to clear the caches when you make any change to hook_menu(), otherwise the changes won't be picked up.


why some PDOException errors are displayed in details on users screen and some other not

The problem is - error that gets displayed means "Hey, I cannot connect to database! To many users already!". And the setting you are using to prevent error display are in database. And watchdog's log is in database. That's why Drupal shows it - it cannot know you set it not to, the very error prevents it from knowing. And even if it could, it cannot log it in any other way than to user's screen

To get this sorted out, you need two things:

database-independent log module, like File logging
set variables responsible for not showing alerts in settings.php


How to delete a cck field base in Drupal 6

I believe deleting the fields programmatically like this flags the fields as deleted by CCK or the Field API in Drupal 6/7. You must then run Cron to have the system fully purge the database tables from the system.


How to add 'add to cart' button to view based on a search index?

I changed the index from the Commerce Products to the product displays, and this got me a different range of field choices. I could have probably achieved a similar result by adding a relationship, but I wanted this to be relatively clean and simple.


What is the default operator in Rules module conditions?

From official Rules documentation:

  By default, Rules assumes AND operators between conditions (if no OR
  group is explicitly used).

Syntactically there is nothing wrong with your rule.

A little tip for troubleshooting this rule (because obviously that rule does not give you any error messages) - add action "Show a message on the site" and output values from your conditions in that message. If the values shown are correct but the rule still malfunctions - try deleting it and then recreate it.

Also, you can try using Rules condition "Content is published" instead of checking the value of node:status. It is basically the same thing, but maybe in your situation will give a different result.


Insert user password into e-mail body sent by Rules for Ubercart's order completion

This is impossible because Drupal saves hash of passwords in the database, so you can't access the original password.


Calculate webform total from select list fields

You can use Webform Calculator module for your purpose.

This module provides a formula webform component for computed values, where you can enter a mathematical calculation based on the other fields. E.g. Create a formula field with value formkey1 * 0.1 * formkey2.

Let us know incase of any concern/query regarding this.

Thanks!


As far as i know, there  is no module which will display exact User Interface as check-boxes that will integrate with date module.

What i would like to suggest is to create time field to display from and to time of timing slots using date module.

If you need exact User interface what you are asking then follow below steps.

Add checkboxes field with different timings.
Then create date from and to time fields.
Hide date from and to fields using css.
On click of check-boxes update the hidden date from & to fields using jquery or javascript, so that you can use Date module features.


How can I redirect user, while showing them a status message?

In general, never send responses from custom code. See How do I set a cookie using $response->headers->setCookie() in a form submission handler?
In this case you are sending a redirect response to the client while Drupal builds the real response containing the cookie to the session where the message gets stored. The real response never reaches the client because you've already sent them away.
If you don't have a controller to return the redirect you can use an event subscriber to set the response the Drupal kernel returns. See this code example https://drupal.stackexchange.com/a/274494/47547.
In your case you would set a status message instead of a custom cookie:
/src/EventSubscriber/MymoduleSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * mymodule event subscriber.
 */
class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    if (!$this->routeMatch->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($this->routeMatch->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if ($some_condition) {
        \Drupal::messenger()->addStatus('My message');
        $redirect = new RedirectResponse('/foo/bar', 302);
        $event->setResponse($redirect);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 31],
    ];
  }

}

mymodule.services.yml
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    arguments: ['@current_route_match']
    tags:
      - { name: event_subscriber }


How to Allow User to Choose to Pay by Invoice OR Credit Card with Drupal Commerce

If you have multiple payment options available, the customer will be prompted to choose the payment option they want.

If you're not picky, you can use Commerce Custom Offline Payments and just create a payment type for an invoice.


How to use the Rules module to flag a node that has just been created?

FYI, after a lot of search I discovered that Rules2 support in Flag for Drupal7 is already in dev. I tried it and it works well!

There is also a patch as stated here: http://nodeone.se/blogg/learn-flag-with-nodeone-part-7

Not easy to google out! :P
Bye!


you could do this with a view. I was about to post you a long detailed post on how to get this done, but found this post on the subject that explains it in great detail.

Basically, you create a view and from there you have sort options available for your comment fields.

Credits to DAO Design for the blog post, hope that helps, cheers!


In this given image(second image), it is clear that there is a value " "(space) coming for the field Footer Col3.

Check in Footer Col3 field settings or in any custom module if you are set any default value for that field.


Use CKEditor on textarea in custom module's controller response

I'd imagine you just return the same element you'd build into a form, and use a format that's configured to use a WYSIWYG:

return [
  '#attached' => ...,
  '#type' => 'text_format',
  '#title' => 'Foo',
  '#format' => 'full_html',
];

See the TextFormat class for more options.


Saving a file should be a fairly simple job with PHP. If you want to do it when an order is completed, you could make a conditional action for it, or use one of the hooks that's invoked when the order is completed.

If you have an concrete problems on how to do this, you should refine your question.

If you want to save the mail sent, this would hold the order info, you could create a custom module and use hook_mail_alter to get the mail text:

/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  if ($message['id'] == 'uc_order_action-mail') {
    $message_text = $message['body'];
    // Code to save text as txt file here.
  }
}

By default the mail sent with ubercart is a HTML mail, so you might want to create your own text instead.

Whatever you do, you shouldn't alter Drupal or any of the modules, you should create your own module(s) that make the alteration. If you are new to Drupal development, you should read the developer guide.


You can enter a file parameter in the hook_menu function and the file will be included before calling the page callback function.

<?php
function my_module_menu() {
  $items = array();
  $items['my/custom/path'] = array(
    'title' => 'My title',
    'page callback' => 'my_function',
    ...
    'file' => 'my_module.pages.inc',
  );
  return $items;
}

Now, you can place your my_function in the my_module.pages.inc file.
You can place submit and validate handlers (forms) in this page as well.

files[] = my_module.pages.inc

will not work. It's to autoload classes. A good example would be Views file includes.


Direct link to view unpublished node causes redirect loop

I guess I can change my 403 page to something other than /user/login to fix the redirect loop.

Yes, that seems like it would cause the redirect problem.

But it sounds like you want to have a login page when the user gets an access denied message, and there is a module to do exactly that: r4032login

LoginToboggan may provide a similar feature, but I find that r4032login does a very simple thing and it does it well. On the other hand, I've run into several bugs with LoginToboggan.


Migrated data via XML doesn't import to nodes

As per this issue -- I think you need to tell MigrateSourceList where your item id's are, as an example (from isssue):

    // As with MigrateSourceMultiItems, this applies where there is not a separate
    // list of IDs to process - the source XML file is entirely self-contained.
    // For the ID path, and xpath for each component, we can use the full xpath
    // syntax as usual. However, the syntax to select the elements that correspond
    // to objects to import is more limited. It must be a fully-qualified path
    // to the element (i.e., /producers/producer rather than just //producer).
//  $item_xpath = '/producers/producer';  // relative to document
    $item_xpath = '/FMPXMLRESULT/RESULTSET/ROW';
//  $item_ID_xpath = 'sourceid';          // relative to item_xpath
    $item_ID_xpath = 'COL[1]/DATA';

    $this->source = new MigrateSourceXML($items_url, $item_xpath, $item_ID_xpath,
      $fields);

You only have 3 values in your constructor. I haven't done alot with migrating XML (just CSV and SQL). This issue is for D7 -- I think it should apply to D6.


Make a password security check for the register form

It seems like you might want to look into the Password Policy module which probably has a lot of the features you are trying to rebuild.

I also wonder whether it makes sense to build your own user inscription form instead of altering the existing core registration form. Altering forms tends to result in easier integrations with existing modules.


$resourcids = array();
 // Loop through resources and make fieldset for each.
    for($i = 0; $i < count($resources['subscriptionResources']); $i++){
      $resource = $resources['subscriptionResources'][$i];
      $resourcids[$resource['resourceID']]=$resource['resourceID'];
    }

      $form['resources'] = array(
        '#type' => 'radios',
        '#title' => t('Upgrade'),
        '#options' => $resourcids,
        ),
      );

you dont need to use name attributes. drupal form api give name attributes by form name.

when you submit form you get resource id in form_state['values']['resources'] of which is selected. then you identify which radio button is selected.

and By default disabled is false. so you dont need to add disabled.

dont add t() in before t("

")

'#suffix' => t("</td>"),


Make a field theme function work on empty fields

You may want to change the way you are theming the information, for example by overriding node.tpl.php, but if you really want the field function to be run even when the field is empty, you can do it by modifying the node before it gets displayed:

function THEMENAME_preprocess_node(&$variables) {
  if($variables['type'] == 'mynodetype' && !isset($variables['content']['FIELD'])) {
      $variables['content']['body'] = array(
      '#theme' => 'field',
      '#field_type' => 'FIELDTYPE',
      '#field_name' => 'FIELDNAME',
      '#items' => array(),
      '#bundle' => 'mynodetype',
      '#label_display' => 'hidden',
      '#entity_type' => 'node');
  }
}

This will make sure the field is passed to your theme field function, even if it is empty.

To get the values to use for FIELDNAME and FIELDTYPE you can print out the contents of $variables['content'] on a page where the field is not empty.

Again, it might be better to override the theme of the entire node in this situation.


Drupal 7 How to make the value of a user field (site_path/admin/people) dependent on user role

Please never ever use something that uses eval(). Even if you don't migh related security problems because nobody else has access to your site eval() is very very slow.

What you are looking for is hook_views_pre_render()

or a preprocess hok for the specific field. There are plenty examples if you use google.


Populate drop down fields according to other fields in Drupal 7

May be hierarchical select is what you are looking for.

Use one taxonomy field with hierarchy to store brands and models. hierarchical_select module will create nice widget for choosing them.


If you look at the Display Fields in CCK, eg www.yourhost.com/admin/content/node-type/NODETYPE/display, you can exclude fields from the $content variable that is passed to the node template.  I'd look into that and use $content instead of $node->body if it isn't excluded from there as well.


As you requested, this is an example how I did using field names.

In your .theme file:

function THEME_preprocess_form_element(&$variables) {
  //This is a list of fields in contact form
  $showAfter = array('name', 'mail', 'subject[0][value]', 'message[0][value]');
  if (in_array($variables['name'], $showAfter)) {
    //If is one, I change here how to display instead using different twig file
    $variables['element']['#title_display'] = 'after';
    $variables['label_display'] = 'after';
  }
}

Now, if you want use different twig file for each field name use this...

.theme file

function THEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#name'])) {
    //Name can be a string like this, 'subject[0][value]'.
    //When this happen, I just get 'subject'.
    $suggestions[] = 'form_element__' . explode("[", $variables['element']['#name'])[0];
  }
}

Then in your HTML appear something like this:

<!-- FILE NAME SUGGESTIONS:
   * form-element--subject.html.twig
   x form-element.html.twig
-->

Note:
The main problem is how you get form_id in preprocess or theme_suggestions (form_element Hook), I didn't find a way to get this information.


Default user relationships with the site admin

I was able to achieve this with rules + user relationship rules modules.

Export:

{ "rules_follow" : {
    "LABEL" : "follow",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "user_relationships_rules", "rules" ],
    "ON" : [ "user_insert" ],
    "DO" : [
      { "user_relationships_rules_action_create_relationship" : {
          "relationship_type" : "1",
          "requester" : [ "account" ],
          "requestee" : "1",
          "approve" : 1
        }
      }
    ]
  }
}

Rule Details:
Event: After saving a new user account

Conditions: None

Action: Request, create or approve relationships between users

Rule Settings:
Relationship Type: [your defined relationship] (follower)

Requestor: (Data Selection Method) Data selector "account"

Requestee: (Direct input mode) "1" (or the user ID of your admin account)

Approve Relationship: TRUE


List of certain user flagged nodes in a view

1) Create a Node View

2) Add a relationship Flags: Node flag (select the required flags and tick "Include only tagged Nodes"

3) Add another Relationship Flags : User (use the above relationship on this)

4) Add Argument User ID (named Contextual Filters in Drupal 7) and use the relationship "Flags : User"

5) Add the required fields.


Is there a way to park a domain name to a single Drupal node?

I was able to set different domain-based landing pages for existing nodes of our main site using the Domain module. This module is fairly complex and will either be exactly what you need, or not.

Our use case is that we have multiple one-page partner projects, such as campaigns, that need their own domain name but that share content from our regular website, such as our blogs.

The following are the steps taken for Drupal 7.

Be sure to read the entire readme file, the quick install and the install instructions before starting. There are many variables specific to your use case and environment.

Step 1

In order to use it, you will need to be able to configure the domains on the server to reference the primary website's docroot. In my case, that means I needed to point the domains over to the same server, and set up different vhost files as follows:

<VirtualHost *:80>
        DocumentRoot "/var/www/html/example/docroot"
        ServerName example2.com
</VirtualHost>

Step 2

You will then need to add some code to your sites/default/settings.php. Make sure the path is correct, according to your set up.

/**
 * Add the domain module setup routine.
 */
include DRUPAL_ROOT . '/sites/all/modules/contrib/domain/settings.inc';

Step 3

Once this is done, install the domain module and enable only the domain module, but none of the submodules yet. Then rebuild permissions (/admin/reports/status/rebuild). Then enable the domain_conf anddomain_settings and any others. Once enabled, set your primary domain to default.

Step 4

Add your new domains by clicking on "Create domain"

Step 5

In order for the blog and other relative links to go back to the primary domain, I needed to set the following in advanced settings (Structure > Domains > Settings):

(Here, FosterClub is my primary domain).

After this, there are other sub-modules you can enable to further customize what you need to accomplish. Be sure to set your permissions. You are also able to assign domain access to specific roles and users, which allows them to edit and create content restricted to specific domains, using the "edit domain content" permission, with the domain_content sub-module:

This is a screenshot of settings under a specific user.


Fatal error: Call to undefined function cache_get()

For me, the cause was different: some errors are not caught by Drupal's error handler.

I used a new DateTime() in my settings.php (probably very rare)
It generated an error because the date.timezone setting in my CLI php.ini wasn't set.

To find the real error (this is the interesting part of the answer for all of you, I think) :

Edit your module.inc, line 723.

Add these lines before the cache_get call.

if (!function_exists('cache_get')){
    debug_print_backtrace();
}
$implementations = cache_get('module_implements', 'cache_bootstrap');

It might give you lots of information about the real source of the issue!


How to show the number of user points within the user who posted a comment?

User Points

  Services integration: allowing retrieving and updating points on your    site using web services.
  Rules integration
  Views integration
  A block displaying the number of points a user has gained
  A block displays the top users who earned points
  A status message telling the user how many points were earned/lost    and their total points
  A detailed point total report for each individual user
  A point total report for all users

Profile2

  The module is aimed to provide a simple, but extensible solution    providing a similar end user interface like the core profile module
  by default.
  Multiple profile types may be created via the UI (e.g. a general    profile + a customer profile), whereas the module provides separated
  permissions for those.
  Optionally, profile forms are shown during user account registration.
  Similar to the deprecated core profile module, fields may be    configured to be private - thus visible only to the profile owner and
  administrators.
  By default the UI behaves similar to the deprecated core profile    module, thus showing each profile type in each own tab below
  user//edit. Via the included "Profile pages" module profiles can
  be viewed and edited at their own page and get their own menu link,
  e.g. "My profile".
  Thanks to the foundational entity API the module integrates well with    Rules as well as Features - thus profile types and the
  associated    fields can be exported into feature modules. Once the
  Entity tokens    module (part of the Entity API) is turned on, there
  are also token    replacements available.
  You may use Views and/or the Search API to provide listings or    searches for profiles


How to identify item_selector for Migrate API JSON imports

Think I have a solution, posting here in case it helps others. I tried to find a solution using xpath by using JSON browser like http://jsonpathfinder.com/ which gave me a path like this to find a field:

  results[0].members[0].id

The source JSON is coming in as an array but it doesn't appear that the way migrate_plus is handling selectors (splitting on the '/' symbol) is able to handle an xpath array designation, which was flagged in this issue https://www.drupal.org/node/2883803.

To get around this, I thought it would be easier if I could just change the source JSON to fit what migrate_tools can handle so I setup a simple router on my site:

import.my_wrapper:
  path: '/json/wrapper/my.json'
  defaults:
    _controller: '\Drupal\import\Controller\WrapperController::MyWrapper'
  requirements:
    _permission: 'access content'

Then built out the controller to use Guzzle to pull down my source URL normally and then flatten it so that migrate_tools can handle it:

  private function PrepJSONData($data) {
    $data_array = json_decode($data);
    $data_array = $data_array->results[0];
    $data = json_encode($data_array, JSON_UNESCAPED_SLASHES);
    return $data;
  }

I then updated my fetcher in my migrate yaml files to point to the route I had defined on my local site:

  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: https://example/json/wrapper/my.json

Leaving this question open in case anyone else can propose a more efficient approach.


What do we hook in Drupal 6 for inbound URL rewrites?

hook_URL_inbound_alter was introduced as part of a contributed module in Drupal 6 (URL alter), and was moved to core with Drupal 7.


How can I create a view showing count of users by birth year?

You could try out the following module which enables aggregation on your chosen granularity: https://www.drupal.org/project/views_date_format_sql

After enabling, a checkbox will appear in the Date field setting of the view, called 'Use SQL to format date'.


How can I find all database schema changes introduced in a CiviCRM major version upgrade?

One way to do it would be to pore through the CRM/Upgrade/ directory in the new version, looking for schema changes. However these are distributed across multiple files, depending on which alpha or beta version the change was introduced in. E.g. the next_sched_contribution_date change was introduced in this file:

civicrm/CRM/Upgrade/Incremental/sql/4.4.alpha1.mysql.tpl


How to skip the description step when uploading a file for a specific field?

You could probably acheive that by implementing

hook_field_attach_form

and setting the required values (e.g #required => TRUE or unsetting the description element.).

The entity_type and entity values are available for conditionally showing / hiding data there.


instead of this part of the array

$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

i had to put the field name , not the file name.

'field_document' => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);


How to create field template for displaying taxonomy terms as list in full content page?

Use template_preprocess_field()
You can try something like this in your template.php:
/**
 * Implements template_preprocess_field().
 */
function YOURTHEMENAME_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#object']->type == 'YOUR_CONTENT_TYPE_NAME') {
    $output = '';

    // Render the label, if it's not hidden.
    if (!$variables['label_hidden']) {
      $output .= '
' . $variables['label'] . ':
';
    }

    // Render the items.
    $output .= ($variables['element']['#label_display'] == 'inline') ? '
' : '
';
    foreach ($variables['items'] as $delta => $item) {
      $output .= '
' . drupal_render($item) . '
';
    }
    $output .= '
';

    // Render the top-level DIV.
    $output = '
' . $output . '
';

    return $output;
  }
}

Once implemented, try flushing you theme cache, it should work.


Why is loading a field value from a group of nodes taking 30 seconds plus?

I'm guessing that the difference between the fast runs and the slow runs is caching. Within field_attach_load is a call to cache_get_multiple(). The field values can load from a cache which should be a lot faster: https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_load/7

To investigate further I recommend using devel module's query logger. It can show the amount of time spent within queries. If that is not sufficient you can use a profiler like XHProf or Blackfire to see exactly which function calls are taking the most time.


attach an programmatically generated pdf file to a node

I didn't use PDF Using MPDF, so not sure what will be the file path for the PDFs got generated.

Anyway, these are general steps you need to perform for attaching files to a node.

Create a file object representing our physical file
Make it a managed file by calling file_save()
Fill file field with file's properties and fill field's other properties like display and description
Save the node to make attachment effective

You can utilize sample code below to get idea how to work on it.

<?php
// We have complete file path.
$file_path = '/whatever/path/to/file/sample.pdf';

$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location.
$destination = 'private://PDFs/';

// Make sure destination directory exists
//before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_pdf[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_pdf[$node->language][0]['display'] = 1;
$node->field_pdf[$node->language][0]['description'] = 'Our special PDF';

// Save node to make the attachment effective.
node_save($node);

Apply correct file path and destination directory. Here is the post explaining it in detail: Programmatically Attach Files to Node in Drupal 7


How can I add a "Back to Search" link to user profiles?

You can do this wih a new module modifying the user profile view.

// Implements hook_user_view().
function MY_MODULE_user_view($account, $view_mode, $langcode) {
  $account->content['link'] = array(
    '#weight' => -10,
    0 => array(
      '#markup' => 'Back to Search',
    ),
  );
}

Note: When adding a hook always remember to clear caches

If you also want to preserve the filter that the user has applied you can do so within your filter in the view by selecting 'remember the last selection' and selecting the roles that you want this for.


How can I have the nodes grouped in descending order and the nodes in ascending order?

You can use hook_views_query_alter

function MODULENAME_views_query_alter(&$view, &$query) {
   //print_r($view->query->orderby);
  if ($view->name == 'VIEWNAME') {
  // check the position on the orderBy function in the query
  // For this you can check the values with print_r() function.
   $view->query->orderby[0]['direction'] = "ASC";
  }
}


Here is the code to display the Edit Form in Node View page:

<?php
// modules/custom/custom.module

function custom_preprocess_node(&$vars) {
    module_load_include('inc', 'node', 'node.pages');
    $node = $vars['node'];
    $form = drupal_get_form('mytype_node_form', $node);
    $vars['content']['edit_form'] = $form;
}
?>

Notes:

You need to replace custom with your module's name and mytype with
the machine-readable name of your content-type.
I just used a clone of $vars['node'] to prevent probable problems
caused by the fact that $vars is passed by reference; though it
might not be necessary.


Drush aliases and Permission denied (publickey,password) problem

A possible cause is that you are not specifying your remote user in the drush alias file.

For example, if the ssh command that works to allow you to login is:

ssh myuser@example.com

Then an alias might look like this:

$aliases['dev'] = array(
  'uri' => 'http://www.example.com',
  'root' => '/var/www/vhosts/example.com/docroot/',
  'remote-host' => 'example.com',
  'remote-user' => 'myuser'
);


Mainly contextual filter works with /blog/page/[contextual filter id] e.g. /blog/page/2

By default its hard to pass the contextual filter id to a block, but you can do it this way

If you have url blog/page/2 then you can set this as shown in the image(3rd argument is 2 that will  be passed to view block ), also add necessary relations accordingly.

Hope it will help you.


You can do this with hook_menu_alter() in a custom module or theme, for example using the following code.

function custom_module_menu_alter(&$items) {
  unset($items['blog']);
  unset($items['blog/%user_uid_optional']);
  unset($items['blog/%user/feed']);
  unset($items['blog/feed']);
  return $items;
}

Make sure to clear the cache.


The solution was easy: it's already integrated in Drupal. Just activate the media module and go to Administration->Configuration->Media and there's a very, very, very²²³ powerful IMCE configuration panel.


How can I update text_format value in Ajax callback?

Don't change $form in an ajax callback. See this documentation for D7:

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

  Details and Warnings

  Changes to the form must only be made in the form builder function, or
  validation will fail. The callback function must not alter the form or
  any other state.

For D8 there is in the moment only documentation for the new syntax, but not for the basics. Use the D7 doc's instead.


Actually, the documentation for node.tpl.php says, in the description for the $content variable.

  An array of node items. Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.

The node body is a field, and you should use render($content['body']) to render it.

The note about field variables is the following one:

  Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node->body['en'], thus overriding any language negotiation rule that was previously applied.

You should use $body only when you need to access the field's raw values, not to render the field.


views Filter field equal to the value of another field

From what I understand of your request you are adding a view on a node display page and want to use a field on that page as an argument in the view, if this is the case you want to add a contextual filter and under default value select php and then do a node_load or db_select to load the field from the node being viewed.


Script exits on drupal_bootstrap_full when run from system cron

I found the issue is i have multiple PHP versions installed on my system because my hosting company is running plesk. PHP 5.2 is a base version and it looks like drupal loads something that makes php5.2 fail.  After upgrading my script to point to the proper 5.5 version of php everything is running as expected.  Thanks to all who replied.


Show a different view mode depending on role

Turns out, there's a hook for that.

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}


Is there an easy way to check for http resources when I am switching to https?

Saint Mary's College in Notre Dame, IN has developed a script to look through the node_revisions table and help you visualize the references. You will likely have to adapt what they have written to fit your situation, but you can check it out on github.


Override field template with custom module

I'm sure there must be an easier way to do this but this is what I typically do:

1.
Register an overriding theme implementation with the Drupal theme registry. So, in mymod_theme(), add a new item. The variables key must match that of the media_youtube_video theme i.e.

/**
 * Implements hook_theme().
 */
function mymod_theme() {
  return array(
    'my_media_youtube_video' => array(
      'variables' => array('uri' => NULL, ...), // see media_youtube_theme() for this
      // bundle the template file with the module itself
      // i.e. theme/my-media-youtube-video.tpl.php
      'template' => 'my-media-youtube-video',
      'path' => drupal_get_path('module', 'mymod') . '/theme
    )
  );
}

2.
Add a preprocess hook for the original theme implementation and suggest your new implementation here.

/*
 * Implements hook_preprocess_media_youtube_video().
 *
 * Or more generally, hook_preprocess_THEME().
 */
function mymod_preprocess_media_youtube_video(&$variables) {
  // If your overriding implementation is not a template but
  // is implemented in a different file,
  // then remember to include the file explicitly at this point..
  $variables['theme_hook_suggestions'][] = 'my_media_youtube_video';
}

Suggestions are evaluated by the theme system in a LIFO fashion. You can read more about this here.

Suppose you are aware that another module is also following the same approach as this one to override the implementation, then you can implement hook_module_implements_alter() and force your hook_preprocess_THEME() (see above) to be called last. You can read about hook_module_implements_alter() here.

This holds good for Views also. In summary, you just need to find out the correct unique name of the original theme implementation you want to override (typically defined in the source module), add a preprocess hook and add your overriding suggestion there.


UC Node Checkout for pay to publish user content?

Try Pay-per-node

This module allows creation of a number of nodes of chosen type for some users. It temporarily overrides the node creation permissions and keeps track of the number of nodes the user can create.

It can be used as standalone module or as an e-commerce plug-in. In the second case paypernode can be integrated with Ubercart, providing a new "product feature" which will allow, upon product purchase, to create a number of nodes.


Display different form of user's name to different users?

Reference: http://drupal.org/node/1194546

Basically, the easiest way to do this involves a couple steps:

First, implement hook_username_alter() in your custom module to change the username dynamically, depending on the context of the username's display (you can, for example, load the global $user object and display one form of the account in question's name to $user's with the role 'teacher', and another form to $user's with the role 'authenticated'...

Second, you will only be able to dynamically control the username as returned by $user->name or by theme('username', account) using hook_username_alter(). You can't change a username dynamically via realname, because that module stores the name in the database and caches it for performance reasons.


Is there more elegant way?

Not really - the NID doesn't exist until the node has been saved the first time, so there is no way around this if you want to save the node title.

However, you could just add the NID to the title when the node is loaded:

function hook_node_load(&$nodes, $types)
{
  foreach($nodes as $node)
  {
    if($node->type == 'my_type')
    {
      $nodes[$node->nid]->title = '#Bill ' . $node->nid;
    }
  }
}


Use the Bean module, this will allow you to create custom Block types with fields, even image fields. It integrates nicely with the blocks module.


WSOD and Drush cc all fail after deleting a view of a long-time-ago deleted module

Since I happen to know from WSOD afte uninstalling the Memcache module and deleting it's folder that you just stopped using Memcache, then I know that your Drupal site has just reverted back to using the database cache.

You probably had entries in your database cache from before you switched to Memcache in the first place.  Those really old database cache entries are now back in use.

You're trying to clear caches, which is absolutely the correct thing to do. However, there's a nasty bug in CTools that prevents you from clearing the cache if a particular CTools cache entry is broken: https://www.drupal.org/node/1775612

In this case, though, the manual fix is pretty simple. You need to truncate the cache table in your database. That should allow the cache to rebuild itself normally.


Error when updating Bootstrap 7.30 to 7.35

This is probabbly not related to bootstrap theme itself, because the function bootstrap_menu_link() is the same in both versions.
As I can see the error is because the element key is empty

22. $element = $variables['element']

So, when the the function try to call the l() function, throw an error fatal, because is expecting an array as 3rd argument

52. $element['#title'] = l($element['#title'], $element['#href'], $element['#localized_options']);


Checkout this using hook_preprocess_node()

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

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

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

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


Pathauto insert taxonomy term custom url

You can use the following pattern:

[node:field-taxonomy:parents:join-path]/tools/[node:title]

(manually set the middle part of the pattern).

Or, if you have several terms (not just Safety Tools), you can use

[node:field-taxonomy:parents:join-path]/[node:field-taxonomy:url:path]/[node:title]

([node:field-taxonomy:url:path] is the path component of the term's URL)


Split a date field output into two spans

If your current approach works, consider sticking with it.  Use field_get_items() to get past the "field won't always have the language" problem.

To answer the original question, at admin/config/regional/date-time you'll find a tab to create a new format.  You can somewhat laboriously create a format based on something like:

<\s\p\a\n \c\l\a\s\s="\f\o\o">l F j</\s\p\a\n> - <\s\p\a\n \c\l\a\s\s="\b\a\r">g:i a</\s\p\a\n>

All the backslashes may not be necessary, but you have to backslash escape any character that is a special date code.

Then edit a type or make a new one that uses your format with the markup built in.


HTML mail - how to properly format message

In Drupal 7, it's the implementation of MailSystemInterface::format() that formats the message body and changes it to a string; before that, $message['body'] is supposed to be an array.
In Drupal 6, drupal_mail() receives an array for $message['body'], and changes it in a string.

// drupal_mail() in Drupal 6

// Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Concatenate and wrap the e-mail body.
  $message['body'] = is_array($message['body']) ? drupal_wrap_mail(implode("\n\n", $message['body'])) : drupal_wrap_mail($message['body']);

Compare the code you are showing with the code used by the Drupal 7 implementation (DefaultMailSystem::format()).

public function format(array $message) {
  // Join the body array into one string.
  $message['body'] = implode("\n\n", $message['body']);
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = drupal_wrap_mail($message['body']);
  return $message;
}

Drupal requiring $message['body'] to be an array of strings is made clear in hook_mail_alter(), which describes it as follows:

'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.

Since hook_mail_alter() is invoked right before the format() method, that method is supposed to get an array, not a string.

 // drupal_mail() in Drupal 7

 // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => isset($from) ? $from : $default_from,
    'language' => $language,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

  //  …

  // Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);

The only reason I could see to check if $message['body'] is a string is to protect the code against modules not correctly updated in the passage from Drupal 5 to Drupal 6. In fact, Drupal 5 passed a string for body, as evident in the example for hook_mail_alter() shown in the documentation.

function hook_mail_alter(&$mailkey, &$to, &$subject, &$body, &$from, &$headers) {
  $body .= "\n\n--\nMail sent out from " . variable_get('sitename', t('Drupal'));
}


Page Manager user/%user/edit selection rule only called when user has 'administer users' permission

use context rule in page manager page.

Home » Administration » Structure » Pages-> selection rule-> from drop down select role-> add-> assign role(selecting by check box).

done.


The control over the Panel-col's (Panel columns) can be maid manually via the relevant TPL file (each one of the natural Panels' layouts has it's own TPL).

The TPL files are stored at sites\all\modules\panels\plugins\layouts. Check there for the layout you use for your panel.

At my case, I've edited the layout "twocol". It's TPL is inside it's directory (also named "twocol").

There I've changed:

<?php print $content['left']; ?>

<?php print $content['right']; ?>

To:

<?php print $content['right']; ?>

<?php print $content['left']; ?>

After I did this flip, I still haven't seen the change in responsive mode... This is because a change had to be made in the CSS file also... The CSS change is basically comprised of a float: change, and a media screen and () change. Inspect each Panel-pane to get more info on the float and width and then make these, and any other needed changes, in the CSS file.

This manual editing seems to me to be the only way for RTLization\flipping the layouts. I hope the developers of the module would make a more "friendly" option for RTLization.

Note: Better make a backup of the edited versions of your files and store them outside the sites\all\modules\Panels folder - This could save time in case a Panels update would delete them; Even though this action is relatively short.


How do you render a Node's Last Saved date in a Region Footer (ie, inside a Block on every page)?

I think you can add to the yourtheme.theme file next thinks;

function yourtheme_preprocess_region(&$vars) {
  $vars['node'] = \Drupal::routeMatch()->getParameter('node');
}

and afterwards in your twig template each region will have available variable node.

{% if node %}
  {{ node.changed.value|date("d/m/Y H:i") }}
{% endif %}

Don't forget to clear cache.


Using blocks!

Create your new menu,  and assign it to your left sidebar block.   then, configure that menu's block settings to only appear on certain content types.


Well choosing a database for your site depends on many ways,
I prefer MySQL to keep it quite simple.

MySQL is preferable PHP sites because:

Drupal 7 now comes with default table engine which is InnoDB(advantages over MyISAM) for
MySQL
MySQL has choice of table types for better read performance.
Drupal has PHPMyAdmin Web Interface for MySQL.
WAMP,XAMP comes with MySQL so it makes life easier when you use MySQL
Drupal's much better tested with MySQL

http://drupal.org/node/37268


How to make a list of all nodes of content type ABC on a site (not a sitemap)?

Of course you can use Views (d'oh!) to do this.

Just make a view of content type landing page showing fields and then add a link to content and check the box for show URL as text.


How can I create an alias to point to an uploaded file?

I agree with Clive and base oh his comment, to redirect all files to another route you can use .htaccess route direction. So,
first solution:
add to following line in your .htaccess file.
RewriteRule ^sites/default/files/(.*)$ /files/$1 [L,NC]

note: you can use whatever you want instead of files, like assets etc.
PS: if your files are Media types, with pathauto module you can create a pattern to redirect them additionally you can let the user override them the what path he wants.
second solution:
install https://www.drupal.org/project/file_entity module and then with pathauto module you can create an alias for files.  like files/file-title.
third-solution: use https://www.drupal.org/project/path_file module

The Path File module allows content editors to upload files and
specify the url at which they will be available. Normally, when
uploading a file to Drupal with the same name as an existing file, it
is given a new name instead of overwriting the existing file. This can
problematic when file urls are referenced in content, menus, etc but
may need to be updated in the future. The Path File module allows you
to mitigate the impact of those changes by setting up a canonical url
alias which will always point to the most up-to-date file


Establish relation between node and gmap marker

I suggest you to use this module to create views related to your nodes to create gmap with markers:

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


How do I know if a user has access to a private file in the node template

If your using the Pages Module then you can make different page 'variants' for different roles.


how can have this url car1?category=blue car?category=red car2?category=blue

for every views is necessary to have one exposed;
but isn't possible manage the

1) car1 | car2                        menu1
2) Allcolor | red | blue | yellow     menu2

menu2 how a submenu of menu1, also if isn't a unique vocabulary?


There might be a simpler way but I think this should be pretty reliable:

// Inject the entity_type.manager service instead if possible.
$class = \Drupal::entityTypeManager()
    ->getDefinition($entity_type_id)
    ->getOriginalClass();

$interface = 'Drupal\Core\Entity\FieldableEntityInterface';

if (in_array($interface, class_implements($class))) {
    ...
}


problem with Views module (installation)

The views module was installed as a part of commerce_kickstart in sites/all/modules/commerce_kickstart/modules/contrib. You removed that distribution, which is a good idea because it was installed in the wrong directory (should be in /profiles).
Most probably you then downloaded and reinstalled a fresh views in sites/all/modules.

If you move a module you should clear the cache or (in some cases) rebuild the registry.

The easiest way to clear the cache when you cannot reach the admin of the site is to go to /update.php and run the update process (take a backup first).
Other options are the Registry Rebuild module or Drush (drush cc all).


What is the purpose of sites.php and how does it relate to settings.php?

Looking at conf_path() should help clarify the relationship here. conf_path() builds the default subdirectory (inside the sites directory) Drupal will goto for settings.php (and other site-specific configurations). It's default search behavior can be overridden with sites.php.


Add custom operator for condition() in search_api

Maybe this trick will help you. You can go upstream and implement hook_query_alter instead

function yourmodule_query_alter(&$query) {
if ($query->hasTag('search_api_db_search')) {
        $is_search = FALSE;
        $tables=$query->getTables();
        //dpm($tables);
        //only run for the query that really matters to you. Try to find something unique in this
          foreach ($tables as $table) {
            if ($table['table'] == 'search_api_db_your_important_table'  ) {
              $is_search = TRUE;
            }
          }

          if ($is_search) {
            //use query functions normally eg.
            $query->innerJoin('search_api_db_your_table', 'custom_table', "custom_table.item_id = t.item_id");
          }
  }
}


User Login Destination | to his first submission | Webforms

You can achieve using hook_user_login() function.

function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location.
  // Get the logic and fetch where do you want to redirect.
  // Here i am redirecting to node 34. You can fetch your own webform submission path
  // where do you want to redirect.
  // Fetch the submission of done by the current users. by using http://api.drupalize.me/api/drupal/function/webform_get_submissions/7 function
  $redirection = 'node/34';

// Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}


In both Drupal 6 and Drupal 7, you can use variable_get.
The CMI initiative will likely deprecate this function in Drupal 8.

$name = variable_get('site_name', '');

Notice the blank '' at the end, which is the "default" value, in case a variable isn't defined.


How to build render array with node title linked to node for a list of nodes

As pointed out by @4k4 I used the entity reference field formatter, which does not apply here. Theming as link, as answered in How do I theme a link? does the job:

if ($teaser_display) {
  $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
}
else {
  $value = [
    '#type' => 'link',
    '#title' => $node->label(),
    '#url' => $node->toUrl(),
    '#cache' => ['tags' => $node->getCacheTags()],
  ];
}


cache_render database table growing in size

There are some ongoing improvements to e.g. cache 404 pages only for a short time.

Make sure that cron is running, so that expired caches are deleted.

Also consider using an alternative cache backend like Redis or Memcache, both have a max size that the allocate and delete items that have not been used for a while.


Is there a way to enable the Gutenberg editor so I can use it with custom blocks?

Currently it's not possible. Although Gutenberg module provides a Drupal text editor plugin, like CKEditor, it relies a lot on the node edit form to provide the editing experience.


How do I delete content (nodes) that a user no longer has the right to create?

This code gives you the basic idea:

$nodes = node_load_multiple(array(), array('type' => 'my_type'));// load node by certain type
foreach ($nodes as $node){
    $uid= $node->uid;//get the node author id
    $nid = $node->nid;// get the node id
    $author = user_load($uid);//load the author of the node
    if (!in_array('your_role', $author->roles)) { //the author has not your_role role
        node_delete($nid);
    }
}

if you copy this code in the theme_preprocess_html of your template.php, for every page it checks the nodes and its author roles and delete the node id its author has not the role.

If you need to run this code once a user role is updated, you can use Rules module :

I am not able to run this code right now, but it should work correctly. You can use devel module to correctly get the $node properties ($nid and $uid).


Generating URLs based on taxonomy vocabularies and terms

In your Pathauto Patterns (Admin>Config>Search and Meta Data>URL Aliases>Patterns /admin/config/search/path/patterns ) in the Content Paths section, find the appropriate content type and use the Tokens (called Replacement Patterns) to fill in the field.

In the described case, it might be something like the following:
[node:content-type]/[node:field-category]/[node:title]
or
interviews/[node:field-category]/[node:title]

Be sure to expand and check what tokens you have available.


$text = token_replace('token example - [node:title]', array('node' => node_load(123)));


Sass error with zen 5, 'it is not clear which file to import

So, this ends up being more of a environment/sass issue I post this here because I encountered in working with Omega, and I figured someone else would bump into this. Depending on your set up, especially if you're using a task manager, SASS file globbing might not be functional.


Generate 1D bar code based on user defined input

You have content of type A and it contains a field called B , B is your serial fieldneedrst of all your field B must get multiple values , this can be set through Field UI. If you are going to collect more than 10 values per each content you can select unlimited values , but this has some DB overhead , after that drupal itself will create the form with multiple value , if you have chosen a specific number for that field for example 3 values , there will be 3 widget to get values , else if it is unlimited you will have an ajax add element button .
If this is not what you want and you want to enter the number of barcodes at the beggining then you must alter the form using hook_form_alter (you must write a module) , inside that hook add a counter element to your form (it gets the repeatation s count) and then use ajax to add widget to your form .
Each widget must be added to your field in your form , so drupal will understand that all the data inserted in these widgets relates to your field.
If you want to do it by writing a module and need some code ,I can add some code later.


User cannot view their Orders in Ubercart

Enable the Allow customers to view order invoices from their order history in Order settings, see the below image may be this will be the problem for you and i am not sure because i have drupal 6 installation only.


Drupalgap: Hello World sample - where is app folder?

The app folder is in the folder mobile-application

Root folder drupal

mobile-application

app

modules

custom

my_module


expose filter work with ajax only on inner pages but work with button submit on front page

Disable Use ajax in View settings, in THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) function do like this:

function THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form)
  // dpm($form_state)
  if ($form['#id'] == 'MY-VIEWS-FORM-ID') {
    if (!drupal_is_front_page()) {
      $form_state['view']->use_ajax = true;
    }
  }
}

flush the cache.


As Jimajamma pointed out, the Location module along with Views will allow you to filter by distance. I am currently using zipcodes to filter by, but one could do geocoordinates as well.

Here is a step by step article on how to achieve filtering.  Although the article is a tad old, it is still relevant and can easily be adapted for drupal 7.

http://drupal.org/node/359463


How to integrate webform into multi form wizard into drupal 7

You could set the redirection path of the webform to your new form upon completion. By default it stays on the node page.


How to add vocabulary terms to a taxonomy category

taxonomy_vocabulary_machine_name_load() returns an object or FALSE. You're checking for exactly TRUE by using ===.

Any of the following should work (sorted by my preference):

if ($vocabulary) {
if (is_object($vocabulary)) {
if ($vocabulary !== FALSE) {
if ($vocabulary == TRUE) { // only two equal signs here


Can drush show list all available modules?

No, drush can't do that.

Why should it when you can see the entire list yourself on drupal.org.


How to create custom date display format in drupal 7?

If you are comfortable with coding then go for template file changes.
You have to do changes in node.tpl.php.

Else you can do also without coding refer https://stackoverflow.com/questions/8375674/how-can-a-custom-drupal-date-format-be-added

If you have created view for event display then it is easy to display date field as you want.
Go to date fields setting. There is a option for formatter. Like below screenshot. Here you can add custom date display format.


for mailsystem to work, you need to implement MailSystemInterface class and enable your new mailsystem class as default, for example in module hook_install():

    variable_set('mail_system', array_merge(
       variable_get('mail_system', array('default-system' => 'DefaultMailSystem')), // Previously set mail_system variable
       array('login' => 'MyCustomMailClass')   // My new key(s) which ADD to the previous keys
    );

Note: array('login' => 'MyCustomMailClass') "login" is a module name, which will be used to identify your new mailinterface.

Next you should call your new mailsystem from hook_mail(), like:

drupal_mail('login', 'registration', $form_state['values']['register_email'], language_default(), $params, 'mail@exmaple.com', true);

And class implementation could look someting like:

class MyCustomMailClass implements MailSystemInterface {

/**
 * Concatenate and wrap the e-mail body for plain-text mails.
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 *
 * @return
 *   The formatted $message.
 */
public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);

    if ($message['module'] == 'login') {
        $body =  $message['body'];
        $message['body'] = array();

        // Convert any HTML to plain-text.
        $message['body']['plain'] = drupal_html_to_text($body);
        $message['body']['plain'] = drupal_wrap_mail($message['body']['plain']);

        // Wrap the mail body for sending.
        $message['body']['html'] = drupal_wrap_mail($body);
    } else {
        $message['body'] = drupal_wrap_mail($message['body']);
    }

    return $message;
}

/**
 * Send an e-mail message, using Drupal variables and default settings.
 *
 * @see <a href="http://php.net/manual/en/function.mail.php
  " title="http://php.net/manual/en/function.mail.php
  " rel="nofollow">http://php.net/manual/en/function.mail.php
  </a>   * @see drupal_mail()
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 * @return
 *   TRUE if the mail was successfully accepted, otherwise FALSE.
 */
public function mail(array $message) {
    $mimeheaders = array();

    if ($message['module'] == 'login') {
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // main header
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = "multipart/alternative; boundary=\"".$separator."\"";

        // message
        $body = "--".$separator.$eol;
        $body .= "Content-Type: text/plain; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['plain'].$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['html'].$eol;
        $body .= "--".$separator."--";

        foreach ($message['headers'] as $name => $value) {
          $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          preg_replace('@\r?\n@', $line_endings, $body),
          join("\n", $mimeheaders)
        );

        return $sendM;
    } else {
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

        if(isset($message['customMode']) && $message['customMode'] == 1) {
            $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed; delsp=yes';
        }

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $heads = join("\n", $mimeheaders);

        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
          // on Unix and CRLF on Windows. Drupal automatically guesses the
          // line-ending format appropriate for your system. If you need to
          // override this, adjust $conf['mail_line_endings'] in settings.php.
          preg_replace('@\r?\n@', $line_endings, $message['body']),
          // For headers, PHP's API suggests that we use CRLF normally,
          // but some MTAs incorrectly replace LF with CRLF. See #234403.
          $heads
        );

       return $sendM;
    }
}}


Programatically render a view in twig template

Right, twig no longer allows you to execute php code anymore. This is a main feature of twig and its security model.

I'd suggest to use a preprocess function for now and there call the function or even better add a render array with #type view, with #view_id and #display_id, as it gives you caching as well.

On top, maybe add an issue against core. That sounds like a really helpful thing to have

Oh and views_embed_view should be changed to enable caching as well.


Restrict Menu options when building Nodes

What I ended up doing was using TEMPLATE_form_node_alter() and creating my own duplicated versions of menu_parent_options(), _menu_get_options() and _menu_parents_recurse() so I could call them instead of the default drupal functions to build my menu. And in _menu_parents_recurse() you can access the link information like link_path, and just set the menu links I wanted to exclude.

function _my_menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
  foreach ($tree as $data) {
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
    // Exclude menus that are absolute/external
    if (stripos($data['link']['link_path'], 'http') !== false) {
        $data['link']['mlid'] = $exclude;
    }
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
      if ($data['link']['hidden']) {
        $title .= ' (' . t('disabled') . ')';
      }
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
      if ($data['below']) {
        _my_menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
      }
    }
  }
}

I was hoping for a more "correct" method (hook_preprocess_link maybe, but it doesn't exist in D7, only 6 and 8) but this one works.


Drupal's version of Wordpress' wp_insert_post()?

Are you sure you want to do it programmatically?
You can just create the Content Type and use Permissions to control which user's roles can add/edit/delete that type of content.


how to overreide page.tpl.php with my custom menu

I guess you could do something like this:

function MYMODULE_preprocess_page(&$vars) {
  $patterns = 'node/edit/restaurant/*/barcodes';
  if (drupal_match_path($_GET['q'], $patterns)) {
    $vars['theme_hook_suggestions'][] = 'page__node__edit__restaurant__barcodes';
  }
}

That would let you use page--node--edit--restaurant--barcodes.tpl.php after a cache clear.

As an aside, your page arguments are wrong in the router item, should be:

'page arguments' => array('leo_MSTag_barcode', 3), // <-- Index of arg is 3, not 5


Please refer to following Drupal documentation example for advanced configuration of search query:

https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

$query->keys($search);

'+', '-' works by default in $search(searched keyword)


How to display parent term name of a term located in a paragraph?

1st you have to make relation with the field who reference to taxonomies after that youhave  to make another relation with your paragraph field to get the job title


I've experienced that in Drupal 7 you must not rewrite to a clean URL destination, even if you have clean URLs enabled.

(This is possibly a duplicate of: Rewrite URL not working.)


How do I let non-admin user approve comments?

You need to give the "Administer comments and comment settings" permission to the role and then it will be able to approve the comment.


For this you have three options

a) either use third party resume services. I recommend best one RChilli . We implemented them for various client.s

b) Or you can build your own algorithm for Resume Parsing.

c) 3rd one if you are getting fixed format of resumes then write own  using drupal parsing api.

Let me know if I can be of further help.


What steps do I need to take to use Drush Make on a Windows machine?

I found the solution on this page. There were several steps but it really wasn't that difficult. For some reason it doesn't download items from Github but that might be something to do with the path variable not being set correctly and I just downloaded a few modules from Github manually.


Attach PDF file to Drupal Commerce Order Notification

Problem #1. Getting a copy of the PDF.

The function views_pdf_rules_action_save() almost did it. I changed

$display->handler->execute('', 'F')

to

$display->handler->execute('', 'E')

As TCPDF has an option to generate the PDF as an email format. I don't need to save the file with the resulting security and overwriting challenges.

Problem #2. Stripping the email and base64decode

The email format added the HTML already has the headers. I didn't dig enough to bypass the Drupal mail array processing. Instead the heading was stripped. You could use more of the provided mail headers.

$email_attachment = _yhivecoupons_views_pdf_rules_action_save('commerce_gc_user_giftcards:pdf_1', null, '');
$email_attachment_parts = explode("\n", $email_attachment);
$content_type = array_shift($email_attachment_parts);
$name = array_shift($email_attachment_parts);
$encoding = array_shift($email_attachment_parts);
$disposition = array_shift($email_attachment_parts);
$filename = array_shift($email_attachment_parts);

$clean_email_attachment = implode("\n", $email_attachment_parts);
$clean_email_nobase64 = base64_decode($clean_email_attachment);

      $my_attachment = array(
    'filecontent' => $clean_email_nobase64,
    'filemime' => 'application/pdf',
    'filename' => "tester.pdf",
    'filepath' => NULL,
  );
  $message['params']['attachments'][] = $my_attachment;

Problem #3 Permissions

This process is still executed in a context where the user was not logged in. I am printing out a person's coupons so need their login details.

I don't think this is the best way to do this, as the process is not checking unique email addresses yet.

global $user;
$user_obj = user_load_by_mail($message['to']);
$user = user_load($user_obj->uid);

Log out user at end.

Instead I am using commerce_immediate_login which does the same thing but in a rule using the ui generated by 'create login for anonymous users'. The order of the rules is specific.

This is my views PDF call function with the 1 character change from views_pdf_rules_action_save(). A tested way of getting PDF content from views_pdf.

function _yhivecoupons_views_pdf_rules_action_save($views_pdf, $arguments, $path) {
  $splits = explode(':', $views_pdf);
  $view_id = $splits[0];
  $display_id = $splits[1];

  if (!empty($view_id)) {
    $view = views_get_view($view_id);

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

    // Try to get pdf display
    if (!$view->set_display($display_id)) {
       // Try the display type
       if (!$view->set_display('pdf_1')) {
        // There is definitly no pdf display
        return;
       }
    }

    $view->pre_execute();
    foreach ($view->display as $id => $display) {
      if ($display->display_plugin == 'pdf' && isset($display->handler)) {
        // arguments '' and I
        return $display->handler->execute('', 'E');
       }
     }
  }
}


So the basic problem is that a vocabulary is not fieldable. In theory this is easy to fix, but I don't know if they lack this functionality because it would cause technical difficulties, or to avoid confusion users.

To make a vocabulary fieldable, implement hook_entity_info_alter:

function hook_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_vocabulary']['fieldable'] = TRUE;
}


Why computed field is not getting displayed while creating content

Try adding the following JavaScript to your theme or in a module (so it's added on the page you are working on with the fields):

It's pretty rudimentary, but it works!  You might want to expand it to work on keypresses rather than .change() events.

Drupal.behaviors.jqFill = {
    attach: function(){
      $('#edit-field-half-und-0-value, #edit-field-full-und-0-value').change(function(){
        half = parseInt($('#edit-field-half-und-0-value').val());
        full = parseInt(+$('#edit-field-full-und-0-value').val());
        total = half + full;

        if(!isNaN(total)){
          $('#edit-field-total-und-0-value').val(total);
        }
      });
    }
  }

Note I got the field names from your other question here.


It does what you almost exactly described. Export to Drupal archive... creates a tar.gz file (tarball) with a backed up docroot folder (your drupal site code) & a .sql file (DB dump). This is everything you need to export your site to any host that runs MySQL/MariaDB & Apache/PHP