db_query - Get all nid in more than one nodetype

The correct way to use db_placeholders() with page_query() is shown in taxonomy_select_nodes(). In your case, the code should be the following one.

$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$args = array_merge(array($user->uid), $type);

$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $args);


Without any module it is not possible to send HTML emails. This is because the default plugin the MailManager class (which is a plugin manager) uses to effectively send emails contains the following code. (See PhpMail.php.)

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'] = MailFormatHelper::htmlToText($message['body']);

    // Wrap the mail body for sending.
    $message['body'] = MailFormatHelper::wrapMail($message['body']);
    return $message;
  }

The comment clearly states: Convert any HTML to plain-text.

If you look at MailFormatHelper::htmlToText(), you will see the code that is converting the HTML markup in plain text, in particular the following that changes any  tag as you saw in your test email.

  // Replace inline  tags with the text of link and a footnote.
  // 'See the Drupal site' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(]+?href="([^"]*)"[^>]*?>(.+?))@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();
  $footnotes = '';
  if (count($urls)) {
    $footnotes .= "\n";
    for ($i = 0, $max = count($urls); $i < $max; $i++) {
      $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
    }
  }

You need a module that defines a new mail plugin using a different implementation of the format() method and make the MailManager class use it. As said in the documentation for MailManager::getInstance(), the class uses the configuration in system.mail.interface. (The array returned from \Drupal::config('system.mail.interface').) In your example, an array value for custom_forward_formard (e.g. 'custom_forward_forward => 'custom_forward_mail', where custom_forward_mail is the plugin ID for the class implemented by your module) would do the trick.


How to create a select box field to select from a filtered list of articles?

Step 1

To have such a list of articles that can be referenced, you should first (repeat: first) create a view (with the Views module) to create a list of all the articles that are allowed to be selected. And the display type of such view must be an Entity Reference display.

Step 2

Your select box field (to select from a filtered list of articles) should be field that looks like so:

Field Name = Anything you want, eg field_articles_list.
Field Type = Entity Reference, using these additional settings for it:

Target type = node
Number of values = 1 (probably, though something like "unlimited may do as well).
"Mode" (within "entity selection") = Views: Filter by an entity reference view. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an Entity Reference display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
Pick any of the other options to define this field as you see fit.


In fact, like it's a custom field type, your change in the schema can be detected and applied if you launch the drush command drush entity-updates (or drush entup).

All tables which implement this field (like node__field_my_field_type or paragraph__field_my_field_type) will be updated. So you don't need to use an hook_update to update the schema of all these tables.

The big problem with this command is many errors are silent and sometimes, the command don't return errors but the schema hasn't been updated and still proposed by the command to be updated.


How to send an email to a specific user on new account creation using Rules?

You can do setting "admin/config/people/accounts" to sent notification email on account activation.


Create a multistep Webform and set to "non-linear" with sidebar showing which steps have been completed?

I searched for how to create this functionality, and found this on the drupal site Link for creating multi-step webforms


With the form elements you are using, the output you obtain is the following one.

        Check1

          <input type="checkbox" id="check1" name="check1" value="1" class="form-checkbox">

        Check2

          <input type="checkbox" id="check2" name="check2" value="1" class="form-checkbox">

        Check3

          <input type="checkbox" id="check3" name="check3" value="1" class="form-checkbox">

        <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">

 is wrapped to all the elements because it's a prefix for $form['basic'], which contains all the form elements.

I would use the following code.

  $form['basic']['keys']['check1'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check1',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix'=> '

',
    '#suffix' => '
',
  );

  $form['basic']['keys']['check2'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check2',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['basic']['keys']['check3'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check3',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '
',
    '#suffix' => '

'
  );

  $form['basic']['keys']['text'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type'=> 'textfield',
  );

Its output is the following one.

        <input type="checkbox" id="edit-check1" name="check1" value="1" class="form-checkbox">
        Check1

        <input type="checkbox" id="edit-check2" name="check2" value="1" class="form-checkbox">
        Check2

        <input type="checkbox" id="edit-check3" name="check3" value="1" class="form-checkbox">
        Check3

    <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">


Can I add the value of a field in a checkout pane to a completed order email?

Typically, you'd alter a form via hook_form_alter() and then sort out through a custom validate / submit handler how to process and save the data so it could be used later. However, I'd recommend something different, because in that approach you'd have to also create a place to store the data and a way to render it in a token, field, Rules data selector etc. yourself.

The easiest way to collect data and use it later in these various scenarios is to use a field. So instead of altering the form directly, I'd figure out how to get a custom field into the checkout form. You have two basic options:

If the data has something to do with customer profile information, like billing or shipping information, simply add the field to the customer profile type and it will appear on the checkout form. I'm not entirely sure how the token system works with respect to the Rules e-mail action, but the data will be there and field tokens will be there to make it happen somehow. Might require further investigation or a module.
If this data is stand alone and you just need it to appear on the form in its own checkout pane, I'd add the field to the order in a fieldgroup and use the Commerce Fieldgroup Panes module to make it into a checkout pane. Then you'd have the field data on your order usable from a token as well.


Drupal's attach behaviours : react on all newly loaded content?

This, from the comments in misc/drupal.js, explains how it's supposed to work:

Drupal.attachBehaviors is added below to the jQuery ready event and so
runs on initial page load. Developers implementing AHAH/Ajax in their
solutions should also call this function after new page content has been
loaded, feeding in an element to be processed, in order to attach all
behaviors to the new content.


Running a customized cron task very often

Is it overkill to run drupal cron so frequently ?

The answer to that is...it depends. If your cron task needs to run every 10 minutes, then no, it's not overkill. If it doesn't, then it is overkill. What you probably need is something like Elysia Cron, which lets you schedule cron jobs for specific modules on a an individual basis. That way you can run your custom labour-intense function as often as you need to without invoking the rest of the system's cron hooks.

  What are the main tasks that drupal cron is executing ?

There's a list of core hooks that will be invoked on a cron run here, I don't think listing each one of those here would be prudent (there are 16 of them) - suffice say to say quite a lot happens; the caches are flushed which is probably a point of interest.

Bear in mind that many contrib modules also implement hook_cron(), so if you want an exhaustive list of functions that are invoked on cron you'll need to go through those files manually.

  I understand that every task run within cron must check the last time it was executed so it is not run too frequently,

The must part of that is not true, there's no 'rule' for whether a task run on cron needs to check its last run time. There are plenty of situations where such a mechanism would be advantageous, but you absolutely don't need to do it. Again it depends on what each task is actually doing.


Field template in theme based on Garland

Your preprocess function is not necessary in this situation because Drupal's default behavior is using this sort of files. Try print_r($variables['theme_hook_suggestions']); and see all relevant suggestions.

Your problem is the wrong filename; try field--field_is_new.tpl.php instead.

The general recommendation is using theme functions:

function theme_field__field_taxonomy($vars) {
  $output = '';

  foreach ($vars['items'] as $delta => $item) {
    $array = explode(';',$item['#markup']);

    if (count($array)) {
      $output = '
';
      foreach ($array as $value) {
          $output .= '
' . trim($value) . '
';
      }
      $output .= '
';
    };
  }

  return $output;
}


Definitely you will have to change your preprocess hook to replace arg(3) that is hard coding it in an aspect and definitely not make it suitable for manual call.

Can you please investigate $variables for the value being passed as argument to theme()? I hope you will get it there.


Finally found it. I knew it had to be something simple.  I was using the wrong field type. Turns out it should have been list_boolean instead of simply boolean.  I also simplified the code

    <?PHP
        /**
         * @file
         * Creates a custom format for boolean fields, a checked checkbox for true
         * and unchecked for false
         */

        /**
         * Implements hook_field_formtatter_info()
         */
        function CheckBoxFormatter_field_formatter_info() {
            return array(
                'checkboxes' => array(
                    'label' => t('Checkboxes'),
                    'field types' => array('list_boolean')
                ),
            );
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function CheckBoxFormatter_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
            $output = array();
            $img = array("uncheck.jpg","check.jpg");
            $disp = array("Unchecked","Checked");

            if($display['type'] == "checkboxes") {
                foreach($items as $delta => $item) {
                    $output[$delta] = array(
                        '#markup' => '<img src="' . $img[$item['value']] . '" alt="' . $disp[$item['value']] . '" />'
                    );
                }
            }
            return $output;
        }


media library thumbnails missing for txt and pdf

Using 7.x-2.x-dev instead of 7.x-1.1 solves this.


How to add expose View filter for a derived field

Sadly I needed to filter the results myself in the Views alter hook.

Results Alter,
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Query Alter
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7


How to increase priority of my custom CSS?

You have added wrong CSS here. Background color will not works with tr tag because we have style of td over tr tag.
Please correct with this code

tr.distrib0 td {
 background-color:#FF0000 !important;
}


The second example won't work because user_profile_form() takes a user object as it's argument, not an id. I suspect your form is not being outputted because you're not actually calling print on it...render() just prepares the string it doesn't actually output it.

Try this code:

$account = user_load(1);
print render(drupal_get_form('user_profile_form', $account));

EDIT

You'll also need to include the user.pages.inc file where the function itself lives:

module_load_include('inc', 'user', 'user.pages');


No matter which size is my viewport, the narrow.css file is the only one triggered with IE7 and IE8 in my Omega site

You can load css file by using this code:

drupal_add_css(path_to_theme() . '/css/ie8.css', array(
  'weight' => 999,
  'browsers' => array('
      !IE' => FALSE,
      'IE' => '(lt IE 9)&(!IEMobile)'),
      'group' => CSS_THEME)
);

== 2nd option ==

try Respond.js module

  This Drupal module provides IE 6-8 support for responsive themes.


Drupal 8 separate pages for separate taxonomy terms

Finally I found answer and posting it here in case someone needs it.

To do this you need to create the following function in your your_template.theme file:

use Drupal\taxonomy\Entity\Term;

function stravel_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()
      ->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()
      ->getRawParameter('taxonomy_term')
  ) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

This allows you to create page templates such as page--taxonomy--mytaxonomy.html.twig to display single term data. Now you can easily add regions, blocks and views as usual.

However,
to display data related to the relevant term, you need to add contextual filters.


Ranjan is correct, you should add a node reference field to the Project content type so it can reference a State-Capital

In order to display any info about the state on the Project page you can use the Views 3 and Reference modules.

For this example let's say the node reference is labeled "Project Location", and the State Capital is Austin, Texas.

Here are some steps you can follow:

1) Create a View

-- Create a new view block that displays State-Capital type nodes.

2) Add a Relationship to the view

-- Add a Relationship: Content: Project Location. This will allow you access to the fields of the Projects that reference Austin, Texas.

-- Give the relationship an identifier. Let's say related_project.

-- Save the relationship.

3) Add a Contextual Filter to the view

-- Add a Contextual Filter: Content: Nid.

-- Edit the contextual filter.

-- Set the Relationship in the contextual filter to related_project.

-- Look for WHEN THE FILTER VALUE IS NOT IN THE URL.

-- Set it to Provide default value -> Content ID from URL. This will get the nid of your Project.

-- Save the Contextual Filter.

-- Add in your fields. (Title at least)

4) Test it

To test in the preview, input the nid of your Project example as a contextual filter in Preview with contextual filters:

Save your view!

5) Enable the block in your node pages

After the view is complete, configure the new block to display in content type Projects.

I hope this helps.

Updated: 2014/06/18


Redirecting user links to their profile2 pages

This can be done with a combination of

hook_preprocess_username (make links go to profile path)

Something like:

function MYTHEME_preprocess_username(&$variables) {
  $account = $variables['account']
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // This gets passed onto theme_username
    $variables['link_path'] = 'user/' . $variables['uid'].'/profile/path';
    // Possibly:
    // $type = $profile->type();
    // $path = profile2_page_get_base_path($type) . '/' . $account->uid
  }
}

and then the picture override in

hook_preprocess_user_picture (override user picture)

Something like:

function MYTHEME_preprocess_user_picture(&$variables) {

  $account = variables['account'];
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // You could use a custom 'display' parameter, e.g image_style
    $image = field_view_field('profile2', $profile, 'field_image');
    $variables['user_picture'] = render($image);
  }

}


Here is how to use cache tags in the context of custom blocks which I have tried and works but I think it applies to other contexts
Use default drupal tags
In the build array you can specify cache > tags > node_list and this block content would get invalidated (refreshed) when ANY NODE is  changed with nothing else to do on your part
public function build() {
    return array(
        '#markup' => MY_MODULE_awesome_dynamic_node_content(),
        '#cache' => [
            'tags' => ['node_list'], //invalidate when any node updates
            //'tags' => ['node:1','term:2'], //invalidate when node 1 or term 2 updates
        ],
    );
}

Alternatively you can put in one or more node/term/user IDs to invalidate the array on specific nodes or terms as shown in the code comment above.  Note: you can mix and match nodes, terms, users and custom tags as you see fit.
Use your own tags
if you want to have your own way of clearing your build array add your custom unique tag in the build array (any unique string will do)
public function build() {
    return array(
        '#markup' => MY_MODULE_awesome_dynamic_node_content(),
        '#cache' => [
            'tags' => ['MY_CUSTOM_UNIQUE_TAG'],
        ],
    );
}

and in your custom code logic call invalidateTags with your own tag
function MY_MODULE_custom_clear_cache_logic(){
    ...
    \Drupal\Core\Cache\Cache::invalidateTags(array('MY_CUSTOM_UNIQUE_TAG'));

if you want to read more about drupal 8 cache internals


How to test upgrade availability with drush exit codes?

The exit codes are defined in includes/drush.inc. Your logic seems sound, but I can't verify that is correct/always will work.


Getting Files to show up on new submitted Module page

Found answer. Apparently I missed the part where sandboxes do not have download buttons on the project pages. And I was trying to add an issue for MY project, rather than submit an issue to Drupal.org.


You are looking for cache_clear_all. You want to set first argument $cid to NULL, as you want expire all your objects. Now you only need to figure second argument, $bin. For sure you have to clear cache_page bin. If it's not enough, look inside your database for cache_% tables (where % means any string, per SQL standard) to know what bins are available to you.

Last but not least, dynamic regions may be huge performance hit. Think twice if that's what you really need.


The main error is that you aren't passing the last two arguments of  file_save_upload() to that function, since you are putting them in the array you pass as second argument. The code you are using is the following one; see the comments I added.

  $file = file_save_upload('calllogrtap_file', array(
    // First line of the array
    'file_validate_extensions' => array('csv'),
    'public://mrtap/', FILE_EXISTS_REPLACE
    // Last line of the array
  ));

As you aren't passing the last two arguments to file_save_upload(), the function is using the default values for those parameters, which are:

$destination = FALSE
$replace = FILE_EXISTS_RENAME

The first values is making Drupal save the uploaded file in temporary://; the second value is telling Drupal to rename the file if there is already a file with that name.

The function call should be the following one.

  $file = file_save_upload('calllogrtap_file', array('file_validate_extensions' => array('csv')), 'public://mrtap/', FILE_EXISTS_REPLACE);

If you change the code in this way, then the following code line is not necessary, since the uploaded file is already moved in public://mrtap/ from the call to file_save_upload().

$file = file_move($file, 'public://mrtap/', FILE_EXISTS_REPLACE);

If filename is the ID of the form element for uploading the file, the following code probably needs to be changed.

$form_state['storage']['filename'] = $file->uri;

Probably, the correct line is the following one.

$form_state['values']['filename'] = $file;

I would also keep the code to validate the user input in upload_rtap_validate(), and the code saving the file as managed file in upload_rtap_submit().
For example, see the code used from the form handlers for system_theme_settings(), system_theme_settings_validate() and system_theme_settings_submit(). (I replaced the comments with mine.)

  // system_theme_settings_validate()
  $file = file_save_upload('logo_upload', $validators);
  if (isset($file)) {
    // The user upload the logo file.
    if ($file) {
      // The uploaded file passed the validation in $validators.
      $form_state['values']['logo_upload'] = $file;
    }
    else {
      // The file upload failed.
      form_set_error('logo_upload', t('The logo could not be uploaded.'));
    }
  }

  // system_theme_settings_submit()
  // If the user uploaded a new logo, save it to a permanent location.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

In your case, you could use file_copy() instead of file_unmanaged_copy(), or file_save() as your code is doing.


I think you are looking for Remember values

  This module enables Drupal to remember entered values from selected
  fields upon new node submission, stores them in the database and then
  pre-fills appropriate fields on the next node-add form. This is useful
  when a user needs to enter many nodes at a time and some of the
  fields' values are repeating.


Module for managing permissions on per node basis integrated with shopping cart or checkout

Content Access module restricts users per node basis or per content type basis.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

You need to use commerce checkout hooks and Content Access API to achieve this. Try rules modules too it may help with out using coding also.


Custom fivestar widget does not display custom icons

Without seeing your file structure it is difficult to discern your problem.  But I suspect the hook is having issues with the path to your css.  I have found a really nice tutorial to do this, it setups a widgets folder in your custom module and uses file_scan_directory to scan all custom star folders in that folder.

https://www.drupal.org/node/234391

Be mindful that there is a slight error in the code as it is outdated, in the foreach, you need to use $file->uri instead of $file->filename for the array key.

foreach ($files as $file) {
    if (strpos($file->filename, '-rtl.css') === FALSE) {
      $widgets[$file->uri] = drupal_ucfirst($file->name);
    }
  }


"Fatal error: Call to a member function setFormClass()"

The code shown in the question doesn't correctly bootstrap Drupal. An external script needs to do that, differently from a module. While loading the autoloader allows PHP to find the Node class, that isn't sufficient to bootstrap Drupal correctly.
I usually use the authenticate.php file as guideline for writing code for an external script file that needs to bootstrap Drupal.
use Drupal\Core\DrupalKernel;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

// Change the directory to the Drupal root.
// Edit the following line to make it point to the directory containing the autoload.php file.
chdir('.');
$autoloader = (require_once 'autoload.php');

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

  // A route is required for route matching.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);

  // Ensure our request includes the session if appropriate.
  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('node', 'core/modules/node');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('node');

$node = Node::load(123);
$node->set('field_number', 222);
$node->save();

Actually, $kernel->preHandle($request) should be sufficient to load all the modules, since it contains the following code.
// Load all enabled modules.
$this->container->get('module_handler')->loadAll();

The code that explicitly loads the modules isn't necessary. At the same time, not explicitly loading the modules makes the code dependent from the installation profile, as the previous code line only loads the modules the installation profile enabled.


Using Fieldgroups with Entity Registration Module

You need to add corresponding group to add steps in it. See image.


How to measure time taken for a Feeds processing (benchmarking)?

The Ultimate Cron module will tell you how long the import takes and keeps track of time for each feed import.

In your feed Basic Settings, for Periodic Import, make sure you set it to As often as possible.

In Ultimate cron, jobs tab, Remember to run the scheduler cron job first, then the Feeds cron jobs

Once you have a number, you can manually do the math on how many nodes per second.

Note: the cron run speed will vary based on your server machine. A more powerful machine will get the cron job done quicker.


creating and theming register form in drupal 7

You can try this one

To implement hook_form_alter() in a module and set the form's #theme property:

    function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

and add this code to template.php

    function mytheme_theme($existing, $type, $theme, $path){
      return array(
        'user_register' => array(
          'render element' => 'form',
          'template' => 'templates/user-register',
        ),
      );
    }

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

Also, create a user-register.tpl.php in

  sites/all/modules/YOUR_module/templates/user-register.tpl.php

to add the 'markup' for the desired output and

<?php echo $rendered; ?>

to print the form.

For more information, follow this https://www.drupal.org/node/1211520

Hope, it works.


I found a way to do this, but I'm still interested to know if this is the right approach (and if bad things will happen with a very large number of groups and users).

Both menus are created using hook_enable in the install file of the module (the development module is an excellent example on how to do this).

Like I say in my comment, I don't think you can create dynamic menu items so I'm creating a menu item for each group (when a group is added, I need to do a menu_rebuild). To determine if the menu item should be visible for a user, I created an access callback that checks if a user is part of that group. This callback will be called with every page request, so it will always work.

The secondary menu works with a wildcard and a to_arg function. For example, a menu item is set as $items['pmenu/%get_groupid/grouppage'] and in the function get_groupid_to_arg($arg) I'm extracting the groupid from the path with arg(1), which is returned (for details see hook_menu and the Menu example). The secondary menu items also use the same access callback to check if the user may see the menu item.

Finally I had to apply a fix for the theme, because the corresponding primary or parent menu item (group) would not be set as active if a secondary menu item was selected. I'm using Marinelli and applied the patch in comment 14 of this issue. That didn't quite work, so I changed it a bit to only look at the path when checking for a parent as described in comment 16.


Seems like there is a non-drupal solution:

if(jQuery.browser.version.substring(0, 2) != "8.") { alert("not ie8"); }

It is not very handy as I have to paste inside the brackets the content of cufon-drupal.js content.


How do I save username and password using a "Remember me" checkbox in the login form?

I think Remember me module doing the same job which you wants.


"Follow the user's language preference" option in Drupal language preferences does the trick.


Go to YOUR_SITE/admin/people/permissionsand under the Automated Logout section uncheck the Change own logout threshold option for authenticated user.


Content subscriptions/notifications from multiple terms?

I have a similar use case for my site.  What I do is utilize views loops.  I create a view rule that accepts multiple taxonomy terms (I use AND rather than OR.  I think you would too).  Any user who has all the items in their profile is then sent a PM when on Create New Content.  It's not terribly elegant but it works.  I think it may be a bit too restrictive.  But Them's the breaks.


Unlimited Custom Form Fields - Without Ajax

My issue was from improper checking of array key values. Below is the approach for non-ajax form adjustment (which is very similar to ajax).

MYMODULE/src/Form.php:

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    // Make our call to the rebuild function.
    '#submit' => ['::rebuildFormSubmit'],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      // This is important. Must check isset() to avoid Undefined index notices.
      '#default_value' => isset($config->get('field')[$i]) ? $config->get('field')[$i] : '',
    ];

  }

  return parent::buildForm($form, $form_state);

}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

Related question: Get an Un-submitted/Active Form Field Value in $form_state?.


Create a view and then under display configuration settings set Items to display = 6 and also select sorted by as Newest First. Then go to Filter Criteria and add filter  Content: Has taxonomy term Then select term "Beautiful" Then add a new block display to the view and save. Refer the images below.

Step 1:

Step 2:

Step 3:

Step 4:

Step 5:


Drupal 7 multilanguage front page using templates

theme_hook_suggestions is array

$vars['theme_hook_suggestions'] = array('page__cnfront');


It won't be available directly in the template. First you should query the content created by that user and then pass it to template file using preprocess function. Finally render the node.

First to find the node created by the user

$nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();

(Hope the user creates only one node or else you got to check it)

Then get the node content

$variables['ss_node'] = drupal_render(node_view(node_load($nid)));

The final code should be like

function template_preprocess_page(&$variables, $hook) {
  global $user;
  $uid = $user->uid;
  $nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();
  $variables['ss_node'] = drupal_render(node_view(node_load($nid)));
}

Finally you can just print the $ss_node in user-profile.tpl.php


Display suite, two layouts for the same node?

You can do this by using different view modes.

On the content type edit page (eg. admin/structure/types/manage/page) you can set a default view mode for node blocks of that content type.
On the content type manage display page (eg. admin/structure/types/manage/page/display) configure the full content display mode (or default if you haven't enabled the full content mode) the way you want the full pages to display and configure the view mode you specified in step 1 the way you want the blocks to display.
You mention display suite in your question. You can also create additional view modes using display suite (admin/structure/ds/view_modes)


That isn't possible - drupal_goto() happens server-side, and you can only affect tabs/windows with client-side code.

You would need to stop using drupal_goto(), and instead insert some javascript into the page which opens the new URL in a new tab upon refresh.

Some (including myself) would also argue that you have no "right" to do this - let the user decide whether they want a new tab or not. Be careful of trying to force your will onto them. See Target Blank is Evil for a wonderfully opinionated bit of rhetoric on the matter.


Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery

This is really just kiamlaluno's answer, but they never posted it so I'll just copy it here verbatim:

Drupal Console has not been updated to run on new Drupal versions.
It's even less compatible with Drupal 9, as many classes or methods
have been removed.


How to make several instances of nivo slider in Drupal 7?

You might want to take a look at the Views Nivo Slider module. It allows you to construct the slider using views. Since you can create blocks with views, you should be able to build several galleries (by creating other views).


Boost module, drupal-server encoding issue

boost_deliver_html_page() sounds like the issue. In your settings set $conf['boost_message_debug'] = FALSE; FALSE is the default value for that variable, this being TRUE seems to be causing the issue for you.


Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date_views/theme/theme.inc and go find line 165.

Change these two lines:

$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

To these two lines:

$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.


How to set the default value of a CCK field

In order for you to use PHP you must return a simpler array:

return array(
  'value' => 'my_text'
);

Also, if all you want is to set a default value, you don't need to use the PHP option.

First, define the allowed values (manually or via PHP, doesn't matter)
Then click save
Now click edit to go back to the form. Close to the top there will be a "Default Value" fieldset populated with the allowed values. Just select one!


Can you set the Media module to only show specific images?

Media module 2.x uses views in its media browser.  You can edit the standard view, or create new ones, and use relationships and (exposed) filters.


"Can't create table errno: -1" when trying to create the cache_rules table on D7

When importing/exporting databases from/to Drupal try using Backup & Migrate as this only attempts to backup the structure of the cache tables rather than the data too.


You have to render the content build() returns:

block.html.twig:

...

{{ content }}

Even if it's only an empty markup string. Otherwise the cache max-age can't bubble up.

A better approach would be to return from build() a custom template, which you use for the html markup instead of the block template. See https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

Then you don't need a preprocess hook and caching works with the default block template.


Drupal 7 cron does not run civicrm Scheduled Jobs

You should configure a separate cron entry for CiviCRM on your server. CiviCRM's Managing Scheduled Jobs is the reference documentation here.

Best practice is to run your CiviCRM cron separately.

Many CiviCRM tasks (eg delivering large email runs) are not suited to Drupal's typical cron schedule.
Running CiviCRM cron from Drupal means that an issue with another Drupal module timing out or causing cron to fail may prevent CiviCRM tasks running.
Likewise, running CiviCRM cron from within Drupal might prevent other Drupal cron tasks firing if CiviCRM cron timed out or failed.

While it may be possible to configure Drupal to run CiviCRM's cron (eg CiviCRM Cron or Elysia Cron modules), I wouldn't recommend that approach.

Things to check when debugging CiviCRM cron -

Are you calling cron from the same user account that your webserver runs as? CiviCRM cron tasks may write access to the templates_c/ directory and can fail if called as a user which can't write there.
Do the tasks execute when called from the CiviCRM Scheduled Tasks page? Visit civicrm/admin/job?reset=1 then click More > Execute Now
Is there output from the PHP command to execute CiviCRM cron? If so it may indicate errors. Use su to assume the user account your webserver runs as when doing this.

Since we use Drupal extensively with CiviCRM, we fire most site crons using

drush -u 1 @example.org civicrm-api job.execute auth=0 --out=json

where @example.org is a configured alias for the site in question.

We call CiviCRM cron frequently (max wait for a site is a few minutes) to reduce wait time and avoid queue buildups.

A cron entry for a site might look like this in /etc/cron.d/civicrm

MAILTO=webmaster@example.org
*/7 * * * *    www-data    drush -u 1 @example.org civicrm-api job.execute auth=0 --out=json

... but you'll need to adjust this for your environment. You might want to call specific tasks frequently and others once a week; you definitely would need to check the user, Drush alias, and path to Drush shown above!

We also route our cron output to syslog for analysis, but that's well outside the scope of this. CiviCRM cron doesn't set the Drush output status (drush_log()'s $type parameter) as other Drush commands do.


Comments - Allow deletion of comments on your content without Administer Comments permission?

Should be doable with the User Comment module in Drupal 6, or the Comment Access module in Drupal 7. They both add permissions so that authors can approve, delete or administer comments on their own content.


how do I get the depth of a MenuLinkContent?

Here is our approach:

$menu_link = $variables['element']['#original_link'];

$depth = 0;
$parent = $menu_link->getParent();
if ($parent) {
  while ($parent) {
    $parent_parts = explode(':', $parent);

    $parent_entity = \Drupal::service('entity.repository')->loadEntityByUuid($parent_parts[0], $parent_parts[1]);
    $parent = $parent_entity->get('parent')->get(0)->value;
    $depth ++;
  }
}

Hope to help


How to access referenced entities programmatically

The following $node->get('tags')-referencedEntities() will return a list of all the referenced entities.


How do I open up a YAML Form in a bootstrap modal window

The drupal way to do this would be to use blocks. The YAML Form module has the feature to put form in blocks. Place the form block in a region, where you want to have it on the page. Then style it in a block template:

block--my-form.html.twig

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

                {{ content }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


Should I use the theme layer or a module to create a complex, static page?

The "Drupal way" would be to NOT create a module to hold content, and NOT create a module for a specific page(s). "Drupal way" would likely be to (1) put all of the language/content w/markup into a node, (2) put other outside-of-content markup and styles into *.tpl.php files and css files, (3) put any PHP functionality that isn't available already in contrib into a custom module, and (4) NOT put any content/language into a theme or into a module.


How do I ensure new dependencies added to the info.yml of an existing enabled module are picked up?

I think you are mixing dependencies to modules with dependency to libraries. Your code adds a PHP module dependency to core/jquery, and I don't know any module of this name.
(When in module.info.yml)
If you want to add a (JS or CSS) library dependency, use the libraries: key and not dependencies:
(When in module.libraries.yml)
Remember that just defining a library does not automatically load it, you still must add it in module.info (or load it dynamically)


wrong translation in admin/structure/views

The Views list is a config entity list and these are listed override free:

ConfigEntityListBuilder::load

  public function load() {
    $entity_ids = $this->getEntityIds();
    $entities = $this->storage->loadMultipleOverrideFree($entity_ids);

    // Sort the entities using the entity class's sort() method.
    // See \Drupal\Core\Config\Entity\ConfigEntityBase::sort().
    uasort($entities, [$this->entityType->getClass(), 'sort']);
    return $entities;
  }

This is intentional. The pros and cons are discussed in these issues:

Config entity admin lists show configuration with overrides (eg. localized)

Menu overview always shows the untranslated config entities


Referencing other nodes created by the same author

some time ago, I created something similar. A drop down box (client profile) for the current user only - i.e. when creating a content type, the user would be able to choose a client profile, but only from a list of client profiles THEY authored.

I accomplished this using the following:

using a custom Node Reference Module, I created a field on the content type that used the node reference as a drop down box
added the following to the .module file, around line 878:

global $user;

if($user->uid != '1') $query->condition('n.uid', $user->uid, '=');

This creates a condition on the sql query that if the user isn't 1 (admin) it references the user id of the node creator, relative to the current logged in user, while Admin can override

If you going to go with this approach, be sure to rename the files and module into a CUSTOM module (I renamed mine custom_node_reference for simplicity).


Managed file input is removing input values of appended input fields by ajax

I'm not sure if this is a good solution, but now I'm taking values from $state['input'] instead of $state['values'].


Any function that is part of the database abstraction layer in Drupal 7 works with every database engine for which there are the necessary classes to work with that database engine.

If you look at the code of db_query(), you will notice it is generic enough to work with every database engine.

function db_query($query, array $args = array(), array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }

  return Database::getConnection($options['target'])->query($query, $args, $options);
}

This code is not different from the code executed by db_select().

function db_select($table, $alias = NULL, array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->select($table, $alias, $options);
}

If you compare those functions with the code executed from db_delete(), you will notice the functions are essentially wrappers around Database::getConnection().

function db_delete($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->delete($table, $options);
}

It is Database::getConnection() that, indirectly, builds the object necessary to execute the queries in the database engine, using the following code.

  $driver_class = 'DatabaseConnection_' . $driver;
  require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
  $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
  $new_connection->setTarget($target);
  $new_connection->setKey($key);

As SQLite is supported in Drupal 7, db_query() doesn't need to be altered to execute optimized code for SQLite, as the code that it is optimized for that database engine is already contained in the DatabaseConnection_sqlite.


Is it possible to call response()->setStatusCode() within hook_theme_suggestions_page_alter?

You don't need this code by the way, it is in core since D8.8.x, see https://www.drupal.org/node/2960810.
If you want to change the status code then do this in an event subscriber. If you want Drupal to build a normal 404 page and only change the status code of the already built error page then use a response event subscriber and set the status code:
$response->setStatusCode(200);

See this answer for the scaffolding https://drupal.stackexchange.com/a/201297/47547


Install the devel module http://drupal.org/project/devel. In your code call dpm($form);


Views have the CSS class option under Advanced (third column). There you can set the class to be output to all displays of that Views or override for single Displays.

Most themes won't output that class directly on the <table> element, it is usually output on a <div> that contains the table.

That can be enough for styling in CSS, but if you want you can override the twig template or use the preprocess function in your theme for more control.


How to increase the speed of SQL Views queries?

Take the query from the Views admin and from the mysql command line, or phpmyadmin add the EXPLAIN keyword in front of it. Assure it's using indexes on query criteria and that the query is optimized.

If it's not a fully optimized query then simply add an index to your SQL schema as needed until it's as optimized as it can be.

You can either add the index directly to tables through phpmyadmin, or create a module to index the necessary db fields (and then drop indexes if the module is disabled).

Drupal ships with a db that is not fully optimizted for any query you could generate with views. Module creators make general assumptions in the table they make to provide primary keys for example -- but they don't index every column of their schemas as taht would be wasteful. How you use Fields on your site is different from how I would use fields on my sites ... etc.

1 module that may help you index your Drupal fields (after evaluating the EXPLAIN output is) Field Index:

  Field modules don't always add indexes for its columns (value column
  of text field for example), this leads to poor performance in views
  when we would like sort or filter views using the unindexed columns.
  We can check the query executed by views and add custom indexes
  manually, but it's not easy to deploy.

  With field_index module, we can create custom indexes for fields. The
  indexes are exportable.


Copying a site to a multi-site installation

How can I confiure it so it works on / rather than on /drupal7

This has to do with your Apache VirtualHost. It probably is pointing to /usr/share/ instead of to /usr/share/drupal7. So in order to access the content in the drupal7 folder, you need to add the folder to the url.

  Question 2: How can I fix the 404 error?

Relating to:

  But if I go to e.g. www.foo.com/drupal7/members I get: 404: The requested URL /usr/share/drupal7/index.php was not found on this server.

The first thing is figuring out if there is an index.php file there. If so, does it have the correct permissions?

It seems to be an Apache error, not a Drupal error at this point. ;)


I don't know of a Drush command for this, but if you know your view's machine name or ID wiping it from the database isn't too hard.

SELECT vid FROM views_view WHERE name = 'your_views_machine_name';
DELETE FROM views_view WHERE vid = id_from_above;
DELETE FROM views_display WHERE vid = id_from_above;

That should be the last you ever hear from that view.


The right way to do this if you are using a Drupal module is to set up a form using the Form API and process things within the context of a module. You can also use a contributed module such as Webform to accomplish this too, but if you want something really custom, you should not just create a form in a template file.

All of this said, make sure your "action" is set to the same path as your menu item and that after you have created your hook_menu entry you clear the cache, so your menu item becomes part of Drupal's menu registry.


How to create a "read more" button using AJAX in a module?

That tutorial won't help you. That's for more advanced stuff.

I would not use a form, but a simple link with an ajax response.

But if you want to use a form you need to create a proper Drupal form. Too much to write here to explain that so just take a look here https://www.drupal.org/node/2117411

Your buildForm should be something like

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // The default value for working with non JS should be taken from the route and adding 1.
  $form['page_number'] = array(
    '#type' => 'hidden',
    '#default_value' => 0,
  );
  $form['my_stuff'] = array(
    '#type' => 'value',
    '#value' => [],
  );
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Read more'),
    '#button_type' => 'primary',
    '#ajax' => array(
      'callback' => 'Drupal\example\Controller\MyController::myFormSubmit',
    ),
  );
  return $form;
}

You can call this form in your page with (changing accordingly):

$form = \Drupal::formBuilder()->getForm('Drupal\example\Form\ExampleForm');

You do all the stuff you want in your submitForm, and not in the callback if you want the form to work without JavaScript. If you don't care you can do in the ajax callback. I will assume you do it in the submitForm.

/**
 * {@inheritdoc}
 */
public function submitForm(array $form, FormStateInterface $form_state) {
  $page = $form_state->getValue('page_number');
  $stuff = getStuffFromDatabase($page);
  $result = array();
  foreach($stuff as $key => $item) {
    $tmp = new \stdClass();
    $tmp->id = $item->id;
    $tmp->title = $item->title;
    $tmp->description = $item->description;
    $tmp->image = $item->image;
    $result[] = $tmp;
  }
  $page++;
  // Here for non JS you probably would just redirect to the proper page
  $form_state->setValue('page_number', $page);
  $form_state->setValue('my_stuff', $result);
}

Then in your MyController::myFormSubmit

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AfterCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

public static function myFormSubmit(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $selector = $form_state->getValue('my_stuff');

  // Here you build the render array based on the output you want on the page
  $build = [
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  ];
  // The selector is as if you did this in jQuery
  $response->addCommand(new AfterCommand(
    '.some-selector',
    $build
  ));
  $response->addCommand(new HtmlCommand(
    '.some-selector-that-wraps-the-form',
    $form
  ));
  return $response;
}

That's the gist of it. It should put you on the right track.

If you want to use a simple link. You need your initial function to take that into account and send what you have now for non JS and a response as in the ajax submit callback when it's called through JS.

Note that if you add a class "use-ajax" to a link and write the link as "/some/path/nojs" Drapal.Ajax will change that to "/some/path/ajax" so its easy to know if the called was made through Ajax or not.


Manage Display formatting settings won't work

Manage Display is for the front end, not the back end (i.e. not the entity edit form).

When the field value renders on the front end, you'll see the formatting you've chosen.

There's probably not much point trying to force formatting for a number in the backend, it makes more sense to take the raw number and then only manipulate it upon output. But if you absolutely need the functionality, it'll likely be a custom JS job as Drupal doesn't have anything built in to handle it.


Add an existing field is belong to Drupal core only.

You are not getting the option to Add an existing field because you have not created any field as of now. You cannot add an existing field until you have created it as a new field first. After you have created the new field, you can attach that field to multiple content types using Add an existing field

The Drupal.org documentation does not recommend that you re-use fields:

  "It is recommended to create new fields, rather than reusing existing
  ones, unless you have a clear reason to do so".


Webform radio button sets common functionality

AFAIK javascript is the only option and I do not see any help in the Drupal webform module

You could do it effectively in javascript/Jquery.

Another option as Beebee suggested you could force all the 4 radio buttons into a single set.

<div id="content">
 <input type=radio name="chooseme" value="1" />
 <input type=radio name="chooseme" value="2"/>
 <input type=radio name="chooseme" value="3"/>
 <input type=radio name="chooseme" value="4"/>
</div>

Now,user would be left to choose any one of the four radios.


You can found it at https://www.drupal.org/project/contribute

  The Contribute module adds a 'Community information' section to
  Drupal's status report (/admin/reports/status) which encourages
  individuals and organizations to join the Drupal community, become
  members of the Drupal Association, and contribute to Drupal projects,
  events, and more.

Maybe you should read this article: The Webform module now depends on the Contribute module


How do I break my query result into smaller chunks

According to https://www.drupal.org/node/1848368

  Queries may also be restricted to a certain subset of the records
  found. In general this is known as a "range query". In MySQL, this is
  implemented using the LIMIT clause. To limit the range of a query, use
  the range() method, which takes two arguments: the first specifies
  offset and the second specifies limit

  In most cases we want "the first n records". To do that, pass 0 as the
  first argument and n as the second.

<?php
// Limit the result to 10 records
// where 0 is offset and 10 is limit
$query->range(0, 10);
?>

  The following example will instruct the result set to start at the 6th
  record found (the count starts at 0) rather than the first, and to
  return only 10 records.

<?php
$query->range(5, 10);
?>

  Calling the range() method a second time will overwrite previous
  values. Calling it with no parameters will remove all range
  restrictions on the query.


How to get acces to XML tag attributes via XPath parser settings?

Solution is:
using Xpath string() function

string(@Id)

string(@Name)

string(@TypeMU)


For Drush 9.5.2 and Drupal 8.6.5 I use the following:

drush theme:uninstall THEME_MACHINE_NAME
drush theme:enable THEME_MACHINE_NAME
drush config-set system.theme default THEME_MACHINE_NAME


en/ language prefix remains after uninstalling internationalization module and dependencies

the en/ prefix comes from core module Locale, you can change the configuration here: /admin/config/regional


Re-indexing of site stalled, & running cron won't advance

This problem was caused by discussion forum posts with a single comment from a user whose id was no longer in the user table (threads with more than one comment, even though one was from an invalid user id, did not cause the error).

The fix was to find comments with invalid user ids, then change those ids in the Comment table to 0.

This SQL query identified the problem user ids:

SELECT DISTINCT a.uid FROM comment a left join users b on a.uid = b.uid
WHERE b.uid IS NULL

With the problem user ids identified, you can either edit the table directly, or use UPDATE to change the column values.

With those values changed in the comment table, the re-indexing proceeded to 100% without a hitch.


How to make page.html.twig based on Vocabulary?

Because you have not included the PHP code that contains the Class.

See Namespacing in PHP.

According to term.php the name space is Drupal\taxonomy\Entity.

So you need to add use [name space]\[class name]; at the top.

Therefore, it would be use Drupal\taxonomy\Entity\Term;.

Example:

<?php

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}


Use a different confirmation url on completed webform submission in email confirmation link

There is actually a Set the redirect URL field in the "confirmation" email page setting which i totally missed. See below:


How to alter country dropdown in location module?

You are correct, hook_form_alter() is a good start.  If you are looking to alter a content type form (and the CCK Location field), one method I have used is to create a really small and simple custom module implementing hook_form_alter().  Details/instructions on creating this module can be found below (for Drupal 6, should be similar if not the same for 7).

As an example, I am calling this module 'custom_countries', if you want to change the name, you can always rename the files and do a search and replace in them later.

First you need to create a new folder in your modules folder (sites/all/modules, etc).  (All files created from now on should be placed in this folder). Next, create a new file called custom_countries.info and put the following inside and save:

name = "Custom Countries"
description = "Changes the list of countries available from Location module for certain content types"
core = 6.x

Next, create another file called custom_countries.module, place the following code inside and save the file:

<?php
/**
 * @file custom_countries.module
 * Module to change the countries options of location module
 * for certain content type(s)
 */

/**
 * Implementation of hook_form_alter()
 */
function custom_countries_form_alter(&$form, $form_state, $form_id) {
  // Replace "YOUR_CONTENT_TYPE with the name of the content type desired
  if ($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['#after_build'][] = 'custom_countries_after_build';
  }
}

/**
 * Make changes to countries field after all fields are rendered
 */
function custom_countries_after_build($form_element, &$form_state) {
  // Replace FIELD_NAME with the machine name of the location field for your content type
  $form_element[FIELD_NAME][0]['country']['#options'] = array(
    'ca' => 'Canada',
    'us' => 'United States',
  );
  return $form_element;
}

Important: be sure to read the comments and change 'YOUR_CONTENT_TYPE' to the machine name of the content type your location field is in (possibly just 'profile' if using default content_profile settings).  Also, change 'FIELD_NAME' to the machine name of the location field.

Finally, enable the module at admin/build/modules.

Now when you are creating/editing the content type you specified, you will only see 2 options in the countries list.  Using this method, you can now easily make changes to other forms as well.

The idea for this came from Make Location form fields available to hook_form_alter().  If in the future you decide to add other countries, the complete list of key/value pairs can be found at http://api.lullabot.com/location_get_iso3166_list/5


How do I get Drupal to preference one of a module's .tpls over another?

Update the modules weight in the DB.

This code is for a custom module, when enabled:

/**
 * Implements hook_enable()
 */
function YOUR_MODULE_enable() {
    db_update('system')
    ->fields(array('weight' => 1))
    ->condition('type', 'module')
    ->condition('name', 'YOUR_MODULE')
    ->execute();
}


Indexing is done during cron runs. When you've set up indexing, don't ask for it to be indexed again, unless you want it to start from scratch.

If you want to increase the percentage, and don't want to wait for the next scheduled cron run, run cron manually by navigating to Home » Administration » Configuration » System  » Cron and press Run cron.

If you want to automate this, set up an external cron and trigger it every 10 minutes until indexing is done.

There is no setting to index everything instantly. If that is what you want to do, the answer is that this is not possible. You have to be patient. The reason there is no such setting is because that would put a too heavy load on your system. The system is designed to work the way it works for a reason.


Possible to use EntityStorageBase::loadByProperties() to specify that field is or is not empty?

Only in a narrow scope where "empty" for the field means the empty string ('') and it's stored as such in the DB.

EntityStorageBase::loadByProperties() uses a helper method, ::buildPropertyQuery(), that chains comparisons using the IN operator. As such, you can't use negation or special comparison cases (e.g. IS NULL if "empty" means NULL in the DB).

Unless you have simple string comparisons for your field, you're better off skipping ::loadByProperties() and using EntityStorageBase::getQuery() to retrieve a query object that you can customize to fit a "empty" / "not empty" query.


How to change head title of a page having a Omega 4 subtheme?

Changing head title for a page in Omega 4 based on node id - same approach will work for any other content. (code below goes into template.php)

Didn't test if this method supports described above HTML injection.

    function yourtheme_preprocess_html(&$variables) {
        if ($node){
        $mynodeid = $node->nid;
// this will set "Custom Title" for a node with NID = 10
        if($mynodeid == 10) {
            $variables['head_title'] = t('Custom Title');
        }
      }
    }


How do you disable Cron on a staging / dev server?

Yes, you can do this in your settings.php file (as you have mentioned that is the only difference between versions).

You would do it like this (in your settings.php file):

// Disable drupal's built in cron trigger.
$conf['cron_safe_threshold'] = 0;

For more information see Defining variables in a site's settings.php $conf array.

Edit
How this works is:

Variables are loaded from the database (or the cache if they have already been cached).
If those variables were not already in the cache they are saved to the cache.
The $conf variables from the settings file are added to the variables and take precedence over variables from the database.

So variables from the database are cached, but variables from settings.php are not.


How do I update a multi-dimensional commerce product field with Views Bulk Operation?

For any future travelers.

This may be my ignorance but it seems like you -must- use commerce_product_load(), even thought it kinda looks like the $entity object is the same as the $product object.

$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( LANGUAGE_NONE => array( 0 =>
    array('length'=>  $entity->field_length['und'][0]['value'],
          'width'=>   $entity->field_width['und'][0]['value'],
          'height' => $entity->field_height['und'][0]['value'],
          'unit'=>"in") ) );
commerce_product_save($product);


Is there any example for real project where field of deciamal type been used?

Here's a link to an explanation of Drupal's different number types (integer vs. decimal vs. float) with some examples. Basically, it breaks down as follows:

Integer: You're storing numbers without fractional digits (e.g. a field that stores a product stock quantity, XX units)
Decimal: You're storing numbers with a fixed amount of fractional digits. (e.g. a field that stores a price, $XXX.YY)
Float: You're storing numbers with a variable amount of fractional digits. (e.g. a field that stores latitude/longitude coordinates, XX.XXXXXXX..., YY.YYYYY...)

Also of note is the underlying data structures of integer/decimal/float that gets stored in the database. See Fixed point vs. Floating point for some discussion on the differences.


Image styles to make all user inserted images appear as circles

To create the image style you want, you'll need to install the ImageCache Actions module to get the "Rounded Corners" effect.  Note that when you install this module, you need to turn on several different modules in drupal (and I'm not sure which one provides "Rounded Corners"):  image_styles_admin, imagecache_canvasactions, image_effects_text, imagecache_customactions, imagecache_coloractions, imagecache_autorotate, imagecache_actions.

Once you have the Rounded Corners effect, you should be able to create the behavior you are looking for.  Here's an example:

The only thing that you can't see on the screenshot is the "radius" setting for the rounded corners effect.   To get a truly round image, it should be set to half of the height/width used in the scale & crop step.  In the example, scale & crop is set to 100x100 and radius is set to 50.  If you set scale & crop to 500x500, you'd set radius to 250.

Once you've got the image style you want, go to Administration > Structure > Content Types, and choose the content type that has the image field.  Go to the "Manage Display" tab, and click on the settings icon for the image field.  This will allow you to select the image style to be used for this image field.

You may need to do this for multiple display modes for your content type, for example "Default" and "Teaser."


Export and import content from one drupal site to another?

If you're exporting into an empty site, the Backup and Migrate module is the one you want.  It will let you clone all contents on a Drupal site, including comments.  (Or only certain tables such as thos associated with nodes and comments, if that is what you want).

The Node Export module will only let you import/export nodes.  Comments, for instance, is not nodes.

The Migrate module is a more general framework for migration (including migration data not originating from Drupal into a Drupal site).  It gives you a lot more control over the process, but I think it is overkill if all you want to do is to export and then inport into an empty site with the same version of Drupal.  Incidently, if you still want to use Migrate, check out Drupal-to-Drupal data migration.  It is based upon Migrate, but designed to specifically migrate (and refactor) data from one Drupal site into another.


Prevent path based breadcrumb in theme, or, don't show breadcrumbs for 403/404 responses?

You could add a visibility condition to the breadcrumb block. For 404 there is this module block_in_page_not_found and if you negate the condition the block is displayed on all pages other than 404's:

If you want to exclude 403 pages as well you can extend this module and add a check for

$status->getStatusCode() == 403

to Drupal\block_in_page_not_found\Plugin\Condition\PageNotFoundRequest::evaluate.

Or use the patch from this issue Allow blocks to be configured to show/hide on 403/404 pages, when it applies again.


How to disable "Add To Cart" button on select products?

On What ever products you dont want customers to buy or add to cart, the easiest solution is just hide them using css for that button alone.

.parentclass #add-to-cart
{
  display:none;
}

Or

you can use uc_auction module and let the products be auctioned for particular period of time.there will be no add to cart button.


How can I limit Webform submissions by date

Download Webform 7.x-4.0-beta3

On the Webform > Form Settings, half way down the page you can set the total submissions limit, and set time frames for limitations.


Create node--articles.html.twig and place it in your theme's templates folder.

{% if content.field_name.0 is empty %}

{{ content.field_name_other }}

{% else %}

{{ content.field_name }}

{% endif %}

Note:

content.field_name.0 gets the raw value


How to find users with password same as their username

If you are trying to do this while they are registering, there are good modules for the task, a simple search finds Password policy module, It is also on S.O:

  A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.

However for already registered users, you have to hash their username as a password and compare it to their actual hash stored in database, if they are the same, you have cracked their password!

Hashing the passwords, The Druapl way user_hash_password()like this:

$user = user_load($id_of_user);
if($user->pass == user_hash_password($user->name)) {
  block_and_punush_lazy_user($user);
}

// maybe use it like this:
for($uid=2; $uid< MAX_UID_IN_DB; $uid++) { // FROM 2 ONLY!!
  if($user = user_load($uid) {
    if($user->pass == user_hash_password($user->name)) .... // Punish
  }
}

A more quick solution is to do it solely in database using it's hashing functions. You should check the password.inc in user module and extract the hashing algorithm. implement the same function in mysql and do a:

SELECT `uid` FROM `users` WHERE `pass` = MY_CUSTOM_HASH_FUNC(`name`);

And DO make a backup of your database before doing these stuff.


Drupal's "Add to Cart" field shows product variations instead of individual options

It looks like the products you've referenced from the "wrong" image do not all share the same attribute fields in common. One frequent mistake in this regard is forgetting to toggle the checkbox on the field edit form to instruct Drupal Commerce to treat a product field as an attribute field on Add to Cart forms.


I use a function from this blog post to retrieve the fields value, it's quite handy as it allows you to parse the different values of the field (also it handles value or nid).
Drupal 7 tip : Get field values from entity objects like nodes, users, taxonomy...

Regarding the und, I'm not very sure why is this happening, I saw this issue: Field display languages are cached before locale has changed field language, but I have to wrap my head against this.


view to list already added referenced nodes to all content types by user

OK i managed to do it, for anyone curious heres how i did it:

I created a new View
I filtere it to show content of type DELIVERY
i added 2 Relationships
First relationship being the BOOK Reference field and the other being Author relationship
I then added a Contexiual Filter of NID and set it to default value and NID From URL
That was it, and i added the Book ref field to show the books


It looks like you simply don't have the migrate_tools module enabled in the Postgres environment.


Boy this is a big one. Got solution with Commerce Search API, simply re-created Kickstart's Collection view and got same result. View looks like this now:

As you can see it all runs in one Display only. Each taxonomy term menu link generates a view display for its category term listing product display nodes rendered via entities.

Also following this Commerce Search API video tutorial really helped to understand the basics how it works: http://vimeo.com/53404289


Webform doesn't send hidden input if sender is not logged-in

Can you give us the token you use for the hidden field? Maybe the token you use only available for logged user. I used hidden fields but with a general token (for example date or ip_adress) and it works fine for non logged users


My aim is the implementation of a Mediator Pattern. Best practice to do this is using the Event Dispatcher Mechanism.
This is explained here.

A good example of implementing the mechanism, even create your own event type (above the existing types of Drupal) is described here


Configuring the new display modes in Drupal 8

As you've found out through comments, the title is currently hardcoded.

The reason for that is that the title isn't controlled by the view mode in the default behavior. It's whether the node thinks he's on his own page vs. not. A behavior that's not easily configurable.

Would have been nice to fix that but like many other things, we didn't enough time.

Apart from using templates to do, you could also consider to use Display Suite, just like in 7.x, it allows you to control the title, pick from different layouts and so on.


Is there a module for tracking changes to a Drupal site's configuration?

I think you are looking for Configuration Management module.

  The module knows where configuration was changed and allows users to
  either "activate" a configuration that was changed in the datastore,
  or "write" to datastore if a configuration was changed in the
  activestore. If you enable the diff module, you can see the what is in
  the activestore vs. datastore.

and I'm not using this module before.


Modifying an Existing Entity Column in hook_update_N

cache_clear_all() with no arguments clears cache_block and cache_page only; entity and schema cache both live in the cache table, so clearing that bin explicitly should do the trick:

cache_clear_all(NULL, 'cache');

Or if you want to clear the specific entries:

cache_clear_all('entity_info', 'cache', TRUE);
cache_clear_all('entity_property_info', 'cache', TRUE);
cache_clear_all('schema', 'cache', TRUE);

I'm assuming you've already updated your hook_schema() implementation to match the new scheme, or implemented hook_schema_alter() for the same if you're doing this on behalf of a different module.


Editing the template for Comments editing page

As the comment page does not use it's own theme so you probably have to do it as outlined in this question.

But, If you just want to redirect the comment page back to the original post, the latest dev version of the Global Redirect module has a setting for this. I recently did this on a site as the comment pages were causing SEO problems.


How to save an uploaded image in an admin form?

You have used system_settings_form_submit() so you can add custom submit handler for your form by adding this code to your hook_menu

function backgroundimage_admin() {
    $form = array();

    $form['backgroundimage'] = array(
        '#type' => 'managed_file',
        '#name' => 'backgroundimage_image',
        '#title' => t('upload image, huh!'),
        '#default_value' => variable_get('backgroundimage', ''),
        '#description' => t("Here you can upload an image to the background!"),
        '#required' => TRUE,
        '#upload_location' => 'public://backgroundimage/'
    );
    $form['#submit'][] = 'backgroundimage_form_submit';
    return system_settings_form($form);

}


How to prevent User Roles from getting reapplied?

Try to run this: show tables like '%role%'; MySQL statement. In the results returned you should see a users_roles table (not users_role). To that table's columns are stored the uid and rid, therefore you will be able to find all users that have assigned with a role or more, and possibly an answer to your question.

I would kindly suggest you, since those roles are appeared again and again, to search any by chance or forgotten user_save implementation within your code.

Hope this help!


Actually its easy. Just look at the implementation Views Global handlers which is available in views.views.inc.

Below is the example how you can add field handler without having a table,

Specify your custom handlers in hook_views_data like below,

/**
 * Implements hook_views_data().
 */
 function my_module_views_data() {
   $data['custom']['table']['group'] = t('Custom');
   $data['custom']['table']['join'] = array(
     // #global is a special flag which let's a table appear all the time.
     '#global' => array(),
   );

   $data['custom']['custom_handler'] = array(
     'title' => t('Custom Handler'),
     'help' => t('Custom Handler.'),
     'field' => array(
       'handler' => 'views_handler_custom_handler',
     ),
   );

   return $data;
}

Create a inc file for your handler an put your logic there. something like below
Here the file name would be views_handler_custom_handler.inc

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
 class views_handler_custom_handler extends views_handler_field {
   function query() {
     // do nothing -- to override the parent query.
   }

   function option_definition() {
     $options = parent::option_definition();

     // Override the alter text option to always alter the text.
     $options['alter']['contains']['alter_text'] = array('default' => TRUE);
     return $options;
   }

   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);

     // Remove the checkbox
     unset($form['alter']['alter_text']);
     unset($form['alter']['text']['#dependency']);
     unset($form['alter']['text']['#process']);
   }

   function render($values) {
     // Render your content.
     return 'Sample';
   }
}

Specify this new handler file in your module's info file
Clear the caches

Now the new field handler will be there in the field list.


Block visitors based on geographic location conditionally in .htaccess on multi-site install

You can add this restriction directly in the vhost of your client instead of .htaccess. At that level you should hace a vhost per site.


The title is displayed in a block. Go to the block layout (/admin/structure/block), look for the block "Page Title", click on "Configure" and set the visibility on "Pages" to hide for <front>:


InnoDB gone missing as database type - has anyone seen this error before?

On Debian 6, this can also happen when you change the innodb_log_file_size parameter. Sometimes mysql does not start; other times, it just starts up, but the InnoDB engine is not enabled. The solution is to remove ib_logfiles from /var/lib/mysql and restart mysql.

See this issue in drupal.org.


Implement an API to use HTTP extensions like CalDAV

I solved this.
I added method to the route and @Method({'PROPFIND'}) to the source (I am not sure if this is needed for Symfony).
class DavController extends ControllerBase {

/**
 * @Method({"PROPFIND"})
 */
 public function dav() {
     //Get the data, fill into xml twig

        $response = new Response();
        $xml = \Drupal::service('renderer')->renderRoot($build);
        $response->setContent($xml);
        $response->headers->set('Content-Type', 'application/xml');

        return $response
 }

module_name.routing.yml (this seems to be mandatory):
    entity.dav_controller.dav:
        path: 'path/to/dav/enpoint'
        methods: [PROPFIND]
        defaults:
            _controller: '\Drupal\path\to\DavController::dav'
            _title: 'my_title'
        requirements:
            _permission: 'access content'

This works in 8 and 9.
Note that this does not involve the Drupal REST API. This is supposed to be an own implementation and won't solve the issue for anyone who wants to use REST API to answer to such methods. I am not experienced enough with Drupal to explain if and how one could configure REST API to accept HTTP methods not listed in the REST API documentation. Maybe one could extend own controllers from the REST API, but I didn't inquire into how to do that.


How to create a multi vendor Drupal commerce website?

eCommerce in Drupal generally comes down to 2 modules:

Ubercart
Commerce.

Commerce is very powerful and flexible, and I'm sure you could use it to build your use case, but it might take a lot of work. It has a great distro called Commerce Kickstart to get you up and running quickly. And Pantheon will give you free hosting for you dev site and install the distro for you!

Ubercart is older, and still powerful, not quite as flexible. But this module may meed your use case exactly: Ubercart marketplace.

Other module :

Commerce-Marketplace


You can add more fieldset by Add new group option available in Manage field page, please find the below screenshot..

And you can drag and drop the filed inside the fieldset as you required


What is the Drupal 6 equivalent or alternative to hook_node_load?

I've found that hook_nodeapi fits my use case: https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6


Accessing Additional User Profile Fields

I think I found it. There is one additional step it seems.

global $user;
$user_full = user_load($user->uid); // user_load(uid) returns the complete array
var_dump($user_full);

I now have access to my custom profile fields through $user_full


There are several uses of field collection, but as the name implies, it's all about "Collecting fields" into groups.

I have a personal use case where I have a content type called "Project". Each project, can have several "subtask"s, and each subtask has a boolean, "completed".

If I have a normal multi-value field for "subtask", how do I conveniently stick a "complete" checkbox on to them? That would be it's own multi-value field, and there would be no connection between the data points, nor any easy way to theme the edit page to make them look like they belong together.

However, since "subtask" is actually a field-collection with a "name" and a "checkbox", they are logically grouped together, both in storage and in rendering.

If one want's a "quick" solution to a similar problem, then FC is an excellent module. However, if I were to build something serious, I would first consider if Relation can solve the problem instead. This will probably not always be the case, but with a bit of extra work, using relation instead of FC will yield a more flexible solution.


If you want to do it sitewide, you can edit the definitions at admin/config/regional/date-time/formats

You can also add your own formats there, and then use them in format_date() similar to what @Epok outlined.


So I think there is no way to tell batch to restart when it's gotten an error response. What you could do is to not return a possible error but rather re-try the request using your own wrapper. So could do

try {

  $TestRetry = new TestRetry();
  return $TestRetry->test();
}
// And I think you won't need this but handle the exception in your wrapper class.
catch (Exception $e) {
  watchdog_exception('scrape', $e);
  return FALSE;
}

and in your wrapper, you could attempt to retry the request to avoid an error. So your wrapper may look like this:

<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

class TestRetry {

  public function test() {
    $handlerStack = HandlerStack::create(new CurlHandler());
    $handlerStack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
    $client = new Client(array('handler' => $handlerStack));

    $response = $client->request(
      'GET',
// @todo replace to a real url!!!
      'https://500-error-code-url'
    )->getBody()->getContents();

    return \GuzzleHttp\json_decode($response, TRUE);
  }

  public function retryDecider() {
    return function (
      $retries,
      Request $request,
      Response $response = NULL,
      RequestException $exception = NULL
    ) {
// Limit the number of retries to 5
      if ($retries >= 5) {
        return FALSE;
      }

// Retry connection exceptions
      if ($exception instanceof ConnectException) {
        return TRUE;
      }

      if ($response) {
// Retry on server errors
        if ($response->getStatusCode() >= 500) {
          return TRUE;
        }
      }

      return FALSE;
    };
  }

  /**
   * delay 1s 2s 3s 4s 5s
   *
   * @return Closure
   */
  public function retryDelay() {
    return function ($numberOfRetries) {
      return 1000 * $numberOfRetries;
    };
  }
}


Is there a way to create a Rules component programmatically?

Rule components can be programmatically created- although they can be quite cumbersome to code from scratch.  I'd recommend building a component with some conditions, actions, and rulesets and exporting it.  Then you can analyze the exported php to determine how to define your custom component set.

You'll most likely want to reference:

A list of the hooks available for the D7 version of the Rules module can be found here:  http://www.drupalcontrib.org/api/drupal/contributions%21rules%21rules.api.php/group/rules_hooks/7
A good set of Developer Documentation for custom rules (albeit an old set of documentation for the D6 version of Rules) can be found here:  https://www.drupal.org/node/298486


a bit confused as to what exactly you are asking but i'll answer anyway. also, this question does not seem drupal specific.

yes... you can have both sites in the web root so to speak. however, vhosts will allow you to run both sites from any directory you want. take a look at the apache documentation on vhosts..

if you are doing your development local, you can adjust your hosts file to have sites dev1 and dev2 (for example) point back to your local development box (localhost).

as for removing the folder from the basepath, vhosts will handle this for you.

your vhost config might look lke this in httpd.conf

<VirtualHost *:80>
 ServerAdmin aasdf@asdfl.net
 DocumentRoot /var/www/html/dev1
 ServerName dev1
 ErrorLog logs/dev1-error_log
 CustomLog logs/dev1-access_log common
</VirtualHost>
<VirtualHost *:80>
 ServerAdmin aasdf@asdfl.net
 DocumentRoot /var/www/html/dev2
 ServerName dev2
 ErrorLog logs/dev2-error_log
 CustomLog logs/dev2-access_log common
</VirtualHost>


Views - D7 - Filtering by authorname only works with admin role

I just installed the Administration Views module and ran into this issue.  Setting the "View user profiles" permission fixed the problem.  Thanks @Marius Ilie.


Can I do a scrollable calendar/events listing with a Drupal module?

Yes, I believe that you can do that with the full calendar module.

In the example link you posted when you click left or right though the months an ajax request is actually happening returning the next months set of events.

The full calendar module also has ajax support.

To turn ajax on on your calendar you need to look at a setting called Use AJAX under the advanced section:

There is a similar question, AJAX in a calendar view block, which may also be of interest.


The function drupal_json_decode() (D7 only) can convert a json string to the corresponding php data structure.

In Drupal 6, you can directly use the PHP function json_decode(), just remember that you need PHP 5.2+ for that.

As I almost assumed, the part you're having problem with is not converting the JSON string to a PHP structure you can work with, but sending that from the client side to the server, so that you can access it with PHP (Try to provide more information what exactly you want to do when asking questions and you'll get better answers).

drupal_json_decode() is, in fact, just the very last step in the whole process. You obviously can't access that function (or anything else that is PHP) directly from jQuery, so you need to send it with jQuery.post() to the server, where it can be processed.

To be able to do that, you first need to define a endpoint where the data can be sent to by implementing hook_menu(), for example your_module/endpoint. In the page callback that you defined there, you can read the sent data in from php://input, for example with $json = file_get_contents("php://input");. Then, you can use the mentioned function to parse $json.


Disable jquery.ui.theme.css only for front end?

I would use user_is_anonymous() function like this:

function yourtheme_css_alter(&$css) {
  if(user_is_anonymous()) {
    $exclude = array(
      'misc/ui/jquery.ui.core.css' => FALSE,
      'misc/ui/jquery.ui.theme.css' => FALSE,
    );
    $css = array_diff_key($css, $exclude);
  }
}


It turns out my pane was a fieldable panel pane. As far as I can tell, these panes serve as templates, and when placed in panels, they are copied into one-off panes.

So my solution was to add another copy of the fieldable panel pane, this time making sure to check the 'reusable' box. Then, I replaced all the one-off panes throughout the site with the reuseable pane.


upload picture and make it my css background-image

You can do something like this:

hook_node_view($node, $viewmode, $langcode)
{
  if(count($node->field_background_image) && isset($node->field_backround_image[LANGUAGE_NONE][0]['uri']))
  {
    $node->content['#attached']['css'][] = array
    (
      'type' => 'inline',
      'data' => '#some_div{background-image:url(' . file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']) . ');}',
    );
  }
}


How to achieve a particular layout (view within a view, custom template, or ____)?

A simple solution would be to use node reference on the destination node which reference video nodes. Then it's just a matter of theming to convert the node references (node ids) to videos.


Is it possible to approve an Enitity Form?

Define a field called "Approval Status" in your entity form with two values Approved / Unapproved
Be Default set it to "Unapproved"
Use Views to list your custom entities see below post for reference

How do i use views with a custom entity?

Update "Approval Status" using VBO. See this article to find out how to create simple action.


Best way to build bio content specific to the user

If the bio pages can be created for people without an account on the site, then I would create a new content type to use for the bio data; if the bio data needs to be strictly linked to the user profile, I would add new fields to the user accounts.

I would also create a new content type if I want the bio information to be completely searchable. When searching for users, the User module looks just for the username or the user email (in the case the user who is searching as the permission of administering users).

  $find = array();
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
  $query = db_select('users')->extend('PagerDefault');
  $query->fields('users', array('uid'));
  if (user_access('administer users')) {
    // Administrators can also search in the otherwise private email field,
    // and they don't need to be restricted to only active users.
    $query->fields('users', array('mail'));
    $query->condition(db_or()->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  }
  else {
    // Regular users can only search via usernames, and we do not show them
    // blocked accounts.
    $query->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('status', 1);
  }

To search users basing on the content of any field attached to user accounts, you should use a module that implements user search differently from the User module, or create yourself one.

As for changing the template used for user accounts, that is not different from changing it for a node; the only difference is the template file used by default: user-profile.tpl.php for a user account, and node.tpl.php for a node.

You could also use the Profile 2 module; in this case, the profiles would be an entity different from nodes, and they would be fully searchable with the Views module or the Search API module.


Ok everything is fixed, there were 2 points :

Clean the cache when the media 'masterclass_private_video' is called, so the request to AWS s3 has the correct "Expires" timestamp when call by my VueJs API.
Clean the render cache of the content view in my drupal backend.

Clean the media cache for the API :
function mymodule_entity_load(array $entities, $entity_type_id)
{
  $tags = [];
  foreach ($entities as $entity) {
    if ($entity->bundle() === 'masterclass_private_video') {
      foreach ($entity->getCacheTags() as $tag) {
        $tags[] = $tag;
      }
    }
  }

  if (!empty($tags)) {
    Cache::invalidateTags($tags);
  }
}

Clean the page cache :
function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display)
{
  if ($entity->bundle() === 'masterclass' || $entity->bundle() === 'masterclass_chapter') {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

To be clear, the goal is to reset the $expires, so the AWS s3 works :
function mymodule_s3fs_url_settings_alter(array &$url_settings, $s3_file_path)
{
  $split = explode('/', $s3_file_path);

  if (in_array('private', $split)) {
    $file_path = getenv('AWS_CLOUDFRONT_ENDPOINT') . $s3_file_path;

    $expires = time() + 86400;
    $private_key_filename = '/var/www/my-drupal/keys/pk-cloudfront.pem';
    $key_pair_id = getenv('AWS_S3_KEY_ID');

    $canned_policy_getters = Drupal::service('mymodule.aws.signature')
      ->getCannedPolicyGetters($file_path, $private_key_filename, $key_pair_id, $expires);

    $url_settings['custom_GET_args'] = $canned_policy_getters;
  }
}


What you are asking for is included in core Views, unless I am mistaken.
In a new Content view you will be able to add a "Content: Node operations bulk form" field and that offers you an option for "Save content".

You could even use the default "Content" view...

that already offers that option out of the box:


Drupal 7 pass a custom form fileds input as arguments to the url on submit

$form_state['redirect'] = array(
  'move-quote',
    array(
     'query' => array(
       'move-quote' => $form_state['values']['location'],
     ),
    'fragment' => 'optional',
  ),
);

should work in your submit function. Try also

$form['#submit'][0] = 'custom_form_submit';

and clear your caches.
Also http://drupal.org/node/291680 was helpful


for Grade F on Make fewer HTTP requests

Locate them at admin > configuration > development > performance. There you'll see two options:

Aggregate and compress css files.
Aggregate Javascript files


Change image background colour when cropping

You could try with ImageCache Actions module. Enable Imagecache Canvas Actions module that is shipped with ImageCache Actions and than change your style effects order to:

Scale
Define canvas (set your color and scale dimensions)
Crop


Stop caching images in views, force reload of jquery image slideshow when images are externally updated

with firebugs net panel click on image1.png, select cache and get this information

Last Modified
Last Fetched
Expires

Your currently setting the html page to not be cached in the browser (which is already the case by default). If the images are hosted on your server, you need to adjust your apache .htaccess rules and have these images not be cached. Drupal's default htaccess uses a 2 week cache for everything other than php scripts. You need to make an exception for your images with filesmatch. Example:

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Match image1.png, image2.png, etc...
  <FilesMatch ^image\d+\.png$>
    # Disable browser caching.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

If the images are not hosted on your server simply append a question mark with the current unix time to the end of the image src. Example:

image1.png?1317717247


I figured out how to add a field to the menus (not menu links, the actual menus). I use the machine name of the menu's title as a key and store the value with the key I use in the $form variable.
Here is my code:
function myModule_form_menu_edit_form_alter(&$form, $form_state, $form_id) {
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $my_field = $config->get(str_replace('-', '_', $form_state->getformObject()->getEntity()->id()));

  $form['my_field'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => $my_field,
  '#weight' => '0',
  '#required' => FALSE,
  );

  $form['actions']['submit']['#submit'][] = 'myModule_custom_submit';
}

function myModule_custom_submit($form, $form_state) {
  $key = str_replace('-', '_', $form_state->getformObject()->getEntity()->id());
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set($key, $form_state->getValue('my_field'))->save();
}