In the People list, change from time span display to date display

I'm not aware of an existing module that will do this but the following function in a custom module will do the trick:

function MYMODULE_form_user_admin_account_alter(&$form, &$form_state) {
  // Get the user IDs listed in the form
  $uids = array_keys($form['accounts']['#options']);

  // Since loading the user objects will incur overhead it would be best to get the
  // created data directly from the users table. It's a shame because this query has
  // already been run in user_admin_account(), but it's not saved anywhere that we can
  // easily pick it up.
  $sql = 'SELECT uid, created FROM {users} WHERE uid IN (:uids)';
  $created_data = db_query($sql, array(':uids' => $uids))->fetchAllKeyed();

  // Loop through the results and change the column data for the "Member for" column.
  foreach ($created_data as $uid => $created) {
    $form['accounts']['#options'][$uid]['member_for'] = date('d/m/Y H:i', $created);
  }

  // Finally change the header to say "Member Since"
  $form['accounts']['#header']['member_for']['data'] = t('Member Since');
}

The only thing you might want to change is the date format...see PHP's date() function for all the available tokens


Views: How to list nodes by 2 vocabularies with “%” on url path for contextual filters

try this:

create the view as a table with fields
include the style field (exclude from display)
under table settings, 'group' the results by the style field

You can tweak the layout for the headers with some simple css


How to make all menu links without www? (shortened menu links)

No, this is something that is been handle at the server or DNS level. From the GUI, you do not have control of where you application (Drupal) can will run.

If you are running Apache you can add this code to your .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Source: Force drupal 7 to place "www" in front of urls


Creating a Redirect from old url to root

Assuming this question is about D7, you can use the Rules module for this, with a custom rule that looks like so:

{ "rules_redirect_some_path_to_the_frontpage" : {
    "LABEL" : "Redirect some path to the frontpage",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Default.aspx?id=index",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path is no longer in use, you will be redirected automatically to the homepage" } },
      { "redirect" : { "url" : "[site:url]" } }
    ]
  }
}

If you have the Rules UI module enabled, you should be able to just import the above rule, then "enable" it, and that's all you'd need to do.

What this rule actually does:

Check if the current path is Default.aspx?id=index
If that's indeed the path, then a redirect to your frontpage will be performed.

Note: feel free to adapt the first Rules Action (to display a message), or if you don't want such message at all, just remove that Rules Action.


Anyway to disable minification (make line breaks) in the source view of CKEditor WYSIWYG

Edit WYSIWYG profile that uses CKEditor and in "Cleanup and output" settings check "Apply simple source formatting". (screenshots below for visuals)


How to access cookies in Views PHP Code filter?

Checked with the views php module.

Then i get the cookies stored.


How to sort feed aggregator's items in Views according to its category?

I'm hoping you've answered the question by now but just in case, I'll answer it for anyone who comes looking for it.

(Drupal 7)
If you only have two feed categories then after creating your aggregator view, add the "Aggregator Category: Category" field to your view. Make sure to check 'exclude from display' or it will show the category title in duplicates. Then, go up to your format settings of the view and add "Aggregator Category: Category" to "Grouping field Nr.1." This will sort and split your feed items into the different categories.

If you have several feed categories and only want to use two of them, you would add the filter "Aggregator Category: Category ID" with the values 1 and 2, or whatever the category ID is of the category you want. Then repeat the steps above.


Though the question is pretty old, I would like to add my suggestion to it. I don't think changing the field type directly in the database is a good idea.

Create a new field (long text) with the necessary settings, and add it to the content type.
Then you can use the following script to copy all the old field values (text field) to new field (long text).

<?php
// Assign value from old_field to new_field
$nodes = node_load_multiple(array(), array("type" => "your_type"));
foreach ($nodes as $node) {
  $node->field_new = $node->field_old;
  field_attach_update('node', $node);
}

Finally delete the old field and use the new field for further use.


Would Drupal send to an alternative email address for reset password?

You'll want to create a custom module, please see https://www.drupal.org/node/1074360

You can then implement hook_mail_alter().

/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  // Alter password reset
  if ($message['id'] == 'user_password_reset') {
    // Load the user by email address
    if ($user = user_load_by_mail($message['to'])) {
      // If you have another user field with their alternative email address, add to the $message array
      if (!empty($user->field_user_alt_mail)) {
        $message['to'] = $message['to'] . ', ' . $user->field_user_alt_mail[LANGUAGE_NONE][0]['value'];
      }
    }
  }
}

edit: changed 'password_reset' to 'user_password_reset' as per Paul's comment.


is it possible to load data of one block in the tpl of another

I'm not 100% sure if this will work, but it's worth a try!

You may be able to use module_invoke to place block 2's content into the template of block one using the following code in your block-mymod-1.tpl:

$block = module_invoke('block', 'block', 'view', '2');
print $block['content']

This post might help to explain more, but for your needs you are only interested in the first and last arguments.  The first tells Drupal which module you're invoking, and the last is the block ID of the node you're looking to load the data for.


why are users logged out after 2 days of not logging in

The answer here explains the difference between the cookie types and when they destroy the session: Why is session.cookie_lifetime set to 23 days?

To answer your question specifically:

If you extend the session.cookie_lifetime to be longer, the session will last longer and users will less frequently require to login. If the user opens the page within session.cookie_lifetime from the last visit, the session will be extended for another session.cookie_lifetime. This can be repeated several times, but never longer then session.gc_maxlifetime after which a user is always forced to log in again.

If you extend the session.cookie_lifetime to last for eg. 4 days (so it survives the weekend), users that always open the page on workdays will have to login once every 23 days (session.gc_maxlifetime). You can also extend this value to last as long as you want.

Please keep in mind that although hitting the enter might be annoying, if security is part of your job as well, it might not be a good idea to have sessions lasting for long periods of time. Have them survive the weekend by having them last a day longer will not cause much problems, but allowing them to extend for ever and ever (session.gc_maxlifetime) could introduce security vulnerabilities.


If you're using D7 hook_html_head_alter is your friend.

something like

function my_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['type']) && $element['#attributes']['type'] == 'application/rss+xml') {
      unset($head_elements[$key]);
    }
  }
}

Otherwise your attempt seems to be the best solution. Perhaps try ungreedy regex?

<link rel="alternate" type="application\/rss\+xml" title="[^"]*?" href="[^"]*?">


Add bootstrap icons next to fields in node page

Use the preprocess function, like:

function YOUR_THEME_preprocess_field(&$variables) {
  $element = $variables['element'];

  if (isset($element['#field_name'])) {
    if($element['#field_name'] == 'field_business_phone') {
      foreach ($variables['items'] as $k => $value) {
        $variables['items'][$k]['#markup'] = '' . $variables['items'][$k]['#markup'];
      }
    }
  }
}

Or overwrite the field templates, in a file named field--field-business-phone.tpl.php, containing something like:

<?php

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field__items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field__item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>> <?php print render($item); ?>

    <?php endforeach; ?>


How to add link to create relationship in a view

I found out this could be done without writing custom code.

In the view:

I added a field, User:uid.
I unchecked "create a label" and "link this field to its user"
Using Rewrite results, i checked Rewrite the output of this field and input "Add as friend".
I checked the "Output this field as a link" and then added the path www.example.com/relationship/[uid]request/1?destination=user/[uid]

That solved the issue.


How to get an array of values of node ids from entity reference field with EntityMetadataWrappers

Should be as simple as:

$ids = $wrapper->field_foo->raw();

And if you want an array of entities instead:

$entities = $wrapper->field_foo->value();


Disclose billing cycle information on order page to customers

Make sure that in your roles/permissions that users have permissions to view licenses:


Getting different results for admin versus non-admin user on view when there is a relationship

Seems like this problem is related to this drupal bug https://www.drupal.org/node/1349080 .

Solution: Edit your view > Right column "Advanced" > Query settings: check "Disable Query Rewriting"

Simple explanation for the bug and the solution https://www.drupal.org/node/1276450#comment-10451305, quote the comment below

  Actually, this is a bug, in Drupal core, and there is a fix, in
  #1349080: node_access breaks any query that has node table appearing twice with a left join. It just has not been committed to Drupal core
  yet, because the fix is a bit brittle and may not work in all corner
  cases. It has to do with the node_access system, and any view that
  connects the node table or an entity table multiple times (e.g. via a
  relationship), when there is any access module enabled on the site,
  will trigger it.

  Disabling SQL rewriting will bypass the issue, and should be entirely
  safe to do, unless you have some access rules you want to enforce
  (such as products in an OG group that only members of that group
  should be able to see) -- in which case you can usually address that
  by adding your own explicit filter to the view instead of relying on
  the core node access to filter it out for you.

  If all your products are public, there's no need for this node_access
  check.

Cheers


Why are the images missing in newsletter emails created using Simplenews?

For Sending newsletter with image you have to send mail in HTML format not in text format. One more thing for Html mail format you have to use Mimemail or Html mail.

Mail content images have absolute src path. So that image will be accessible by email.


Drupal 8 is providing a hook to alter the region template_preprocess_region, it would prepares values to the theme_region.Adding the following codes in THEMENAME.theme file would solve the problems,

function themename_preprocess_region(&$variables) {
  if ($variables['region'] == 'sidebar_second') {
    $variables['elements'] = shuffle_assoc($variables['elements']);
    $content = '';
    foreach ($variables['elements'] as $key => $value) {
      if (is_array($variables['elements'][$key])) {
        $content .= \Drupal::service ('renderer')->render($value);
      }
    }
    $variables['content'] = array(
      '#markup' => $content,
    );
  }
}

function shuffle_assoc($list) {
  if (!is_array($list)) {
    return $list;
  }

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key) {
    $random[$key] = $list[$key];
  }
  return $random;
}

For more details, check here


Unable to send email using "SMTP Authentication Support" module

I would suggest you to use the module Mandrill

First you can go to mandrillapp.com and create an account.

After account creation go to Api and generate an Api key.

Then after installing the module on drupal instance. Go to Configuration->Mandrill->Add the Api key and your site is ready to send mails.

Hope this helps.


Instead of deleting the user and risking something going bad, why don't you try just to change his e-mail address in the SQL table? If you change #144's mail won't you then be able to edit, delete his account through the usual UI way?


how do i get fields value of webform before entering into database?

You can use hook_form_alter to achieve this in your custom module.

/**
 * Implementation of hook_form_alter().
 */

function your_custom_module_name_form_alter(&$form, &$form_state, $form_id) {
  // Add validation for a particular Webform node:
  if ($form_id == 'webform_id') {
    // Simply add the additional validate handler.
    $form['#validate'][] = 'mycustom_extra_validate';

    //$first = array_shift($form['#submit']);
    //array_unshift($form['#submit'], $first, 'mycustom_extra_submit');
  }
}

/**
 * Validation handler for Webform .
 */
function mycustom_extra_validate(&$form, &$form_state) {
  //condition to check validation
}


How can this buying logic be achieved using drupal commerce and/or ubercart?

This isn't going to be easy to do with either Drupal Commerce or Ubercart. What you're proposing is a very specific, custom bulk Add to Cart form. You're going to have to code it yourself in a site-specific module. The closest you can get would be Commerce Cart Extras, but you'd still have to reformat it to look like your proposed grid and also to have a live updating order total in the footer.


Maybe your problem can be solved using the Menu HTML module. It seems to have been designed to solve issues such as the one you describe.

  This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. The idea is to use this for external links for which you want to display a logo of the visited site or simply to add strong on some words.


Node create progrmatically with multiselect

You just need to keep adding new values underneath the language array, for example:

foreach ($_POST as $field_name => $field_value) {
  $node->{$field_name}[LANGUAGE_NONE][]['value'] = $field_value;
}


Drupal Commerce add multiple products to cart at once with different attribute values

Since your not sending a single SKU, you could just overwrite the validate and submit handler for the add to cart form and then, using the existing validate and submit handlers as a blueprint, write your own logic to add multiple products. You'll want to make sure you create line-items for each of the variants your adding to the cart so that pricing is calculated properly, but it should be a fairly straightforward process.


Change markup shown before the search result

This answer has already been answered on stackoverflow. Here's a copy paste of what Cornel Andreev wrote.

You have to alter the route defined by the search module.
In order to do so:

Define in your mymodule.services.yml file following:

    services:
      mymodule.route_subscriber:
      class: Drupal\mymodule\Routing\RouteSubscriber
      tags:
        - { name: event_subscriber }

Create a class that extends the RouteSubscriberBase class on /mymodule/src/Routing/RouteSubscriber.php as following:

    /**
     * @file
     * Contains \Drupal\mymodule\Routing\RouteSubscriber.
     */

    namespace Drupal\mymodule\Routing;

    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;

    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public function alterRoutes(RouteCollection $collection) {
        // Replace dynamically created "search.view_node_search" route's Controller
        // with our own.
        if ($route = $collection->get('search.view_node_search')) {
          $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleSearchController::view');
        }
      }
    }

Finally, the controller itself located on /mymodule/src/Controller/MyModuleSearchController.php

    namespace Drupal\mymodule\Controller;

    use Drupal\search\SearchPageInterface;
    use Symfony\Component\HttpFoundation\Request;
    use Drupal\search\Controller\SearchController;

    /**
     * Override the Route controller for search.
     */
    class MyModuleSearchController extends SearchController {

      /**
       * {@inheritdoc}
       */
      public function view(Request $request, SearchPageInterface $entity) {
        $build = parent::view($request, $entity);
        // Unset the Result title.
        if (isset($build['search_results_title'])) {
          unset($build['search_results_title']);
        }

        return $build;
      }

    }


EDIT:
I realize there is a more generic question here, so I copied my answer over there.

A combination of the following modules can get you quite far:

Display suite
Block reference
Entity reference
Field collection
Bean
Inline Entity Form
Multiple Selects

How?

Create a node type "frontpage".
Add a multiple-value block reference field with "Multiple Selects list" widget.
Set up some bean types to allow different kinds of fancy boxes that can be placed on the frontpage.
In addition you can have Views blocks to be used in the block reference.
One of the bean types could have a multiple-value entityreference to e.g. reference a bunch of products (and have them sortable). I generally prefer this over nodequeue.
Use Display suite to define how each bean and the frontpage itself should be displayed.
Use Display suite custom field templates to have decorated boxes around each bean/block in the blockreference, or each product, etc. Check hook_ds_field_theme_functions_info(). This stuff is powerful and awesome!
Tell the client / content editor to use the contextual links to edit individual beans.

This should give you some material to play with ..
More detailed questions should be discussed in dedicated stackexchange questions, since this is quite broad.


Inserting submenu to main menu using jquery - good idea?

What I would like to do is to somehow inject the block menu items
inside primary menu.
Or is there a better drupal way of doing this?

TB Mega Menu allows you to put blocks and view blocks inside your menus. Perhaps you should consider using this module instead.


If you want something like drupalgardens (aka new sites), you can use drush site-install, but you will still need to create the site directory and what not.

If you have a basic template for the new sites you should probably create an install profile or feature module and have it set everything up.


Possible to access source database in prepareRow() in Migrate module?

2 simple approaches:

You call the other DB explicitly like you do any other place to talk to it from drupal.

// Method #1
$query = Database::getConnection('default', 'for_migration')->select('source_table', 'st');
// $query = ....

// Method #2
db_set_active('my_other_db');
// ... code here ...
db_set_active();  // switch back to normal DB connection in-use. This is important.

Method 1 is outlined here: https://www.drupal.org/node/1014558
Method 2 is outlined here: https://www.drupal.org/node/18429

Your other option is to not do it in every prepareRow() explicitly. Think outside the box :P. Why re-query this information within every prepareRow() -- that just slows down your migration. You can define this custom $tid_map lookup array in your Migration class's constructor as a data member to the migration class itself. You only query it's value a single time (on migration startup). prepareRow then just checks the stored array whenever needed. You may or may not have to use a static variable to assure the value is saved and preserved throughout the Migration lifetime ... I'm not sure.


How to override file_public_path in install profile?

You probably want to look at this very recent blog post from PreviousNext: Collecting and writing configuration settings to setting.php from an install profile for answers to this question and your other about creating your own step in an install profile.

From that blog post regarding their install profiles form submit handler:

  Then we had to do the actual storing of these variables. Now at this
  stage the database connection is not setup so you cannot call
  variable_set(), you have to use another of Drupal's lesser known api
  functions - drupal_rewrite_settings(). This is the function Drupal
  uses to write the $databases variable to your settings.php. But with
  some minor wrangling you can use it to also write $conf variables to
  settings.php, which are from that point forward available for use via
  variable_get(). And therefore available for us to use to define our
  connection settings for the solr server. Because
  drupal_rewrite_settings should only be called once (to avoid having
  your settings overridden) we had to duplicate what the standard
  install does - ie writing the database settings - then we could write
  our own $conf settings.


Making it so registered users can't add/edit taxonomy terms to nodes

Found a module that does this: Taxonomy Role


Use drush to download drupal core files directly into directory rather than subdirectory

drush dl drupal --destination=/var --drupal-project-rename=www


Large, regular product import for Commerce

Hopefully this helps someone else.

I used XHProf in an attempt to figure out why the Feeds import was slowing down so much. It appears that the culprit is DrupalDefaultEntityController::cacheGet.

As the number of entries in DrupalDefaultEntityController's entityCache increases, performance drops off a cliff.

I resolved the issue by importing the nodes manually.


Add cck field as scoring factor to drupal standard search

Implement hook_update_index in a way that calls search_index. The source code of search_index tells you how the $text argument is analyzed. From a quick look at the source, I would wrap the field content in <h1> tags. Not that the string only applies to searching, not to rendering. So it does not need to represent the actual structure of the node.


How to use Drupal as static website generator?

I do not think there are any plans for the static project to be ported to Drupal 8.

However, a workaround to turn your Drupal 8 into a static site is by using the wget --mirror command. This will take an exact copy your site.


Dynamic pricing of products/line items with a "pricing entity"

So this first alter hook handles price on product display.

But price needs to be handled again with another hook: commerce_dynamic_pricing_commerce_cart_line_item_refresh.
This handles prices regarding current line items in cart.

I also needed to avoid combining same type of line items into "quantity groups".This works well in:

    $line_item->data['context']['add_to_cart_combine'] = FALSE;


This should work:

.menu-block-12,
  .menu-block-14 {
    float: left;
    width: 100%;
    clear: both;
  }


Type of drupal cache to be cleared on new hook implementation

If you look at the module_implements() function, it uses the following code to reset the hook cache:

cache_set('module_implements', array(), 'cache_bootstrap');
drupal_static_reset('module_hook_info');
drupal_static_reset('drupal_alter');
cache_clear_all('hook_info', 'cache_bootstrap');

You can just use the same code to do it yourself.


What is the difference between havingCondition and having?

I figured it out though trail and error.

Example of a having clause:

$query->having('user_count > 0');

Example of a havingCondition clause:

$query->havingCondition('user_count', 0, '>');

Essentially you can pass the alias, value and operator as separate arguments into havingCondition, but have to pass them all as one string into having.


Drupal 7 Schema API Data types does not support the DATE datatype that you find in popular SQL dialects such as MySQL.  My preferred solution is the same as the one you suggest (set the column to varchar and store it as a an ISO 8601 format date string: 2013-05-07 for May 7, 2013).  It is human readable (useful when debugging) and it is the format used by the DATE format of most SQL dialects.

For date arithmetic, I use built-in PHP-functions such as gregoriantojd to convert to Julian dates to compute date differences, etc.

While it is possible to force Drupal to use the DATE type to your SQL dialect of choice - see this answer for details, a varcharis the simplest and most portable solution.

For displaying a date in Drupal, you may want to use the the Drupal format_date function (from common.inc), as this makes sure that dates are rendered consistent across the site, and adapt month names, etc. to the preferred language.  Note that this function takes a Unix timestamp as its first argument, so you need to convert from the ISO 8601-format to a Unix timestamp in order to use this (and this won't work for dates fore 1970-01-01).  Because of this limitation I instead use a small custom module with a slightly adapted copy of this core function that shares the format templates with the core function, but accepts an ISO 8601 date and datetime as valid input. I also supply my own custom format (you can set up this on the Home » Administration » Configuration » Regional and language  » Date and time  » Add Date type admin page) without any hours, minutes or seconds.

PS: Some people recommend using Unix timestamps (seconds from epoch starting 1970-01-01) for anything that has to to with time and date.  However, I do not like to use Unix timestamps  for dates where the resolution wanted is whole days.  In addition to not being human readable, and having a rather limited timespan (making it inappropriate to store the date of birth for someone born before 1970), Unix timestamp dates based upon the local time tend to produce weird bugs when dates cross seasons because DST is being taken into account when you do not expect it.  It may be considered strange that I depreciate the Unix timestamp when the format_date function wants this format - but I find that storing the dates in the database  in the ISO 8601 format is so attractive that I put up this extra conversion step when calling the format_date function.


How to theme "My Results" (quiz module) tab that´s inside the user´s profile?

Copy and paste (and rename) the original theme function to your template.php file, than just change what you need. Remembering that $variables is an array. Use the dpm function of the devel module to look at what values are in $variables that you can use.


Linked images from the Media module in WYSIWYG having A tags stripped when rendered to template

I posted this as an issue on the media_wysiwyg module bug tracker over at https://www.drupal.org/node/2357993 and have been working my way through it since. Here is the best result I have managed to achieve so far copied from my responses to that issue.

This issue is mostly caused by the file_entity module. To work round this I have restricted the view modes available to media_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

I have then created an override template for the file entity called file--image--wysiwyg.tpl.php (see https://www.drupal.org/node/1793548) and I have the following code in it:

<?php

hide($content['links']);
print render($content);

This has now removed all the annoying links, headers and wrapping <div>s from the output EXCEPT for the media_wysiwyg wrapping  mentioned in comment #4.

As this is just one wrapping <div> and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping <div>.


Drupal 7 Bartik Menu tabs changed to vertical list - how to reset back to tabs?

Try turning off "Aggregate and compress CSS files" on /admin/config/development/performance and then use right-click inspect element (firefox or chrome) to identify the css responsible for the override. You should see the bartik css files overridden by something else causing this behavior.

A clear cache never hurts either.


You can theme secondary menu using THEME_links__system_secondary_menu like the following:

function THEME_links__system_secondary_menu(&$vars) {
  // Get links:
  $links = $vars['links'];
  // Get the index of last menu item.
  end($links);
  $last_ele_index = key($links);
  // Here do your logic by change ...
  // $vars['links']['$last_ele_index'];
}


you could place a watchdog('cache_clear_backtrace', print_r(debug_backtrace(),1); in that cache_clear_all() function to see from the log why/ where that happens.


Conditional statement doesn't work in node.html.twig

content.field_number is the rendered output and the value of the field is somewhere inside the render array, for example in a #markup. But this will change whenever someone reconfigures the view mode.

It is better to use the node object in this case, because the field value will be available for all view mode configurations:

{% if node.field_number.value %}
  not zero
{% else %}
  zero
{% endif %}


During form validation, can you "stash" a form for an end user while they fill out a different form?

I just looked at your Entity Availability project page, and it looks interesting. You are facing the classic Temporal dependency problem of all scheduling systems (eg Departure time depends on Arrival time). This is the one data dependency which cannot be resolved statically.

The Webforms module uses $_SESSION to store information for multi-page forms for the anonymous user. In the case of the Webform module, the submission ID ($sid) is saved the $_SESSION, and the $form_state is saved in and retrieved from the database, however I see no problem with using $_SESSION to maintain a working copy of the $form_state object ($_SESSION['form_id'] = $form_state;). However, I would suggest you look at a cache_entity_availability table keyed on, perhaps, form_id and uid, just in case the session expires (servers down, network problem etc).

Thanks for the additional info, and good luck with the project.


I assume you are not setting you default_value for the file field and that you are using a managed_file field.

The default value should be the fid of the file that has been uploaded before.

Something like this:

$form['profile_image'] = array(
  '#title' => t('Profile picture'),
  '#type' => 'managed_file',
  '#description' => t('Upload a photo for your profile.'),
  '#default_value' => $previously_uploaded_file->fid,
);

In your case I'm not exactly sure where the $previously_uploaded_file->fid will come from, but I assume it will be in your form or form state or else you will have to get it from the database or something.

If you are using a regular file field instead of a managed_file file field I don't believe you can set a default value.

In that case you have to make sure that when you do the user save that you are not overwriting the file with an empty value.


How to eliminate extra Drupal Logout Link

Try using the Devel Themer (https://drupal.org/project/devel_themer). That works kinda like a firebug/backtrace for themeing, and it should point you to where those links are coming from. Keep in mind Themer is a bit buggy, and can cause some issues, so you might want to switch it off when your done, but it should help you diagnose your problem.


E_DEPRECATED and E_NOTICE errors showing in dblog / syslog despite disabling in php.ini

In drupal_environment_initialize(), Drupal changes the report level with the following code.

// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

The value of E_ALL changes basing on the PHP version, and it is:

--------------------------------------------------------------------------------
PHP   | Value expressed using the other constants                              |
-------------------------------------------------------------------------------|
Before| E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
5.2.x | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE                                                          |
-------------------------------------------------------------------------------|
5.2.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR                                    |
-------------------------------------------------------------------------------|
5.3.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR | E_DEPRECATED | E_USER_DEPRECATED |
-------------------------------------------------------------------------------|
5.4.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_STRICT | E_RECOVERABLE_ERROR | E_DEPRECATED          |
      | E_USER_DEPRECATED                                                      |
--------------------------------------------------------------------------------

With all the PHP versions, error_reporting(E_ALL | error_reporting()) causes any warning to be raised; since PHP 5.3, it causes any deprecation message to be raised too.

drupal_environment_initialize() is the only place where Drupal sets the error level. A custom settings.php file could change it with ini_set('error_reporting'). Since settings.php is included after drupal_environment_initialize() is executed, that file could restrict the error level, or expand it; this means that with PHP 5.3, settings.php could cause E_STRICT errors to be raised too.

function _drupal_bootstrap_configuration() {
  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');
  set_exception_handler('_drupal_exception_handler');

  drupal_environment_initialize();
  // Start a page timer:
  timer_start('page');
  // Initialize the configuration, including variables from settings.php.
  drupal_settings_initialize();
}

About the error levels, the PHP documentation has the following notes:

  In PHP 5 a new error level E_STRICT is available. Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

If you are using PHP 5.4, that would explain why Drupal is recording E_STRICT errors, since Drupal adds E_ALL to the error level.


How to make form_alter act upon boolean choice rather select list

Assuming you mean checkbox (HTML doesn't have a boolean input type), the property is checked, so you can use:

':input[name="field_date_type"]' => ['checked' => TRUE]


You can add image field in taxonomy.You can find option like this.

Then add image field instant of title.


The node table doesn't have a text or created_time column so I'm not sure what data you're trying to select. Regardless, here are a couple of examples that use a subquery to select the title and created columns for a single random node from a pool of the ten most recent:

Subquery in the FROM:

$subquery = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->orderBy('n.created', 'DESC')
  ->range(0, 10);

$query = db_select($subquery, 'n2')
  ->fields('n2', ['title', 'created'])
  ->orderByRandom()
  ->range(0, 1);

Which is roughly equivalent to:

SELECT n2.title, n2.created
FROM (
  SELECT n.title, n.created
  FROM node n
  ORDER BY n.created DESC
  LIMIT 10
) AS n2
ORDER BY RAND()
LIMIT 1

Subquery in the WHERE:

$subquery = db_select('node', 'n2')
  ->fields('n2', ['nid'])
  ->orderBy('n2.created', 'DESC')
  ->range(0, 10);

$query = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->condition('n.nid', $subquery, 'IN')
  ->orderByRandom()
  ->range(0, 1);

Which is roughly equivalent to:

SELECT n.title, n.created
FROM node n
WHERE n.nid IN (
  SELECT n2.nid
  FROM node n2
  ORDER BY n2.created DESC
  LIMIT 10
)
ORDER BY RAND()
LIMIT 1

And the code:

You could also try a JOIN approach, it's worth trying a few methods to see which has the best performance.


avoid duplicated records with drupal_write_record

This function can take 3 arguments , in this situation the third argument acts as an array of primary keys and if we pass the third argument to the function (primary key), it will update the record, if don't pass - it will insert a new record .


Hi make sure you are enable the webform functionality  like this
check
http://prntscr.com/bur06a
 if not working then  follow  tutorial


Autocomplete field not using Entity Reference list settings

This is a known bug in Drupal 8, see: View output is not used for autocomplete display you could try the patch in #76

There was also another disccusion about the same thing here Views Filter by an entity reference view not working as expected, before it was closed as duplicate.


What would make all content of a certain type return a 404 on the node page?

The author of the nodes in question (just happened to be the same author for all of the nodes in this content type) was missing from the user table. To be clear, the user was not properly deleted - the row was simply removed from the database.

I'm guessing that this caused the db_fetch_object() function to fail within node_load() when it tried to JOIN the user table on the nonexistant uid:

$node = db_fetch_object(db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE ' . $cond, $arguments));

But it failed completely silently - I that's guess because this scenario would never happen if the user had been deleted properly (Drupal 6 automatically sets the Author of all content created by a deleted user to Anonymous (uid == 0).

Lot's of red herrings while troubleshooting, but maybe this will help someone in the future that doesn't realize they're using a half-sanitized database.


This is working for me. Note: You will need to know the numerical $id of your Feed from the D8 DB table feeds_feed. In my case it is 1 so $id = 1.

use Drupal\feeds\Entity\Feed;

function mymodule_cron() {

  /**
   * Runs single feeds on cron
   */

  $feed = Feed::load($id);
  if (!$feed->isLocked()) {
    $queue = \Drupal::queue('feeds_feed_import:' . $feed->bundle());
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.
      $feed->setQueuedTime(REQUEST_TIME);
      $feed->save();
    }
  }
}


For select fields to accept a default value, this value must be part of the #options list.

So you have to add the option before you can set the default value (important is the array key):

$form['submitted']['destinataire']['#options'][$email_dest] = $email_dest;
$form['submitted']['destinataire']['#default_value'] = $email_dest;

Then to hide the form element you can do:

$form['submitted']['destinataire']['#access'] = FALSE;

Or to keep it visible but disabled:

$form['submitted']['destinataire']['#attributes']['disabled'] = 'disabled';

But in any case, the submitted value for select elements must be part of the options list, otherwise it won't be accepted as a valid submission value. This is one of the many ways that Drupal tries to prevent malicious form manipulation.

For the difference between #value and #default_value: if #value is set, then it doesn't matter if a user chooses a different value for the form element. The finally submitted value that arrives in the submit handler will be the value set with #value. It's hardwired so to speak. #default_value on the other hand is more like a suggestion, it is changeable by the user and whatever is chosen will also arrive at the submit handler.


Properly handling menu items in a custom module

You can programatically add/remove menu items on install/uninstall and/or enable/disable events. But that's not how we do usually.

Implement hook_menu and you will be fine to go with almost any menu item implementation.

A few points.
Set menu router item's 'type' => MENU_NORMAL_ITEM and it will now be in a menu. Unless you set 'menu_name', it will be placed in the "navigation" menu.
See the huge (and very helpful) text on the page. Also, have a look at examples module for high-quality hook_menu examples.

Good luck!


What functionality is available from Drupal.theme()

These are the JS theme functions defined by core:

Tabledrag

Drupal.theme.prototype.tableDragChangedMarker
Drupal.theme.prototype.tableDragIndentation
Drupal.theme.prototype.tableDragChangedWarning

Vertical Tabs

Drupal.theme.prototype.verticalTab

Overlay Module

Drupal.theme.prototype.overlayContainer
Drupal.theme.prototype.overlayElement

Many contrib modules also define their own theme functions, it's not possible to list all of those here so your best best is to run a grep -nr "Drupal.theme.prototype" /path/to/drupal and see what's available in your own installation.

It's also worth bearing in mind that individual theme functions will only be available in the page if the file that contains them has been included. So if the Overlay module is disabled, for example, the related theme functions won't be available. If the vertical tabs JS hasn't been added that won't be available, and so on.


If you want to have the current NID of the viewed page in your view, you should use the following:

In your view:
At the Arguments section you select "Node:nid", in the configuration of this argument at "Action to take if argument is not present:" you can choose "Provide default argument" after that you choose "Node ID from URL".

And there you have your NID in your view.


Add a sticky class to node displayed via View

You already get the sticky class on views-row in most themes if your Format Show is set to Content.

But if it's set to Fields you can do it through the interface with the help of Content: Sticky at top of lists field.

Add the Sticky at top of lists field from Content Category to your View
Under Output format setting for this field choose Custom and then enter your desired class name into the offered field:
Custom output for TRUE
node--sticky
Custom output for FALSE
[____leave empty____]
Under Rewrite results uncollapse the Replacement patterns and copy the code for this field. It will be something like {{ sticky }}.

Don't enable Rewriting, this step is just to copy the pattern.
Save the Field settings and check the views results - do you see the class name listed for nodes that you know are stickied? If yes then edit the field again and Exclude from display
Under Format: Settings paste the pattern into the Row class input field

You will now have the text you entered for the TRUE sticky state appear as one of the classes next to views-row class.


You're probably looking for

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

views-view-fields--search--results.html.twig

In your view click on your title field and uncheck Link to the content.

then your template file

{{ fields.title.content }}

Not really sure if you really want # as href. I think you want to link to content. So add Path as a field.

{{ fields.title.content|striptags }}

Note: You'll probably want to use |striptags if you do not strip the markup from the views UI. Unless you do not mind having <divs> wrapping your title text.

then {{ fields.field_machine_name.content }} each of the rest of your fields that you want to output.

  Important: Make sure TWIG DEBUG is off, as it tends to screw up templates in Views.


Running module unit tests from CLI: "Class '..' could not be found"

Ok, so the solution is

From Drupal root directory:

sudo -u www-data php core/scripts/run-tests.sh --url http://d8.localhost/ --class "Drupal\system\Tests\Installer\InstallerTranslationTest"

Assuming that your site is available under http://d8.localhost, and it is an installed site.

Maybe you want to use --verbose for more output.

Documentation on drupal.org: Running Tests Through command-line


Try it like this:

function yourthemename_theme_suggestions_html_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'html__testHTML';
}

Replace "yourthemename" with your theme name.


If you want a fast solution, you might want to look into using Display Suite or Fences... I recommend Display Suite.

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

It will let you change the label as you want from the admin UI, no file editing needed.


Why can't I programatically create a location field in a node?

It's simply because the stable version of the Location module doesn't support Entity API.

There's a patch here that claims to provide the missing support, obviously use with caution on a dev version of the site first.


You can do this by using the Domain Access module which is meant for creating a site (with one code base and one database) where certain content is accessible by DomainA and other content is accessible by DomainB. In your case you can set all content to be accessible to both domains and just change the site settings for the front page based on current domain. In D8 there is the Domain Site Settings module which makes this easier, but in D7 you should use Domain Variable to change site_front based on the current domain.

This method will allow you (for example) to create two view pages or nodes or whatever (one for each domain) and display completely different content (or content in a different order) depending upon the domain.


How to change text format of summary/trimmed field?

You can't, it always has the same format. The field only stores a single format. And it has bugs with ckeditor, as you've found.

I would definitely recommend to use two fields. We'd like to remove the text with summary field type, it's unnecessary complexity but it was too late for 8.x.


Replace the file on disk while running the migration

As a temporary fix I have implemented the following in the prepareRow function.

function prepareRow($row) {
  // Delete the file if already present.
  $file_path = drupal_realpath($row->dest_dir . '/' . $row->name);
  if (file_exists($file_path)) {
    unlink($file_path);
  }
}

However, I am still not sure about the way it is recommended in the Migrate module.


Is uploading/download executable files harmful in drupal?

You'll want to make sure that your server is not configured to execute files of the given extensions in any way.

As a general precaution, you might also configure that file field to use the Private file system, which allows access to those files to be controlled by Drupal's permissioning system.


Update command won't work for multisites

As a test, change your working directory to the directory that contains the settings.php file for the site you want to operate on, and then run drush pm-updatestatus.  See if that bootstraps correctly.  If so, the issue is with your alias files.  These should work, so long as 'root' and 'uri' are set.

Note, however, that if all of your contrib modules are in sites/all, then one run of pm-updatecode will update the code for all sites. You will need to run drush updatedb for every site that shares any code updated by the last run of pm-updatecode.  Drush does not manage this for you, even with pm-update (which runs updatedb on just one site).

This is the added cost of multisite configurations -- you have to be a lot more careful with your update processes, and must update all of the sites at the same time.


Maybe the PHP memory_limit, after submit content it take a lot of memory for PHP and it die.

You can request they increase memory_limit to check. But to get more information correct, can they give the error.log of webserver and error_log of PHP for easy know what happend.


How to upload/insert images in content from module?

I have tried the below code with node_save method but not with entity_create way. Check if it works.

$dir = 'public://';
if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
  $file = file_save_upload('image', array(), $dir, FILE_EXISTS_RENAME);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $attachment = array(
    'fid' => $file->fid,
    'display' => 1,
    'description' => $file->name,
    'title' => $values->tooltip
  );
}

$article = entity_create('node', array(
  'type' => 'article',
  'title' => generate_demo_content('lorem_ipsum_title'),
  'body' => array(
    'value' => generate_an_article(),
    'format' => 'full_html',
  ),
  'field_attachment' => $attachment, //may need to change here
));


webform + form builder: how to clone an existing form

Use node clone module to clone that webform node. Then, you will have a new node with webform fields.


Node translation syncing problem with entity references

Had the same problem, wrote this little workaround:

function YOURMODULE_i18n_sync_translation($entity_type, $translation, $translation_language, $source, $source_language, $field_names) {
  foreach ($field_names as $field_name) {
    $info = field_info_field($field_name);
    if ($info['type'] == 'entityreference') {
      $items = field_get_items($entity_type, $source, $field_name);
      foreach ($items as $delta => $item) {
        $translations = translation_node_get_translations($item['target_id']);
        if (isset($translations[$translation_language])) {
          list($id, $vid, $bundle) = entity_extract_ids($entity_type, (object) $translations[$translation_language]);
          $translation->{$field_name}['und'][$delta]['target_id'] = $id;
        }
      }
    }
  }


This feature was added with the resolution of this issue:

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

To use this resource, make a POST to:

?q=rest/user/request_new_password.json

...and send along a name

name=john

...or e-mail address:

name=john@example.com


How to allow a route to a user as long as he has the good role?

I've never personally tried this, but it looks like in your routing.yml file, you can specify a _role permission under requirements:

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

my_module.your_route:
  path: '/your_menu_path'
  defaults:
    _controller: '\path\to\your\controller'
    _title: 'Menu title'
  requirements:
    _role: 'beneficiary'


While adding fields to your view, you will see fields named like Content (historical data) : Field name select those and you will get the revision data.


Why aren't the titles of my items in a new product type not displaying at check out? - Commerce

It's a bit of a gotcha, but I suspect under user permissions, you may need to check the "View products of [type] type" permission for anonymous / authenticated users.


Disable caching on a custom plugin block

I got the same issue that you, here is what it worked for me.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MY_MODULE_preprocess_block(&$variables) {
  $blocks_to_cache = [
    'SOME_block',
  ];
  if (in_array($variables['base_plugin_id'], $blocks_to_cache)) {
    $variables['#cache']['max-age'] = 0;
  }

}

So, In my my_module.module I search if I'm displaying this block, then I clean the cache for that block. You can several block names.


Separate Comment Form DIV from Comments DIV

Answered in comments of question, edit the html within the comments.tpl.php file of the theme's templates folder.


Yes. The Devel module has a submodule called Web Profiler. Once the Web Profiler module is enabled, there will be toolbar in the footer. The toolbar contains a DB inspection button signified by a DB "stack" with the number of queries performed and the time to perform them. Click the button will show you a profile of the DB queries made in the last request.


You have to rely on user_load to load the $user object, edit what's appropriate, in your case $user->status, then user_save the modified object.

You could also use db_query to update the users table directly if you know what you're doing.

As for triggering the rule, this post explains how to do it.


How to update custom content type fields value in bulk?

Without a lot of detail about your problem I suggest you research these modules:

Views Bulk Operations (VBO)
Views Bulk Edit
Feeds
documentation for the Feeds module for Drupal 8

VBO works through Views: you create a list of the nodes you want to edit. VBO provides a field through which you can select nodes (checkbox) and then you can perform operations on them.

Feeds can update existing nodes from a CSV file (create new nodes too). They're a bit trickier to configure, mapping must be tested thoroughly and you need to make sure the entries are unique, but once you have them set up correctly you can use them over and over again.


Use the Message module along with the message notify module. Message module is Drupal 7's answer to activity-streams and a flexible Messaging & Notifications system.

http://drupal.org/project/message
http://drupal.org/project/message_notify


What are the major differences in building an install profile for Drupal 8?

Apart from specific code changes like converting the .info file to a .info.yml, the biggest conceptual change is that most of what an install profile will contain are configuration files.

Basically, you can take the configuration directory of in installed site, copy it into the config folder of an install profile and then you're already pretty close to building an install profile that will at the end look like the site.

There will still be a few challenges, for example dependencies between configuration and content. Lee Rowlands (@larowlan) is working on a default content module that allows to import content entities from .yml files too https://github.com/larowlan/default_content, but you can't just stuff all of it into an install profile.

Take a custom block for example. You have a block configuration, which depends on  a custom block content, which in turn depends on a custom block type (bundle of the custom block). I'm guessing the way to solve that will be to split an install profile in a set of modules, that depend on each other.


Generate PDF with wkhtmltopdf after batch finished

The Finish function runs in the background and you can't return file there, the solution for your case is redirected to another page and create and return pdf file there.

something like drupal_goto('your_custom_url_to_generate');


Uploading images to CKeditor in a file field way?

I'm not 100% sure but maybe insert module is a suitable solution for you.
INSERT:

Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
This module was previously known as FileField Insert.


Using field api to get key of select list option

I hope this may help

 $key = $form_state['values']['whatever'];
$options = list_allowed_values("field_whatever");
$value = $options[$key];


A solution that comes to mind is using the field collection module to create a collection with a quantity and entity reference field. I've not used that module with Drupal Commerce so there might be a more commerce-centric solution there.


There's no built-in way to do this, afaik. Are the sites truly separate sites? Drupal multi-site?

You could build a custom module that uses one of the hook_preprocess_XXX functions.  In that function you could do a mysql query with the "sessions" table.  If there are 2 active sessions, block/redirect the user.  Session management would be tricky though.  You'd want to change the session timeout length for that site, and also encourage your users to logout when they're done browsing to make room for the next guy.

edit: process for the content type,  or you could look in to hook_menu functions which might be cleaner, though I am not sure it will work.


Add class to body depending on role of author of user page

This can be achieved by using the template_preprocess_html function in the template.php file of your theme.

function yourtheme_preprocess_html(&$vars) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    $user = user_load((int) arg(1));

    if (in_array('standard', $user->roles)) {
      $vars['classes_array'][] = 'standard-member';
    }

    if (in_array('premium', $user->roles)) {
      $vars['classes_array'][] = 'premium-member';
    }
  }
}


If I understand your question, I think that you can use a custom module (in this example, the name of the module is test_remove_field) and include the following code:

function test_remove_field_form_alter(&$form, &$form_state) {

    if (arg(0) == 'node' && arg(1) == 'add') {
    $form['field_test']['#access'] = 0;
    }

}

Note: remember that field_test must be your respective field name.


I don't know this for a fact but I think it's because the serialised objects contained in the data column are pretty large.

I just checked a production site of mine and the data column for views_data:en contains a serialised string that is 572824 characters long. I kid you not! Imagine loading that on each page request (fortunately that doesn't happen in my case).

The main cache table on the same website is currently at 1.4MB, with just 16 records in it.

On another, less-than-a-week-old dev site, the cache_form table is at 6.3MB, with just 142 records.

I know 1.4MB and 6.3MB aren't large amounts of data as such, but if you take into account the fact that it has to be processed and passed from MySQL to PHP I think that's where you'll find the bottleneck.


How can I extract a specific field from a set of nodes?

Use views, add fields - only the image - display for that content type only if published. done.

If you want to fine tune it, do some theming.


How do I create a view with filter on a field built using the date module?

You have 2 types of date filter handlers in Views ; try not to use the one that is your field but the date field, that will ask you on which date field it'll filter.


CTools - How to limit the result of ctools_export_load_object()?

You are right; that is how you should call ctools_export_load_object() to filter the returned objects. Keep in mind that:

For each condition you can just enter a value a database field must have
If you enter more than one condition, the function will return the objects for which all the conditions are verified

The code used from the function for handling the conditions is the following one.

  else if ($type == 'conditions') {
    foreach ($args as $key => $value) {
      if (isset($schema['fields'][$key])) {
        $query->condition($key, $value);
      }
    }
  }

Because that code, you cannot get (for example) the objects for which the date is 1337020900, or 1337020910, or 1337020940, or 1337020906. You cannot choose the operator to apply for the conditions, which means (for example) that you cannot get all the objects for which the date is greater than 1337020900, or lower than 1337020900.

The difference between ctools_export_load_object(), and db_query() is that:

ctools_export_load_object() doesn't just return the objects obtained from a database table; it returns also object returned from a specific hook. This is done from the following code, contained in _ctools_export_get_defaults().

if ($export['default hook']) {
  if (!empty($export['api'])) {
    ctools_include('plugins');
    $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'], $export['api']['minimum_version'], $export['api']['current_version']);
    $modules = array_keys($info);
  }
  else {
    $modules = module_implements($export['default hook']);
  }

  foreach ($modules as $module) {
    $function = $module . '_' . $export['default hook'];
    if (function_exists($function)) {
      foreach ((array) $function($export) as $name => $object) {
        // Record the module that provides this exportable.
        $object->export_module = $module;

        if (empty($export['api'])) {
          $cache[$table][$name] = $object;
        }
        else {
          // If version checking is enabled, ensure that the object can be used.
          if (isset($object->api_version) && version_compare($object->api_version, $export['api']['minimum_version']) >= 0 && version_compare($object->api_version, $export['api']['current_version']) <= 0) {
            $cache[$table][$name] = $object;
          }
        }
      }
    }
  }

  drupal_alter($export['default hook'], $cache[$table]);

ctools_export_load_object() can automatically join tables, if it finds the right information in the database schema defined in hook_schema().

// Build the query
$query = db_select($table, 't__0')->fields('t__0');
$alias_count = 1;
if (!empty($schema['join'])) {
  foreach ($schema['join'] as $join_key => $join) {
    if ($join_schema = drupal_get_schema($join['table'])) {
      $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
      $query->fields('t__' . $alias_count);
      $alias_count++;

      // Allow joining tables to alter the query through a callback.
      if (isset($join['callback']) && function_exists($join['callback'])) {
        $join['callback']($query, $schema, $join_schema);
      }
    }
  }
}

ctools_export_load_object() caches the result obtained, which means it could not execute any query at all.
ctools_export_load_object() uses many functions that are defined in the database schema. You can look at the comments contained in the code for ctools_export_get_schema() to see which functions are used.

As side note, a comment contained in ctools_export_get_schema() says (emphasis is mine):

  Please do not call these directly, always use the ctools_export_crud_* wrappers to ensure that default implementations are honored.


How come Drupal Console is not downloading all commands?

After spending hours on chasing this same issue, i quit and now use drush to create boilerplate stuff such as module, plugins etc.
After you install drupal site via composer with --dev try the following.

./vendor/drush/drush/drush generate module-standard # other generate commands there as well


Combine Webforms to export multiple form results in a single CSV

Webform 4.x is integrated out of the box with views on drupal 7.

Upgrade to last webform 7.x-4.x release.
Create a view: webform submissions
Select each field: webform submission data:Value and your webform node to extract the fields

To download all results the best option is Views data export, you should configure it to use batch for better performance.


Add icon to module's menu item in Administration menu

I figured it out. Now, this might not be the very best way to solve it, and some things should probably be changed, but this will be fine for now. Let's assume the module name is pizza.

First, create a directory called css. Inside this folder, create a css file with the name of the module. In this case it would be pizza.css.
Since there needs to be an icon next to the module's menu item title on the administration menu, this is the CSS we'll need (or similar):

.toolbar-icon-pizza-main::before{
    background-image: url('../../../../../sites/default/files/pizza-icon.png');
}

Second, we will need a libraries file in the module's root (where pizza.info.yml is located); call it pizza.libraries.yml. Inside this file write something along the lines of this:

toolbar-icon:
  version: 1.0
  css:
    base:
      css/pizza.css: {}

Here, base probably should be changed to theme, since this is an aesthetic to the module.

Third, move into pizza.info.yml, we need to include the library we made into the module. Add this to the bottom:

libraries:
  - pizza/toolbar-icon

Fourth, move into pizza.module, where we're going to add this:

/*
 * Implements hook_toolbar_alter()
 */
function pizza_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'pizza/toolbar-icon';
}

This fixed it for me.
Source:
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


How to override the H1 element from module?

This is the sample code that will overwrite the title page of Drupal, you have to locate within the template.php file of the active theme Drupal website.

function YOUR_THEME_NAME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'your-content-type-name') {
    $custom_title= "My custom title on node: ". $node->title;
    $vars['title'] = $custom_title;
  }
}


I see that you have not returned the $items array before exiting hook_menu. I assume it is a typo, but just incase it is not, you need to insert return $items; before the end of the function.

You need to check whether or not Drupal is able to fetch the value returned by drush_get_option().

Can you check in your hook_init(), the value of drush_get_option()?

Something like the following code should work.

function silverpack_config_init(){
  $test_sitename = drush_get_option('site_name');
  dsm($test_sitename);// Install Devel Module to use dsm()
}

Clear the cache, and refresh twice to see if you receive anything back from Drupal. If it is not returning anything, that means either "site_name" is not registered in your database table, or drush is not getting the context properly.


Found out this is an existing issue with OG 7.x-1.4: http://drupal.org/node/1572480.


How do I add an expression into a query?

Change the code to the following one.

$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$query->addExpression('MAX(nid)', 'max_nid');
$query->execute()->fetchAssoc();

The value returned from fetchAssoc() is an array. Since you are assigning the value returned from fetchAssoc() to $query, and then calling $query->addExpression(), you rightly get the error. You cannot call a method on something that is not an object (in this case, an array).

If you want to list all the node IDs and set max_nid to the maximum value, you can use the following code.

$query = db_select('node', 'n');
$query->fields('n', array('nid','type'));
$query->leftJoin('node', 'n1', 'n1.type = n.type');
$query->addExpression('MAX(n1.nid)', 'max_nid');
$query->groupBy('n.nid');
$result = $query->execute()->fetchAll();4


How to get a field with a relationship in a view

Follow this steps:

Add a relationship of brand to the view. This will get you to display the properties and fields of the brand entity.
Add another relationship for the brand field which references to the category entity using the entity reference field. This relationship should use the previous relationship (like nested relationships).
Now you should be able to display the properties and fields of the category entity as well.

Note: I've written this generically; it should work for any type of entities (e.g. Nodes, Users, Files, Taxonomy, etc.)


Print selected fields in page tpl Drupal 7

First, If you want to print selected field then you should to do it in node.tpl.php and not in page. There are many ways to do this :

If you just need to render the fields in default way, you can go to Admin > Content Type > Your Content Type > Manage Display and hide the fields you want.

If you want to do it through template files then you can use it using :

hide($content['field_name']);
print render($content['field_name']);

You can just remove print render($content); and write :

print render($content['field_name']);
print render($content['field_name2']);


Warning: Permission Denied, While clearing the cache

Check your temp folder under "admin > config > media > file system": It should be writeable.


How can I theme some blocks with the same theme?

Block Theme module will be really helpful. You have a select box where you can choose different tpl.php files for each block you configure


How to redirect the user using hook_init?

/**
 * Implements hook_init().
 */
function mymodule_init() {
  global $base_url;
  if (user_is_anonymous() && arg(0) == 'user') {
    drupal_goto($base_url . 'mylogin');
  }
}


I think first you have to attach the webform to the content type(under webform settings) and then you can use this module https://www.drupal.org/project/webform_default_fields to add fields to the web form.
cheers


How does the Search synonyms module work?

Jasper, I had a look at the code in the module. There is only one function in the module, and I don't think the module does what is says in the description on the Drupal project page.


How to show the content type diffrent types in a block?

Use Views module to create multiple blocks for different news types. Once you creates blocks using views, assign them to regions from Admin -> Structure -> Blocks.


How can I verify users the first time they log in?

Log in to Drupal by POSTing the user credentials. Make sure you set the "Content-Type" header. This starts the user's session.

POST URL:

/user/login?_format=json

Header:

Content-Type: application/json

POST data:

{
  "name": "username",
  "pass": "password"
}

Successful response:

{
  "current_user":{
    "uid": "1",
    "roles":[
      "authenticated",
      "administrator"
    ],
    "name": "username"
  },
  "csrf_token":   "asda09820380_2238019280dk09n908asjdlkajdaoa",
  "logout_token": "asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj"
}

Use the CSRF token in subsequent GET, POST, PATCH, DELETE etc. requests by setting the header:

X-CSRF-Token: asda09820380_2238019280dk09n908asjdlkajdaoa

To log out, use the logout token in a POST request. This ends the user's session.

/user/logout?_format=json&token=asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj

GET login status:

/user/login_status?_format=json

GET token:

/rest/session/token

References:

JavaScript and Drupal 8 RESTful Web Services
Change record: Additional RPC endpoints: user/login user/login/status user/logout user/password/reset


Webform submissions are content entities, so something like this should work:

$query = \Drupal::entityQuery('webform_submission')
    ->condition('uid', $uid);
$result = $query->execute();


Is it possible to override/replace an event subscriber

You can do this by creating a ServiceProvider class.

Example service provider class to override the path_subscriber service.

namespace Drupal\MY_MODULE;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the path_subscriber service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    // Adds entity_type.manager service as an additional argument.
    $definition = $container->getDefinition('path_subscriber');
    $definition->setClass('Drupal\MY_MODULE\MyCustomPathSubscriber')
      // Custom arguments.
      ->addArgument(new Reference('some_argument'));
  }
}

Another solution is to override the service in MY_MODULE.services.yml, like this:

path_subscriber:
  class: Drupal\MY_MODULE\MyCustomPathSubscriber
  arguments: [# The arguments]


How do I disable/enable a module on all sites within a multi-site Drupal installation using drush?

Drush has the ability to interact with each site within a multi-site installation via the @sites argument.  Anytime you are within the directory structure of your platform, the drush @sites command will target all sites rather than a single/no site.  In this way, any drush task can be accomplished across all sites.

Some concrete examples:

Disable the dblog (core database logging) and devel module on each site

drush @sites dis dblog devel -y

Enable the speedy module on each site

drush @sites en speedy -y

Change the admin theme for all sites

drush @sites vset --yes admin_theme "ember"

Check to see if any sites in the platform have the cdn module enabled

drush @sites pml --no-core --type=module --status="enabled" -y | grep cdn

These (and many more commands) work with any version of drush >= 4.x


Pre fill multiple paragraphs while adding node

You can't reuse existing paragraphs, you have to create new paragraphs for each node:

$paragraph1 = Paragraph::create([
  'title' => 'Paragraph 1',
  'type' => 'paragraph_type1',
]);
$paragraph1->save();

$paragraph2 = Paragraph::create([
  'title' => 'Paragraph 2',
  'type' => 'paragraph_type2',
]);
$paragraph2->save();

$node = Node::create([
  'title' => 'Node with two paragraphs',
  'type' => 'article',
  'field_paragraph' => [$paragraph1, $paragraph2],
  ]);
$node->save();

You could place this code in a custom controller:

  public function addCustomContentType() {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => 'custom_content_type',
    ]);

    // create paragraphs, don't save them yet, in case the node is not submitted

    $paragraph1 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 1',
      'type' => 'paragraph_type1',
       // more field data
    ]);

    $paragraph2 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 2',
      'type' => 'paragraph_type2',
      // more field data
    ]);

    // prefill the paragraph field in the node with the paragraphs
    $node->field_paragraph = [$paragraph1, $paragraph2];

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;


Custom formatter for a multi-valued field

here a sample for rendering (image) fields but you can easily access to other fields of entity:

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

Another line example for manual image rendering:

$output .= '<img typeof="foaf:Image" src="'.image_style_url('YOUR_IMAGE_STYLE', $your_entity->your_field['und'][0]['uri']).'" alt="'.$your_entity->your_field['und'][0]['alt'].'"/>';


How to use HTML in a webform component's title?

At first, I misread your question and created Issue #3036393: Allow basic HTML markup in element titles.

Checkboxes do support HTML markup.

The below YAML…

checkbox:
  '#type': checkbox
  '#title': checkboxsup
checkboxes:
  '#type': checkboxes
  '#title': checkboxes
  '#options':
    one: onesup
    two: twosup

…renders via Bartik as…

If you can replicate and document this issue, please create a ticket on Drupal.org.


What hook can alter fully rendered html?

I highly recommend you not to alter the page output when you clearly know where the bug is. See Bala's answer. Or may be you want to let us know what is the exact problem ?

To answer your question, to alter the content that is going to be rendered, use hook_page_alter


Create a checkboxes-field with a radiobutton for all items

You can also achieve that using the Double Field module.

Go to your content type and add field Type as Dobule field and Wideget as checkbox and checkbox

You can add Prefix or suffix for each field to display them as label for them.

Additionally you can use the Field Group module to make them under a roof.

Here is the screenshot:


How to get the unread message count using EntityFieldQuery

If you are using the privatemsg module you can use privatemsg_unread_count().


Subscribe/unsubscribe user from mailchimp list after purchase

Because MailChimp doesn't want you to just subscribe people without their permission, it makes you put this into a field.

We have clients, however, who put the subscription opt-in into their Terms of Use agreement. A way around this is to create your own rule:

/**
 * @file
 * Rules integration for the mailchimp lists module.
 */

/**
 * Implements hook_rules_action_info().
 */
function mymodule_rules_action_info() {
  $items = array();
  $items['mailchimp_lists_id_user_subscribe'] = array(
    'label' => t('Subscribe or unsubscribe entity from a MailChimp list ID'),
    'parameter' => array(
      'entity' => array(
        'type' => '*',
        'label' => t('Email Address'),
        'description' => t('The email to subscribe.'),
        'wrapped' => TRUE,
        'allow null' => FALSE,
      ),
      'list_id' => array(
        'type' => 'text',
        'label' => t('MailChimp List ID'),
        'description' => t('The list ID found in the mailchimp dashboard.'),
        'allow null' => FALSE,
      ),
      'subscribe' => array(
        'type' => 'boolean',
        'label' => t('Subscribe'),
        'description' => t('True to subscribe, False to unsubscribe'),
      ),
    ),
    'group' => t('MailChimp'),
    'access callback' => 'mailchimp_lists_rules_access_callback',
    'base' => 'mymodule_rules_action_entity_subscribe',
  );
  return $items;
}

/**
 * Action callback: Subscribe an entity to a list.
 */
function mymodule_rules_action_entity_subscribe($entity, $list_id, $subscribe) {
    $email = $entity->value();

    $choices = reset($field_info['instance']['default_value']);
    $choices['subscribe'] = $subscribe;

    if ($subscribe == 1) {
        mailchimp_subscribe($list_id, $email);
    } else {
        mailchimp_unsubscribe($list_id, $email);
    }
}

Where mymodule is the name of your custom module. This will provide the rule integration you're actually looking for.

Be careful, though: This method could get you banned from Mailchimp. It's best to combine it with a double opt-in process to prevent people from reporting subscription abuse.


drupal 7 - views conditional not working

If I correctly understand your point, you would like a view to display two latest nodes of a specific content type. While displaying these nodes the view should check:

External link is provided or not

If External link is provided then output that as a field of view, if External link is not provided then output the URL Path of the content.

I can achieve this with just Views without the need of the Conditional one, unless I am misunderstanding your questions. I have the following steps for you to achieve what I stated here,

Create a content type with link field and either Pathauto or custom URL supplied
Create a view with content type as the one created
Choose Field for Format Show and the select whichever field of the content type you are interested including the External Link & Path fields
Click on the external field link, once opened change the title to New Title or whatever fancy
You would need to use the NO RESULT BEHAVIOR settings of this field
In NO RESULT BEHAVIOR supply the placeholder for PATH which is [path] - The path should be included among the fields
Save and there you go the result, if the node is not having an External link then it will display the path as value of external field, otherwise it preserves the supplied external URL. Screenshot for more detail

Create content types as follow:

Configure view as follow

Configure the NO RESULT BEHAVIOUR as follow

There you go the result of your view, first content types does not have external URL and the second content types does have (don't forget to include the path as one of the fields or you won't be able to access it)


How to unpublish postings according to the value of a field?

Your question seems to exist of actually 2 questions, so here are 2 parts of an answer to address each of them (I'm assuming this question is about D7).

Part 1

Refer to my answer to "How to specify a Rules condition related to select list values?" for an example Rule (in Rules export format) that allows for specifying a Rules condition related to a specific value selected via a selection list.

With this (and some minor tuning of that sample to fit your field and values), you have an answer to your "if choice X, than unpublish after Y period of time".

Part 2

Refer to my answer to "Redirect users with specified roles to specified term pages", which shows how you can redirect to various URLs (depending on some role). It also explains 2 possible approaches for either creating multiple rules (1 for each role) versus just 1 rule (by using the Conditional Rules module).

With this (and some minor tuning of that sample to fit your case here), you have an answer to your "does this mean that I have to make 3 different rules, one for each time limit". The actual answer is: either way can work (personally I'd go for just 1 rule, using the Conditional Rules module).

PS: So yes this can be done without PHP, it only requires some site building using the Admin UI for Rules.


What is the 'System' display option in Views?

Today I was in the same situation, so I decided to look and this is what I found:

  So, for anyone stumbling upon this, 'system' displays are only to override core views (which you do through the System Path Settings area in the Advanced section of views) and I should just be using a page display with a path that begins with '/admin/' if I want to make custom admin views.

Here is the link: https://www.drupal.org/node/2539256#comment-10150524


View Group By field with mult-value field

You can also uncheck the box "display all values in the same row" under the multiple field settings menu in the configure field settings. Doing this "denormalizes" the data. This works for both content and taxonomy terms - in my case accessed via entity reference. This way you can make the best choice between content and taxonomy in your design.


Custom content for several Spanish speaking countries

I think it's the best solution, or at least we used the same. In Switzerland, we have the Swiss German, that is a little bit different from German.

So we took the German translation as a base and created another language, like de-ch. Then with i18n and all other modules, we translated the differences.


Views Galleriffic- pagination does not show

1) Turn off the Views pager (ie set it to "All items).

2) In the "Style" set the number of thumbnails you want to display before the pager. If you have 17 images you can set it to "9" there.

3) Make sure you have the top or bottom pager turned to "yes" in "Style".

Any luck? I just tested it with views-6.x-3.x so it should work if you have the right settings.


How do I set 'Locale settings' fieldset, in the user profile form, to uncollapsible?

Found it!
The point is that your hook_form_alter is called before system_form_alter, so you don't see the timezone. You need to reorder the implementation of hooks with hook_module_implements_alter

Here is the full code:

function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['CUSTOM_MODULE'];
    unset($implementations['CUSTOM_MODULE']);
    $implementations['CUSTOM_MODULE'] = $group;
  }
}

function CUSTOM_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  $form['timezone']['#collapsible'] = FALSE;
}

Credits to this post.


Updated Answer for your Updated Question:

In views you will need to add one of 2 fields.  'Content: Path' is likely the one you are looking for though.  Below is where to find it.

1) First you need to open your view for editing.

2) Next, find "Content: Path" and add it to your view.

3) Side note - If you would like a simple link you can add "Content: Link" in stead.  You also have access to Content: Edit, and Content: Delete among others.

Pre-update:
I will update this answer if you clarify your question. Specifically what you mean by 'as a field value.'

As I currently understand your question I think this may be what you're looking for.

I believe you will need to use drupal_lookup_path() to find a path alias.

Example:

drupal_lookup_path('alias',"node/".$node->nid);

  Source: Drupal Community Documentation for drupal_lookup_path()

  Given an alias, return its Drupal system URL if one exists. Given a
  Drupal system URL return one of its aliases if such a one exists.
  Otherwise, return FALSE.

  Parameters

  $action One of the following values:

  wipe: delete the alias cache.

  alias: return an alias for a given
  Drupal system path (if one exists).

  source: return the Drupal system
  URL for a path alias (if one exists).

  $path The path to investigate
  for corresponding aliases or system URLs.

  $path_language Optional language code to search the path with.
  Defaults to the page language. If there's no path defined for that
  language it will search paths without language.

  Return value

  Either a Drupal system path, an aliased path, or FALSE if no path was
  found.


How to fix call to undefined function libraries_get_path() in multi-site install?

...since the second site inherits everything from the first site..."

To the best of my knowledge that's not how a multi-site setup works; in my experience there's no inheritance involved. Core code/modules/themes/libraries etc can be shared between any number of sites, but each has their own separate database (and files structure, potential for site-specific modules/themes etc.).

When you add a new site you get a fresh Drupal install, none of the settings from any of the other sites in the setup are copied over.

An inheritance-based workflow wouldn't make sense, as multi-sites can contain any number of completely different Drupal sites - the point is that they can share the resources mentioned above, and when it comes time to upgrade core/contrib modules you only have to do it once for all the sites in the setup.

You can solve the specific problem you're currently having by enabling the libraries module on the new site; but if your custom theme relies on other contrib modules to be installed as well, those will need to be enabled before the site will work properly. Similarly, if the custom theme relies on settings/variables that were available in the default site, those will need to be restored.

I think in your case it would make more sense to clone the default site and database into the new one (bypassing the installation procedure entirely), then make the necessary adjustments to distinguish it from the default site afterwards.

Either that, or wrap the default site's functionality up in Features/Config, perhaps creating an install profile along the way, and use that to instantiate the a clone when you need one.


How to setup a development server on Linux?

It should work with no or limited changes. However, some modules include fully qualified paths in database tables or variables, so it is worth checking.

Some areas to look at are:

settings.php, particularly the database array, $cookie_domain, and $base_url
The sites directory: are you using the default directory or one tied to your development environment? If your material is in sites/my.dev.com then you'll have my.dev.com in the files table
URL related modules like securepages, xmlsitemap, and so on

When I am moving from dev to production, I also use drush to double-check that I missed nothing. Running drush vget dumps the content of the variables table, so I can grep that for URLs. For example to see all the variables that have www.indiemade.com hardcoded:

$ drush vget | grep indiemade
securepages_basepath: 'http://www.indiemade.com'
securepages_basepath_ssl: 'https://www.indiemade.com'
seotools_base_url: 'https://www.indiemade.com'
xmlsitemap_base_url: 'http://www.indiemade.com'
...

One other tool you might want to look into is drush migrate, well explained here.


What WYSIWYG editor allows me to select styles from a dropdown 'out the box'?

CK Editor is the best in my opinion, and it should provide this option out of the box - it is a shame about the bug. In Drupal 6 I use drop down styles for all the line stuff and templates for including more complex block level elements such as jQuery show/hides. I really cant recommend enough how well it works. I suggest that you try the patch before ditching ck editor and seeking an alternative...

Drupal 7 is still pretty new so you will encounter small issues such as you describe, if you are dealing with bleeding edge this is something you have got to expect... otherwise use Drupal 6


PHP require_once() warning with hook_menu

If you look a bit closer at the path in the error message:

  /var/www/html/drupal/modules/system/demo_usernames_form.inc

You'll notice it's trying to find your include file in the system module.

It's happening because the user module's implementation of hook_menu() has this in it:

$items ['admin/config/people'] = array(
  'title' => 'People',
  'description' => 'Configure user accounts.',
  'position' => 'left',
  'weight' => -20,
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

Notice the file path at the bottom, explicitly setting the path Drupal should look for the included file in.

Since properties are inherited from parent paths, and the path of your item sits nicely under that one, you get an implicit file path that you weren't expecting. The result: your module path is no longer consulted when the system tries to find the include file.

To fix, just add the correct file path to your hook_menu() code:

$items['admin/config/people/usernames']=array(
  'title'=>'bad usernames list',
  'description'=>t('configure not allowed usernames'),
  'page_callback'=>'drupal_get_form',
  'page arguments'=>array('demo_usernames_form'),
  'access arguments'=>array('administer site configuration'),
  'file'=>'demo_usernames_form.inc',
  'file path' => drupal_get_path('module', 'demo'),
);

And flush them caches.


How to check if view result is empty Twig

You can use twig_tweak Module, and use drupal_view_result extension like:

{% if drupal_view_result('who_s_new', 'block_1') is empty %}

For more info look at this module Cheat sheet


How to create a menu option with HTML in its title from a module?

Modules can implement preprocess and process functions for theme functions using a template file; for theme functions not using a template file, Drupal 7 allows module to implement a preprocess function.
For example, the mymodule module could implement mymodule_preprocess_menu_link() which is a Drupal 7 preprocess function for theme_menu_link().

Preprocess and process functions are useful when the variables passed to the theme function need to be changed. If there is the need of changing the output of the theme function, then a module needs to implement hook_theme_registry_alter() and change the function called to serve the output of a theme function.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_link'])) {
    $theme_registry['menu_link']['function'] = 'theme_mymodule_menu_link';
  }
}

With this implementation, theme_mymodule_menu_link() would be the function called when a module calls theme('menu_link', /* … */).

References

theme()


Submit of custom node with imagefield ends without warning after imagefield save

The issue had something to do with duplicate translations for button labels that basically lead to only the file field being submitted when saving the node, see: http://drupal.org/node/684426 A simple update of the localization files solves the problem and makes you hate Drupal just a teensy bit.


Creating Custom Modules tutorial doesn't work - help!

class HelloController extendes ControllerBase {

You spelled extends incorrectly.


How do I use hook_form_alter() to add CSS classes to a custom input field in user_register_form?

Looks like you're trying to use the HTML ID of the element you're interested in as the identifier in PHP - not quite how it works.

For a field API field, that will look more like:

$form['field_personal_best'][LANGUAGE_NONE][0]['value']['#attributes']['class'][] = 'foo';

Your mileage will probably vary there, have a read of Why is hook_form_alter() so messy? for some relevant information, and make sure you have the Devel module installed to help with debugging (dpm($form) will tell you pretty much everything you need to know).


Copying prod multi-site installation to dev multi-site installation

I was able to get the current running prod version converted to use composer with out an issue.

If you have converted your site to use composer , you dont need to copy the whole code base into the new server. Just copy the config,custom modules, composer.json, composer lock files and other reqired files except the core, vendor and contributed modules into new server along with sites directory folder and run composer install in the root directory of the server.This can be done by initiating a git repo in the current code and using the default .gitignore file which is available in code.And cloning the same repo in new server.
As you have already copied all the files into new server.
Just run rm -Rf vendor , rm -Rf web/core and rm -Rf web/modules/contrib and run composer install from the root directory in the new server.
After doing this you will probably get your site running in Dev environment as well.


How to convert Drupal 6 profile taxonomy value to array?

The drupal stores the users data in serialized format to get it in array format  you can use
unserialize ( string $str [, array $options ] )
function in php.
here is the example for you to get better understanding PHP : unserialize() function


How to embed private videos hosted on Amazon S3/Cloudfront using JW Player module?

Use this php function to get signed url

function getSignedURL($resource, $timeout)
{
//This comes from key pair you generated for cloudfront
$keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

//Read Cloudfront Private Key Pair
$fp=fopen("private_key.pem","r");
$priv_key=fread($fp,8192);
fclose($fp);

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
    echo "
Failed to load private key!
";
    return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
    echo '
Failed to sign policy: '.openssl_error_string().'
';
    return;
}

//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

return $url;
    }


Move "Items per page" selector to the top of the content

This is the answer I got from a forum.

    {{ exposed | without ('items_per_page') }}

    {{ exposed | without('my_first_other_filter', 'my_second_other_filter') }}
    {{ rows }}


What are efficient solutions to prevent a huge amount of panes in a Panel?

Panels have "varients" with selection rules.  You can set up which variant is triggered by which value in the url variable that you named in the path setup.  This way, you can have your pane layouts not get so cluttered with options that are only visible a fraction of the time, but still have the same capability.  Either way, the check for display is a growth order of O(1) so not that much of an efficiency concern.  The views would be a better place to increase efficiency, set a limit and a link to the full list in a footer.


View restricted to a specific taxonomy term

Assuming I understand the question correctly - potentially the easiest way to achieve this is to add a 'Term Reference' field to your 'Property' content type.

This needs to point at the taxonomy 'Train Station', and you can have multiple term references if you need other terms to describe properties.

You can then use this term reference field as a view filter. You'll be looking for "Content:term_reference_field_name" as opposed to "Content:Has taxonomy term" This will allow you to filter on a particular taxonomy term.

Good luck!


$query = \Drupal::entityQuery('node')
                ->condition('status', 1)
                ->sort('created' , 'DESC');


How to disable or make fields unpublished, but not delete them

The easiest solution offhand is to make the fields non-required for registration. And then setup the Field Permissions module temporarily to not give Edit permission to Role(s) you don't want to see those fields.

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


What it's the easiest way to add a flash frontpage without alter Views node page?

Try using Themekey if its a different look and feel altogether... or Frontpage. Although you can create a node and have that node set as the frontpage in the sites configuration page. You have to use jQuery to have the page render the flash in drupal. As for redirection, what you will have to do is create a jQuery or actionscript that gets redirected at the end of the presentation or use the rule module that gets the page redirected after your particular condition is met. That is what I used on a previous project.


In view add a relationship Content: Author

Then choose User: Name under fields,

this will display author name


Should I include arguments in views_embed_view or in a hook_views_pre_view function?

views_embed_view takes arguments as the third parameter. Since you have to use that to print a view on-demand, might as well pass them along there.