How to create a custom context by using Drupal's context API?

Ok, I figured it out and I'm describing it here. It's really surprising for me that it's not explained anywhere else as of now.

Let's say we have a content type news that have a field field_section storing reference to the term from the sections vocabulary. Now, everytime we are on the node's page, and this node is referencing a section, we want to trigger the context, that will give as a Term object representing our section. Moreover we have a block plugin, that depends on the availability of this section, and should be visible only if section is available on the current page.

We could do this with the node context, but then we would have to add logic checking the content of the field_section of our node, in every context aware plugin that needs this information, and we want to have this simplified to just having context active when section is available on the current page - that's the whole point.

So first off, we have to provide a service that implements Drupal\Core\Plugin\Context\ContextProviderInterface, and tag it with context_provider tag, like that:

  mymodule.section_context:
    class: Drupal\mymodule\ContextProvider\SectionContextProvider
    arguments: ['@context.repository']
    tags:
      - { name: context_provider }

Note that we are injecting @context.repository service, we will be able to extract the node context from it. We are dependent on the node being available in the first place, so we can as well reuse this context. We could also inject here @node.node_route_context service directly and have more explicit dependency, but I felt that it would be more clean to do this trough the repository service. It's up to you.

Now the code of our context provider:

namespace Drupal\mymodule\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextInterface;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class SectionContextProvider
 */
class SectionContextProvider implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * @var ContextRepositoryInterface
   */
  private $contextRepository;

  /**
   * @param ContextRepositoryInterface $contextRepository
   */
  public function __construct(ContextRepositoryInterface $contextRepository) {
    $this->contextRepository = $contextRepository;
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {

    $nodeContextId = '@node.node_route_context:node';

    /** @var ContextInterface $nodeContext */
    $nodeContext = $this->contextRepository->getRuntimeContexts([$nodeContextId])[$nodeContextId];
    $value = NULL;

    /** @var NodeInterface $node */
    $node = $nodeContext->getContextData()->getValue();
    if ($node && $node->hasField('field_section')) {
      $value = $node->get('field_section')->entity;
    }

    // We are reusing cache contexts.
    $cacheContexts = $nodeContext->getCacheContexts();
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts($cacheContexts);

    $contextDefinition = EntityContextDefinition::create('taxonomy_term');

    $context = new Context($contextDefinition, $value);
    $context->addCacheableDependency($cacheability);
    $result['mymodule_section'] = $context;

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    $context = EntityContext::fromEntityTypeId('taxonomy_term', $this->t('Mywebsite Section from Node'));
    return ['mymodule_section' => $context];
  }

}

Basically will are getting the current node from the node context, and then extract section data if it's available.

But that's not all.

We want to make our plugin block dependent on the context, so we are are adding to its annotation:

 *  context_definitions = {
 *    "mymodule_section" = @ContextDefinition("entity:taxonomy_term:sections", label = @Translation("Mywebsite Section"))
 *  }

But it still won't work, and that's the tricky part. We also have to configure the context mapping of our plugin block. We can do this by providing it as a part of default configuration like that:

  /**
   * @return array
   */
  public function defaultConfiguration() {
    return [
      'context_mapping' => [
        'mymodule_section' => '@mymodule.section_context:mymodule_section',
      ],
    ] + parent::defaultConfiguration();
  }

And ONLY THEN it will work. The block wont be rendered if context is not available, and if it is, we can access the term referenced by node's field_section field by:

$sectionTerm = $this->getContext('mymodule_section')->getContextData()->getValue();

That's way too complicated for this to not have any documentation, but I hope this description will help someone.

And if anyone know, where on the drupal.org website I could write up a documentation for that, please let me know, we have to improve that stuff.


How to render specific form elements from the *.theme file

The base hook form from the question is for rendering the HTML form tag. To render single form elements you need to specify a separate custom template.

1. Register the custom template in a theme hook

mytheme.theme or mymodule.module:

/**
 * Implements hook_theme().
 */
function mytheme/mymodule_theme() {
  return ['entity_moderation_form' => ['render element' => 'form']];
}

2. Add the custom template to the form

While building the form

EntityModerationForm::buildForm():

  public function buildForm(array $form, FormStateInterface $form_state, ContentEntityInterface $entity = NULL) {
    ...
    $form['#theme'] = ['entity_moderation_form'];
    return $form;
  }

or to an existing form in a form alter hook:

mytheme.theme or mymodule.module:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme/mymodule_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#theme'] = ['entity_moderation_form'];
}

You can skip this step if you use as template name the form id, see the comment from @BradJ.

3. Use the custom template to style single form elements

entity-moderation-form.html.twig:

{{ attach_library('content_moderation/content_moderation') }}

{{ form.current }}

{{ form.new_state }}

{{ form.revision_log }}

{{ form.submit }}

{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

The example is from the core module Content Moderation.


Oh my god... It had to be something stupid. This was the sollution:

On Fonts.com go to "Manage Web Fonts", and add a domain. The HTML I tested was on my localhost, the Drupal wasn't.

Glad I found the answer when I was walking outside...


git post-receive hook to trigger drush rsync without prompt or with predefined answer

Add the --yes option to your Drush command.  This assuredly will work if you place it before the rsync directive.

For example:

drush --yes rsync @dev @live

Drush rsync is different than most Drush commands in that it uses strict option handling.  Commands that work with strict options pass all extra flags that appear after the Drush command name on to the tool that is being invoked.  Thus, drush rsync --yes @dev @live will fail, because the --yes will be ignored by Drush and passed on to rsync.

For more information, see:

drush topic docs-strict-options


You can do this by using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

How to Send Follow-Up Emails Using Rules Scheduler in Drupal 7 ?


Staging process -- how NOT to overwrite user content/data @ DB push to Production site?

This is a big architectural issue and as answers to the other question says: UUIDs in core in D8 will be a big improvement. They'll give all content a unique ID (independent of the content id in the database), and so if you make important modifications to content in some staging phase, the software could reconcile which content is worth transferring.

There's a UUID project for Drupal 7, which I believe Deploy module can use in this way.

  The integration with Services module alters all UUID enabled entity
  resources (nodes, users, taxonomies etc) to be based on UUIDs instead.
  This way it becomes easier to share and integrate content between
  sites. This functionality is used by Deploy module.


How to restore uploaded backup in Drupal 7 (public files or entire website) correctly?

I think it's a concurrency issue when D7 makes a file object in db.
try to use this modules Upload QC
please let me know if it works with you.

also try to check the temp file name. and make sure tat the database is restored correctly.


How to display entity properties using hook_entity_view_alter? Help with syntax

Accessing the entity

hook_entity_view_alter does not have an $entity parameter. This is a problem that has been addressed in Drupal 8 (see https://drupal.org/node/1618140).

In the mean time you can't be certain that the entity is available, because it depends on the function that invokes hook_entity_view_alter in the first place. Anyone can invoke hook_entity_view_alter, any may (or may not) provide you with the entity in the build array.

The EntityApiController from the entity module (which is not core, but is a requirement for eck) adds a '#entity' field to the build array which contains the entity. My feeling is that it should be safe in most cases to rely on this, but you can't be 100% sure that it will be there.

Here is an example, assuming a required field 'field_mycustomfield' which has a 'value' property (eg. simple text field):

function mycustommodule_entity_view_alter(&$build, $type){
  if ($type == 'mycustomentity' && isset($build['#entity'])){
    $value = field_get_items($type, $entity, 'field_mycustomfield');
    $build[] = array(
      '#type' => 'markup',
      '#markup' => "My custom value: " . check_plain($value[0]['value']
    );
  }
}

Adding values to the build array

You have a small mistake in your code: to be able to modify the $build parameter, you must take that parameter by reference (as showed on the documentation for hook_entity_view_alter). Look at my example above and notice the & before $build.


How to display different page content to Anonymous user and to Authenticated User in drupal 7.x?

The "content" and "information" part of your question doesn't make sense to me. I'm posting a general guide to displaying different content on a per role basis, and you can update your question/comment if you need any part clarified.

I would use Panels. You can use it on either a custom page such as "example.com/information" or on a per conent basis to display different content or parts of the content, on a per role basis. Example below if for "content"/"nodes".

Install the Chaos tool suite (ctools) module, and Panels.
Enable the Page Manager and Panels modules.
Enable the node template.
Create a variant of type "Panel", call it "Authenticated user view".
Pick a suitable layout.
Go to the "Selection rules" settings and add a "User:role" setting to limit viewing to a certain role, such as authenticated user.
Go to the content tab, and add your "Node: Content" to a suitable region so that your content shows up.
Repeat steps 4-6 but call the variant "Anonymous user view". Make sure it's below the first variant in the list.
Add whatever you want your anonymous users to see to the second variant.
Save

That should be all. Using Panels requires a bit of understanding of the tools it provides, and I probably introduced a great deal of new Drupal terms to you in this answer. I recommend you start by viewing these videos here.


I am unable to create a variable in template.php that I later want to use in node--content-type.tpl.php

These are the steps I would take to resolve (re-trying after each step)

Clear theme registry cache - /admin/config/development/performance - Clear Cache
Use the more general function mytheme_preprocess_node($variables), clear cache, try again

If the more general function works, your issue is likely that you have incorrectly named the template, try:kpr($vars['theme_hook_suggestions']) if you have the Devel Module installed.  If not, you should. Otherwise you can print_r($vars['theme_hook_suggestions']).  Is your template included in there?


Not showing clickable links in search results

A couple of possibilities. Is the site using Search API views? If so perhaps there is a search results view that you can adjust.

Another idea might be that someone has customized the search results templates in the theme to be unlinked or otherwise weird. Check in your theme folder for any search related templates.


AJAX callback function has to be defined in the same file?

use form_load_include() in your form definition function. I put this just above the return $form; line.

form_load_include($form_state, 'file_extension', 'your_module', 'your_file_name_without_extension');


This is from drupal_goto

  Usually the redirected URL is constructed from this function's input parameters. However you may override that behavior by setting a destination in either the $_REQUEST-array (i.e. by using the query string of an URI) This is used to direct the user back to the proper page after completing a form. For example, after editing a post on the 'admin/content'-page or after having logged on using the 'user login'-block in a sidebar. The function drupal_get_destination() can be used to help set the destination URL.

It seems like your destination parameter is set so you have to clear destination parameter or use header function


How to automatically add the permission "edit" on a node to a user who is not the author?

Install Content Access and ACL, and then use Rules to add Person 1.2 as a person able to edit that content.

You may find this question helpful: Node access by role or user, what module(s) should I use?

The Content Access module gives you role permissions at the content type and (optionally) node level. By default, node level permissions are disabled but you can enable it on a type-by-type basis.
If you install ACL module, Content Access can give you per user permissions at the content type and node level.


How do I maintain persistent information over a multi-step input process?

Easiest is just save to $_SESSION which effectively stores it using the cookie for you. Are these anonymous users? Care may need to be taken if cookies are disabled in that case.


How to show a block on pages with url parameters?

Found the answer Restrict block to specific pages is broken when using view pagination

Turns out the block I was trying to display was a View which was also set to display a pager (even though one doesn't appear). Turning the pager off resolved the issue.


D6->D8 Migrate failing to copy any nodes

In migrations, programmatically you can make requirements so a migration cannot be ran until another migration has already been ran (migrated).

  Operation on Nodes (page) failed followed by Migration d6_node:page
  did not meet the requirements. Missing migrations d6_user.
  requirements: d6_user.

So what this error is saying is you need to run d6_user first; before you can run d6_node:page.

Why you might ask? Because nodes have authors, so the user's need to be already migrated so the node can set the authors. Otherwise, you would end up with nodes that don't have authors.

  Migration d6_node_revision:page did not meet the requirements. Missing
  migrations d6_node:page. requirements: d6_node:page.

Like wise here, you can't have a revision until a node exists. So you need to run d6_node:page before running d6_node_revision:page


Best way to export Commerce orders, line items, and customer profiles from live to dev?

I ended up exporting the tables from Sequel Pro using the "DROP TABLE IF EXISTS" syntax and then importing them (see screenshot).

If you don't use the DROP TABLE syntax (I believe this is the option in phpmyadmin) then just delete the tables before importing.

Basically, I spent a half an hour browsing the field_data_fieldname tables and others to see what sort of content they had and if they were pertinent to orders, line items, or users. I erred on the side of more db tables rather than less.

One of my field_data_fieldname fields was shared with other entity types, in addition to commerce_order, and so rather than clobber the incoming values, I had to create INSERT queries. Using Sequel Pro cut and paste did that for me. Make sure to get the field_revisions_fieldname table as well.

Make sure you empty out your cart before you import, else the cart will point to a possibly non-existent order and throw an entity metadata wrapper exception.

Here's the full list of tables:

`commerce_customer_profile`;
`commerce_customer_profile_revision`;
`commerce_line_item`;
`commerce_order`;
`commerce_order_revision`;
`commerce_payment_transaction`;
`commerce_payment_transaction_revision`;
`field_data_commerce_customer_address`;
`field_data_commerce_customer_billing`;
`field_data_commerce_customer_shipping`;
`field_data_commerce_line_items`;
`field_data_commerce_order_total`;
`field_data_commerce_shipping_service`;
`field_data_commerce_total`;
`field_data_commerce_unit_price`;
`field_data_message_commerce_body`;
`field_data_message_commerce_line_item`;
`field_data_message_commerce_order`;
`field_data_message_commerce_payment`;
`field_data_message_order_display_name`;
`field_data_message_text`;
`field_revision_commerce_customer_address`;
`field_revision_commerce_customer_billing`;
`field_revision_commerce_customer_shipping`;
`field_revision_commerce_shipping_service`;
`field_revision_commerce_total`;
`field_revision_commerce_unit_price`;
`field_revision_field_phone_number`;
`og_role`;
`og_role_permission`;
`og_users_roles`;
`users`;
`users_roles`;


Error sending Drush commands to remote host

In order for remote commands to work, you must make sure that drush is in your PATH.  This is often done by putting something like the following in a line that bash will source when it starts up:

export PATH=$PATH:$HOME/local/drupal/drush

A lot of folks put a line like this in their ~/.bashrc file, but note that on a lot of systems, this file begins with a line similar to the following:

[ -z "$PS1" ] && return

This means that everything below the line above will only execute when bash is running interactively; if you put drush in your PATH after this point, you will be able to run drush when you log in to your remote machine, but not when you attempt to call drush remotely (e.g. via drush, as shown above).

There are many solutions to this problem.

Set your PATH before .bashrc bails out.
Make a symbolic link to your drush executable from a directory that is always in your PATH (e.g. sudo ln -s /path/to/drush /bin)
Set %drush-script as described in examples.aliases.drushrc.php.


Where can I add this jquery code to apply to a view block?

One quick way could be to add it inline in a preprocess function.

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
      }
    }

If you prefer you could also add it as a file that you store in your theme. This would include a file called myfile.js under the folder for your theme /js

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         global $theme_path;
         drupal_add_js($theme_path . '/js/myfile.js');
      }
    }


CSS-tags added using Display suite on products disappears

I am not trying to do any grid nor gallery, but have had success with Colorbox.
http://drupal.org/node/1230232 for info on enabling it.


Restrict what content can be added to a panel page (using panels & organic groups)

I guess that by:

when admin of group A edits the panel page

you mean edit the group's node that is being viewed through a panel,and not that he can edit the panel's settings,
and when you're saying

selects Existing node when adding content to a panel pane

you mean that selects content through field (entity-reference). That said, you don't need to make panels respect OG permissions -I am not sure if that's possible- but to filter out the content showing in that field based on Group A or B. To achieve that you may use field_get_items, see the contents of the field and check which node belongs to which group (every node belonging to a group has a Group id (gid) by that gid you can node_load the group node and access its fields) and configure set/unset the field's values accordingly or even you may use hook_form_alter to do so.


composer-install of Drupal8 creates a tmp####/ folder. How to manage & clean it?

You shouldn't keep the tmp folder. The scaffolding plugin should delete tmp folder after it copied the necessary files into the web folder. Not sure what went wrong on your machine.

Fixed in https://github.com/drupal-composer/drupal-scaffold/issues/33


I think you should check the permission of "sites" and "files" folders. You cannot access to the folder.

I think something happened when you uploaded the website. Usually I do a fresh installation of drupal then I upload the files inside "all" folder and the files insidethe "files" folder inside "default". In the end through Backup and Migrate module I upload the db.

It must be a permission problem if you see the images there.

Let me know.


Where should I add the unique identifier cookie code?

I think hook_boot() would be the best place for your code:

This hook is run at the beginning of the page request. It is typically used to set up global parameters which are needed later in the request.
Only use this hook if your code must run even for cached page views.This hook is called before modules or most include files are loaded into memory. It happens while Drupal is still in bootstrap mode.

(emphasis mine)


How do you validate against empty form fields in D7?

I figured it out on my own: The process is the same as in Drupal 6. The arrays have just changed a bit. To use a custom validation with hook_form_alter() and a custom validation function, you would load your form_state values as follows (example based on fields from profile2):

function example_validate($form, &$form_state) {
  // Store our field values to validate against.
  $fieldname = $form_state['values']['profile']['field_name']['und'][0]['value'];

  if ($fieldname == null) {
    form_set_error('profile][field_name', t('Error Message'));
  }
}

The actual value for our fields is now found in the 'und' array. Since the #parent property of these profile fields is an array, use 'foo][foo2' format to specify the element for which to show the validation error. See form_set_error().


How to prevent a site from ever using experimental core modules?

This is by far not as black and white as you make it in regards to experimental modules.

First, on a mission critical production site, you don't want to do anything directly on production. Completely irrelevant then if it's an experimental module or not. Any configuration change or module should be tested first. There are modules to enforce a read only configuration system for example, that's one way to approach that. One example is Configuration Read-only mode, note that I have no personal experience with it.

Second, there are experimental modules and there are experimental modules. The first experimental module apart from migrate, wich is a special case anyway, was big_pipe. Which is now officially stable in 8.3. It is a module that has zero data, zero API, zero configuration, zero UI. You just enabled it and it does its thing. As such, it was perfectly fine to use it on production already and people have been doing that, myself included. After testing it first, like any other module/functionality. If you found a bug, you could disable it from one minute to the other, without loosing any data or critical functionality.

On the other side of that spectrum is content_moderation and anything around that. Once you start using it, it is a critical and central part of your content creation workflow, and getting rid of it again is much harder. We specifically made it so you could uninstall it, and your content that was published was still published and same for unpublished. But your workflows and metadata around that would be gone. Also upgrading is likely going to be tough from 8.2 to 8.3. That's also why we're working hard to get media_entity into core as a non-experimental module, so people have a stable API and data storage that they can rely on.

Third, the concept of experimental modules is pretty new and there's a bunch of modules in core that we would have made experimental if we could have back when they were added. rest.module and the related modules is one example there.

And last, lots of contrib modules are at least as experimental as experimental core modules, they just don't warn you about that in such an obvious way. Especially development/pre-beta versions. They just don't warn you about themself in such an obvious way.

To summarize, as with many other things, you need to do your research about an experimental module before using it, and for example check if it's big_pipe-like or content_moderation-like. And then decide what that means for your site.


Add values to an existing custom entity bundle

One approach is using entity_metadata_wrapper:

  The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier.
  Wrappers make it easier to get and set the values of fields and
  properties as well as to programmatically retrieve additional
  information about these elements and iterate over lists of values in a
  consistent manner.

Example:

$entity_wrapper = entity_metadata_wrapper('myentity', $id);
$var = $entity_wrapper->field_flag->value() + 1;
$entity_wrapper->field_flag->set($var);
$entity_wrapper->save();


how does links__system_main_menu() work?

Drupal renders the array argument you passed by looking up a suitable theme hook for links__system_main_menu.

The meaning of the argument should be documented in the module that provides the theme hook.


What I would do is create a new content type "Specific page" (id: specificpage).

In the content type, put all the "fields" / content that your client can edit. You don't want your client to break your HTML structure, but he probably wants to edit the title, the content, the background color, etc. Define all the fields he could want to edit and create them in your content type.

Use this code to theme the "page.tpl.php" for this specific content type:

function phptemplate_preprocess_page(&$vars) {
  if (arg(0) == 'node') {
    $vars['theme_hook_suggestions'][]  = 'page__' . $vars['node']->type;
  }
}

Then create a page--specificpage.tpl.php based on the original page.tpl.php, put it in your theme folder, structure your HTML content and display the fields defined by your client in the back-office.

[Edited the answer bc I did a mistake in the code and template suggestion]


Go to:

  admin>configuration>people>account settings

Scroll down and you will see 8 email options for account activities such as account activation, password recovery, etc..

The Default token inside these emails is [site:name] which I presume is what's giving you trouble? Or do you have it set to [site:url]?

Regardless possible next steps:

Manually set the link location by adding something like this to the emails ... (kind of hacky)
"http://www.mywebsite.com"
Add HTML functionality to your emails... and then apply above solution with nice html link markup (still hacky)
Try setting a specific domain as your $base_url in sites/default/settings.php. This will disable the dynamic detection of your base domain...
Failing the above investigate further here:- Your Drupal Site Pretending to be Another.


Fetching specific node fields instead of whole nodes using EntityFieldQuery

No, there isn't. EFQ can only return the entity id's.

While there might be ways around it, there is a logical reason for that: Modules might alter the values of those fields in various hooks, there is no guarantee that the directly returned values are the same as when loading an entity.


what is the default file template in drupal when you set your own theme?

If the active theme doesn't have a page.tpl.php, the default page.tpl.php from core is used.

See Default theme implementations for more information.


Never mind! By using {{ dump() }} I was able to see that I can get the individual blocks by using:

{{ elements.search }}

{{ elements.menu }}


How can I get a user_reference type field working that allows me to enter names that don't exist on the site as well as ones that do?

Autocomplete username looks like it does the auto complete bit for user registration. It's fairly simple. And could probably be adapted for your UI needs. image annotate looks like it does something similar, but without the ajax.

If you end up making it and publishing it, you can always post it here as an answer.


Drupal 7 views: Get NID in views using contextual filters

If you are loading and displaying your view in the node.tpl or node--<content-type>.tpl file, you could supply the current node nid as an argument to your block view, then you can setup a contextual filter for Content: Nid. I would do something like this:

 // get view
 $view = views_get_view('YOUR_VIEW_NAME');
 // set display for view
 $view->set_display('YOUR_VIEW_BLOCK_NAME');
 // set current node nid as argument to view
 $view->set_arguments(array($node->nid));
 // execute view
 $view->execute();
 // render view
 print $view->render();

You could also try to use views_embed_view() which I think would be the preferred way to do this. It takes two parameters, name and display_id, any additional parameters will be passed as arguments to the view:

print views_embed_view('YOUR_VIEW_NAME', 'YOUR_VIEW_BLOCK_NAME', $node->nid);

I'm not sure that this helps, the question is a little vague=)


You are correct, the core date.formatter service uses the native PHP date formatting strings, none of which have 'a.m.' or 'p.m.' in them.

If you really need this, I suspect this would work.

Create a new module, with a class that extends DateFormatter.
In the format method, call the parent method, and then do string replacment to convert 'am' to 'a.m.' and 'pm' to 'p.m.'
Replace the date.formatter service with the one you created.

This may have side effects that I'm not thinking of right now.


I presume you are using postgres.

psql, the commandline tool that Drush uses to manipulate the database, has no provision to pass a password as a commandline option, so Drush cannot provide it even if it knows what it is.  You may set up a .pgpass file in your $HOME directory to supply the password; it should contain entries that look like this:

localhost:5432:*:www-data:PASSWORD

If you create this file, and insure that it is chmod 600, then psql will no longer prompt for the password.


Import xml with Feeds module. Only one value is imported

For example, our relation's key will be test case's GUID (Test cases (Entity reference by Feeds GUID) (field_test_cases)):

Content type test_set:

field_test_cases: Type - Entity Reference, Target type - Test case
(type test_case), Number of values - unlimited.

Content type test_case: standard Title and Body fields.

Test case's importer's config:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_cases';
$feeds_importer->config = array(
  'name' => 'Test cases',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'text()',
        'xpathparser:1' => 'text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
      ),
      'context' => '/report/test_sets/test_set/test_cases/test_case/test_case_name',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_case',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

Test set's importer's config:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_set';
$feeds_importer->config = array(
  'name' => 'Test set',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'test_set_name/text()',
        'xpathparser:1' => 'test_set_name/text()',
        'xpathparser:2' => 'test_cases/test_case/test_case_name/text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
        'xpathparser:2' => 0,
      ),
      'context' => '/report/test_sets/test_set',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
          'xpathparser:2' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
        2 => array(
          'source' => 'xpathparser:2',
          'target' => 'field_test_cases',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_set',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);


A reference module is what you're looking for. References is the standard right now, though there are other options such as Entity Reference.

To use your reference module, add a "node reference" field to your Release content type. When configuring that field, allow it to refer only to nodes of the "Scene" content type.

For the sort order, I believe if you use the autocomplete widget for your nodereference field then it should give you sorting capabilities on the Release node-add form, without needing another field in the Scene content type or any more work in Views. Just make sure when configuring the nodereference field that you set the number of allowed node references to "unlimited".


Put eform's label and textfield(input) separate

The Render API, similar in Drupal 7, allows you to add a #theme property to use a hook_theme defined template. The theme definition should use "render element", and that will be available in the template preprocess function. The way that it's usually done is to modify or create the render array in the preprocess function, and set #theme to table (in Drupal 7 calling theme('table') was possible).

Edit: Removed second paragraph which referred to modifying the theme.


You should set your path in admin/config/system/overlay_paths_ui whit pattern like this node/add|600px. (I test it by myself, it effect after I clear cache in admin/config/development/performance  ).
This module cant help you to set a height for overlay.(you can patch this module to provide your require   ).
Final and good solution for do your job is use css, set css in your css file

#overlay {
height :xxx px; !important
width :xxx px; !important
}


You can redirect user after checking their role(by using below PHP snippet)

<?php $GLOBALS['user']->roles; ?>

Your code will look something like this:

<?php
if($GLOBALS['user']->roles == 'editor') {
  drupal_goto("dashboard_editor"));
}
?>

Note: this will work only when a user has single role associated with him.


As far as I've understood, it is actually NOT possible in Drupal 8: https://drupal.org/node/1906806

EDIT: the patch at the above link DOES work for me with the interdiff I just posted, so if you feel adventurous, you can give it a try!


Core jQuery not working in Bootstrap theme

Yaml is heavily indentation oriented.

There are yaml validators like: YAMLlint. It will also the intendation for you. But not the wrongly set header option.

You have two indents (spaces) to much before the dash, plus js: needs to be upped too. Also the header property is set wrong, check the docs - if you want the js in the header, it needs its own library definition:

mysubtheme:
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

  This will work ! (but is in the footer)

This is how the two library definitions will look like:

slippry-css:
  css:
    theme:
      css/slippry.css: {}

and

slippry-js:
  header: true
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

You'll need then to add both libraries!

Maybe this will work too:

mysubtheme:
  header: true
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

To debug your libraries, use libraries_ui


Drupal commerce show taxonomy image in product variation

You need the Commerce Fancy Attributes module.


Where DHTML Menu link's title is getting printed

By implementing theme_menu_link(), you can adjust the menu links to whatever you need.


Views itself will tell you which file to use as a template.  Go to the config page for the relevant view and choose Theme: Information under Other.  This will print out a list of potential templates; the template shown in bold is the one that is in use.

To get the node type, you can use the dpm() function of the devel module.  For example, if you have devel enabled, you can simply insert dpm($row) in the template file, load a page containing the view in your browser, and then dig through the output.


how to display a media description in a twig template?

I got the media description in the preprocess
function template_preprocess_media(array &$variables) {

  $bundle = $media->Bundle();

  if($bundle == 'file') {
    $field_media_file = $variables['content']["field_media_file"];

    if($field_media_file[0]["#description"]){
      $desc = $field_media_file[0]["#description"];
    } else{
      $desc = $variables['name'];
    }
    $variables['description'] = $desc;
  }
}


Unfortunately you've no way to find everywhere this info will appears, as it will depends of the modules/templates that you're using.

So you need to identify where it is displayed, and check if user id is equal to 0 ( 0 = Anonymous user).

You can do this in hook_preprocess for example, or just add a condition in your template.
Like for example the default node.tpl.php is like this:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

You could add this condition to hide the infos for anonymous user:

<?php if ($display_submitted && $uid != 0): ?>

    <?php print $submitted; ?>

<?php endif; ?>


Ajax on Autocomplete does not fire again, if previously fired

The basic idea behind this is to simply cache the AJAX response of an autocomplete query keyed by the query string itself. Eg.

q = 'I',
cache miss
cache['I'] => [ 'India', 'Indonesia', 'Italy', 'Iceland' ]
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

q = 'In'
cache miss
cache['In'] => [ 'India', 'Indonesia' ]

q = 'I'
cache hit
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

If you inspect misc/autocomplete.js in Drupal 7, you'd notice that there is a Drupal.ACDB (Autocomplete Database for those curious) object. What's more interesting is the search() method implementation in the same object. You'd notice that given a query string, first the in-memory cache object is looked up first before an AJAX request is made. This is something that you might want to emulate too.


If you want to replace the whole site pager with a drop-down list, you should write a custom module (see 1 and 2). If you want to show it only for some pages, you just invoke the module (see 2):
1. Declare this in the template.php of your theme (replace YOURTHEMENAME and YOURMODULENAME with the appropriate theme/module name):

function YOURTHEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
  global $pager_page_array, $pager_total;
  // Calculate various markers within this pager piece:
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  return drupal_get_form('YOURMODULENAME_pagerform', $_GET['q'], $pager_max, $pager_current);
}

2. Create a custom module, adding the following code to the YOURMODULENAME.module file:

function YOURMODULENAME_pagerform(&$form_state, $path, $pager_max, $pager_current = 0) {
  $form = array();
  $pagers = array();

  for ($i=0;$i<$pager_max;$i++) {
    $pagers[$i] = $i+1;
  }

  $form['pager'] = array(
    '#type' => 'select',
    '#title' => t('Current page'),
    '#options' => $pagers,
    '#default_value' => $pager_current,
    '#attributes' => array('onchange' => 'this.form.submit();'),
  );
  $form['path'] = array(
    '#type' => 'value',
    '#value' => $path,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array('style' => 'display: none;')
  );

  return $form;
}

function YOURMODULENAME_pagerform_submit($form, &$form_state) {
  drupal_goto($form_state['values']['path'], 'page='.$form_state['values']['pager']);
}

p.s. The code was quickly written in browser without any debugging, so may be some errors happen, but it's should give "idea".


Upgrade Drupal 6 to 7 using Drush 5 in Windows

That functionality is now available as a separate module: Drush Site Upgrade

  The new home for site-upgrade drush command, which streamlines the major version upgrade process for Drupal.

There's also some reassurance that this will work with the latest version of Drush:

  IMPORTANT: Drush Sup 7.x-2.x requires Drush 5 or later.


I had this problem and it was due to weights I had on the menu links as well as the actual ordering in the menu admin page. I re-ordered them in the normal menu settings page, and then I was able to order them properly in the TB Mega Menu settings page.


Create a simple date formatter to be used in views

You should:

Create a new date format: /admin/config/regional/date-time/formats
Create a new date type that uses the format you just created: admin/config/regional/date-time
Use that date type in view.


Integrate the drupal distribution with already existing site

Have you tried the Recruiter Features module?

You can simply download and enable this feature instead of the install profile and see if it does what you need.


Go to URL as in fig (for page comments on page content type). Change the type of text to Plain text as shown.
You can change the comment settings for article or book in similar way by just replacing page from the URL with the respective content types.


How can we create a search form to display a specific node

Make an exposed filter (with autocomplete) of the register number in your view (showing all these desired nodes), enable it's exposed filter block (Advanced > Exposed form in block : Yes)

Now place this block where ever you want, hit apply, you should be taken to the views page, only showing one result. (Make sure the full rendered node entity is shown)


How to create a distribution list for sending eMail?

You can use the Rules module for this, simply by using Rules Action "Send mail to all users of a role". So all you'd have to do is to create a role that corresponds to your "user group", and grant access to the role you created for it.

However, if your user group consists of many, many users, then you might want to use a more granular approach as details in my answer to "How to delay sending emails using Rules to avoid being considered as a spammer?".


How to change order of javascript files in Drupal 6?

If you look at drupal_add_js() and drupal_get_js(), you will see the details.  Unfortunately, module_invoke_all() or it's cousins, don't get called, which means there are no hooks.  Boo.  A related issue is that when you aggregate, you loose the ability to do string manipulation (eg, explode, reorder, implode).

The best way to handle this is to alter the weight of the JW Player Module.  One way to do this is to edit the {system} table and edit the weight column value.  With the weights, lower numbers run earlier, higher numbers later, and where there is a tie, they run alphabetically.  Make sure you clear cache when you do this.  See Change module's weight - by module or manualy for some more details.

If this doesn't fix the problem, then the JS files aren't being added by the same hook.  I am not sure what can be done it in this case w/o hacking the module.

A total sledgehammer approach would be to not include the your code, but to add it in the theme's .info file.  This should add it after all modules.


How to redirect to the webform node when it just created?

try it with return

function webform_chshb_webform_insert(\Drupal\webform\WebformInterface $webform) {
    $webformnode = \Drupal\node\entity\Node::create([
        'type' => 'webform',
        'title' => $webform->label(),
        'webform' => ['target_id' => $webform->id()],
    ]);
    $webformnode->save();
    drupal_set_message(t('Node %label created.', ['%label' => $webformnode->label()]));

    $nodeid = $webformnode->id();
    $response = new RedirectResponse("/node/$nodeid/edit");
    $response->send();
    return;
}


Toggle CCK field visibility with CCK radio buttons

There is a contrib module written for just this: Conditional Fields. Here is a quote about it (from the module's project page):

... allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


Using View to List a Member's Organic Group with Inherited membership

After digging around in the default views, I found a work around for my problem.

I cloned the view OG User groups (OG membership) which is normally attached to the user profile. I then filtered content against some custom fields to resolve my problem.

Its a work around admittedly, but I would advise people to check some of the other default views or the og_extras module for additional views.


drupal2dupal migration add a default taxonomy term

I was able to do it by typing in the name of the Taxonomy term , not the tid next to the field i wanted to import


Every time you create a node in SQL, God kills a kitten. There are multiple hooks that fire on node creation, that make sure that a new node is processed corectly. The correct way to create a node is with a node_save() function. It will fire the correct hooks, and register the node where it should. Please refer https://drupal.org/node/1388922


getting response back from a Java Servlet to Drupal

To force download, you want to set the proper headers for filename, content-disposition and content-length. In your case, it may need to be set from the Servlet application, but without knowing the details of $response, that's difficult to determine.

In general, though, your headers should look something like this:

'Content-disposition:attachment;filename=foobar.pdf' (content-disposition:inline is the opposite of this)
'Content-length:1234567098'


Why default template suggestion use double dash instead of single dash?

I do believe it's just to add separation on the off-chance that the region/content type/page name has a dash in it, itself. block--my-impressive-module--delta.tpl.php is a lot easier to see that the intended target is block named my-impressive-module, than if it were block-my-impressive-module-delta.tpl.php (now there's no separation between the three name sections). It's possible for a region/content type/page name to have a dash, but none will have two dashes, so it's a reasonable substitution.


view content by two taxonomy terms from two vocabulary

In Views you can do it with Exposed filters.

Just add filtering by your two vocabularies to your view (FILTER CRITERIA) an set each filter "Expose this filter to visitors, to allow them to change it". That will show form to enter taxonomy tags to filter on views page. AND logic "show the contents tagged with both terms" works by default (set each exposed filter to "required" if you dont want to allow "all", that way user must select something).


checkout this awesome og video tutorial, it will show you most of the steps needed. To add a picture to a group you just add a field type "photo" to your group node.
And to display the list of groups you'll use views. I haven't figured out yet how to show the count of members that belong to each group. I posted that as a separate question.


Views taxonomy exposed filter, show tree/hierarchy in drop down menu

The filter Taxonomy: Term ID (with Depth) will display the option "Show Hierarchy In Dropdown" when you select the Dropdown widget.


I am not sure if you are looking for a composite element or just a simple one, but I found a great example for a Composite element posted by the user lpalgarvio.

Using the example module makes it all simple, in this case you are extending the class WebformCompositeBase to implement your own composite element.

Another example would be to take a look at the elements which ship with Webform module and how each is implemented. According to the webform 5 (D8) module maintainer he is wanting to add such an example into the webforms module.

Update:
There are three examples of custom elements in the webform module itself, all quite clear and detailed:

Composite element - webform/modules/webform_example_composite
Element - webform/modules/webform_example_element
Handler - webform/modules/webform_example_remote_post
Config examples - webform/modules/webform_examples (pre-built forms)


How do I link a thumbnail image to its content programatically?

Something like this...

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;


welcome page before main page (home page)

If you're happy to go down the module route, the following should get you started.

You're going to want to set a cookie to see if the user has been to the site before.  If the cookie is set, then you know the user has been to your site ebfore and it shouldn't redirect to the splash page.

function MYMODULE_init() {
  if (!isset($_COOKIE['mysite_firstvisit'])) {
    drupal_goto('path/to/splash/page');
    setcookie('mysite_firstvisit', '1');
  }
}


Rules might be what your looking for. you have to find a module that plugs into rules that can check ip.


Add a custom attribute to the main div of a node only on teaser view mode

We can use preprocess function to change OR add an attribute to our node main div.

function MYMODULE_preprocess_node(&$variables){

  // Array of aatributes which we want to pass to the node div.
  $attr_array = ['tarbot' => 'value'];

  // Condition for teaser format.
  if ($variables['teaser'] == TRUE) {

    $variables['attributes_array'] = $attr_array;
  }
}

by using this function we will get our node div in this form

<div class="node" tarbot="value"> </div>


When posting OG content, how to choose only from Content Author's Groups?

As far as I know the default is to provide all groups you have access to and so if you are some sort of admin then you will have this problem.


How can I merge a content type's fields and settings from dev to staging?

To fix the issue include config in optional directory instead of install directory in your features module. It will then only install the config which are not present in the new site. Which will solve your issue.

When I try to enable to the module I get a screen full of "unable to install" because the configuration already exists errors.

Ok, I misread your question. To update existing config as well you need to do partial cim.
Copy the feature configs into a different directory named feature-config-sync (can be anything other than standard folder names) in default site config directory. And execute the below command. It will import new config and update existing configs if needed. Limitation is it wont delete any configs.

drush cim --partial --source=../path/to/config/feature-config-sync

IIRC you can even map the module install/optional config directory as source during partial import.
Once your import is done you can delete the feature-config-sync directory.


Can we access paragraph field in views-view-unformatted.twig?

I don't think you can get the value of field from paragraph field inside views-view-unformatted.twig all you can get is the target_id of referenced paragraph using view.result[key]._entity:

I suggest to use template_preprocess_views_view_unformatted like the following:

function YOURTHEME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
  if ($view->id() === 'YOUR_VIEW_ID') {
    $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
    foreach ($rows as $id => $row) {
      /** @var \Drupal\node\Entity\Node $node */
      $node = $view->result[$id]->_entity;
      // Get paragraph field.
      // Change field_paragraph by your filed ref to paragraph.
      if ($node->hasField('field_paragraph')) {
        $paragraph_ref_id = $node->field_paragraph->getValue()[0]['target_id'] ?? NULL;
        if ($paragraph_ref_id) {
          /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph_entity */
          $paragraph_entity = $paragraph_storage->load($paragraph_ref_id);
          // Get the value of your field.
          // Change field_paragraph_text by your field.
          // And set another variable to use in twig.
          $variables['rows'][$id]['should_display_row'] = ($paragraph_entity->field_paragraph_text->value !== NULL) ? TRUE : FALSE;
        }
      }
    }
  }
}

Now in your views-view-unformatted.twig you can check on row.should_display_row like the following:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if row.should_display_row %}
    <div{{ row.attributes.addClass(row_classes) }}>
      {{- row.content -}}
    </div>
  {% endif %}
{% endfor %}


You are missing a colon after depx-slides:

dexp.slides:
  version: 1.x
  css:
    theme:
      css/plugins/font-awesome/css/font-awesome.min.css: {}
      css/admin.style.css: {}
      css/plugins/rs-plugin/css/settings.css: {}
  js:
    js/dexp.layerslider.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.revolution.min.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.tools.min.js:  {}
  dependencies:
    - core/jquery
    - core/jquery.ui.draggable
    - core/jquery.ui.dropable
    - core/jquery.ui.sortable
    - core/jquery.ui.dialog
    - core/jquery.ui.tab

The YAML is pretty strict about format. You can run it through a linter like YAML Lint - that is how I noticed the colon was missing.

After making that change, clear your cache and require your library (either in the info file or by attaching it with #attached or attach_library in a twig file) it should work.

The official docs page has all the info you need about attaching libraries, but the YAML must always be correctly formatted.

That YAML Lint tool, by the way, works for any YAML. If you ever work on a routing, permission or other YAML files, it can check if it is valid or not which is the first step to debugging YAML - simply eyeballing it is not good enough - use the tool that will just tell you. There is an npm package available to run it from command line (I do recommend).


You're getting the error "MySQL server has gone away". Usually when this happens during Drupal installation, it's related to MySQL's max_allowed_packet setting. I'd recommend bumping that value up to 32MB. The process for changing that value on Amazon RDS is detailed here: https://survivalguides.wordpress.com/2012/02/02/change-the-max_allowed_packet-amazon-rds/


Move to Online Mode only one site of two multi sites sharing the same code base

if you mean "update" with "put online" then it is not possible, because - as you pointed out - all sites share the same code base.. updating the sites/all folder will update both. the database updates need to be performed separately.

if you have only one website online that you want to update then just upload the changes from the sites/all folder.. that updates themes and modules.

cheers,
j


Webform translation while keeping single node

The method in the documentation is working:

Go to the Webform Form settings at node/1/webform/configure
Check "localization by string translation" and "Expose webform
component strings suitable for translation."
If dealing with an existing webform, then go to Go to Configuration -> Translate interface -> Strings
Enable "Webform localization" checkbox (this is important)
And Refresh Strings
Then you will be able to see the string in Configuration -> Translate interface -> Translate

At least this works for me.


hook_menu_link_alter() accepts only one argument in Drupal 7. That's why your code isn't working.

Try the following:

function YOURMODULE_menu_link_alter(&$item) {
  if ($item['menu_name'] == 'YOUR_MENU') {
    dpm($item);
  }
}

I have wrapped it in an if check, since otherwise it would run dpm for all menu links on a page and depending on the amount of links it may cause memory overflow or timeout.


How can I prevent HTML tags getting rendered as plain text?

You need to unescape HTML. There are two working ways to accomplish this.
First you can mark your field as "raw" and the html would render correctly.
{{ your_field | raw }} should render ok.

As a second resort you can use twig's autoescape functionality:

{% autoescape false %}
{{ your_field }}
{% endautoescape %}

By this way you are telling twig not to escape html markup.


You can try using hook_entity_translation_insert and use a common logic with hook_entity_insert


How and when are commerce licenses created, and when does the state change to "active"?

It looks the license is being activated when the "order paid in full" trigger fires, and I didn't have a payment system in place. I thought I had it configured to bypass this, but enabling the example payment system and the payment ui solved the problem.

However, the user still doesn't have access to the node associated with the ACL, so I need to figure that one out, as well.


l() is printing "http://node/16" when gets "/node/16" as argument

Pass node/16, instead of /node/16.

The API reference for l() tells you that the $path argument is passed to the url() function. url() considers "/node/16" as a full URL (although the term "full URL" is not formally defined).


There are several options:

You can use the getter method for the node id (available for all entities):

$node->id()

You can use magic methods to access any field of any content entity:

$node->nid->value

The above code will actually trigger the below:

$node->get('nid')->get(0)->get('value')->getValue()


"Limit list to selected" and default to all selected?

If you want to define a default value for a limited list of items in a Views exposed filter, you can achieve it by altering the exposed filter in a custom module:

function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  $filter_field_id = 'my_filter_identifier';
  if (isset($form[$filter_field_id])) {
    $options = array();
    $options['First option value']  = 'First option label';
    $options['Second option value'] = 'Second option label';
    $form[$filter_field_id]['#type'] = 'select';
    $form[$filter_field_id]['#options'] = $options;
    $form[$filter_field_id]['#default_value'] = 'First option value';
  }
}

In order to make it to work, you need to uncheck the "Limit list to selected" option in the Views exposed filter. Of course, you also need to know the real values of your list items.

If your Views default value includes multiple options from the list, and you do not want to allow the user to select multiple options at once, you will also need to add a new filter blocking the other undesired options.


How to sort taxonomy terms on a term reference field?

If you're stuck using a term reference field, here are some widget options:

https://drupal.org/project/term_reference_sortable
https://drupal.org/project/ttr_configurable_widget
https://drupal.org/project/taxonomy_orderselect


How to place a block in two different regions?

As stated above you can certainly use Multiblock but the are a few other ways as well.

One is to use the Context module where you can create different contexts where any given context can render the same block or sets of blocks but with different conditions.

The other method I use is to use the module_invoke function. You could invoke the module and block in a node or page preprocess function by creating a variable for the block display and then call the variable in a node or page template. An example would be something like this:

In your theme's template.php file. This example calls the Disqus module's comment block:

/**
 * Override or insert vars into the node template.
 */
function mytheme_preprocess_node(&$vars) {

  // Define the node.
  $node = $vars['node'];
  $nodetype = $node->type;

  // View mode check (Optional).
  if ($vars['view_mode'] == 'full') {

    // Content type switch check.
    switch ($nodetype) {

      case 'blog_post':
        // Disqus comments block.
        $block = module_invoke('disqus', 'block_view', 'disqus_comments');
        $vars['block_disqus_comments'] = $block['content'];
        break;

    }
  }
}

Here we created a template variable called block_disqus_comments for use in a node template. This calls a block that was created by the Disqus module called disqus_comments. You can now call that on one region in one template and in another region within another template. We set a case of the content type blog_post but theoretically you could add other content types or conditions depending on your needs.

We then can render this in our blog node template as:

<div class="disqus-wrap">
   <?php print render($block_disqus_comments); ?>
</div>

The nice thing about either of these methods is that they can be carried forth in code and sent to your code repo via Git. (For Context, you would need the Features module to do that).


Is it possible to set the sitemap option programmatically using the module Simple XML Sitemap?

There are API methods to alter stored inclusion settings and generate the sitemap programmatically. There is no documentation other than the documentation page and code documentation which is pretty complete. Here are the service methods which can be used to accomplish what you need:

getSetting()
saveSetting()
getSitemap()
generateSitemap()
getGeneratedAgo()
enableEntityType()
disableEntityType()
setBundleSettings()
getBundleSettings()
setEntityInstanceSettings()
getEntityInstanceSettings()
removeEntityInstanceSettings()
bundleIsIndexed()
entityTypeIsEnabled()
addCustomLink()
getCustomLinks()
getCustomLink()
removeCustomLink()
removeCustomLinks()

You can chain these methods like so:

\Drupal::service('simple_sitemap.generator')
  ->saveSetting('remove_duplicates', TRUE)
  ->enableEntityType('node')
  ->setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])
  ->removeCustomLinks()
  ->addCustomLink('/some/view/page', ['priority' = 0.5])
  ->generateSitemap();

I have just added the above information to the documentation page, we would appreciate anyone further contributing to it.


How to get body field within THEME_page_alter

According the hook_page_alter() documentation you should be able find the body like that.

$description = $page['content']['system_main']['nodes'][$nid]['body'];

But if you still have the problem you can display all data from your page with the help of Devel module or simply with a print_r($page); and look where is the content that you're looking for.


@cilefen is correct: The purpose of the Libraries CDN API module is not downloading a library, but making the libraries found on a CDN available for your site; if then you are using the Libraries API module, it avoid the needs to download the libraries you need.

  Libraries CDN API is an API module to query CDN services to automatically provides libraries on your site.

  t also provides an integration with Libraries API. If your module depends on a library that needs to be downloaded and installed in sites/all/libraries and if this library is also hosted on a CDN, this module allows you to use the CDN version of the library very easily, without the need to download the library.


Create a button with an icon in render array, that can be themed by arbitrary contributed themes

You can create a custom HTML tag like this:

return [
  '#type' => 'html_tag',
  '#tag' => 'button',
  '#value' => 'whatever value...',
];

Another solution is to render a custom theme that creates the button, like:

return [
  '#theme' => 'your_template',
];

You can read more about rendering custom templates here.


How do I avoid duplicates when using a reference field?

I removed the duplicates using hook_views_pre_render().

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $filtered_nids = array();

    foreach ($view->result as $key => $row) {
      if (in_array($row->nid, $filtered_nids)) {
        unset($view->result[$key]); // remove the duplicate
      } else {
        $filtered_nids[] = $row->nid;
      }
    }
  }
}

Probably not the best solution, but it works for my case.


How to pass an argument from the URL to a views exposed filter?

Assuming you are using arguments (contextual filters D7.x) you can make another display that is attached to the main display.  This attached displays should be programmed to provide a summary list when the argument is not present, and to present the list as a jump menu.  You can then set up the jump menu to select the current URL argument (contextual filter). This provides a select menu for an argument, that shows the current argument if it is specified in the URL.  An example of this is the results summary page I created for our club's main fundraising race.

The main view page display has three url arguments: year, race category, and gender. The attached view has year as its first argument and race category as the second argument.  The second argument is programmed to list available categories (for that year since year is a required argument) if no category URL argument has been specified.  When setting up the jump menu settings it was set to "select the current argument".  The attached display is also set not to inherit the parent display's arguments.  That way when we link (main event page) to a specific category results, the selector shows the results filtering taking place and allows people to easily select a different summary.

Note -  this was done in D6.x using Views 2.16

Clarification - it is critical that the attached jump menu display is set not to inherit the parent display's arguments, but that the jump menu is set to display that argument. Otherwise the attached view won't display the jump list when the url argument is present, rather it will display the resulting content (however you set that up).  For my results summary page I had to pass the year argument to the attached jump selector view via PHP - eke!!


How does one set up aliases per domain on a multi-domain site?

Domain Access does allow you to have per-domain auto alias settings (but I have never tried this), but I am only seeing one alias on an edit page.

A less than idea option if you are using Panels is to have a panel page for each path, and then create a selection rule for each domain, and then assign the node that way.  This would be a lot more work, though.


For getting user based on current page, you can try to use $account = menu_get_object('user') code.
Var $account will contain user object.
Read more about this function here: https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7


if you only want save node type. You can use code example below

<?php

use Drupal\node\Entity\Node;
$node = Node::create([
  // The node entity bundle.
  'type' => 'article',
  'langcode' => 'en',
  'created' => REQUEST_TIME,
  'changed' => REQUEST_TIME,
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  // An array with taxonomy terms.
  'field_tags' =>[2],
  'body' => [
    'summary' => '',
    'value' => '
The body of my node.
',
    'format' => 'full_html',
  ],
]);
$node->save();


Entity template file/suggestion not working

I figure this out and it was relatively simple.   I added a preprocess function to template.php for entities and added the template file back in to theme_hook_suggestions array.

function theme_preprocess_entity(&$variables){
  $variables['theme_hook_suggestions'][] = 'entity__your_template_name';
}


Do I need to optimise images for smaller file sizes?

Drupal does this for you; check your ImageCache settings (look for it under admin/settings), since it basically runs ImageMagick or uses GD in the background to do the image conversions. There is a quality setting that should do what you need.

IIRC, ImageMagick does a good job. The external GD library when called from PHP apparently aren't as reliable, but the built-in GD also does a good job, I think. Ultimately, you have to test this to see if it meets your own standards.


Set another page.tpl.php if a parameter is set

Rename page-fb.tpl.php to page--fb.tpl.php and then modify your code to use $vars['theme_hook_suggestions'][] = 'page__fb'; instead of what you got currently. For further information you can check out the Drupal 7 Template Suggestions page.


The file's called .htaccess and it's in the root of the Drupal installation. A lot of operating systems hide files that start with a ., so that might be way you can't find it.

If it's simply missing, just download a fresh copy of Drupal and copy the default .htaccess file from there.


Pager will come by default in blogs template or not?

If you are creating a custom template for the blogs created by the blog module you will have a variable called $pager available to you in that template. Wherever you want it displayed you can just add something like this:

<?php echo $pager ?>

If you look in blog.pages.inc you'll see that the "pager" is added to the "$build" render array in each of the menu callback functions defined in that file.


Create a field , select field type as Date (ISO format) or Date. And choose only year, hour, minutes, seconds(if needed). Select Date entry options under MORE SETTINGS AND VALUES , choose custom format as H:i

Add time format for H:i and also go-to admin/config/regional/date-time and add date type (to display in node view).
In add/edit page for time picker(only hours)

In view page

Hope this helps you with out any help of other modules.


You can do this with CSS

ul.menu ul.menu li a:before {
  content: "- ";
}

Or, you can do something similar with list-style-image or a background-image.

Keeping stuff like that out of markup makes things cleaner.


CSS/jQuery not showing in Drupal 7 when upgraded from 6

Theming system as a little bit changed on Drupal 7. You should give a look at that page for more informations.

For your file-system problem, you should check the configuration of File system and see where is trying to put the files from the temporary folder.

By default Drupal tries to put that into sites/default/files, so check if the rights of this folder as write/execute/read for the owner and the groupe and if the group is at least the web server.

Also, maybe this problem with file-system can likely fixe your CSS/jQuery problem. So try to fix it before read the documentation from the new theming changes on Drupal 7.


You're on the right track.
You also have to add a row to the og_ancestry table. Someone posted sample code for Drupal 6 here.

/**
 * Implementation of hook_nodeapi().
 */
function mymodule_nodeapi(&$node, $op, $arg, $page) {
  switch ($op) {
    case 'insert':
      // let's autocreate a Wiki node for our Top wiki page when we create a Group
      if ($node->type == "group") {
        global $user;
        include_once (drupal_get_path('module', 'pathauto') .'/pathauto.inc');
        $path = pathauto_cleanstring($node->title);

        $wiki->type = "wiki";
        $wiki->status = 1;
        $wiki->uid = $user->uid;
        $wiki->name = $user->name;

        $wiki->title = $node->title . " Wiki";
        $wiki->body = t("This is the Wiki for your Community. Any member is allowed to edit this page. Be the first to edit this page by selecting the EDIT tab above and deleting this content and replacing it with your own.");
        $wiki->path = "wiki/" . $path;
        $wiki->og_initial_groups[0][$node->nid];
        $wiki->og_groups[0] = $node->nid;
        $wiki->og_public = 0;
        $wiki->og_groups_names[0] = $node->title;

        if ($wiki = node_submit($wiki)) {
          node_save($wiki);
          $sql = "INSERT INTO {og_ancestry} (nid, group_nid) VALUES (%d, %d)";
          db_query($sql, $wiki->nid, $node->nid);
        }
      }

      break;
  }
}


what when displaying a variable with kint crashes?

Usually D8 $variables contain way too much data, and browser struggle to render it for you.
I strongly suggest to use xdebug or similar debugger, all modern IDEs support it. It makes developer's life much easier.
However, there is a workaround without having xdebug configured:

function my_theme_preprocess_field(&$variables, $hook) {
    var_dump(array_keys($variables));
    // or better:
    kint(array_keys($variables));
    // or:
    dpm(array_keys($variables));
}

This will return you top-level keys, then you can drill down to the next level:

dpm(array_keys($variables['some_key']));

For objects use type casting:

dpm((array) array_keys($object));

Set Kint as Variables Dumper on /admin/config/development/devel (with Devel Kint module enabled) and you'll get nicely structured output.

In Twig templates you can use something like this:

{% for key, value in content %}
    {{ key }}
{% endfor %}

UPD: Valuable comment from Kevin for TWIG:

{{ kint(content|keys) }}


Browsers can be pretty aggressive about caching. Provided you're not using some other caching layers like redis/memcache, varnish, or a CDN, I'd start by disabling the browser cache.

In Firefox, open the inspector and click on the gear icon in the top right to open the Toolbox Options menu. Under the Advanced settings section, check the 'Disable HTTP Cache (when toolbox is open)'. I think Chrome is very similar in this.

Also be sure to use the hard refresh option. For Firefox it's Ctrl+f5. https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly


How to Display terms only if associated with a node

Hmm... I'd try something like this:

Change this part of your code:

foreach ($children as $term) {
  $output .= '
';
  $output .= l($term->name, 'taxonomy/term/' . $term->tid);
  $output .= '
';
}

to something like this:

// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
  // If not empty, run the foreach loop:
  foreach ($children as $term) {
    // Then check to see if any nodes exist for that term id:
    $number_of_nodes = taxonomy_term_count_nodes($term->tid);
    // If there ARE nodes...
    if ($number_of_nodes > 0) {
      // ... then add them to the output:
      $output .= '
';
      $output .= l($term->name, 'taxonomy/term/' . $term->tid);
      $output .= '
';
    }
  }
}

Hope that helps... :)


How can I change the drupal form action based on Radio button selected?

You can change the Form action in submit function

    function your_form_name_submit($form,&$form_state){
          if($form_state['values']['radion_button_name'] == 'abc') {
         $form_state['redirect'] = url('path/to/redirect');
        }
    else{
       $form_state['redirect'] = url('path/to/redirect');
     }
}

hope this will help you!!


How do you wrap a link around the block header text with Drupal?

I f I understand that your question is How to make block title a link? You can use this module http://drupal.org/project/block_titlelink


Does commerce send an order notification email to site admin (site email) out of the box?

It doesn't look like it does, no. There is, however, a rule set up to send the order notification to the user. It's called "Send an order notification e-mail".

You can easily clone this rule, but instead of sending the email to the owner of the order, send it to the admin's email address.

The admin user isn't available as a data selector for this rule, so you'll either have to expose it yourself somehow (not sure exactly how you'd do that without custom coding off the top of my head), or simply switch to 'direct input mode' and put the email address in manually.


Rules: fire at adding term only when one of this term anscestors is other specific term

Write your own condition for rules

function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_needs_veryfication' => array(
      'label' => t('ONE OF THE ANCESTORS of created term is specific term'),
      'group' => t('mymodule'),
      'arguments' => array(
        'aplication_node' => array(
            'type' => 'node',
            'label' => t('A fancy condition'),
        ),
      ),
      'module' => 'mymodule',
    ),
  );
}
function mymodule_condition_needs_veryfication($node)
  if(condition($node))
    return true;
  return false;
}


Stop displaying errors in production server in Drupal 7

Did you try this way : admin/config/development/logging ?

(Where you can choose to display every messages, or just errors, or no message at all)


Sub-directories in module's templates directory

You just need to specify the path to the template in hook_theme(), eg

function MYMODULE_theme() {
  return [
    'list_block' => [
      'variables' => [],
      // Underscores are not converted to dashes automatically in this case.
      'template' => 'account/list-block',
    ],
  ];
}


How to display an image from theme directory to a drupal block by php code?

In your image "alt" attribute, you have 2 single quotes before oil ad and a single quotation mark following it. That syntax doesn't look right to me. Maybe THAT is causing some error somehow? If not then read on below for further narrowing down your issue.

Assume you used admin/structure/block/add to create that block, with a "body" in which you added that img tag.

When doing so, you also need to select the "text format" (below the body) to be used. You wrote you used "php text format", though I'm assuming you mean "test format"="PHP code".

To further ivestigate where your problem is actually coming from, try to further narrow down your issue. By FIRST creating such image tag without using any PHP code. And instead use some text format like 'Full HTML' and/or 'Filtered HTML', something like so (I intentionally did not correct the syntax of the alt attribute, because that might produce the error you're searching for ...):

<img src="/some/path/that/is/hardcoded/images/oil-ad.png" alt=''oil ad">.

If that works then have a confirmation that your issue is NOT because of some text format configuration issue related to using the "img" tag.


It is possible to reference content types from one another but not with the core field system. There are currently 3 modules that offer this functionality:

References
Entity Reference
Relation

I'll let you read the module pages yourself to decide which one is best for your use case.

Each of the modules provides a field type that you can attach to one content type to reference another. The fields behave just like any others in the system and so can have a static or unlimited cardinality.


Controlling block page display options programatically

i solved it by giving configuration in hook_block_info function

function hook_block_info(){
    $blocks = array();
    $blocks['appendices_page_options'] = array(
        'info' => t('Appendices Page Options'),
        'status' => TRUE,
        'theme' => 'MY_THEME',
        'region' => 'MY_REGION',
        'weight' => 0,
        'visibility' => 1,
        'pages' => "aboutus/*",
        'custom' => FALSE
    );

    return $blocks;
}


How to access a remote site using the command line (with drush)?

go into your drush folder
Copy the file examples/example.aliases.drushrc.php to root of your drush folder and rename it to aliases.drushrc.php
Read the comments in that file and this slideshare
create your aliases for both the local site and development site (on shared or vps)
make sure you have a proper ssh connection setup to your remote server


Override global JPEG quality value based on cookie

This would need a bunch of image styles, a custom field formatter, a custom module that reads that cookie value, and a speed test of some sort.

You'd need to create image styles for each of the quality tiers that you want. That part can be done with the built-in image styles module.
Then you'd want to create a custom module that:

Detects the speed of the client's connection and sets that cookie. It can simply be JS downloading a 1KB file download whose start and end times are recorded and set on a cookie.
Supplies a custom field formatter to image fields that, instead of making you select a fixed quality, will select the image style and render the image with that image style on-the-fly. As an added bonus, you could allow the formatter to be configurable by exposing a form that allows the selection of which image style to use at certain speeds.
Lastly, detects the cookie that was set earlier and informs the field formatter which image style to use based on the cookie value.

This assumes that all imagery are coming from fields (because of the field formatter). For theme imagery, you'll need to render your images by hand in the same way as above, sans the field formatter.


Trying to theme my user login/registration/password reset pages in Drupal 7, going bonkers

It is a simple module for Customize Drupal Login, Password and Register pages with background images.
https://www.drupal.org/project/simplelogin


Change sort order of SOURCE STRING list at User interface translation page to alphabetical instead of date created

It depends on what you want to call "good" & "non-hackish".

If you're looking for a simple configuration change, then no; there's no configuration change that you can make to modify the translation strings order.

If non-hackish includes using Drupal APIs to override routes & services in a custom module, then yes.

You can use a custom module to override the locale.translate_page route with your own custom controller & form class that will do the same work of TranslateEditForm::buildForm(), but modify the behavior of
::translateFilterLoadStrings() so it produces a different ordered list of translation strings.

The string order is the result of a method in the locale.storage service that performs the dynamic query (see StringDatabaseStorage::dbStringSelect() where the query is built). You'll probably have to override that service in some manner to provide the same structured query object, but with an orderBy method added to execute the same query but with the sorted order you're looking for.


Is it possible to disable (or reject) selection of parent terms in taxonomy reference fields at node creation or edit?

Taxonomy Term Reference Tree Widget allows you to disable the selection of parents. Hope this helps you out.


Workaround for missing migrate-deregister command in Drush 10.3.1?

Those migrations are stored as configuration.
When you run drush migrate-upgrade --configure-only the command created various migrate_plus.migration.* config data related to your D7 migration.
If you remove the config, you'll remove the migrations. For example:

If you have config captured in a sync directory, do a drush cex, remove all migrate_plus.migration.* yml files, then drush cim. Drush will drop all migration configuration on import.
If you'd rather delete the migration directly, drush cdel will let you specifically delete a migration.

Even if you delete the migration config, some migration metadata is still kept around in the database (see migrate_map_ & migrate_messages_ tables). They'll be re-used if you re-import migration config. If you're finally finished with your migrations, you can delete them.


The solution was to rename my template files so that the extension was tpl.php instead of just .php. Once I renamed the files to add the tpl the files started working instantly.


Without knowing the full scope or what modules/custom code you've already developed, this could be done fairly easily with a hook_menu, custom form and a content type. The new content type would have a multi-select (probably auto complete) node reference field which will allow for simple reordering. You could then implement a hook_menu with a custom form returning all the newsletters in a select list and when the form is submitted you can use node_load() to get all the referenced nodes from the selected node. Your submit handler would pass the applicable values to whatever batch mail module/functions you're using.


Images Not Uploading to sites/default/files/*

Please check admin/config/media/file-system page on your site to see if the file directories are set correctly and accessible by Drupal. It's possible the server is configured differently from your local installation or the relative directories are set incorrectly in the configuration fields.

As for the comments about permissions and ownership - it seems you can run chmod on the directory, so the intention was that you would run chown on the directory to set the owner to the Apache group (on Ubuntu it www-data).


Apple-like button style carousels in Drupal 7?

The Views Slideshow module can do this and is stable for Drupal 7.


From single site to multi site of an existing site broke all pages images

I reckon that the paths which are stored in the database refer to the old url. In such case, you need to run a SQL command inside MySQL that corrects the paths.

To fix entries inside field_data_body table, you can run this command:

UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/all/files', 'sites/mysite.com/files');

You have to do the same for the corresponding revision table.


What is the fastest way to convert a large volume of documents (.html) to drupal nodes

The module that appears as most suitable for you is called HTML import. This module will divide one single large HTML document into a structured Drupal book where the heading level hierarchy is respected. This module works with HTML exported from Word; HTML document converted from PDF as well as HTML document exported from Adobe InDesign.

This makes it possible to use a single HTML page, created in a word processing program and saved as HTML, or other structured HTML, to create a multipage Drupal book in a single step.  You actually need to collate the output from all your .docx files into a single HTML-file before converting to HTML to use HTML import in a single step.

In case your requirements are beyond what HTML import is capable of, below is a list of all the (usable) Drupal modules I am aware of that can be used to bulk import HTML (and some other formats) into a Drupal site:

HTML import  - Import a single HTML page created from MS Word and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes.
HTML2Book - This also imports a single HTML page and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes, but requires you to clean up the tagsoup created by MS Word first.
Import HTML - Import all of an existing, static HTML-site into a Drupal site as nodes.
Feeds - Import or aggregate data as nodes, users, taxonomy terms or simple database records.
Migrate - Provides a flexible framework for migrating content into Drupal from other sources, including HTML.
Node import - Allows users to import content (node, user, taxonomy) from CSV or TSV files. Requires you to convert from HTML to CSV. (no Drupal 7 version)

Of these, the simplest to use are HTML import and HTML2Book. However, both can only handle a single HTML page. For more complex conversion tasks, where you need to convert a large static HTML-site made up of several interlinked pages, one of the other modules may be more suitable.

Also: Whatever tool you use, never experiment with bulk import on a production site. Unless you're a lot more clever than me, there are going to be false starts and botched imports. Cleaning up thousands of nodes damaged by an import gone wrong is not fun.  Always experiment with bulk import on a throwaway staging site that just can be discarded wholesale when things go wrong. Transfer the settings and do the import on the production site when you're sure you have a working set-up.


How to modify a field value at theme/Views level?

copy /modules/field/theme/field.tpl.php to your theme folder and rename it to field--field-site-link.tpl.php (if field key of your field is field_site_link), edit template, see comment in file for avalable variables, or just override existings


Allow user to enter unpublished content from the site in Drupal 7

You will probably want to set the content type to not be published by default, by simply editing the content type, and un-checking "Published" in the lower tab menu.

This will create the content unpublished, and from there you can handle the approval process however you'd like.


You can use my very favorite drush command:

drush fu your_feature

This is the same as using "recreate" in the UI except that it will update your feature directly where it resides in your code base (usually at /sites/all/modules/your_feature).

Now you can copy that folder (or zip it up if you like) and use it on any site you'd like.


Double values (products) in Commerce cart form

In the commerce_cart _form view under Advanced, edit the Query Settings, and set it to DISTINCT.


How to run `drush make` on the existing Drupal installation?

You can run drush make again on the existing Drupal installation, but you've to specify --no-core parameter.

  drush make --no-core                      Build an installation profile within an existing Drupal site


I would solve it on an Apache level by using Alias or mod_rewrite.


This should help you directly or get you started in the right direction -  Combine fields filter case-sensitive search


how do i add a login menu to superfish menu module?

Instead of using SuperFish, you should consider using:
TB Mega Menu

TB Mega Menu allows you to create a mega menu with an innovative
back-end user interface and synchronized with Drupal core menu.

Synchronized with Drupal core menu, auto updated if there’s any change with - -  - Drupal core menu
Bootstrap framework
Responsive ready
Multiple built-in styles designed with years of theming experience
Visual and friendly user interface - what you see is what you get
Custom style for each element of your mega menu, just input extra css class name
Multiple built-in CSS3 animated effects
Work independently with themes

Speaking from experience, I know you can add the login block to TB Mega Menu
Here is a Video Tutorial


Using views arguments to highlight/alter corresponding entries instead of filtering

Ended up just manually making a menu to display the same information... Surely there should be support for one of: node path aliases as arguments OR menu generation from nodereference tree OR menu generation from url aliases (ideally from only selected nodes)
Alas i found none of the above. I feel gross for creating the menu manually but there seemed to be no other way. Thanks for checking this out...


Execute drush command against against multiple groups

You can create a new alias group that is the combination of the two (by hand):

$aliases['newCombinedGroup'] = array(
  'site-list' => array(
    // Dev group 1 sites
    'site1',
    'site2',
    'site3',
    // 7_36 group 2 sites
    'site6',
    'site7',
    'site8',
  ),
);

This is discussed in this other thread:
How to use Drush's concurrent execution capability?

Another option as pointed out by the maintainer of Drush here:
https://drupal.stackexchange.com/a/134472/3279

is to compose your alias group site names for example from a PHP array of site names, then build your alias entries programmatically by looping through these site  names and filling out the contents of the drush alias itself.

So something like:

// This is untested example code.
$sites_in_dev = array('site-dev-1', 'site-dev-2');
$sites_in_736 = array('site-1', 'site-2');

$aliases['newCombinedGroup'] = array(
  'site-list' => $sites_in_dev + $sites_in_736;
);
$aliases['@dev'] = array('site-list' => $sites_in_dev);
$aliases['@7_36'] = array('site-list' => $sites_in_736);

foreach ($sites_in_dev as $sitename) {
  if ($sitename == 'site-dev-1') {
    $aliases['Dev1'] = array( /* ... */ );
  }
  if ($sitename == 'site-dev-1') {
    $aliases['Dev2'] = array( /* ... */ );
  }
}

foreach ($sites_in_736 as $site) {
  // ... etc ...
}

.... You get the idea. Also I would refrain from using @7_36 as an alias name. In general PHP variables shouldn't start with numbers -- and while an alias isn't a php variable persay you're playing with fire by giving it a name that would be an invalid php variable name; when evaluated now and in future versions of Drush ... who knows how that will behave.


You have two options:

Domain Access has it figured out

Domain Access module excerpt:

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

Then, you need Domain Roles:

  Allows you to save user roles per domain. Allows a certain user to be just authenticated on one domain and admin on another etc.

You can't totally prevent cross-logins, but you can make user logged in with no permissions at all, except to log out.

If you prefer Multisite approach

You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);

Taken from this answer.

Then, in hook_user_login(&$edit, $account) test if user has a role he needs to access given page, and if not, logout him with proper message.