Is it possible to make a "private" distribution not listed on Drupal.org?

On drupal.org, a distribution is a single download containing Drupal core, contributed modules, themes, and pre-defined configuration. You could create a distribution locally, using the same tools used on drupal.org to create a distribution, but that would involve creating a drupal-org.make file using drush make, which is a command removed from Drush.

Instead, as Drush itself suggests, you should use Composer. Create a composer.json file, locally, and add all the dependencies (including modules) you need with composer require. If then you need, for example, to create specific content types, roles, taxonomy terms, or other entities, you could create an installation profile, as described in How to Write a Drupal 8 Installation Profile. Using an installation profile doesn't work for already created sites, but for sites you still have to create, a custom installation profile helps in building a site.

As example of what an installation profile can do, see the content of the core/profiles/standard directory, in particular the config directory, which contains the configuration files necessary to create the default entities you normally use on the default Drupal installation. The install/node.type.page.yml file is a configuration file that defines a node content type. (The filename is important for Drupal to understand it's a node content type.)

langcode: en
status: true
dependencies: {  }
name: 'Basic page'
type: page
description: 'Use basic pages for your static content, such as an ''About us'' page.'
help: ''
new_revision: true
preview_mode: 1
display_submitted: false

An installation profile can have dependencies and a list of core modules that needs to be installed but that aren't dependencies of the profile (see the standard.info.yml file), implement hook_install() (see the standard.install file) and other hooks a module can implements, including the one to alter the site configuration form shown during the installation of Drupal (see the standard.profile file).

function standard_install() {
  // Set front page to "node".
  \Drupal::configFactory()->getEditable('system.site')->set('page.front', '/node')->save(TRUE);

  // Allow visitor account creation with administrative approval.
  $user_settings = \Drupal::configFactory()->getEditable('user.settings');
  $user_settings->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save(TRUE);

  // Enable default permissions for system roles.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access comments', 'post comments', 'skip comment approval']);

  // Assign user 1 the "administrator" role.
  $user = User::load(1);
  $user->roles[] = 'administrator';
  $user->save();

  // We install some menu links, so we have to rebuild the router, to ensure the
  // menu links are valid.
  \Drupal::service('router.builder')->rebuildIfNeeded();

  // Enable the Contact link in the footer menu.
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $menu_link_manager->updateDefinition('contact.site_page', ['enabled' => TRUE]);

  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access site-wide contact form']);

  // Allow authenticated users to use shortcuts.
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access shortcuts']);

  // Populate the default shortcut set.
  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('Add content'),
    'weight' => -20,
    'link' => ['uri' => 'internal:/node/add'],
  ]);
  $shortcut->save();

  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('All content'),
    'weight' => -19,
    'link' => ['uri' => 'internal:/admin/content'],
  ]);
  $shortcut->save();

  // Allow all users to use search.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['search content']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['search content']);

  // Enable the admin theme.
  \Drupal::configFactory()->getEditable('node.settings')->set('use_admin_theme', TRUE)->save(TRUE);
}

Installation profiles cannot be changed once Drupal is installed. If you need to use a different installation profile, you need to re-install Drupal. If you aren't creating sites ex-novo, instead of an installation profile, you can create a custom module that you install on existing Drupal sites. A module can still create new entities or entity bundles via configuration files, have code executed when it's installed (via hook_install()), and define its dependencies. See, for example, what the Forum module does, for example with its config/optional/node.type.forum.yml file.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A forum topic starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

There are some light differences between a configuration file used from an installation profile and a configuration file. Those differences allow a module to be uninstalled and re-installed, and have its entities (or entity bundles) re-created when the module is re-installed. (Doing differently, re-installing the module would shown an error complaining about the entity existing already.)


How do I get Path Auto to display one value in the URL structure when node:field has multiple values?

For multiple cardinality fields you can use a pattern like [node:field-name:1] (note the use of hyphens instead of underscores).

This is an example of the tokens available for a field called field_profile_categories with multiple values:

I think in your case the pattern should be:

[node:field-restaurant-category:1]

Although the comments in the token table suggest that deltas start at 0, so you might need to use [node:field-restaurant-category:0] if you want the first item to be used.


db_select with groupBy(CAST(column as DATE))

The solution that worked for me was to group results via php.


How do I set a variable in the configuration file setting.php and use it from code?

in settings.php:

$conf['yoursite_something'] = 5;

Then, in your code:

// Second argument is the default.
variable_get('yoursite_something', NULL);

Make sure to prefix the variables, either with the module you're using it in or with the site name.


This is a very frequent problem. Drupal has a simple solution. It is called the Context module.

The context module will allow you to ONLY show information based on term throughout the whole website. Or, only show information based on a user role. So a teacher will have different Views show in a block than a student who will have different Views based on the internship they have.

The context module also allows you to stack. You can have a context for A, B, C, D. In the Right block region of the page.tpl.php that shows four different blocks based on the taxonomy terms selected. If the student selects term A & B. Then they have the Views block for a & b show at the same time. Or, they can have terms A, B & C. If term A shows 1 block and term B shows 1 block then A & B will have two sidebar blocks showing. If intership C is much more complicated and requires 5 blocks of information then a student with terms A, B & C will have 7 blocks on one page.


You may use hook_menu_alter function to do it

/**
 * Implements hook_menu_alter.
 */
 function MYMODULE_menu_alter(&$items) {
   $items['user/login']['weight'] = 0;
   $items['user/password']['weight'] = 1;
   $items['user/register']['weight'] = 2;
 }


How Print individual fields in a view row by row

If you work with Format:Unformatted list try to override the views-view-unformatted.html.twig, you will have the ability to add class to parent or inside each row.


php in views contextual filter for different user roles

You could also use user_access() to see if a user has the rights do to something.
If you use some core administrative tasks, you can be sure that it will trigger only for administrators

E.g.

global $user;
if (user_access('administer site configuration')) {
  $query = $_GET['query'];
  return $query;
}
else{
  $account = user_load($user->uid);
  $myfilter = $account->field_custom['und']['0']['target_id'];
  return $myfilter;
}

Note: I used $account instead of $user_uid to store full user object; most of the contributed modules and core name the variable this way.


How to include task links in twig node template

https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links
The manual says:

Contextual links are stored in title_suffix. This variable needs to be printed in the html.twig file, such as in this example from block.links.contextual.yml.

<div{{ attributes }}>
  {{ title_suffix }}
  ...
</div>


How to add title of node (where order form was placed) to custom line item order in commerce

I found a pretty bad solution: I added to the node template the following jquery, which really just writes the node title of the current node to a field in the line item.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function(){
        var title= $('#page-title').text();
        $('#your-line-item-field-id').val(title );
        $('#your-line-item-field-id').prop('disabled', true);
});
</script>


Exposing webform submissions for Views, but not giving anonymous users permission to view all submissions

You will have to give following permissions to anonymous users from permissions page. admin/people/permissions

View any webform submissions

Allows viewing all webforms and submissions.


How do I convert "entity:node/9 in a link?

You have to rewrite

$value = $block_content->get('field_link')->getValue()[0];

to something like this:

$value = $block_content->get('field_link')->first()->getUrl()->toString();

See What is the correct way to get the link url?


How to get the enabled manage displays per node type?

You can use this service:

EntityDisplayRepository

  Provides a repository for entity display objects (view modes and form
  modes).

Example:

$view_modes = \Drupal::service('entity_display.repository')
  ->getViewModeOptionsByBundle('node', 'article');

More info: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityDisplayRepository.php/class/EntityDisplayRepository/8.2.x


How to get Fragment value from url in Drupal 8?

You could use it like this:

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);

It gives:

Array
(
    [0] =>
    [1] => node
    [2] => add
    [3] => application
)


The best way to debug a custom token module development

I think I'm following you...you want a way to invoke the tokens you've created outside of their natural context, so you can debug easily? If so, you can use the token_replace() function. As you're defining tokens that need a node object, you'll have to load an appropriate one up for the job:

// Load the node.
$node = node_load($appropriate_nid);

// Prepare the text string.
$text = 'something involving [node:seccion]';

// Set up some options. Your mileage may vary here.
$options['sanitize'] = FALSE;

// Get the replacement text.
$replacement = token_replace($text, array('node' => $node), $options);

That will invoke your module's implementation of hook_tokens(), and the dpm() calls will fire.

If you're doing a lot of token development it might make sense to wrap that functionality in a simple form.


How to remove a "new" indicator when clicking on a link?

The theme function used to add that marker is theme_mark(). You can override that theme function to avoid it adds the "new" marker. Supposing that you override theme_mark() with mymodule_theme_mark(), you could use the following code:

function mymodule_theme_mark($variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }

  return theme_mark($variables);
}

The theme function is used, for example, in node_admin_nodes(), and in theme_node_recent_content(); the latter function calls the theme function using the following code.

$output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
$output .= '

';
$output .= theme('username', array('account' => user_load($node->uid)));

Even better, since preprocess functions are called also for theme function not using a template file, you can use the following code.

function mymodule_preprocess_theme_mark(&$variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }
}

This code is preferable because:

What you really need to do is changing the value of a variable passed to the theme function, not altering the output of the theme function, and the preprocess function is perfect for this case
The code works also when another module override the theme function, while the code I shown earlier makes the assumption no other module overrode the theme function


Embed a single field from an existing content in ckeditor

You can accomplish this using tokens. The exact token used will vary based on your configuration, but if you wanted to embed a the current user's first name, you could use something like [current-user:field_first_name]. Here's one article about them. https://www.ostraining.com/blog/drupal/tokens-in-drupal-fields/


Immediately check if field content already exists in a node form

You can write little custom jQuery snippet using 'blur' event in order to do this. More information you may find on this page http://www.w3schools.com/jquery/event_blur.asp


Altering add_to_cart_form_submit() and random PDOException while adding to cart

When you call commerce_product_line_item_new, drupal is trying to insert an already existant record to the table field_data_commerce_unit_price which has it's primary key defined as :

  PRIMARY KEY (entity_type,entity_id,deleted,delta,language),

Since the product already exists, it fails with a constraint violation error :

  Integrity constraint violation: 1062 Duplicate entry

What you are trying to do could be accomplished by adding a new cost item to the current order based on the attributes you mention, not by modifying the current item price which I guess is what you are trying to do.

So IMHO, you may try to have a base price for your item (or even a 0 price) and once the customer adds it to cart, add another cost item with the charges calculated based on the attributes he sets.


The same you can use in Controller also:

<?php

   namespace Drupal\cssjs\Controller;

   use Drupal\Core\Controller\ControllerBase;

   class CssJs extends ControllerBase{
     public function css_js(){
       $build['#attached']['library'][] = 'cssjs/val_master';
       return $build;
     }

   }


How do I get raw urls with contextual filters to work with views in Drupal 7, when i'm using panels, and panels everywhere?

Try using argument 2 (URL arguments start at 0 not 1) as opposed to argument 3. A Failing that, disable the validation, oftentimes the validation is screwy and excludes valid content.  Start with as little filtering, validation, exclusion, etc. to make sure you're getting data and tighten the parameters from there.


How can I change field suffix due to its value

Views Conditional would be worth giving a try. The module pages says -

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To Not Equal To Greater Than Less Than Empty Not Empty Views
  conditional allows you to output text based on the result of the
  condition.


Why does js click function run multiple times?

Most importantly you have to use the JQuery selector context. Otherwise you run the entire DOM through your js code anytime when Drupal behaviors passes you only context to process.

If your function still runs multiple times, add once() with a unique identifier:

$('input.myCustom', context).once('mySecondBehavior').each(function () {

Don't forget to add the library core/jquery.once to mytheme.libraries.yml, see https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How do I enable PHPUnit testing for a sandbox project on drupal.org?

Given the following comment I found on Can enable tests for sandbox projects, testing is disabled on sandbox projects, which means you cannot enable automatic tests on sandbox projects.

  From pift_project_visibility():

if (!empty($node->field_project_has_releases[LANGUAGE_NONE][0]['value'])) {
// Ensure user has the 'access project testing tab' permission
if (user_access('access pift project testing tab')) {
  return TRUE;
}

  }

  So as long as the releases piece is taken care of, the 'enable' checkbox should never appear (and thus users will not be able to enable testing).

The issue has been created in the project that handles the automatic testing for projects hosted on drupal.org. The comment says that the automatic tests are enabled for the projects with enabled releases. Sandbox projects don't have releases enabled, so also the automatic tests are disabled.

As Drupal.org Git administrator I can confirm that none of the sandbox projects has the Automated testing tab, which I instead see on full projects. (It's not a matter of permissions, as my role on Drupal.org allows me to set automatic tests for any project.)

To answer How did you enable automated testing on this sandbox project? that project has automatic tests enabled because it's a full project, despite the project name. I can say that because the path alias automatically set for a sandbox project is similar to https://www.drupal.org/sandbox/grayside/1876908, the path alias for the #Heading module. Furthermore, a sandbox project has a Promote tab as in the following screenshot.

For the other project, this is what I see.


There are two ways to go about this.
Pure JS
You can send the date shown to the JavaScript either via drupal_add_js or as a data attribute and let the JavaScript manage the date changes. You would need to change the current date +/- 1 when clicking on a button and figure out the name of the day and the day number of the day and display that. This should be relative simple to do.
AJAX
You can let the use AJAX and send the selected date to a custom menu callback which returns the markup for the new date.
Of the two solutions I would prefer the pure JS version. The Ajax version is more complex to implement and will generate a bigger load on the webserver. It could be a nice solution if you want to do advanced theming and don't want to place that logic in the JS (like weekends / holidays etc are displayed in different styles)


Views exposed filter to take multiple values

You can use Better Exposed Filters module for this type of requirement you have.

Using this module you can add multi-select option for group names, so you will filter your results on multiple values.


(File) File: Path outputs only first item

This is expected behaviour following from your Views configuration, there is no way to instruct Views to maintain a 1-1 relation between the (File) File: Path (which gives you one file path for each image) and the Content: Image (which gives you one image formatted field with multiple images included). As a result, they are 'combined' (cartesian product) and you should actually be getting a very long list of all combinations of images and image paths.

By using the Image URL Formatter module you should be able to do what you need, here is a screenshot:

I added the "Content: Image" field twice, each time unticking the "show images in same row" option. The first one was formatted as an Image, the second one as an Image URL. And things worked as expected.

Good luck!


how to do a conditional subquery with db_delete

I think your current way is that fine for multiple table handle like that. From this Delete from Multiple Tables using db_delete link you can see that:

db_delete takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.


Render image or entity in a custom block!

You can do this in a View block. Add a contextual filter for the content id and configure it to provide the default value "Content ID from URL":

The view mode Teaser would be in your case a custom view mode (for the content type "article") only containing the product teaser field, configured to render the target entity in a second view mode "advert" (now for the content type "product").

If you want to do this in code, then get the node from a context plugin (see this great answer from @Berdir https://drupal.stackexchange.com/a/188629/47547) and build the render array (if you use the view modes mentioned above you only need one line of code). Very important, never render in Drupal 8, always return unrendered arrays.


Is it possible to change a view from a user view to a node view?

There is no automatic way to convert a user view to a node view or vice versa.

Although you probably could get away with manually combining the fields from the export of your user view with a plain export of a new node view, it would be faster and a lot less problematic to just open the old view and your new view side by side in two browser windows and recreate everything.

Unfortunately a lot of Drupal site building is just checking checkboxes...


Drupal Error : The website encountered an unexpected error. Please try again later

Please try increasing your max_allowed_packet setting in MySQL.

Open my.cnf file & update max_allowed_packet = 16M or more


You can disable Shipping Method Example from the module list itself. I have never enabled that and my shipping method works. I have flat rate enabled for my shipping method. Simply disable the module. Here is the screenshot of my shipping modules tab -


Adding Node to Entity Reference List (Via Rules) Throws EntityMalformedException

Okay I've fixed the error and whilst I'm not 100% sure this was the issue I think it had to do with the fact that the new node had not been saved prior to my attempting to assign it to the other node. Hence it had no node id, hence the error - I think.


Alternate ways to call a function inside a .module file of a module

You should make a drush command. It's not very hard:

function quickdraw_xx_xx_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['quickdraw_xx_xx_additionalfunction'] = array(
    'description' => 'A quickdraw additional function.',
    'callback' => 'quickdraw_xx_xx_additionalfunction',
  );
  return $items;
}

This way, Drupal will bootstrap and everything you need will be there, including dependencies to other files.


If you're already using OpenID, then that should work, but if you dont want to add yet another module and you have access to a server over ssh, you can temporarily route all traffic in a tunnel through the server, which will effectively secure all internet traffic, and allow you to connect to the site and send the password "in the clear" as it were over HTTP, but the SSH tunnel would encrypt it before it left your machine.

If you happen to be on a mac, i highly recommend using Sidestep.app to facilitate quickly connecting/disconnecting from the tunnel.

http://chetansurpur.com/projects/sidestep/

For this to really work for you and not be a complete annoyance, I repeat, you need to have SSH access to a server already set up, ideally, with public key access configured.


How do I implement Entity Reference Behaviour Plugins?

Answer on IRC via berdir: "no, that doesn't exist". So it simply does not exist yet in D8.
Supplementary info provided for field settings in D8 =>
berdir:

note that fields, like all config entities have a concept of third party settings. you can use that to store per-field settings. didn't check the other parts
see https://www.drupal.org/project/allowed_formats for a projects that uses third party settings on fields


How can I use the unapproved comments list as a block?

I would just use Views to list unpublished comments. That wouldn't provide batch operations, but it doesn't seem like there would be a simple way to do exactly what you're asking.


Storing the value of a form submission in a hidden field or the database

if you want a field not to show up on the node page you can either

hide it in display options: Structure -> Manage display (in front of the corresponding content type) -> Format -> Hidden
Hide it in the template file by calling

hide($content['YOUR FIELD NAME']);

The first option makes more sense in my opinion.


PHP error 500 when including a left join on a pager query in db_select()

The documentation says:

  Joins cannot be chained, so they have to be called separately (see Chaining). If you are chaining multiple functions together do it like this:

$query = db_select('node', 'n');
$query->join('field_data_body', 'b', 'n.nid = b.entity_id');
$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'page')
  ->condition('n.status', '1')
  ->orderBy('n.created', 'DESC')
  ->addTag('node_access');


Except the value never gets saved, and I can't process the input text
in hook_entity_presave().

You can add a new validate for your widget:
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  // Your logic code

  // Add validate for your widget.
  $element['#element_validate'] = [
    [$this, 'validate'],
  ];

  return $element;
}

And convert value before save:
/**
* Validate the fields and convert data before save.
*/
public function validate($element, FormStateInterface $form_state) {
    // Logic validate.
    // Code here

    // Convert value and set.
    // Field type text_long
    $value = [
     'value' => 'your value',
     'format' => 'your format'
    ];

    // Field type string_long
    $value = [
      'value' => 'your value'
    ];

    $form_state->setValueForElement($element, $value);
}


In twig you can only merge the top level of an array. So you need two steps, first get the image from the content array and then overwrite #image_style.

node.html.twig

{% set image = content.field_image.0 %}
{% set image = image|merge({'#image_style': 'thumbnail'}) %}

You can now display the image a second time in the changed image style:

{{ image }}


Where drush make downloading my projects?

Normally drush makes default behaviour is to create the site in the current directory - relative to where you run the command.

But the simplest way to deal with this is just to run drush-make with a parameter explicitly stating where to deploy the site:

drush make my.make relative/path/to/my/public_html

or

drush make my.make /absolute/path/to/my/public_html

Obviously replacing the path in question with the appropriate one. Don't understand UNIX file paths? Read up on them on wiki page.

And while I am at it, why don't you take a look at the drush make documentation too.

There are a number of drush configuration files that affect the working directory for drush commands - the most likely candidate being a drushrc file is example.drushrc.php.


If this was just content I would replace #markup with #prefix. It will automatically render without escaping your HTML.

However, it seems like you don't just want to render this HTML. You actually want it to interact with the Drupal Forms API. As such, I would recommend that you parse the data you need from the source and construct the form element the recommend way:

form['example_select'] = [
  '#type' => 'select',
  '#title' => $this
    ->t('Select element'),
  '#options' => [
    '1' => $this
      ->t('One'),
    '2' => [
      '2.1' => $this
        ->t('Two point one'),
      '2.2' => $this
        ->t('Two point two'),
    ],
    '3' => $this
      ->t('Three'),
  ],
];


Make the Main Menu have dynamic links based on url

3 (updated) options (or a combination thereof) for you to consider:

The drupal module Menu Token provides the ability to put variables in your menu options -- and used in conjunction with your existing context filtered views, may work for you if it allows you to construct the menu options you need based on other tokens that it makes available to you.
The other option is to consider an alternative approach (sorry! :) ). This would be faceted filtering. Follow the tutorials here: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages
This is possible on even the most modest of hosting as it does not require Solr (but it can use it if you need that functionality later).
(added in update) Drupal module Menu Trail By Path

I think option 1 (perhaps in conjunction with option 3) might be the closest to what you are looking for though.


depending on you exact set up (which you may be able to modify to suit), you could look into Views Tree module:

  This module provides a tree-based style plugin for Views. It is
  equivalent to the tree-based style template from Views 1.

  It is based off of the list style. Although it generates a nested
  view, there is still only a single query run for the view making it
  quite performant.


Try removing the quotes in ['0'] in the following line.

$s = $node->field_name['und']['0']['value'];


In your file of your theme: "MYTHEME.theme"

Create hook_preprocess_image

/**
 * Implements hook_preprocess_image() to add classes to the search form.
 */
function MYTHEME_preprocess_image(&$variables) {
  ksm ($variables);
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'image-rounded';
    }
}


I'm looking at this documentation and I think it says that you could start from scratch using:

$breadcrumb = new Breadcrumb();

And the class:

use Drupal\Core\Breadcrumb\Breadcrumb


Clean urls - auto path alias - how to remove accents (Á É Ó Í Ñ ) from the urls?

Have you seen transliteration module ?  The project summary says it could be used with pathauto 2.x to use transliteration for URLs.


Ah, I have just figured this out.

This only works when you show all multiple fields in the same row.

Changing the field to display all images in the same row, and displaying them in an unordered list sorted it right away.


Why is menu item for custom module not showing?

You've either forgotten to set the menu_name key for the menu you want to add the link to:

$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
  'menu_name' => 'primary-links',
);

Or you want to use the default ('navigation'), but you're using the wrong type. It should be

$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

MENU_CALLBACK is:

  Callbacks simply register a path so that the correct function is fired when the URL is accessed. They are not shown in the menu.

Emphasis mine.


Why are routing files filled with underscores?

Here comes a hopefully good explanation behind the idea of the routing system
as well as the drupal specific additions to it.

General overview

The Symfony components have two important concepts here. The http kernel is a system which gets the request, somehow ask other systems to produce to define the
piece of code which produces the requested output (a response object) and send the response back to the client. This piece of code is called controller,
so this can be either a pure php4 like function, a method on an object or even a anonymous function.

The system that knows which controller is responsible for the current request is the routing system.

Basic routing file

As module developer you define the list of routes and the corresponding controllers.

Here is an example for a json response:

taxonomy.autocomplete_vid:
  path: '/taxonomy/autocomplete_vid/{taxonomy_vocabulary}'
  defaults:
    _controller: '\Drupal\taxonomy\Controller\TermAutocompleteController::autocompletePerVid'
  requirements:
    taxonomy_vocabulary: \d+

Most symfony documentation mention pattern, but drupal decided to just allow the non-deprecated "path" key in its routing file.

The key concept is the controller which gets some parameters from the system
and converts them to the response. In this example you have the parameter
'taxonomy_vocabulary'. So everything without an underscore is considered to
be a parameter to the controller. If you want to specify a default value,
you put it into the defaults array. In the same yml array you
specify the class and method connected with '::' to tell the system where to look
up stuff. Every other property has nothing to do with the controller parameters
and so are considered to be internal and so have an underscore as prefix.

Symfony itself also allows you to define regular expressions to validate
that the incoming parameter is valid (using 'requirements'). Here it would match to only numbers.

Controller resolver

Once symfony found out which controller is active on the current request,
it asks the so called controller resolver to create an instance of the controller,
that can be executed via call_user_func_array. The controller resolver has one
method to get the controller callable (object + method, anonymous function)
and one method to get the parameters passed to the controller, see Controller resolver

Drupal extensions

This is basically what symfony gives you.

Drupal though is slightly more complicated:

You can check access to the route. For example calling user_access() was very common in Drupal 7 and below.
You don't want to convert the taxonomy_vocabulary to its actual entity object
You don't want to generate the full page response, but just the "main content".

Access check

Drupal has introduced a system on top of the symfony parts that checks whether
the user has access to the current route and alternative throw a 403 (access denied) exception. Access manager

In the routing file you specify this in the requirements part. The most common
bits are listed in the example:

  path: '/user/{user}'
  options:
    _access_mode: 'ANY'
  requirements:
    _permission: 'access user profiles'
    _entity_access: 'user.view'
    _role: 'administrator'

_permission defines a call to user_access(), _role ensures that the user has a certain role (you can specify multiple ones via , for OR and + for AND logic).
_entity_access asks the entity system whether you have access to view the user entity. Per default drupal ensures that you add access checkers allow you to proceed, but you can switch it in the options via the _access_mode.

Upcasting

As mentioned in the listing you don't want to take care about loading an entity,
see /user/{user} as example. For entities you basically just use the name of the entity type and it will execute a entity_load with the ID passed in the URL. Param converter manager

Page response

As written before the controller is responsible to generate the response object.
This would be horrible in Drupal as a page consists of so much more like all the blocks appearing in its regions, the html and page templates etc. Therefore drupal specified a different key to specify a controller which returns the content of a page:

user.page:
  path: '/user'
  defaults:
    _content: '\Drupal\user\Controller\UserController::userPage'
  requirements:
    _access: 'TRUE'

The string defined is the controller used to generate the render array for the main content region of your page.

Another addition is also the way how to deal with forms, as returning a page with a form is slightly
more complex than just a render array, so you can define _form with the FormInterface responsible for the current form.

user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
  requirements:
    _access: 'TRUE'

Note: This covers the most important points from my perspective, though there are for sure many more points to talk about.

TL;DR

Underscores are specified for everything which are not parameters to the controller. This is coming as a sort of "standard" from symfony.
These parameters are upcasted via the param converter and passed to the controller using the controller resolver
Drupal has some additions to make it easier for people to interact with the symfony routing system.


Page scroll issue when using dropdown menu

You could hide it with CSS using body { overflow-x: hidden; }.

It would be better to figure out why the scroll is happening, but it's hard to troubleshoot that without having access to your site.


How do I stringify objects or at least get a string value?

You can try this instead

{% if element['#items'][key].value == 'active' %}


Adding it to the Gemfile alone doesn't install the library. The Gemfile is used by a program called Bundler that manages your Ruby gems for you. You need to make sure you have this installed with sudo gem install bundler and then run bundle install where the Gemfile is located (your theme directory).

Alternatively you could just install font-awesome-sass yourself with sudo gem install font-awesome-sass.


You need to isolate that code out of your form submission handler. When you set the Content-Disposition: attachment header it's going to override the browser behavior of loading a new page.

Instead, you should have your form handler save the output file & generate a success page containing a download link (in case your user doesn't have JS support) and run a JS setTimeout() function that will trigger a download after X seconds. See this SO post for an example.

The download link path can be generated with hook_menu(). Its callback function will use your code snippet above. Depending on the content of the download (e.g. sensitive personal data), you may need to protect this path. This can be done in a variety of ways.


How to get the nid for a newly created node?

The nice thing about Drupal 8, is that it's object oriented, with interfaces, abstract classes etc.

This means that all entities share a lot of methods. To get the id of a node, use the id method

$nid = $node->id();

This also works for users, taxonomy terms and any other entities you create yourself or get from contrib modules modules.

For Drupal 8 development, using an IDE becomes really powerfull as it can help you with what available methods, various instances of classes has.


Why are there entries in sessions table for uid 0?

Do not be alarmed, this is normal. Typically seen in Drupal Commerce sites to keep track of anonymous users also known as user 0.


Multilingual front page- redirect anonymous users based on browser language

This is inspired by a deleted answer, but my first approach would be to have the whole site built with Panels, and then have an English variant and Japanese variant for each.

For each variant, you would use the PHP Code selection rule, and then add your logic.

For unauthenticated users, you could examine $_SERVER["HTTP_ACCEPT_LANGUAGE"] and return the proper thing.  For authenticated users, would would use your normal method.

Preferably, you would put the logic in a module function that you would call from the PHP Code selection rule, so you only need to change things in one place.  You could also do a ctools plugin to make your own selection rule, too, using the same logic.


How do I render a Twig template and load a CSS file from a controller?

As far as I understand, the controller should just contain the following code.

class DefaultController implements ControllerInterface {
  public function hello($name) {
    $twig = $this->container->get('twig');
    $path = $this->templateDir . 'hello.html.twig';
    $template = $twig->loadTemplate($path);

    return [
      '#markup' => $template->render(['name' => $name]),
    ];
  }
}

See also Drupal 8: An Introduction to the New Production.

I still have to find a reason to do this, thought. hook_theme() is still supported by Drupal 8, and it doesn't seem it is getting deprecated, at this time. The only difference is that in Drupal 8, theme() has been renamed _theme(); as such, it should not be called directly.
Since you are asking if your code is considered good practice, I would say no: You should do as you did with Drupal 7, defining a theme function in hook_theme() that uses a template. Then return markup similar to the following one in your controller method.

[
  '#theme' => $your_theme_function,
  '#name' => $name,
];

Replace $your_theme_function with the theme function ID, and #name with the array index used for 'variables'.
Actually, there is a difference between Drupal 7 and Drupal 8: While Drupal 7 allows you to attach JavaScript and CSS, Drupal 8 allows you to attach just libraries, which are a set of JavaScript and CSS files with dependencies.


How to change the title of the button in the user profile form in Drupal 7?


Strange behaviour with hook_entity_field_access

AccessResult::allowedIfHasPermission:

  Creates an allowed access result if the permission is present, neutral
  otherwise.

If access is allowed somewhere else, a failed check for the permission doesn't prevent access, because it creates a neutral result.

As you found out you probably need to build a forbidden access result.


In the code you are showing there are some mistakes.

If you implement hook_node_access_records_alter(), you don't implement hook_node_access_records() (and viceversa)
If you implement hook_access_records(), then you don't implement hook_node_access() (and vice versa).
If you implement hook_node_access_records(), the other hook that need to implement is hook_node_grants().
Returning an empty array in hook_node_access_records() or setting $grants to an empty array in hook_node_access_records_alter() doesn't mean blocking every users from accessing any node. In fact, the function that invokes hook_node_access_records() and hook_node_access_records_alter() (node_access_acquire_grants()) contains the following code.

$grants = module_invoke_all('node_access_records', $node);

// Let modules alter the grants.
drupal_alter('node_access_records', $grants, $node);

// If no grants are set and the node is published, then use the default grant.
if (empty($grants) && !empty($node->status)) {
  $grants[] = array(
    'realm' => 'all',
    'gid' => 0,
    'grant_view' => 1,
    'grant_update' => 0,
    'grant_delete' => 0,
  );
}

When $grants is empty, it adds the default grant that allows users to see the nodes (if other conditions are met).

Even implementing the right hooks, a module is not able to stop every single user from accessing all the nodes, since:

Users with the bypass node access permission can still access any node; this includes the first user created on a Drupal site
When viewing a node that is unpublished, the user who created it can still see it, if that user has the view own unpublished content permission

See the code in node_access(), in particular the following lines.

  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

Assuming you aren't interested in blocking the access to users with the bypass node access permission, or avoiding that users with the view own unpublished content permission can see their own unpublished nodes, then implementing hook_node_access() is the quicker way to avoid some users can see all the nodes, as long as the nodes aren't shown in a list of nodes, for example a view, or the front page, because in that case hook_node_access() is not even invoked.
Differently, the following code surely works and avoid some users can see every node.

function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

If that code doesn't work, then there is an error in the code of the module your wrote, since:

A single module returning NODE_ACCESS_DENY in hook_node_access() stops users from seeing a node (but remember the permissions part)
Drupal core doesn't use hook_node_access_alter(), so a module cannot alter the value returned from your module, and change that value from NODE_ACCESS_DENY to NODE_ACCESS_ALLOW or NODE_ACCESS_NEUTRAL


how to know block id in class which extend from BlockBase

BlockBase is a plugin, and as such has a getPluginId method. As you need this inside the class itself, it's as easy as:

$id = $this->getPluginId();


Is it possible to make hook_view() the same as hook_edit()?

Supposing that "model" is the content type you are referring, then I would use code similar to the following one.

function mymodule_menu_alter(&$items) {
  $items['node/%node']['title callback'] = 'mymodule_node_title';
  $items['node/%node']['title arguments'] = array('view', 1);
  $items['node/%node']['page callback'] = 'mymodule_node_page';
  $items['node/%node']['page arguments'] = array('view', 1);
  $items['node/%node']['access callback'] = 'mymodule_node_access';
  $items['node/%node']['access arguments'] = array('view', 1);
  $items['node/%node/edit']['title callback'] = 'node_node_title';
  $items['node/%node/edit']['title arguments'] = array('edit', 1);
  $items['node/%node/edit']['page callback'] = 'mymodule_node_page';
  $items['node/%node/edit']['page arguments'] = array('edit', 1);
  $items['node/%node/edit']['access callback'] = 'mymodule_node_access';
  $items['node/%node/edit']['access arguments'] = array('edit', 1);
}

function mymodule_node_access($op, $node) {
  if ($node->type == 'model') {
    return ($op == 'view') ? node_access('edit', $node) : FALSE;
  }

  return node_access($op, $node);
}

function mymodule_node_page($op, $node) {
  if ($node->type == 'model') {
    return node_page_edit($node);
  }

  if ($op == 'edit') {
    return node_page_edit($node);
  }
  if ($op == 'view') {
    return node_page_view($node);
  }
}

function mymodule_node_title($node) {
  if ($node->type == 'model' || $op == 'view') {
    return node_page_title($node);
  }

  if ($op == 'edit') {
   return t('Edit');
  }
}

Using this code, the node edit form is always show accessing /node/%node, or /node%node/view for the "model" content type.


Views Slideshow vs list View+jquery cycle lite?

I personally try to avoid using any Views jQuery modules for popular jQuery plugins and prefer just to add the jQuery plugin directly to my theme by adding the .js file to my theme.info file. I will then create another .js file that runs on load that instantiates the jQuery plugin.

I use Semantic Views module which allows you to tune the output of the view to your liking. I will use this module to output the markup in a compatible format for use with the jQuery plugin.

I find that if you use a Views plugin module for something like jQuery Cycle or jCarousel for example, you are limited by the options exposed by that plugin. I prefer not to rely on a 3rd party module which may not support the latest changes or all the features of that latest jQuery plugin.

I would expect there would be a very minimal overhead using if any at all using a Views plugin instead of using the jQuery plugin natively.


Getting og membership type in template.tpl.php

Found the anwser:
This goes in node.tpl.php (tested on Drupal 7, Organic groups 7.x-2.3)

<?php if (og_context()) {
  $group = og_context();
  $userid = user_load($node->uid);
  $roles = og_get_user_roles('node', $group[gid], $uid = $userid->uid, $include = FALSE);
  }
?>

Then use it with something like:

<?php if(in_array('test member', $roles)): print 'Testuser'; endif; ?>

For comments it's a little different:

<?php if (og_context()) {
  $group = og_context();
  $roles = og_get_user_roles('node', $group[gid], $uid = $comment->uid, $include = FALSE);
  }
?>

Works only on pages where groupcontext is available!


Drush command from contrib module not recognized

drush_s3fs_copy_local is the name of the PHP callback function for the command; the command itself is named s3fs-copy-local, with an alias of s3fs-cl.

So:

drush s3fs-cl

Is what you're looking for.


You try this code.

 function youthemename_preprocess_node(&$variables) {
 $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project_pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project_movie';
      }
    }
}

You file name should be node--project_pcgame.tpl.php and node--project_movie.tpl.php.
Clear performance cache, it should call hook_theme_registry_alter(&$theme_registry).


What is the different between an install profile and a drush make file?

Drush make...

  Drush make is an extension to drush that can create a ready-to-use drupal site, pulling sources from various locations. It does this by parsing a flat text file (similar to a drupal .info file) and downloading the sources it describes. In practical terms, this means that it is possible to distribute a complicated Drupal distribution as a single text file.

Note that it doesn't install/set up the site for you - it merely downloads and prepares the required files in the specified locations.

Install profiles...

  Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.

Once you've used Drush Make to download all the files relevant to your project, you go ahead and install Drupal as normal (whether through the UI or with Drush), except you choose your profile during installation.

The code in the profile enables required modules, sets up initial configuration for those modules and the core system, perhaps installs demo content (think Commerce Kickstart), adds menus, sets variables, etc.

Using Drush make to install a profile would be a good question/answer to look at to get an idea of how they can integrate together.


It isn't configurable. You would be better served writing your own routine that executes on a regular interval and searches for temporary files whose creation age is greater than 10 minutes ago.
The DRUPAL_MAXIMUM_TEMP_FILE_AGE constant is specifically intended to inform Drupal on when a file that has not yet been set to permanent should be removed.
If you take a look at system.module, the relevant code is contained in a hook_cron() implementation. The code reads:
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));

My recommendation is to simply implement your own hook_cron() and use the same code, but calculate for files older than 10 minutes.
You will also need for cron to execute on a 10 minute interval. For this, you'll need to add a crontab and install either ultimate_cron or elysisia_cron. I prefer ultimate_cron.
Please see my answer to this question for more information on setting up crontab on a 60 second interval for maximum timeliness. You'll then use elysia_cron or ultimate_cron to control the actual job execution interval.


Drupal 7, Aggregator, RSS no longer imported: The feed from $ seems to be broken, due to an error "Invalid document end" on line #

It turns out that a simple smiley :) wrought all the havoc. The smiley was situated in the first paragraph of a post and was therefore transferred via the feed to Aggregator.

Removing the smiley removed the errors and now the feed is showing correctly again.

I don't know what exactly is wrong with ':)', but somehow it messed things up. Explanations are welcome.


Well, the only method I can think of is to do it the template, but have a feeling there must be a better solution than this... But to do it this way:

Edit your view and under Advanced click on Theme: Information. This shows a list of template file names that would apply to your view. If you had a view called tags then creating a template file called views-view-fields--tags.tpl.php would be appropriate. After adding your template file (in your themes directory) click the Rescan template files button.

The standard template file looks like this:

<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

But if you changed it to this:

<?php foreach ($fields as $id => $field): ?>
<?php if (!empty($field->separator)): ?>
<?php print $field->separator; ?>
<?php endif; ?>
<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php
$current = false;
if(arg(0)=='node' && is_numeric(arg(1))) { // check if we are on a node page
    $node = node_load(arg(1)); // load the node
    $tag = strip_tags($field->content);
    foreach($node->field_tags[LANGUAGE_NONE] as $term) { // loop over the tags attached to the node
        if($term['taxonomy_term']->name == $tag) { // there is a match
            $current = true;
            break;
        }
    }
}
if($current) {
    print ''.$field->content.''; // add a span with current class
} else {
    print $field->content;
}
?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

The disadvantage of this method it that code needs to run for each tag in the list, but it would achieve the desired result.


Pretty sure you can just do:

<?php
$viewName = 'WHATEVER';
print views_embed_view($viewName);
?>


Drupal: showing different page layouts based on form data

I think you should try ctools multistep wizard to generate the multi step form in Drupal. To start with Ctools wizard form a great example is given at the following link http://internetdevels.com/blog/ctools-multistep-wizard-example


Can contextual drop-down menu replace menu tabs?

Contextual tabs module used in Open Atrium distribution seems to be exactly for that:

  Moves the normal Drupal primary tabs into a drop-down "contextual links" menu to the right of the node title.

Screenshot:


Drush 9 command equivalent to core-quick-drupal (qd)?

drush qd is not currently available in Drush 9. It would be easy enough to make a short shell script to call composer create-project followed by drush site-install and drush uli.

This command will probably reappear in a later release, sometime after 9.0.0 stable. A pull request that implemented qd would also be welcome.


How can I theme a form element with hook_preprocess_form_element()?

As @4k4 said, if all you want is to add some classes, then use hook_form_alter() or hook_form_FORM_ID_alter(). $form['your_element']['#attributes']['class'][] = 'your-class is all you need.

I'm pretty sure that single form elements don't have the form ID stored somewhere.


How to use Form API when the form callback is a method?

drupal_retrieve_form() uses function_exists() before calling the form builder, and that function doesn't work if you pass a string such as 'AClass::FormCallback'. If you pass it an array, e.g. array('AClass', 'FormCallback'), you get an error about the function expecting a string.

What you can do is to use a custom function containing code similar to the following one, and use it as form builder.

function mymodule_form_builder($form, &$form_state) {
  $class = $form['#class_callback'];
  $method = $form['#method_callback'];

  if (method_exists($class, $method)) {
    $args = array_merge(array($form, &$form_state), $form_state['build_info']['args']);
    $form = call_user_func_array(array($class, $method), $args);

    return $form;
  }
}

The code is simplified, and it doesn't contain code to check any possible error condition. It works also just in the case of static methods.

For an explanation of the values passed in $form_state, see the documentation for drupal_build_form().


How do I contribute a version of the same module for the latest core version?

Drupal.org apparently doesn't give information for Drupal 8, in the Version control tab of projects. I checked for a project with a Drupal 8 version (the Token module), but even selecting a Drupal 8 branch, the information given is for Drupal 7.

That said, there isn't much difference, with Drupal 8. What I report here are the adapted instructions for Drupal 8.

  Creating Releases

  See the naming conventions for a complete description of how to name branches and tags so you can create releases.

  Branch for a dev release

  This creates and checks out a new branch in one command, then pushes it to Drupal.org.

git checkout -b 8.x-1.x
git push -u origin 8.x-1.x

  Tag for a stable release

git checkout  8.x-1.x
git tag 8.x-1.0
git push origin tag 8.x-1.0


Query URL containing term name instead of term ID on Views Exposed Filters

There's no need to do this in code. You basically need to:

Add relationship to taxonomy term via entity reference field (it would probably also work with term reference)
Add exposed filter using this relationship (search for field Taxonomy Term: Term)

It works fine and you get URL, such as:

recipes-view?tid=vejuu

If you want to have an URL key type-of-meat, you can set it in More drop-down in you exposed filter configuration. The field name is Filter Identifier

I experienced problems with using features trying to prevent duplicates created by joining taxonomy terms.


Is it possible to download sandbox projects with Drush?

It's possible to download sandbox project with drush using make file.

Here is example.make file:

core = 7.x
api = 2
; Sandbox module
projects[range_field][type] = module
projects[range_field][download][type] = git
projects[range_field][download][branch] = "7.x-1.x"
projects[range_field][download][url] = http://git.drupal.org/sandbox/Taran2L/1848632.git
projects[range_field][download][revision] = a1cc04da3c1dd957e6808b7e6a381c5970904863

Then you can execute it via:

drush make --no-core example.make # optional options are: -y --working-copy --no-gitinfofile --verbose


How to inject a product field to product display?

I would personally be using views to either override the product page, or I would hide the fields on the manage display page of the product, and show all the fields using a view in a block with a contextual filter to get the content by ID.

However, you can override the product using a template like node--product.tpl.php and use something like...

<?php print render($content['your_field_name']); ?>

To print your chosen field.


Yes, assuming you have the dblog module enabled, that data is in the database, so you can use whatever language or method you want to extract and analyse it.

The data is kept in the watchdog table.


Before I give you the answer, I would suggest that you do NOT implement this.

This  message is an obvious but friendly reminder that your site is in maintenance mode. Turning off this reminder may leave you scratching your head later, wondering why anonymous visitor John Smith can't access your site. The reason may be obvious to you now but it may not be so obvious as time goes by.

This code snippet removes the 'Operating in Maintenance Mode' message, but preserves other messages. Place this code in template.php and then clear the cache:

function mytheme_preprocess_page(&$vars) {
  if (variable_get('maintenance_mode', 0)) {
    $message_count = count($_SESSION['messages']['status']);
    if($message_count > 1) {
      array_shift($_SESSION['messages']['status']);
    }
    else {
      unset($_SESSION['messages']['status']);
    }
  }
}

Edit: Updated the code, this should do the trick. Added a condition that unsets the 'status' element if empty.

One last thing: The maintenance message also appears on the administration pages. You can remove this message too, but as stated earlier, this is dangerous.

The default theme for the admin pages is 'Seven', which has its own template file. You could copy the above code into Seven's template.php. Or even better, copy the code into a new function in your custom module, mymodule_hide_maintenance_message() for example, and simply call that function within mytheme_preprocess_page.


How do I extend the xmlsitemap module to include the google news / images and videos formats

For news there's the Google News sitemap module

  The Google News module generates a Google news compatible sitemap feed from your Drupal site's content.

I don't think there are existing modules for images/video (I've looked for the same thing before myself and ended up hacking something together).

There's a feature request in the XMLSitemap module's issue queue for exactly this, but it's currently postponed. There are a couple of links on that thread pointing to how others have achieved it, those might be worth a look.


The solution seemed to be putting the explicit "IN" in the query, making the simplified version:

$entity_ids = $query
    ->condition('attributes.color', array('red', 'green'), 'IN')
    ->condition('attributes.building_type', 'bikeshed')
    ->execute();


Progress Bar to prevent repeated WebForm Submissions?

If you just want to limit Happy Clickers, in the webform go to Form settings and there are options for Total submissions limit & Per user submission limit. I would suggest changing the Per user submission limit to once every minute.


Site with Themekey has CSS cross-contamination

I think Nice menus apply to all themes unless you have specified other.

Just go to the following location admin/appearance/settings/your_theme_A.
Then look for "Path to custom Nice menus CSS file"

Then go to your next theme admin/appearance/settings/your_theme_B
And also check "Path to custom Nice menus CSS file"

You might surprise, Nice menu use common CSS file regardless of your theme unless you have changed.


Unable to install the “H5P.Scorm.h5p” library: “The uploaded file was not a valid h5p package”

Short Answer

Font Awesome (4.5.4) libraries needed to be explicitly installed for H5P so that Scorm (1.1.16) can be installed. Details on how that was done near end of answer.

Long Answer

Happily, I was able to self-solve this. Starting with a fresh, clean, 100% new install of Drupal 7.59 I went ahead with this process again. Getting H5PEditor.ScormFile (1.0.8) installed was fine—as before on a more established Drupal 7.59 install—but ran into the same exact issue with H5P.Scorm (1.1.16)… But on this clean install I did get a major clue via more details in error reporting; screenshot below but the text reads:

  “Missing required library FontAwesome 4.5”

I took this error to mean that the Drupal module and related libraries for Font Awesome were not installed and that is why the “The uploaded file was not a valid h5p package.” error came up.

So I went ahead and did that—and installed Font Awesome 4.7 libraries—screenshot below:

Tried installing H5P.Scorm (1.1.16) again… And again, the same message:

  “Missing required library FontAwesome 4.5” message.

So I took this all to mean that H5P needed it’s own library install of Font Awesome, Googled and found this H5P related Font Awesome repo.

Great! So now learning what I learned previously in this other answer, I figured out how to create my own H5P.FontAwesome.h5p library, which WORKS GREAT! Screenshot below to show the process did work and I was able to get H5P.Scorm (1.1.16) installed once the H5P specific Font Awesome library was installed as well:

And to make everyone’s life easier—especially mine—I created a fairly simple Bash script that allows me to automatically create the H5PEditor.ScormFile.h5p, H5P.FontAwesome.h5p and H5P.Scorm.h5p libraries on my macOS machine; see below for source code. Just save it as a Bash file named something like build_h5p_scorm_libs.sh and give yourself execute permissions via chmod u+x build_h5p_scorm_libs.sh and you are good to go.

Library installation order should be as follows:

H5PEditor.ScormFile.h5p
H5P.FontAwesome.h5p
H5P.Scorm.h5p

Genuinely hope this helps someone in the future!

#/bin/bash

################################################################################
# Build the H5PEditor.ScormFile H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-editor-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-editor-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

# Create the 'h5p.json' file.
echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5PEditor.ScormFile.h5p *

################################################################################
# Build the H5P.FontAwesome H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/h5p/font-awesome

# Go into that cloned repo.
cd ~/Desktop/font-awesome

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir FontAwesome && mv {*.css,*.otf,*.eot,*.svg,*.ttf,*.woff*,*.json} FontAwesome

# Create the 'h5p.json' file.
echo '{
  "title": "FontAwesome",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "FontAwesome",
      "majorVersion": 4,
      "minorVersion": 5,
      "patchVersion": 4
    }
  ],
  "mainLibrary": "FontAwesome"
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.FontAwesome.h5p *

################################################################################
# Build the H5P.Scorm H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm

# Create the content directory and copy files into it.
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.Scorm.h5p *


Need to override block.tpl.php in a module

The following worked for me:

/**
 * Implements hook_theme().
 */
function rals_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['block__custom'] = array(
    'render element' => 'content',
    'template' => 'block--custom',
    'path' => drupal_get_path('module', 'rals'),
   );
  return $theme;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function rals_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->bid == 3) {
    $variables['theme_hook_suggestions'][] = 'block__custom';
  }
}

and succesfully uses my module-folder-located template file for rendering the block with bid == 3.

Good luck in any case!


Theming a Fieldable Panel Pane — should I define a View Mode?

Making a field template file would be easier than defining a new mode I think.  That would be the normal way to go about it in Drupal.

In your view under Advanced -> OTHER -> Theme: Information you will find template names for the various fields in increasing granularity.  Create a file with the name that best suits your purposes - in this case probably the one that references just the field name and not a specific view or view mode.

Still inside that window, if you click the field name it will show you the default code for the template file, start with that and then edit to your heart's content.  I suggest using dpm($output); to inspect the content that is being passed to the template file, and following the suggestions in the code comment provided for your view mode.

[edit: I misread, thought you were somehow using these in views.  A template file is still probably the way to go.]


Display (and pass) a custom user field in php

You need to load the user object up fully with user_load(), so the fields get attached:

$account = user_load($GLOBALS['user']->uid);

Then use field_get_items() to extract the field data:

if ($items = field_get_items('user', $account, 'field_company_name')) {
  $company_name = $items[0]['value'];
}


Fields attached to Workflows do not get saved

Please find a full configuration steps tutorial  for workflow https://www.drupal.org/node/1027546.

I also used this for my site.


The best way is to implement a template_preprocess_views_view.  The view object is available as $variables['view'].  kpr this to find the property that has the filters in it.  Process them into something readable.  Then set a new entry in $variables.

Then make a new views-view.tpl.php, and name it appropriately for your view (edit the view, click Theme: Information to see the template suggestions), and add the print statements to output the filter info.


Making rules refresh page when message after one has time to read the message?

You might want to consider

Absolute Messages

  Displays system messages in fully themeable colored horizontal bars on
  top of the page.
  ...
  * messages could be dismissed automatically after a specific time - configurable in module settings for each message type separately,


If you create a variable in themename_preprocess_page(&$variables), it should could be accessed using the variable name itself. Example

function themename_preprocess_page(&$variables) {
  $variables['my_new_variable'] = "String value";
  $variables['my_new_variable_array'] = array(); // Some renderable array.
}

And then in your template you could simply print the first variable directly

<?php print $my_new_variable; ?>

And render the renderable array using the render() function:

<?php print render($my_new_variable_array); ?>

Note: The array keys become the name of the variable, so please make sure to use a unique name to the keys.


Deny access to URL non-authenticated users

To control which user can access a download link, you need what is called a "private file system" in Drupal. Public files are directly served to the visitor by the web server; Drupal doesn't even come into play. Private files on the other hand are served by Drupal, so it can check permissions before sending the file.

You do not need additional modules to enable the private file system and upload files to it. The documentation should get you started. If you want to make it easy to create links in the body text to file download URL's, you could try adding the CKeditor and Linkit modules.


You can use hook_menu_local_tasks_alter for example in the bellow example i will change the order between tab 2 and tab 3:

/**
 * Implements hook_menu_local_tasks_alter().
 */
function YouModule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if (isset($data['tabs'][0]['output'])) {
   $data['tabs'][0]['output'][0]['#weight'] = 0;
   $data['tabs'][0]['output'][1]['#weight'] = 2;
   $data['tabs'][0]['output'][2]['#weight'] = 1;
   $data['tabs'][0]['output'][3]['#weight'] = 3;
   $data['tabs'][0]['output'][4]['#weight'] = 4;
  }
}


You can accomplish this with hook_menu_breadcrumb_alter():

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  $new = array(
    'title' => t('Some title'),
    'href' => 'internal/drupal/path',
    'link_path' => '',
    'localized_options' => array(),
    'type' => 0,
  );

  $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
}

This is a fairly simplified example that creates a new breadcrumb item, and sticks it after the first entry.  The $item parameter will be the router entry for the current page.  If you want to use that, you need to dpm() it to see what is there.  A more concrete example, which assumes that you are on a node page would be:

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  if (arg(0) == 'search') {
    $active_trail = array($home);
  }
  else if (isset($item['load_functions'][1]) && !empty($item['map'][1]) && $item['load_functions'][1] == 'node_load') {
    $node = $item['map'][1];

    $new = array(
      'title' => $node->title,
      'href' => 'node/' . $node->nid,
      'link_path' => '',
      'localized_options' => array(),
      'type' => 0,
    );

    $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
  }
}


How to replace a taxonomy term by its description?

You can achieve your requirement using view. In view configuration, add relationship to "Content: Taxonomy terms on node", then add "Taxonomy term: Term description (Term description)" field.


How create form elements in form theme hook

Answer is simple: form alter hook allows to manage form content on a fly


Functional tests report constants are undefined, even if the constant is set in the test or phpunit.xml

The code in the question only works for Functional tests as they have that method. Lower level kernel and unit tests have no access to that, and thus, they would fail.

Instead, I found that you can add constants to phpunit.xml and then the tests have them defined:

    <php>
        <const name="MYMODULE_API_URL" value="https://api.myproject.localhost"/>
        <const name="MYMODULE_API_KEY" value="123456789"/>
        <!-- Set error reporting to E_ALL. -->
        <ini name="error_reporting" value="32767"/>

Then you can remove the prepareSettings method from functional tests. However, there seems to be another bug (that I can't track down) where tests that use drupalGet can sometimes fail with an undefined constant error, even though it is defined in the configuration file (you can do it in code too, and will still fail).

My only guess here is that its an issue with a new process spawn not getting the defined configuration from phpunit.xml, or files are loaded out of order (test file constants aren't seen?).

I settled on the following. I left the constants defined in phpunit.xml so my unit/kernel tests did not need them littered in the tests. For functional tests, I put prepareSettings back in with some changes:

  protected function prepareSettings() {
    parent::prepareSettings();
    $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
    copy(DRUPAL_ROOT . '/sites/functional.settings.php', $directory . '/functional.settings.php');
    $append = 'include dirname(__FILE__) . \'/functional.settings.php\';';
    file_put_contents($directory . '/settings.php', $append, FILE_APPEND | LOCK_EX);
  }

The contents of the file:

/**
 * @file
 * Functional tests settings file.
 *
 * There is a weird bug where constants are not recognized in certain cases
 * in functional tests, despite them being defined in phpunit.xml.dist.
 *
 * Functional tests should include any required constants here to avoid this
 * bug.
 *
 * @see https://drupal.stackexchange.com/questions/292713/functional-tests-report-constants-are-undefined-even-if-the-constant-is-set-in
 */

if (!defined('MYMODULE_API_URL')) {
  define('MYMODULE_API_URL', 'https://api.docker.localhost');
}

if (!defined('MYMODULE_API_key')) {
  define('MYMODULE_API_key', 'foobar');
}

Now, with the functional test uncommenting all the calls to drupalGet, all tests are passing with no errors about undefined constants.


Extend an existing Views filter (NumericFilter) throws exception

So, yeah I ended up investigating more and more and I needed to specify a config schema definition as it follows.

# @file config/schema/foobar.views.schema.yml
#
# Schema for the views plugins.

views.filter.project_size_range_select:
  type: views_filter
  label: 'Foobar numeric'

views.filter_value.project_size_range_select:
  type: views.filter_value.numeric
  label: 'Foobar Numeric'

The full gist is available here if anyone is interested.


How do I count multifield for body of block?

Use this in your block.html.twig template:

 {{ content.body['#items'].getvalue|length }}

Although to access the individual items, it may be better to create a field template such as
field--node--body.html.twig

then you can do

{{ items|length }}

in that template.


Modifying contribution modules safely and conventionally

You should not modify the contrib module directly and save it. You should create a patch file and use that patch file in the project. This way every time if there is any update in that module, you run drush command and your changed will be safely applied. Please refer this page to create a patch file if you don't know How to create Drupal patch with git.


How to set up multiple occurences of same event with RNG?

I think you will need to create new event entities for each city, add a location field (Address?) and a date field, so your users can tell the difference. You will need to make the discovery layer before the event pages show a clear difference between your events: You could have a table view with the city and data in respective columns. Or a Google maps layer with pins for each city. Where each pin is a link to each event entity page.

If you are looking to enforce restrictions on people from attending both events, you can try RNG Conflict. However I don't think that is necessary in your case.


Compromised D7 Sites due to SQL Injection Security Bug "Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003"

Someone recently came out with a module that should help in this, assuming you have installed drush.  It is called Drupalgeddon

Here is an example of its use:

$ drush -y @sites drupalgeddon-test
You are about to execute 'drupalgeddon-test' non-interactively (--yes forced) on all of the following targets:
sites.abcd-d6.example.org       >> Site is not Drupal 7.                     [ok]
sites.abcde.example.org         >> Site did not test positive. Good luck!    [ok]
sites.abcdef.example.org        >> Site did not test positive. Good luck!    [ok]
sites.abcdefg.example.org       >> Site did not test positive. Good luck!    [ok]

Also note:

Drupalgeddon cannot guarantee a website has not been compromised.


Updating existing products via Drupal Migrate

Took a slightly different approach to solve this.

Upgraded Migrate module from version 2.5 to 2.6
Ran upgrades drush updatedb, made sure the migration groups were registered (did this via migrate ui)
After reading the following articles regarding the new 'trackchanges' hash value option:
http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7
& http://www.acquia.com/blog/migrate-26-framework-changes I now
applied the following to the migrate in step 1):

$this->source = new MigrateSourceCSV($csvfile, $columns, array(
  'header_rows' => 1,
  'track_changes' => 1
));

The use of track changes now allows the same CSV to be uploaded, any new rows will create a product. Any changes will be detected via the hash that this option provides in the migrate_map table - thus causing the particular product to be updated.


How do i install drush for a drupal site which is on shared hosting?

When I google "install drush on shared hosting", the two top hits are exactly what you are looking for.

Learning How to Install Drush on a Non-Admin Rights Server
Installing Drush on Shared Hosting Accounts


How to display 1 full article and the a summary of others

Install Views, then enable the disabled view called Front page.

To get two different view modes for the nodes, you could add an attachment display to the view that shows a single latest article in full view mode and add it to the view at the top. Then you would set the page display (the original view) to display teasers, starting at an offset of 1.

It could also be accomplished with Display Suite.


Is it possible to export my website to a native iOS/Android application?

Mobile App Generator exports a website to plain .html pages so that PhoneGap can compile it into native mobile apps.

  Mobile App Generator assists in creating native multi-platform
  PhoneGap mobile applications for Apple iOS(iPhone, iPad), Google
  Android, Palm, Symbian, BlackBerry and more.

If you want to manage the website through mobile App then take a look at this module Drupad

  Drupad.module is the companion module for the iPhone™ / iPod touch™
  application


Installing extra/additional plugins for standalone CKEditor module library

Here are the steps about how I am doing it:

install CKEditor using the CKEditor module and NOT through using the wysiwyg module.
Put plugin in sites/all/modules/ckeditor/plugins and NOT in /sites/all/modules/ckeditor/ckeditor/plugins
Go to /admin/config/content/ckeditor and click edit on the profile you're using.
Under Editor Apperance, from Available buttons, drag up your plugin icon to the Current tool bar.

Scroll down a bit and you will see a Plugins section.

Checkmark your plugin and save changes.

PS: Here is my CkEditor Global Profile settings /admin/config/content/ckeditor/edit/


How can I print Views Exposed Filter widgets individually using views-exposed-form--mypage.tpl.php?

    <?php foreach ($widgets as $id => $widget):
       if ($id == 'SOMETHING_ID_THATIDENTIFY_B') {
         print '
'.t('TITLE');
       }
       else if ($id == 'SOMETHING_ID_THATIDENTIFY_E') {
         print '
'; //Closing #BCD
       }
    ?>

      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>

        <?php print $sort_by; ?>

        <?php print $sort_order; ?>

    <?php endif; ?>


How to add css class to specific rows base on fields in order commerce view page

Try this hook instead: MYTHEME_preprocess_views_view_table. Your view uses the Megarow table format. The hook you used is called for the list format.


If you get that error, it means that $node->body is not an array, but a string. In that case, PHP would take $node->body[und] as a string offset, and you could not use $node->body[und][0][safe_value].

To notice that both und, and safe_value are considered from PHP two constants, but Drupal doesn't define those constants. In that case, PHP would use as value of the constants und, and safe_value, the values of the strings 'und', and 'safe_value', but you should not rely on that.


If you have access to phpMyAdmin, you can do that manually following this steps:

Login to PhpMyAdmin
Select all drupal tables
With selected: Replace table prefix
From: {empty}, To: yourprefix_
in settings.php (sites/default/settings.php) change in the database configuration: 'prefix' => '', to 'prefix' => 'yourprefix_',
Run cron.


How do I display a field twice in a node's display?

Should be pretty easy if you use Display suite:

Add a dynamic field (admin/structure/ds/fields/manage_ctools) and select the entity type (node).

Your new field should be in the manage display tab of the entity type selected, activate it (put it in the section you want).

Click on the gear icon and then 'select content'

Then drill down in the options (node -> the field you would like to duplicate)

If you don't use display suite just print that field in a tpl.php file.


How to check the stock count of an ubercart node

Note: here's a good page to have bookmarked when you use Ubercart with D6: http://www.ubercart.org/docs/api (as opposed to http://api.ubercart.me for when you use D7).

Also note: this ended up being a lot more in-depth than I anticipated, but I was already knee-deep in it so I figured I'd finish it up. ;) That said...

You're definitely on the right track... Like you said, you could just supply the function uc_stock_level($sku) with the value of $sku, but that might be a lot of SKUs and therefore kind of resource intensive.

Another alternative that should work would be something like this:

Change this part of your code:

$output = '
';
// 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 . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
          $output .= '
';
          }
    }
}
$output .= '
';

To something like this:

$output = '
';
// 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);
    // And then check to see what the current stock level is:
    $stock_level = fetch_stock_level_from_termid($term->tid);
    // If there ARE nodes...
    if ($number_of_nodes > 0) {
      // And if the product is in stock...
      if ($stock_level > 0) {
        // ... then add them to the output:
        $output .= '
';
        $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
        $output .= '
';
      }
    }
  }
}
$output .= '
';

You'll then need to add the function fetch_stock_level_from_termid() to your code as well:

function fetch_stock_level_from_termid($term_id) {
  $sql = "SELECT SUM( {uc_product_stock}.stock ) AS stock
          FROM {uc_product_stock}
          INNER JOIN {node} ON {uc_product_stock}.nid = {node}.nid
          INNER JOIN {term_node} ON {node}.vid = {term_node}.vid
          WHERE {term_node}.tid = %d
          AND {node}.status = 1";
  $stock_available = db_result(db_query($sql, $term_id));
  return $stock_available;
}

Hope that helps... :)


How to translate the search block title?

This is configuration translation. You have to enable the module with this name and then go to block layout, configure a block and click on the tab "Translate block":

/admin/structure/block/manage/mytheme_search/translate


Create a rule for the "Content is going to be saved" event, and add a "Execute custom PHP code" action.
The code you write have access to some variables by reference: $node, $node_unchanged, $user, $author, $author_unchanged, and $user.

For example, you can use the following code to set the title as it was before the node was  edited.

$node->title = $node_unchanged->title;

return array('node' => $node);

Similar code is usable in the version for Drupal 7 of the Rules module; what changes is the variables to which the code has access.


I think you're looking for the Double field module.

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts. For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea Consequently, in all there are 4 x 4 = 16 widget types.

Currently it is not supporting file upload. However, you can make this as support request in that module's issue queue.


Step:1 : You have to choose the format
 Step:1 For this Image

Step:2: Click the Advanced link and go to theme:information
 Step:2 For this Image

Step:3 Choose the style output templete like : Step:3 For this Image

Step:4 Add tpl file and write your css and all. Rescan the templete files and save it..

I choose the style format like HTML List. So I Can wrote codings like this format:Codings


Cant clear cache: Table cache_rules doesn't exist

It's related to this: https://www.drupal.org/node/2160645#comment-9904817

it seems that this is a reoccurring problem for drupal 7 sites. I'm not sure why it happens but it seems the fix is to DROP the cache_rules table and then recreate it again. But sometimes it doesnt recreate the table as it might throw an error -1 on recreation.

I went into the terminal and to the mysql console and did the following:

DROP TABLE cache_rules ;

FYI: I had to set the engine parameter to blackhole in order for it to work. Default it is innodb. I'm not sure what blackhole is for. Just copy and paste into the terminal:

CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=blackhole DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';


How can I overwrite taxonomy field link output?

You can do that like follows.
Go to your view and click on filed (having taxonomy) to change the settings.

Change the Formatter option to plain text. (If you choose Formatter as 'Link' that won't work even you write Rewrite Results')
Check output this filed as link and enter your path. Or you can also use'Rewrite the output  of this filed'

That's it.


How can I output custom html inlcuding js files

If i understand u want to output custom HTML for module, for smoething like this best practice is to preprocess output with twig template, in twig u can generate custom HTML for your needs and of course attach js and css with libraries.
See: Theme system overview.


You can do it easy with the Rules module.


Advanced forum topic list pagination settings is not applied

I found the solution :
The pagination settings in the view are ignored, instead the number of topics displayed on a page is set in the forums configuration in /admin/structure/forum/settings


Add css class to the container of the action button from a Form

Thanks to kint for devel options:

There you go:

/**
 * Implements hook_form_alter().
 */
function twig_block_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, 'contact_message_feedback_form') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary btn-xl text-uppercase';
    // kint($form['actions']['submit']);
    $form['actions']['submit']['#prefix'] = '
';
    $form['actions']['submit']['#suffix'] = '
';
  }
}


You need to install the token filter module for the token insert to work.

Download the module.

Configure the tokens you want to use by role or globaly.

and add the filter in the Text Format:

Then you can use the ckeditor plugin to add the token in the Fields that have this Text format, and thats all.

I've just test and it works perfect.


How to unset the title of a custom form field

@Fazeela Abu Zohra try to unset the value in .theme file. write a form alter and kint $form variable .Find your label value

function est_form_alter( &$form, &$form_state, $form_id ) {
  if($form_id == 'your_form_id'){
    kint($form);
  }

and then simply unset the variable.

unset($form['form_id']['#value']);

Here,i assume you find your variable at $form['form_id']['#value'].Hope it  will be useful to you.


How to re-render a particular field in template_preprocess_node or template_preprocess_field?

In template_preprocess_node($vars), you can do:

$node=$vars['node'];

and then all the fields of the node are available to you, and a quick

drupal_set_message('<pre>' . print_r($node,true) . '</pre>');

will show them to you.  So if you had a text field called field_description you can access it via:

$node->field_description[0]['value'];

and you can then modify to your heart's content, eg:

$node->field_description[0]['value']='What I really wanted to say was....';

and then at the end:

$vars['node']=$node;

sets it on its way.


7 - How can I add a region inside another region?

You cant do it that way. But its drupal and it spread true love, so worry not, heres a solution.

Activate php filter under modules
Create a custom block
add <?php print views_embed_view(yourviewname, block); ?>


og membership role is not displayed in views

To work with user-roles in a view, you also need the relationship "OG membership: OG Roles from membership", where you have to set the relationship to your previously added "OG membership from user"-relation.

After that you are able to display the user's role or filter by user-roles. Hopefully this information was helpful for you.


Link to node for each of the items in a view

If you have option link to content you can check it:

Else you can:

Add new field "Content:Path"
Hide this new field from display
Place it before your desired linked field
Rewrite output of field with: {{ field_name }}

Step 3 is very important : field rewriting tokens needs to be placed before your field.


Creating and Linking anchors using CKEditor

How to create links (anchors) inside a page?

There is an icon with a flag. You click on it and you create the anchor.

If the icon is missing, go to /admin/config/content/ckeditor , edit the respecive profile and customize the icons under section 'Editor appearance'.

  How to add these links to text on a new page?

You add a link as you would:


Include the following within the submit button tag:

onclick="return false"


This how you can create a Views gallery that consists of images that each trigger a Colorbox gallery (with grouped images).
This can be done with a pure views approach.
Install the Image URL Formatter module and create a basic view (filtered by the desired content type) with the following fields:

Content: Nid
Content: Images (your field with images)
Content: Images (the same field, again)

Configure the fields as follows:

Content: Nid

Check "Exclude from display"

Content: Images (the first field, which will be the visible cover image)

Formatter: Image URL
URL type: Absolute file path
Multiple field settings: display "1" value(s)
Rewrite results:

Content: Images (the second field, which consists of links to the other images)

Formatter: Image URL
URL type: Absolute file path
Multiple field settings: display "all" value(s) starting from "1"
Rewrite results:

I'm sharing this because I couldn't find any reference myself (this approach didn't do it for me).


Custom line item fields in Create an Order page

Sounds like you just need to alter the commerce_line_item_table View. Edit this view and add your fields so that they show up when it is embedded when the line item reference field formatter is used.

You'll want to take some extra steps, however, to save your customizations since that view is provided by the module. I would clone that view and update your field formatter's to use that view (it's customizable from the display options!)

Or, implement hook_views_default_views_alter and completely override the view with your own export.

EDIT: Some info on the line item manager widget

In order to get fields to show up in the line item manager widget table, you're going to need to override the widget's theme function. See commerce_line_item_field_widget_form and theme_commerce_line_item_manager.

Essentially you may need to invoke hook_field_widget_form_alter to added your field's value, and then override theme_commerce_line_item_manager to place it properly.

Snippet of a theme override that could be used, to add length

// Add each line item to the table.
foreach (element_children($form['line_items']) as $line_item_id) {
  $row = array(
    drupal_render($form['line_items'][$line_item_id]['remove']),
    drupal_render($form['line_items'][$line_item_id]['title']),
    drupal_render($form['line_items'][$line_item_id]['length']),
    drupal_render($form['line_items'][$line_item_id]['line_item_label']),
    drupal_render($form['line_items'][$line_item_id]['commerce_unit_price']),
    drupal_render($form['line_items'][$line_item_id]['quantity']),
    drupal_render($form['line_items'][$line_item_id]['commerce_total']),
  );

  $rows[] = $row;
}


how about

function mymenu_menu_alter(&$items) {
$global $user;
 if ($user->uid != '0'){
  $items['user']['access callback'] = FALSE;
}
}


Drupal 8 Contextual Filter Exclude option

I ran into the same problem, and I got it working because in D8 I didnt have Search API installed(still beta in D8 at time of this post).  Not sure if you have this extension installed.

Also I had to enable Search API term handlers.  Then you should be able to see the Exclude option in the Views contextual filters.