How to get the country from shipping address in a view?

Implying that you have the Order ID in your view:

Add a relationship to Commerce Order: Referenced customer profile, for the shipping address (Relate this entity to the customer profile referenced by its commerce_customer_shipping value)
Add field for Commerce Customer profile: Address - Country

My output after those steps:

Order ID: 4
Bulgaria

Order ID: 5
United States

FYI the data is located in field_data_commerce_customer_address table commerce_customer_address_country column.


Create Custom Date Formatter for Date Posted Field

In Drupal 7, the created and updated "fields" on nodes (and other entities) are properties and not proper fields.  The display values for these are created in the default template_preprocess_node() provided by core, which some theme and modules may override.

Note these lines:

$variables['date'] = format_date($node->created);
...
// Display post information only on certain node types.
if (variable_get('node_submitted_' . $node->type, TRUE)) {
  $variables['display_submitted'] = TRUE;
  $variables['submitted'] = t('Submitted by !username on !datetime', array(
    '!username' => $variables['name'],
    '!datetime' => $variables['date'],
  ));
  ...
}

So, if you want to change how this is displayed, you need to implement your own template_preprocess_node() (you can do this in a theme or module), and provide your own logic.  You can either update the existing variables, which will allow the existing templates to be used, or you can add new variables and also provide your own node templates.  Typically, I do the later.


How to layout the theme within the regions?

You cannot make region within region. You can place block in a region.
Fix the width of block and float that. You have to use only css to achieve that.

Print wrapper like this

<?php if($page['header1'] || $page['header2']) :?>

    <?php if($page['header1'] ) :?>

        <?php print render($page['header1']); ?>

    <?php endif;?>
    <?php if($page['header2'] ) :?>

        <?php print render($page['header2']); ?>

    <?php endif;?>

<?php endif;?>


d7 link two pages within a (draggable) view by image

I guess you must be taking nid as contextual filter in the single image view
if yes then in your grid view you can rewrite the output for the image field and check the output as link field and link path will be the path of your single image view with nid of current node containing image
Please check the screenshot


How can I prevent a particular page being cached?

For Drupal 7:

Drupal has the function drupal_page_is_cacheable() which can be used to set a page to uncacheable.

Here is the documentation: https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_is_cacheable/7

For Drupal 8:

// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

Then the code is:

public function myPage() {
  \Drupal::service('page_cache_kill_switch')->trigger();
  return [
    '#markup' => time(),
  ];
}

As usual, clean your cache once done.


How can I do the dynamic select in Drupal 7 forms?

You need to focus on #ajax option. That will look like

$form['officers']['officer'] = array(
  '#title' => t('Select the officer'),
  '#type' => 'select',
  '#description' => t('Please, select the officer'),
  '#options' => array(),
  '#multiple' => FALSE,
  '#empty_value' => ' ',
  '#prefix' => '
',
  '#suffix' => '
'
  '#empty_option' => '- None -',
  '#ajax' => array(
     'callback' => 'path/to/callback/handler',
     'wrapper' => 'officer-wrapper',
     'method' => 'replace',
     'effect' => 'fade',
  ),
);

In the submit handler you will have change the form element for #options and render to post back using drupal_json_output.


use this code

<?php
if(!function_exists('contact_site_page')) {
  require_once drupal_get_path('module', 'contact').'/contact.pages.inc';
  $output = drupal_get_form('contact_site_form');
  print drupal_render($output);
}
?>

and put print drupal_render($output); where ever you want to put the contact form.

as another solution you can also assign a region for where you want the contact form to be then place the form in there.


How to prepopulate drupal form and still execute a custom submit handler

Why must you have a separate form? I think a simpler approach would be to modify the existing form on a conditional basis via a form alter hook:

function hook_form_alter(&$form, &$form_state, $form_id) {
  // match our custom content type ('yourContentType_node_form') edit form, and ensure
  // we're editing a specific node
  if ($form_id == 'yourContentType_node_form' && arg(1) == '123') {
    // add new submit buttons
    $form['actions']['submit_one'] = array(
      '#type' => 'submit',
      '#value' => t('Gereed'),
      '#weight' => 10,
      '#submit' => array('custom_form_submit_one'),
    );
  }
}


It depends on your requirements.

What would not recommend is something custom like comma separated values in a textfield. Because that's probably the only option where you don't have built-in views/rules/.. support.

Most of the listed solutions require edit access to the node. If you don't want that, you'd need to write custom code which allows users to add themself.

The user and entity reference modules store their information directly in the field information of the node, which might not scale well if you expect dozens or even hundreds of linked users on a single node (because the edit form will get bigger with each referenced user). The new relation project doesn't have this limiation, because every connection is a separate relation entity, which points to both the node and the user. A possible downside of that might be the additional overhead you have, compared to a simple user reference field.

Flag then is quite different to the others. Users can add themself to a node with it easily, but there is no UI provided to add other users or manage users which flagged a specific node (AFAIK), although you might be able to build something using Views, VBO and so on.


How do I get the output of a single field?

The answer to my own question seems to be like so:

$build['field_headerimage'] = $node->get('field_headerimage')->view();


Exclude node from search API results based on values in existing fields

Given no alternative answers, I solved this problem by

installing the Search API Exclude Entity module
adding a field of type Search API Exclude Entity named search_exclude to the content node
adding the following to my custom rsc module

function rsc_node_presave(EntityInterface $node) {
  switch ($node->getType()) {
    case 'content':
      $node->field_search_exclude->value = <conditions to exclude node>;
      break;
  }
}

going to /admin/config/search/search-api/index/default_solr_index/processors
checking the Search API Exclude Entity box
selecting the Search API Exclude Entity tab at the bottom of the page
checking the field_search_exclude (content) box
reindexing the content

Seems to be working well. When unverified nodes are saved, the search_exclude field is set and that keeps the nodes out of the search results.


You can get the user id from url using arg() function. for the first part you can do something like this.

global $user;
$user_id = arg(1);
if($user->uid == $user_id) {
// means it is logged in user profile - so show edit link

}

For the second part you are loading profile of logged in user, that is why it is always showing your picture you need to do the following instead.

$user_item = user_load($user_id); // user id we got from arg()
print theme('user_picture', array('account' =>$user_item));


Overwrite file_directory_temp function without touching the core?

Code for variable_get() is:

function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

So if value is constant during one page call you need to set:

global $conf;
$conf['file_temporary_path'] = Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') . $conf['file_temporary_path'];

If value can change for each request, you need a more bold move. And  PHP 5.2.0 or later.

class TempClass {
  private $path;
  public function __construct($path) {
    $this->path = $path;
  }
  public function __toString() {
    return Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') . $this->path;
  }
}
global $conf;
$conf['file_temporary_path'] = new TempClass($conf['file_temporary_path']);

That way you'll have an object, that will be converted to string on each use, and on that conversion will retrieve current value from Microsoft_WindowsAzure_RoleEnvironment class.

Where to put it?

Best place for it seems to be a hook_boot(). You need to make sure your hook_boot() is called first. To get your module to run first, use hook_module_implements_alter() or easier and less reliable way - Modules weight module.

If you don't care about the value provided via UI, you can (maybe should) put it in settings.php instead, and substitute reads from $conf['file_temporary_path'] with hard-coded value. You don't need to use global in settings.php.

Conflict with UI

When you open form to edit file_temporary_path, you will see value with Azure's prefix string already prepended. That's not what you want there, as multiple saves would prepend it multiple times. Use hook_form_alter() to change default value to one obtained directly from the database, or, if you hardcoded it in settings.php, to set it to hardcoded string and disable field.


I hate providing a link answer, but in http://docs.aegirproject.org/en/3.x/install/#debianubuntu do steps 1-6 then you can install Aegir.

They main key being you need to do sudo hostname yoursite.com which was not mentioned in other docs.


How to add a catch-all wildcard to hook_menu?

The documentation for hook_menu() says it in the first wildcard example it provides. (Emphasis is mine.)

  Wildcards in Paths

  Simple Wildcards

  Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':

  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.

The reason of this is pretty easy to understand: A wildcard as first component would be a catch-up for every Drupal route.
It would also conflict with the routes every Drupal module defines. This is also the reason why Drupal core uses node/%node for nodes, and user/%user for user accounts: Despite the wildcards being qualified, Drupal would not understand if a URI like 1 is referring to a node or a user account.


Create a Gmap with Views that connects locations of different nodes

This answer is for D7, you'll need the folowing modules: entityreference to relate both contentypes,
 geolocation_views only D7, it displays several nodes in a single map, geolocation, and simple_gmap, this one is for for users to enter city name in a text field, handy tutorials: https://www.youtube.com/watch?v=hdzembWMgPc and https://www.youtube.com/watch?v=Pc0xPiRBb54 and https://www.youtube.com/watch?v=FVvKJlq4Wo8, you will end with something like this, each mark in map links to your day-node, enjoy.


The function you are using

taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'))

And Parameters

$tid: The term ID.

$pager: Boolean to indicate whether a pager should be used.

$limit: Integer. The maximum number of nodes to find. Set to FALSE for no limit.

$order: An array of fields and directions.

In your case we can see you are joining field 't.promote' it seems like the field not present, please review you code once and follow the stranded format  like https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_select_nodes/7


How do I get the count of all messages in the inbox?

There is a privatemsg_unread_count() function in Drupal 7. If that doesn't work in Drupal 6, check the module file for the name of the function.


Send login link in email to registered users

You should be able to use the Login one time module for this.

  Login one time provides the ability to email one-time login links to
  users. You can also choose the pages they will land on.

I would imagine that the users might be able to change their own paswords after using this one time link.  To prevent this, you should be able to use the Edit own user account permission module.

  This module manage edit permissions to the name, mail and password
  profile filed. You can manage permissions to the other profile
  entities by other admin menu settings.


Drupal registry table not populated with test class files

Do you by any chance have the contrib 'simpletest' module installed? (as opposed to the core simpletest module that comes bundled with drupal 7)

I had the same problem you have.

What fixed it for me was uninstalling simpletest.
Than completely deleting the the contrib simpletest module.
Then reinstall simpletest (with the contrib module gone, this will install the core module)

And voila, my test classes started showing up in the registry and all is peachy :)


Hope this will help  you.

In Drupal 7 you can use VIEWS CONTEXTUAL FILTER for your requirement

Steps

Add VIEWS contextual filter for node ID

 item
Contextual filter settings for node ID

Provide the default argument from the URL
Also override the TITLE and the BREADCRUMB

Open browser and type Base_url/view_path/NODE_ID you can see both the TITLE and the BREADCRUMB will be changed based on the NODE ID.


Views Exposed TID Filter Hidden Behind Body

Looks like it is just a minor problem with the overflow property of the parent element. The following CSS rule (specific to your page) should fix it:

#preface-top.row,
#block-views--exp-latestnew-page_1.block {
  overflow: visible;
}


Drupal calling "is_dir" over 4000 times?

When you uninstall a module, you need to disable it first in Drupal module admin. You should then uninstall it via the "Uninstall" tab there.

The same goes for themes, disable in theme admin first.

If you for example, delete the module folder on the file system without disabling the module, Drupal will continue to search for the module in the file system, which can result, among other errors, in the issue you are experiencing.

See also: Avoid re-scanning module directory when multiple modules are missing

In answer to MPD's comment, you will need to do something like

SELECT name, filename FROM system WHERE status = 1;

and cross reference that with the modules on your file system. All enabled modules, and themes too, should be present.

There's also a function ( slightly adapted ) Martin_Dresden posted here:

https://drupal.org/node/1080330#comment-6520842

function MYMODULE_init() {

    $startingtime = microtime(true);
    $o = '
Checking for dead modules ...
';
    $result = db_select('system')
      ->fields('system', array('filename'))
      ->condition('status', '1', '=')
      ->execute();
      $n = 1;
      $m = 0;
    foreach ($result as $row) {
      $path = DRUPAL_ROOT.'/'.$row->filename;
      If (!file_exists($path)) {
          $o .= "#$n $path
";
          $m++;
      }
      $n++;
    }
    $timedif =  round(microtime(true) - $startingtime,3);
    $o .= "Total of $n active modules registered in database. $m dead entries found.
";
    $o .= 'Query Time: '.$timedif.' seconds';

    drupal_set_message($o);

}

That may help debug.


Using one exposed filter on different date fields

Create three different views, each with one exposed filter. Use css class to control visibility, use a bit of javascript to move around.

Refer How to create views tabs in D8?


Module Error for some content types but not for others

You're making an assumption and that is that

$info['widget']['default_value'][0]

Will always be an array. My guess is that for some fields (depending on configuration) that $info['widget']['default_value'][0] will be either NULL, FALSE or a scalar value.


You need to enable the Statistics module from admin/modules.

Configure what you want to track from admin/config/system/statistics

Then edit your view.  Add a Field.  There will be a category called Content Statistics that you can filter on.  Choose the stat you want, and then configure it.

The above is for Drupal 7 / Views 3.  The steps are mostly the same for Drupal 6 and Views 2 or Views 3, but the labels are a little different.

Just keep in mind that Statistics module can cause performance problems on busy sites.  You may also want to check out Radioactivity, and see if that will work better for you:

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.

Radioactivity does integrate with Views and a few places.


how to programmatically check if a context is active

What can be done is to use the context_active_contexts() function.

Sample code, to see if the is_iframe context is active for the current page:

$contexts = context_active_contexts();
if (array_key_exists('is_iframe', $contexts)) :
    watchdog('te','context is_iframe is set');
endif;


Is there a way to add a foreign key to a table?

The underlying DBMS all support this, but Drupal7 Core doesn't really care about Foreign Keys (FKs). Views will notice them and use them abit within joins.

Drupal 7 only supports FK in documentation:
http://www.interworks.com/blogs/jkhalaj/2012/04/12/drupal-7-usage-foreign-keys-schema-api-and-current-default-fk-erd

But, if you know this and understand this, then you can still use this foreign key defintion to create the FKs in a module.install file specific to your DBMS.

I use MySQL typically -- and I have done this for a foreign database my settings.php is aware of within a module.install file:

function _idremotedb_add_foreign_keys() {
  $schema = _idremotedb_schema_definition();
  db_set_active('sa_webextracts');
  foreach ($schema as $table => $table_schema) {
    if (isset($table_schema['foreign keys'])) {
      foreach ($table_schema['foreign keys'] as $fk_name => $fk_details) {
        $src_col = $fk_details['columns'][0];
        $dest_col = $fk_details['columns'][1];
        $dest_table = $fk_details['table'];
        // Create the FK using your DBMS convention. Change this as necessary
        // or add a lookup to the database handler driver type (mysql, postgres, whatever) ...
        db_query("
          ALTER TABLE $table ADD CONSTRAINT $fk_name
          FOREIGN KEY ($src_col) REFERENCES $dest_table($dest_col);
        ");
        drupal_set_message(t('...added foreign key: !fk', array('!fk' => $fk_name)));
      }
    }
  }
  // This index added for either mail-list or login.
  #db_add_index('students', 'uniqueidnumber', 'campusuniqueidnumber');
  db_set_active();
}


Can not find field_image(image) in drupal 7.24

An image field will only appear as an "existing field" if it has already been defined for some content type.  The tutorial you're following assumes it does exist.  It look like this is not the case in your configuration. By default, the standard Article content type has an image field.  You may have removed it, or deleted the Article type.

If there is no existing type with an image field, you need to add it as a new field, as shown below:

If no Image field appears in this menu, you may need to enable the core Image module. To do so, navigate to: Home » Administration » Modules. Then locate the Image module in the core sectio, make sure there is a tickmark next to it, and click Save configuration.


Webform - Validating File Upload with PHP

Found it -.-''.

$form_state['values']['submitted']['foto1'] returns integer 0, which is a "no file" id, instead of another value (webform for Drupal 7 currently returns a numeric string as id). File extension validation and other rules have been executed beforehand, and finally the obtained id can be loaded with webform_get_file($form_state['values']['submitted']['foto1']), obtaining a managed_file entity (actually, as a stdClass instance).

This is the result of DPM-ing the four fields using dev tools in Drupal 7, where foto4 is not filled. The four entries correspond to calls to webform_get_file($form_state['values']['submitted']['foto1']) to foto4-corresponding field path.


system_cron calls cache_clear_all with $cid == NULL, which should just be clearing out expired entries.

My guess is that something else is wrong with the system, and cron is failing as a result.

When you upgraded, did you make sure you ran update.php?

Do you see cron listed as being run in watchdog (/admin/reports/dblog)?

Are there any php or other errors/warnings in watchdog around the cron run?

What does your search index status say (/admin/settings/search)?  cron will index search each run.  If this takes too long, you may have problems.  Try dropping down the number of items per run.

If you run drush cron from the command line, does it run properly?


You can use File Aliases module for this.


Drupal 7 appending class in uc attribute option radio button

I managed to get what I wanted  inside theme_uc_attribute_add_to_cart by using:

foreach (element_children($form) as $aid) {
     foreach (element_children($form[$aid]) as $option) {

        $form[$aid][$option]['#prefix'] = '
';
        $form[$aid][$option]['#suffix'] = '
';

      }
    }

But I really don't want to mess with uc_attribute.theme.inc is there any other way?


Here is an example of putting heading (fieldset) on a comment form that I found a while back: click here.

Basically you need to do a hook_form_alter().

Start by creating a field set:

fucntion HOOK_form_FORM_ID_alter() {

$form['project_report_information'] = array(
    '#type' => 'fieldset',
    '#title' => t('Project Report Information'),
    '#collapsible' => FALSE,
  );

Next, add your fields to the field set and remove the field outside the fieldset:

$form['project_report_information']['subject'] = $form['your_field'];  //add to field set
unset($form['your_field']);                                            //remove field outside
$form['project_report_information']['your_field']['#weight'] = -10;    //of fieldset

Now repeat this for all fields and fieldsets you want.

Look over the link for a more detailed example of someone doing this. What you want is about half way down the page.


I'm afraid twig's dump() is a resource killer. You can follow this issue on drupal.org for more information and alternatives: Twig dump crashes site/server with out of memory.

My advice would be to use Devel's kint() function, and you might want to track Symfony's Ladybug which is under development for inclusing in Drupal 8.3.


Move File Field storage from public:// to another stream wrapper (like s3://)

For the paths that match across the two servers you can just change the paths in file_managed to start with s3://, clear the caches, and the S3 module will handle the rest.

This module should be really helpful, I've just written a module for someone which is pretty similar to what you're trying to do (except the files are pruned from the local file system to S3 on a cron) and the module in that link was a great starting point.

Since the S3 module implements a fully functional stream wrapper you can use all of the usual file functions (file_copy, file_move, file_delete, etc) as normal, without having to worry about where the files are.


Showing Error while insertion of data in database, Drupal 7

Looks like the issue is related to your mysql table member structure. The member table field x1 doesn't have a default value that means you need to serve a value on every insert,  you can solve this in three ways,

Pass the value in the field array Ex: 'x1' => "<value here>",
Add a default value / NULL (based on your requirement) through altering your table

  (ALTER TABLE member CHANGE x1 x1 NOT NULL DEFAULT '') OR (ALTER TABLE member CHANGE x1 x1 NULL)

3.Check your table mode, if the table mode is STRICT change it to SET GLOBAL sql_mode=''; REFERENCE : SQL Mode


Prepopulate a custom user field on registration?

Value field is only used for hidden purpose, it will not populate to user. Check below link

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#val


displaying field from node on page in url in block

I figured out how to do it. Make a template file for that specific node ie: node-job.tpl.php and set the value of that url field (which is available to you while inside of that template file) as a global variable ie: variable_set. Now you can access the url inside of your block using variable_get.


How to show the node delete tab and put a view in it?

By creating a view with path /node/%/delete, you have completely replaced the existing page (the delete confirmation form). According to Drupal logic, this is normal behavior.

What I would do is:

1) Do not use the page display of your view, but add a block display to the view. Add your message as view header. Place that block above the main page content and restrict it to the node/*/delete path.

2) Create custom module, implementing hook_menu_alter with one line of  code (credits):

function MODULENAME_menu_alter(&$items) {
  $items['node/%node/delete']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

Of course you need to replace MODULENAME with the actual name of your module.


Organic Groups - How do I set a default role for new group members?

I found a solution to this by using og_role_grant within hook_og_membership_insert and hard coding my role in there. This works by granting the role to a user who has just been added as a member of a group.
If I had more time I would create myself a form in the backend so it wouldn't be hard coded but for now this seems to work fine.

function MODULENAME_og_membership_insert(OgMembership $og_membership) {

  if('user' == $og_membership->entity_type && is_numeric($og_membership->etid)){
    $roles = og_roles($og_membership->gid);
    foreach($roles as $key => $value){
      if ('ROLE_NAME' == $value) {
        og_role_grant($og_membership->gid, $og_membership->etid, $key);
      }
    }
  }
}


filter with taxonomy-term-alias instead of term-ID?

Create a new Taxonomy:Term ID contextual filter.
Under the form "When the filter value IS in the URL..." select the option "Specify validation criteria".
Select "Taxonomy Term" as the validator.
Select which of your vocabularies you'd like to use.
Under "Filter Value Type" select "Term name converted to term ID".

That should do it. If you have multiple-word taxonomy terms, you should allow the contextual filter to convert dashes in the URL into spaces for the term name. If you have unusual characters in your taxonomy terms, see this post for tips.


Can I change an upload URL to match the original upload?

There are many ways you can approach this to solve it, but maybe the simplest is to just upload the file with the correct (old) name into the location where Drupal expects it. I don't mean upload through Drupal but through your hosting account into the correct folder.

Another way is to add a Redirect from the old URI to the new one, through Drupal Redirect module or on the server configuration (.htaccess usually).


Check if form field contains particular value, if so, do not allow user save

hope I'm not stating the obvious but if your form resides in a template or module you can add server-side validation to the form values using a function like:

function your_form_validate($form, &$form_state) {
  if ($form_state['values']['your_form_field_name']) {
    // Perform PHP validation, and return FALSE if rejected.
  }
}

Also, see Form generation.


filter by taxonomy term = taxonomy term of referencing nodes

If there is no specific requirement to use taxonomy terms to create the relationship between 'hotels' nodes and 'region_page' nodes, I recommend to use the Entity reference module instead.

In your use case, you likely want to attach an Entity reference field to the 'hotels' content type, that allows the content editor to point to a node of the content type 'region_page'.

If I understand it correctly, you already have a View attached to your 'region_page' content types' display. Assuming you're using the EVA: Entity Views Attachment module, you should add Content: Nid as your contextual filter in the particular View, create a relationship using Entity Reference: Referencing entity and then use this relationship for outputting the field 'hotel_images'.

In this way, when viewing a 'region_page' node, the View will show all images that are stored on 'hotels' nodes that have a reference to the particular 'region_page' node.


how to add a serial number column in a view?

You should use Global: view result counter field defined in a view.

OR if you want a serial field for the content type you can use

the module serial field


Any way to get localized term names in node paths

Okay, after 2 more hours of research and development I've finally managed to get the problem solved. I ended up writing a tiny custom module implementing hook_pathauto_alias_alter().

The module has several dependencies:

dependencies[] = taxonomy
dependencies[] = field_extract
dependencies[] = pathauto
dependencies[] = i18n
dependencies[] = i18n_string
dependencies[] = i18n_taxonomy

Here's how I did it (tailored to my special needs, so go on and modify my code)

<?php

  /**
   * Implements hook_pathauto_alias_alter()
   */
  function mymodule_pathauto_alias_alter( &$alias, array &$context ) {
    if ( $context[ 'module' ] == 'node' ) {
      $node = $context[ 'data' ][ 'node' ];
      if ( $node->type == 'news' ) {
        // determine actual context variables
        $language = $context[ 'language' ];
        $pattern = $context[ 'pattern' ];
        $category = field_extract_value( 'node', $node, 'field_newscategory' );

        // translation & preparation
        $category_translated = i18n_string_object_translate( 'taxonomy_term', $category, array( 'langcode' => $language ) );
        $sanitized = pathauto_cleanstring( $category_translated->name, array( 'langcode' => $language ) );

        // re-build the alias
        $alias = explode( '/', $alias );
        $pattern = explode( '/', $pattern );
        foreach ( $pattern AS $index => $part ) {
          if ( $part == '[node:field_newscategory]' ) {
            $alias[ $index ] = $sanitized;
            break;
          }
        }
        $alias = implode( '/', $alias );
      }
    }
  }

?>


Strange symptoms after Drupal 8 core update

You probably have the 8.x-3.0-alpha2 or an earlier version of the rules module installed.

Updating the rules module to 8.x-3.0-alpha3 or later should fix this issue too.


Anonymous user edited data as draft/revision in drupal 6

You can accomplish this with the Workflow module.  You probably also need the Revisioning, Module Grants and Rules modules.


How to fix errors when installing varbase with Composer?

Drupal 8 requires PHP 5.5.9 or greater. The error is informing you that you have a lower version than that installed; specifically that the functionality for obtaining class name using ::class, which was added in 5.5, is missing.

The solution is to upgrade PHP to a version that Drupal supports.


extend() isn't chain-able, it returns a new extended query object, so you need to assign the result back to the query object, e.g.

$query = $query->extend('PagerDefault')->limit(10);

Otherwise the query won't actually be extended and won't have the limit() method, hence the error you're getting.


Context Node Add Form and Wrong Button Position

Have you tried adding the submit button separately from the contact form?

If you are using an override to the node add/edit form in panels, try this:

1. Click on the little gear of your region to add content

2. Select Node form submit buttons which is under the "Form" heading

3. Position the form submit buttons where you want.

We had a similar problem on a Drupal 6 installation, and I think it may work on Drupal 7 as well.

Hope this helps


Taxonomy as exposed Filter -> showing extra Field

I found my solution:

With views reference filter I created a view with taxonomy terms. I added the field WITH umlauts and added this view as filter in my actual view: taxonomy term (referenced). In the next step I selected the refernce filter view.


To achieve this in Drupal 8 we have in the Core the filter_url filter that convert URLs into links.

So we just need to apply the filter to our string.

use Drupal\filter\FilterPluginCollection;

// The text processing filters service.
$manager = \Drupal::service('plugin.manager.filter');
// Getting filter plugin collection.
$filter_collection = new FilterPluginCollection($manager, []);
// Getting the filter_url plugin.
$filter = $filter_collection->get('filter_url');
// Setting the filter_url plugin configuration.
$filter->setConfiguration([
  'settings' => [
     'filter_url_length' => 496,
   ]
]);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

For Drupal 7 is more simple

// Creating the filter.
$filter = new stdClass();
// Adding the filter settings.
$filter->settings = array(
  'filter_url_length' => 496,
);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

Output in both examples:

Read for more information www.drupal.stackexchange.com/q/246298/28275


Drupal 7.27: 408 Request time out in Chrome browser

This is a Chrome bug.

https://meta.stackexchange.com/questions/208790/408-request-time-outs-still-continues/232275#232275

One solution: http://blog.haproxy.com/2014/05/26/haproxy-and-http-errors-408-in-chrome/

Seems to be limited to Chrome, page requests through http:// and servers running HAProxy.


How to replace an unfiltered Search API results view with custom text?

Here’s how I solved this:

First I implemented hook_views_post_build. Note, that I could have probably used most other views processing hooks, too, as I’m only adding custom build information.

/**
 * Implements hook_views_post_build().
 */
function MY_MODULE_views_post_build(&$view) {

  // If there is no explicit search being done, then we show a message instead
  // of all search results. We still have to run the search under the hood so
  // that we have correct search facets available. Therefore we could have also
  // used most other views processing hooks here.
  if ($view->name === 'MY_VIEW_NAME' && empty($view->exposed_input['f'])
       && empty($view->exposed_input['search'])) {
    $view->build_info['MY_MODULE_show_message'] = TRUE;
  }
}

Then I added my custom message to an overridden views-view.tpl.php using the previously defined build info variable:

<div class="<?php print $classes; ?>">

  <?php if (isset($view->build_info['MY_MODULE_show_message'])): ?>

My Custom Message

Enter a search term or select a facet item to filter our products.

  <?php else: ?>

  <?php endif; ?>

<?php /* class view */ ?>


How to increase a scheduled time using a new field and rules component scheduler

What you'll have to do to get this to work, consists basically of these steps:

Create a new rule using event "After updating a node of content type Event, in which you add a Rules Condition to check that the value of the duration field was changed (I suppose you know how to write such Rules Condition).
The Rules Actions to be performed in this new rule to be created, consist of these 2 Rules Actions (in the order specified):

Delete the scheduled Rules Component that got scheduled when the node (Event) was created. That way the node will not get deleted as originally planned. For way more details on that, refer to my answer to "How to delete a scheduled task using Rules Scheduler?". Make sure to understand that it is extremely important, for this to work correctly, that you usve a unique identifier of the scheduled rule ... using the node title for it is asking for trouble (what if 2 nodes have the same title???), which is why I always make the node's nid part of such identifier.
Schedule the same Rules Component you already have (to delete the Event later on) AGAIN, using your "duration field".

What this really means is that your implementing logic that reads something like so "Don't delete this node (Event) after one hour yet, instead give me X more time (as indicated in your duration field) from now on (= the moment the updated node (Event) is updated with that duration field update)".


Continually adding fields to a form each time a button is pressed using AJAX

Assuming all your logic for $form[‘column’][$i] is correct, you can try replacing '#attributes'

$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#attributes' => array(
            'id'         => 'column_wrapper',
        ),
    );

With '#prefix' and '#suffix'

$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

And then in the callback get the values from the complete form.

public function addColumnCallback(array $form, FormStateInterface &$form_state) {
    $form = $form_state->getCompleteForm();
    return $form['column'];
}

I had a similar problem, Ajax does rebuild the form, but using “old” values, so after the $form[‘column’][$i] is completed and calculated, Ajax then just overrides it with the previous $form[‘column’][$i].
If that makes sense.


Get user account content object loaded in node.tpl.php

try this

global $user;
$account = user_load($user->uid);


You can't stay logged in on a different domain except you'd use some kind of single-sign-on system between your domains.

Cookies are assigned to a specific domain, the browser has no idea that he is still on the same website.

You might be able to configure separate content and interface negotation, so you stay always on your own language, or you could use the admin language feature so a certain user always stays in his language when he's on the site. But not sure if that works 100% for editing translations in Drupal 8, havent tried it yet.


I can suggest how you can test what's happening:

Create custom test form with submit function.
Install Xdebug on your LAMP, or WAMP or MAMP
Than watch callstack. look what functions have been called.

Looks you've done some specific changes in your instalation.
Also try to download clear drupal instalation and check forms there.

(P.S. If you have opportunity switch to new instalation).


How to delete a file attachment from the apachesolr index

From Dileno blog:

If you simply want to delete documents from your Solr index by using the web interface, here's a code snippet that lets you do so:

http://localhost:8983/solr/update?stream.body=
<delete><query>id:298253</query></delete>&commit=true

This lets you delete documents where the id field matches 298253.

If you want to delete items that matches more than one field, just add another query:

http://localhost:8983/solr/update?stream.body=
<delete><query>id:298253</query>
<query>entitytype:BlogEntry</query></delete>&commit=true


How to reference a image field and get it's file URI?

I would suggest not doing this, as you lose the benefits of image styles (the built-in image manipulation feature).

Suggesting you make a hook for this template, pick out the url from the source field, render an image with Drupal APIs, and make the result available as a variable on the template.


Copy pasta of Znerol's excellent answer to the incorrect bug I raised:

  The VCL shipping with Authcache Varnish needs to be adapted for
  Authcache Debug. The widget uses a cookie (aucdbg) with a unique value
  for each request in order to distinguish between cache hits and
  misses.

  By default the standard cache policy kicks in for anonymous users.
  I.e. requests having a cookie will be passed to the backend by
  Varnish. When you use ab for testing, no cookies will be sent along
  with the request and therefore the cache actually kicks in. When
  testing with the browser, the aucdbg and js cookies are added by
  JavaScripts and therefore the requests are bypassing the cache.

  Look for Example 4: Trigger key-retrieval for all users, including
  anonymous. in vcl_recv and enforce key-retrieval for all users. When
  this fragment is enabled, requests for anonymous users will be handled
  exactly like those for authenticated users and the default varnish
  cache policy will be disabled.

Un-commenting section 4 in the Authcache default.vcl solved this problem.


I would rewrite second language domain to the "primary" one in settings.php
Something like

if ($_SERVER['HTTP_HOST'] == 'newlang.example.com') {
  $_SERVER['HTTP_HOST'] = 'lang.example.com';
}


How to access individual theme settings from code?

It seems this is actually the recommended way. It is used in theme_get_settings() as well:

$theme = \Drupal::theme()->getActiveTheme()->getName();
...
  if ($theme_settings = \Drupal::config($theme . '.settings')->get()) {
    ...
  }


I think there are two issues you have to think about...

Is the item you are saving in the variable used for calculations?
Is the item you are saving going to be displayed?

Note there is actually a variable translation module located in Localization Module, but it seems you would need to ask for these for each language supported.

In the case of #1, code may be require this variable to be a specific value. This will make it to whether you need to keep a record of all the available translated values of this item that can be entered and compared against.

In the case of #2, you could simply wrap a t() around the variable setting it up for translation, but if it is something like a text field, this will have to be done after one figures out what the item is... Select fields and others would be no problem as you have a finite number of possibilities.

With all that said, if the item is a free-formed text field, I would just allow your user to type in a different value for this item for each language he has enabled using the Variable Localization module.


How to add alt and title attributes to an image gallery View?

You can modify the output by selecting the option to re-write output of the field.

Likely, you will want to change the output of your image field from an image to the "URL to file" option.  You will also likely need to add other fields to your view (e.g., image title), which you will want to hide (an option in for views fields).  Make sure these occur before your image field in the views fields dialog box.

Next you will want to rewrite your image field (check the "Rewrite the output of this field" option for your image field).  Views will now show you a box where you can specify the format of your image field, you will likely what to use something such as

<img src="[field_gallery_image_fid]" title="[title]" alt="[title]" />

Views will then replace the [field_gallery_image_fid] macro with the "URL to file" info, and replace the [title] macro with the node title (assuming you added that field ahead of the image field.

In the field rewrite interface views will provide you with a list of macros/fields you can add, all of these fields must occur prior to the field you are rewriting.  If you don't want those fields displayed (other than in the rewrite) make sure to check the "Exclude from display" option on a given field.


How to open Fontello Icons in new tab or window?

The short answer would be to add a target="_blank" parameter into your anchor tag. Something like:

&fontello_icon_here;

The long answer depends on your context. I hope this helps! If it doesn't please update your question with specifics of what you're trying to accomplish.


How to wrap a contact form with another block?

Have a look at either of the contributed modules below (quotes are from their project pages).
Contact Block

... provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.

Release info: only for D8.
Entityform block

Allows to load a specified entity form as a block.
Usage: Go to the Block layout admin page (admin/structure/block), press Place block in the desired region and select Entity form.

Release info: Either for D7, or D8 (but only an alfa release for D8 right now).


Take a look at Drupal 7 Template (Theme Hook) Suggestions

For content types you can try

node--[type|nodeid].tpl.php

base template: node.tpl.php

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

node--nodeid.tpl.php
node--type.tpl.php
node.tpl.php

To theme a view..

Set up your view; by going to Views -> Add View
Once, your view is completely set up, at the bottom of the view (left column), you will see a link called "Theme Information", click on it.
What you will be presented with is a list of templates (.tpl.php) files that the views uses to theme your data. Basically the file names that are bolded are the files views is using to theme the data.

Check How to create a Custom Template for a View


Menu theme suggestion ignored when cache turned on

function bootstrap_custom_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'header-navigation') {
        //-- This stops the block being cached in drupal 8
        $vars['#cache']['max-age'] = 0;
    }
}

This works for me. Block preprocess is correct.


Pull in all child libraries of a library/module/theme with dependencies in yml

Well, I suppose if you want to pull them all in, you can nest them under 1 library definition.

Or, add another library definition that contains all of the resources, so you can still use multiple or the whole shebang if you want to.


This video https://www.youtube.com/watch?v=Cp2SPiwA2Qg shows exactly wat you want. I ussualy follow these steps:

Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.


Rules add date variable from webform submission

Later I realised that I need to run a custom php code, so I wrote this, which actually works:

// use the submitted time value from the webform and convert it to time, also use it for an end date one year later
$time = strtotime($data['components']['submitted time']['value'][0]);
$time2 = strtotime('+1 year', $time);

//convert to date formats to the format used in these fields
$startdate = date('Y-m-d',$time);
$enddate = date('Y-m-d',$time2);

//update the field values and save the updates
$new_user_request -> field_start['und'][0]['value'] = $startdate;
$new_user_request -> field_end['und'][0]['value'] = $enddate;
user_save($new_user_request);

Hopefully this helps someone else too.


You haven't actually wrapped the element, you've inserted an empty
 immediately before it.

You need to use #prefix and #suffix to wrap an element in HTML:

...
'#prefix' => '
',
'#suffix' => '
'


Would be creating menus totally in views reasonable?

Yes. That's the point of views, you should not worry about performance at that point, just build the menu and if later you find that performance is worse than expected start taking a look at this question, there is a big amount of information on views caching. If you need more you can also go here to find more information on caching and performance in general.


Drupal Facets Block Show everywhere (in non search page)

Depends on what module you are using with facetapi. If you are using search_api, then when creating the view you can add a view display of type "Facets Block" (like you would add a page, block or panel display).

Using that display you can add a facet block anywhere on your site, even on non search pages. And you can also set the search_path you want to redirect to when using the facet block.


ctools_ajax_command_redirect is no longer working to redirect ajax form on successful submit

instead of

  return array('#type' => 'ajax',  '#commands' => $commands);

try this

  print ajax_render($commands);

  drupal_exit();

I had a similar problem, and this code worked for me.

courtesy: Ajax redirect on successful submission is not working properly

Hope that helps!


You can install Better Exposed filters in D7, edit the view and in the advanced fieldset change the exposed form style to "Better exposed filters", then in the settings for this you can choose how you want to display the filters, choose "Links". Also check the boxes for "Autosubmit" and "Hide submit button"


How do I change the original language of a product type?

Since I haven't found any easy way I had to edit it in the database manually and clear the cache after that.
Update:
It's easy with exporting at
/admin/config/development/configuration/single/export
and importing at
/admin/config/development/configuration/single/import


It looks like you need Donation functionality, may entitled as something else.

Following modules might help you.

https://www.drupal.org/project/commerce_donate
https://www.drupal.org/project/paypal_donations
https://www.drupal.org/project/donate

Or a custom form which interacts with https://www.drupal.org/project/pay


programmatically attaching file to file media

The key for file needed to be field_media_file instead of file.


Applying image style to authors pictures in comments without preprocess function

You should be able to do it through straight css, or look into a module that will allow you to customize image styles for different applications.

.comment .user-picture

.comment .user-picture img


How to get content type data on basis of assigned taxonomy?

The EntityFieldQuery class was built to do pretty much exactly that:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product_list')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'tid', $term_id)
  ->propertyOrderBy('created', 'DESC')
  ->execute();

if (isset($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}


Discount based on a field in product display node in Drupal Commerce?

You can do this, I have done so myself. It's been a lot easier to do this than when I needed to do this.

The thing is that in rules, in order to get the fields of an entity, to use it in Rules, you need to either add a condition that the field exists or add a condition that the entity is of type X.

I've attached the base setup that does this for the commerce kickstart install profile. You might be using a different product type, but it should be easy to change.

{ "rules_example_discount" : {
    "LABEL" : "Example discount",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_product_reference" ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:type" ],
          "value" : "product"
        }
      }
    ],
    "DO" : []
  }
}

Update:

Since you are saving the discount on the product display, you are making it more difficult for you. What you need to do, is from the line_item/product context to be able to figure out which product display the product comes from. The easiest way to do that would be to add a node reference field on the line item and then populate that with the product display node when adding the product to the cart. This should be doable with a custom submit handler added to the add to cart form with hook_form_alter. Then you need to tweak the rule accordingly and use the field from the node referenced on the line item instead of the product reference on the line item.


Webform page wizard and submission data - no reference to which page the element was on

My solution for this in the end was to use a method on the webform object called getPagesWithElements.

// Get webform object
$webform_obj = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
// Get page/element structure
$model = $this->getPagesWithElements($webform_obj);


How to get Panelizer to only affect a specific node

I have figured out my error. You need to go to Admin->Configuration->Content Authoring->Panelizer and make sure you don't have the Provide Default Panel option selected for the content type you are using Panelizer on.


How to render a specific page as if the currently logged in user is not logged in?

For an anonymous user, the easiest way to do this is to use a second browser and visit the specific page without being logged in. An alternative to that would be to logout (but that seems to contradict with "user is logged in).

For other (none anonymous) roles, you can use the Masquerade module (for sure). You might consider using this module also for "anonymous users". However be aware of this note on its project page:

  Any previous support to masquerade as "anonymous" has always been buggy and hurts performance on larger sites. To masquerade as anonymous users, logout.

My recommendation therefor is: open that page in a 2nd browser, without being logged in.

PS: works for any currently supported release of Drupal.


Highlight active page in a table row using views

I was able to get the answer using jquery. Hope this will help others who need it. Just add this code into the top of the page template and it will create the active class for you.

<script type="text/javascript" charset="utf-8">

$(function() {
   $('.views-table a.active').closest('tr').addClass('active_row');
});

</script>

Remember to change the "views-table" to match your own table.


Output array data on drush error when showing stack trace

You can use XDebug PHP extensions with the following suggested settings:

xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=1       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=256        ; int: Controls the protection mechanism for infinite recursion protection.

Since you're experiencing Exception type of error, enabling show_exception_trace will show a stack trace whenever an Exception or Error is raised (even if this Exception or Error is actually caught, so you can always disable it). Enabling collect_params, will display the parameters passed to functions when a function call is recorded (including content of the arrays).

See: Xdebug documentation page.

To verify your XDebug settings from CLI, run:

php -i | grep xdebug


Programmatically / by Rules, remove reference of a deleted user from contents created by that user.

supposing the content you want to reassign is of node type, here is how to do it programatically (in a hook_update_N() per example or /devel/php or drush ev...)

  $deleted_uid = 42;
  $reassigned_uid = 80;
  // Reassign nodes (current revisions).
  module_load_include('inc', 'node', 'node.admin');
  $nodes = \Drupal::entityQuery('node')
    ->condition('uid', $deleted_uid)
    ->execute();
  node_mass_update($nodes, ['uid' => $reassigned_uid], NULL, TRUE);
  // Reassign old revisions.
  db_update('node_field_revision')
    ->fields(['uid' => $reassigned_uid])
    ->condition('uid', $deleted_uid)
    ->execute();

hope this helps


Kernel base test for media view displays is failing with: LogicException: Missing bundle entity, entity type media_type, entity id image

I could solve this via:

$this->createMediaType('image');

Also I inherited from MediaKernelTestBase.


Temporarily change the current language during a request

See How to progragrammatically get NodeType translated value in D8?, that example is actually based on user_mail() which has exactly the same use case, to send things like password reset e-mails in the language that the user set in his profile.

That will however only work for stored configuration. I think you can't easily change the active interface language, what you can do is explicitly pass the language to each t() call, also inside twig, at least for t().

The only thing I can think of right now that might allow to override it is do a fake negotiator, set that with setNegotiator() on the language manager, then at the end set back the original one.


How to add a term ALIAS(!) to content URL pattern?

Did you try using the [term:url:path] token? This should grab the aliased path, there is also the [term:url:unaliased:path] token for getting the unaliased path.


Email filter in default admin users/people search form

Looks like this module achieve what you need.


Can I include a list of sub-menu pages in the content of the parent page?

By some coincidence, there is an article on how to embed a block in the middle of your node body content on Drupal Planet today.

It seems to me, though, that if you put the block at the top of your content and floated it with css, maybe with a border attribute, the result would perhaps be better than adding content to an arbitrary location inside the content.


How do you change the core forum module to only show a certain depth?

If you want to change list of forums using hook try hook_preprocess_HOOK something like like

function MYMODULE_preprocess_forum_list(&$variables) {
// dump here forums and search for the forum you want to remove and unset it .
 dpm($variables['forums']);
}


The behavior was an unfortunate side-effect of the admin_language module and the setting Force use of default language.

The "offending" code is at http://drupalcode.org/project/admin_language.git/blob/0167e36c45661502ee6907a5b2b7cad8538b19cf:/admin_language.module#l112

Disabling this options solves the issue.


Yes, it is possible.
What you are asking for is typical faceted search functionality.
You should be looking in the direction of Facet API.

Cheers!


Fatal error: Failed opening required file

Commerce Kickstart isn't a module, it's an installation profile. If you want to add Commerce to your site, try install using drush, or just load all the modules manually.

drush dl commerce

Using the drush command will install Ubercart essentially, and you can setup commerce that way.


In:
structure -> media types -> image -> display

/admin/structure/media/manage/image/display

the image field settings had 'Link image to' -> file

Set this to nothing, removed the theme image-formatter.html.twig template and the file link added to each image was no longer there.


What is the recommended way for handling a multilingual service?

If you are using the language code as a URL prefix, then you should be able to access your endpoint as usual with the language code prefixed to it:

?q=fr/v1/...

For example, to get a node in French you could make a GET call on:

?q=fr/v1/node/123.json


How to show one variation of one product in a View Pane

If what you're seeing is the fully rendered Add to Cart form in your View, then what you're looking to do is impossible without custom code. The Add to Cart form is rendered via the field display formatter on your product display node type. It has no way to interact with the configuration or results of a Views query.

You can create a View just showing variations with an Add to Cart button that doesn't invoke the entire form, but doing so will strip the creating line item of the context of what product display that variation is a part of. This means the line item won't link to the product page like it ordinarily would. You could always link it yourself if you know that each variation only exists on one node via a reverse reference, but you'd likely still lose some functionality related to the standard form's normal grouping of variations.

If that's an acceptable trade-off, then you need to recreate your View using Commerce Product entities as the base as opposed to Nodes. Otherwise you're going to have to create some custom Views plugins.


Set data (current nid) to entity reference field with rules and VBO

I will first confirm if I understood this correctly.

You have a content type where you will show a button. Let's call this content type MainType.
You have another content type called guide.
You have an entity reference field on guide which points to a particular node (nid) of content type MainType.
In nodes of MainType, there is a button which shows all guides pointing to the visible node. You already have this view.
You want to add a link which will create a new guide node with entity reference pointing the node on which the link was clicked.
From your comment: You want to use VBO to set referenced field in selected guide nodes to the current node.

I can't think of a way to do this without code, as the context of the original node is probably lost in the view of guide nodes. However, you can do it in a slightly different way:

Create a Rules component with two variables, both of Node type. First one is your guide node, set by VBO and the second will be your reference to the node.

You should then write your rules actions to set entity field value for guide node's field to the nid of second reference. You can take a look at this video which implements a very similar requirement.

I hope this helps.


How can I avoid wrapping my block into  tags?

I think you should copy block.html.twig (perhaps from /core/themes/classy/block/block.html.twig) in your custom module/theme and make it work for your specific block by naming it block--BLOCKID.html.twig and remove the outer <div> from this twig file.

Alternativelly you can create a custom template


Ouput Node Reference Field Title in Drupal 7

print $field_example[0]['node']->title;

This ended up being the syntax needed to pull just the title from the value of a node reference field.


Try adding --overwrite to your restore command, that will let you overwrite an existing site.


How to escape strings before insert query?

No need to worry about escaping. The Drupal database abstraction layer is taking care of query parameter escaping by turning them into placeholders and escaping the data.


How do I create a custom exposed filter?

There's a module that provides some examples here: https://www.drupal.org/project/views_plugin_examples.  It's limited but has an exposed filter example.

General discussion here:  https://api.drupal.org/api/views/views.api.php/group/views_plugins/7

In broad outline:

Create a custom module, with a subdirectory called "views"
In your .info file, add a line:  files[] = views/MODULE_handler_filter_FILTERNAME.inc Your filter will never show up if you forget this!
In the .module file, add an implementation of hook_views_api():

function MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MODULE') . '/views',
  );
}

Within the views subdirectory, you will need to create two files, MODULE.views.inc and MODULE_handler_filter_FILTERNAME.inc
In MODULE.views.inc, you will need to implement either:

hook_views_data_alter() - for a new filter on an existing entity type that already has views integration, which is more common OR

hook_views_data() - to provide views integration for your custom entity, including filters.

API documentation is available for both functions.

A quick example:

    function MODULE_views_data_alter(&$data) {
       if ( isset($data['users']) && !isset($data['users']['FILTERNAME']) ) {
        $data['users']['FILTERNAME'] = array(
          'real field' => 'uid', // name of entity field to which filter applies
          'title' => t('HUMAN READABLE NAME OF FILTER'),
          'help' => t('HELP TEXT'),
          'filter' => array(
            'handler' => 'MODULE_handler_filter_FILTERNAME',
          ),
        );
      }
    }

All of the real work happens in MODULE_handler_filter_FILTERNAME.inc. This file defines a new class that implements your filter, class MODULE_handler_filter_FILTERNAME.

You will usually want to extend one of the existing views filter handler classes to get the benefit of existing code.  Many of these can be found in subdirectories of the views module directory.  The basic filters are in the "handlers" subdirectory, but many more complex filters may be found buried in subdirectories of the "modules" subdirectory.  The views filter handlers you find there are the best documentation for how to implement a filter, as well as how to extend an existing filter, and you should read through them.

Normally your custom filter class will a) add fields to the extended filter's settings form, b) in the case of an exposed filter, modify the exposed widget, and then c) implement a query() method that does the real work, based on the saved settings and input from the exposed widget.


Views Path Filter might be what you're looking for. It lets you filter nodes by paths in a views filter. I don't know how well it works with exposed filters though.


Two-factor authentication with code sent to email

It looks like the recently posted OTP module supports emailing of its one-time passwords. It's still a sandbox project though and I haven't tried it myself.

It shouldn't be too difficult to add email support to the TFA module you mentioned. If you're interested in getting your feet wet with Drupal development, it might make a good starter project.

I suspect you would have to do some custom development to get Rules to handle generating of the codes. Either of the two options above would probably be quicker.

Maybe it's just an academic point, but keep in mind that by emailing the token, you're straying a bit from the idea of two-factor authentication, which entails "a knowledge factor ("something the user knows"), a possession factor ("something the user has")." The line gets a bit fuzzy already though, when you talk about logging in from your phone or forwarding text to a computer via services like Google Voice.


According to my experience
 causes this problem ,my solution for this is to replace all
 with
  before saving in body field

So try

$body =   str_replace("
", "
",nl2br($item->body_value));


How to print product ID in commerce-product.html.twig template

You need to retrieve it from product_entity

{{ kint(product_entity.product_id.value) }}

  Search "Available Variables" for more information here
  https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product


How to display google map field in hidden div?

If anyone is still interested in this answer, I managed to achieve this by making a css class:

.hide-map {
    opacity: 0;
}

I did mine in angularjs, but in JQuery I'm sure you could use some sort of toggle to enable/ disable the css class when it has loaded.


Why is my JSON looking like this and what can I do about it?

I'm assuming you're talking about the presence of \u003Ca and similar...

It's like that because Json::encode uses the JSON_HEX_TAG/JSON_HEX_QUOT/etc flags. It's done to ensure that all strings in the document are RFC4627 compliant.

You shouldn't need to worry about this, any compliant parser will happily translate the hex back to the original characters.


Prepopulating a multi-select on a webform

I have just read through the code of Prepopulate module, and it seems that as for now it doesn't support the feature you're after. The prepopulate module just assigns whatever is passed as a parameter to #value of the corresponding form element. To have multiple items selected you need to assign to #value something like this: array('Value 1', 'Value 2'); but there is no way you can pass this via parameters.

THe possible workaround is to hack the module code. Add the following code on the line #78 of the file - prepopulate.module

  if($form['#type'] == 'select' && $form['#multiple'] == TRUE) {
    $requestslice = explode(',', $requestslice);
  }

just before this line:

  $form['#value'] = $requestslice;

This change will allow you to pass multiple values as a comma separated list, for example:

  mywebform?edit[submitted][multiselect_name]=Value1,Value2

I have just created a patch for for the prepopulate module that implements this thing, you can find it here:

http://drupal.org/node/1468024


Is there a way to restrict access to a calendar page excepting the owner of the content?

$items['node/%node/calendar'] = array( ...

'access callback' => 'node_access',
'access arguments' => array('update', 1),

I manage to solve this part. I still need help for the first URL


How can I submit a list of flagged nodes to the admin user?

I actually think you are trying to make this too complicated based on your feedback. The simplest way in my mind would be to have a view (using current userid as a contextual filter) that displays the items the user has flagged. This opens up a lot of nice possibilities such as being able to remove flags before submitting, sort, filter, table view etc etc. Then quite simply have a button in the view header/footer that "submits/emails" the view url and user id to the admin. The admin can have the same view just with an extra box for userid (or exposed filter or whatever you want).


URL Alias does not work in Menu-Blocks with i18n (pathauto also installed)

I was still testing and found another bug, that when your browser is in german, you can't switch to english.

So in Configuration > Languages > Detection and Selection (admin/config/regional/language/configure) I unchecked "Browser" from the list.

Now the menu-block uses path aliases too and you can switch languages on the site.


I haven't tested it, but there is a relatively new module with a stable 7.x release that looks like it was built only for this purpose: Node revision Permissions Per Role

  Node revision Permissions Per Role allows to give roles administer per content type node revision permissions without giving them full administer nodes permission.

  For instance, you may let certain users(eg: roles:External-blogger ) manage node revision of a specific content type(eg: blog) but restrict to manage node revision of all other content type that this module is perfectly works for you.


How do I attach a CAPTCHA when adding the contact form to a node?

Webform module is best for creating forms and still having options that come with regular nodes. It also integrates with captcha.

What is the reason you are embedding the form in the node like that?


How to create a view block for comments with nesting and parent relationship

I recommend installing the Views Threaded Comments sandbox module.

  Provides Threaded comments views plugin

I'm a developer, so I'd start there ... if you're not a developer you may not find a sandbox project as a good starting off place, your mileage may vary.


New module service is dependency on old module service - The service has a dependency on a non-existent service

You can add moduleA to core.extension.yml on a new line (with the other modules) as module_a: 0.


The best solution that I have been is the Taxonomy Display module.
It Can handle each view, no matter its URL! it's very powerful!

  The taxonomy display module allows administrative configurable term display pages. This allows administrators to override the default presentation of taxonomy term pages per vocabulary through the taxonomy term page's manage display form.


How can I move a module block's title to display within the block's template?

You can do this by overriding the block template:

create a template called block--block-name.tpl.php OR override all block templates by using block.tpl.php and move the code the prints the title into the content div:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print render($title_prefix); ?>
      <?php if ($block->subject): ?>
       <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

      <?php endif;?>
    <?php print render($title_suffix); ?>
    <?php print $content ?>


EntityFieldQuery essentially just prepares an SQL query and gives you the results, it doesn't return any meta information about the fields themselves.

To get that you can use the Field Info API, e.g.

// Get all fields attached to your bundle.
$fields = field_info_instances('node', 'digital_iq_test_2012');

// Loop through
foreach ($fields as $field_name => $instance) {
  // Load up field info for this field.
  $field_info = field_info_field($field_name);

  // Get the type
  $type = $field_info['type'];
}


settings and switching to external pgsql db

first check whether you are executing your query before  doing db_set_active(); because this function call will set your db to default drupal db.

so you should go like this:

db_set_active('custom_db');

// execute your query related stuff here

then at last switch to your default db by db_set_active();


How to show a block on the user profile page but not the user edit page?

First, enable the PHP filter module and give yourself permissions to use PHP in order to input PHP on the Block visibility settings page.

On the Block visibility settings page, you can check for an argument like this:

<?php
if(arg(0) == 'user' && arg(2) != 'edit' )
return true;
else
return false
?>

Also, see my answer on Stack Overflow.


Please note that items in the cart are not products, but line_items (referenced to the product of course)

I think this hook can fit your needs, but I haven't tested it (in my situation, I added the line item directly using custom functions in my module)


How to create an Orbit slide show based on the zurb foundation?

After many days searching for cause of this problem in throughout of the web resources, forums and reading variety of article, I fond that this issue for this that I don't
keep the Priority of foundation Files Structure in my library, According to the  Zurb Foundation documentation in this page: Installing JavaScript

  It's important that you Make sure "Foundation.js" (or
  Foundation.min.js) files loads after "jQuery.js" (or jquery.min.js).


Can't login: user/login redirects to index page

Do you have drush installed? I would try clearing cache as a first step, probably won't fix it but worth a shot. After that try renaming the theme that you are using to force Drupal to use a different theme, or change the theme manually in the database. Try disabling modules one by one to see if any of them might be interfering. Start with any module that changes paths (like PathAuto...). I also noticed that no matter what your site will not throw a 404 page not found error. If that was intended, then whichever process you used to redirect 404's to index.php could possibly be causing an issue.


How do I add custom content fields to content types in Open Social?

Simple answer after I looked into it more. The issue is just whether the Field UI module (field_ui) is enabled or not. This is a Drupal core module and by default it is not enabled in Open Social. But once field_ui is enabled, then all of the custom fields can be managed appropriately.


Importing PDFs into Drupal as content types

Not an easy task, I guess. Apache Tika is a toolkit to detect and extract metadata and structured text from various documents, PDF included. Is used, for example, by Apache Solr to parse and index PDF (and other) documents.

You may use Apache Tika to parse PDF documents and get the data you want, then create what you need (a Content Type, an Event).

Apache Solr Attachments seems to use Tika to index PDF documents, you can start looking at its code.


Checking Available Update data - AJAX error

It turns out the problem was with Cron, It was not running due to some custom php code.  Remove the code and everything seems fine now.


Is using a TLS/SSL termination reverse proxy currently possible in Drupal 8

The patch you reference was applied to Drupal 8 last month. Drupal 8.0.3 was released 3 February and included the fix. If you're using this version (or later) you should be fine.


How to keep some fields or a content type private

You can do this using Views. Set up a contextual filter for the node id. And then a filter that sets a condition on your date field. This means the View will only have results when (a) your node is displayed and (b) the date condition is matched. Set the filter up as a block. And set that block to show only for that node type.

This is an approach I've used a lot. For example, you can use the same approach to show some fields to logged on users but not to non-logged on users. In effect, you're using the View to show fields depending on some condiiton.


Rules- how can I redirect a user to view their profile only when they update their profile?

{ "rules_cw_profile_redirect_user_to_profile_page_after_edit" : {
      "LABEL" : "Redirect user to profile page after editing account",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "rules" ],
      "ON" : [ "user_update" ],
      "IF" : [
        { "data_is" : { "data" : [ "site:current-page:url" ], "value" : [ "account:edit-url" ] } }
      ],
      "DO" : [ { "redirect" : { "url" : "user" } } ]
}


How do I implement Ctools plugins from other modules?

With the code you shown, you get all the plugins of that type implemented by any module, not just from one module. In fact, when I execute the following code, I get the plugins implemented also from the Views UI module.

ctools_include('plugins');
dpm(ctools_get_plugins('ctools', 'export_ui'));

The module name passed as first argument to ctools_get_plugins() is used to namespace the plugin type: There can be other modules that implement a "export_ui" plugin type, and that is the reason why the function requires the name of the module defining the plugin type.

See also the description given for hook_ctools_plugin_directory():

  This hook is used to inform the CTools plugin system about the location of a directory that should be searched for files containing plugins of a particular type. CTools invokes this same hook for all plugins, using the two passed parameters to indicate the specific type of plugin for which it is searching.


Why did the Apache directive to handle a clean URL get changed?

There was something seriously broken, but it only affected a handful of cases due to fringe nature of the issue. Essentially, what happens is roughly (%26 == &):

Request: /lost%26found
Rewrite: /index.php?q=lost&found

The issue here is obvious when you see it this way: you end up with two $_GET variables, q = 'lost' and found which isn't set properly. Since the q variable is truncated, you end up with the wrong page or a 404 error.

Drupal 7 fixes this by simply redirecting to index.php and then parsing the original query string manually itself, bypassing Apache and PHP's parsing of it entirely.


End points for services module not working

Found a work around for this issue, rather than use the node id I am using the UUID. This is now successfully loading the content.

The UUID id is pulled out of the main list of nodes at /endpoint/node.xml, giving a working url of:

/endpoint/node/e2349095-de4f-4827-919f-3ec28cf392a8


Accessing sub-array data from theme_field__custom_content_type($variables)

I think I get what you're doing...you won't be able to straight implode the items array if it's a sequential set that you're using to build up a list of key/value pairs...

There are probably a few different ways to do that loop, I'd try something like this:

$keys = $values = array();
$count = 1;
foreach ($variables['element']['#items'] as $item) {
  if ($count++ % 2 == 1) {
    $keys[] = $item['#title'];
  }
  else {
    $values[] = $item['#title'];
  }
}

$output = '';
for ($i = 0; $i < count($keys); $i++) {
  $output .= $keys[$i] . ' - ' . $values[$i] . '<br />';
}
$variables['card_subtype_list'] = $output;

Hopefully someone will propose a better solution, that's not exactly elegant. Apologies if I've misunderstood.


How do I render a form in a div through a javascript call

You have to add ajax commands to the ajax response, using the unrendered render array:
$response->addCommand(new ReplaceCommand('#form-container', $renderable));

BTW you can only return a Drupal ajax response if you have triggered an ajax request via ajax.js. Outside of form submits you usually do this by adding the class use-ajax to a link. For custom js code see How to Trigger Existing, Non-Form Ajax from JavaScript Event


Module with block plugin not using custom template

The templates directory must always be a direct descendent of the module or theme root directory, in your case /modules/custom/lrg_osm/templates/ (not modules/custom/lrg_osm/src/templates/).


It doesn't say the module was not found, it says there is no compatible version.

My composer version gives a much better error:

$ composer require "drupal/simple_oauth:^2.0-alpha4"
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove drupal/core 8.2.3
    - Conclusion: don't install drupal/core 8.2.3
    - drupal/simple_oauth 2.x-dev requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - drupal/simple_oauth 2.0.0-alpha4 requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - Can only install one of: drupal/core[8.3.x-dev, 8.2.3].
    - Can only install one of: drupal/core[8.4.x-dev, 8.2.3].
    - Installation request for drupal/core (locked at 8.2.3, required as ~8.2.0) -> satisfiable by drupal/core[8.2.3].
    - Installation request for drupal/simple_oauth ^2.0-alpha4 -> satisfiable by drupal/simple_oauth[2.x-dev, 2.0.0-alpha4].

2.0-alpha4 requires Drupal 8.3. Leaving out the version specifier installs it as "1.0.0-beta5", which is however not listed anymore on the project page and therefore probably not really supported anymore.

8.3.0 will be released pretty soon, so if this is a new project, you could already switch to the recently released 8.3.0-rc1, there will likely only be very few changes until 8.3.0. See https://www.drupal.org/core/release-cycle-overview


how to create a custom skin in jCarousel

OK, after a moment of googling, I can say that apparently you cannot go without writing a tiny module, but even though I myself have been reluctant to write YABM (Yet Another... Module), it took me about 5 minutes.
Have a glimpse at this article, copy and paste the code, change the skin name occurrences and there you go - your skin recognized with clean hands. Thanks to http://timonweb.com.


First of all, if you're going to change the theme, it is recommended to make a subtheme first so that updates don't clobber your changes. See Creating a sub-theme for more details.

As one option, the theme will have a page.tpl.php which is used to construct all the pages on your site. You could add your second image here.

Another way would be to add a block and place it in the footer if you really didn't want to modify the theme directly.


Instead you can try this Advanced Menu module, Menus can now be merged into other menus. This allows users with the appropriate permission to add links to other menus which are then displayed as if there were a single menu.

  Example:

  Create new role "News Manager"

  Create new user "News Editor"

  Create new menu "News Releases", Set "News Manager" as an editor for
  the menu.


How can I replace all my internal links automatically?

Why are you using absolute links? If you were using relative links, of the form /node/22, the problem would not arise.

I am assuming you are using Drupal 7. The answer for D6 would be a little more complex.

If the links are in the node body, and if you have direct access to your database, you can update the text by running a query on the field_data_body and field_revision_body tables.

First, back up your database in case this goes wrong.

Then run the following query on your tables:

UPDATE field_data_body SET body_value = REPLACE( body_value, 'a href="http://www.mysite.com/','a href="http://mysite.net/');

Repeat with the field_revision_body table.

This should change all references to the old domain with the new domain.

If you have links in the comments, you might also want to do field_data_comment_body and field_revision_comment_body, scanning for references in the comment_body_value field.

In the event the links are being generated automatically by a text filter, change the REPLACE patterns accordingly.


How to pass field data from custom node type to webform block?

The only way to do this is using a hook_form_alter against the webform block. Webform is a great module overall but when you step outside of what it provides out of the box it gets complicated. The hook_form_alter will need to be set to only modify that form based on the form ID that gets created when the form is built.

The code will be similar to this:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'webform_client_form_103') {
  // Do your mods.
  }
}

NOTE: 'webform_client_form_103' will be replaced with your form id.


Can I edit Content Y within Content X Edit Form using Rules?

Entity reference and Inline entity form could help you.

Entity Reference:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes)
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a configurable view mode.

  Integration with Views (for both forward and backward references).
  Integration with Entity Metadata (and as a consequence with Search API and the like).
  Integration with Devel generate.
  Integration with Feeds and Migrate (>= 2.3) for painless data import.

Inline Entity Form:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.
  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
  Existing entities can also be referenced. Supports commerce_product_reference, commerce_line_item_reference and entity reference fields. Read the documentation here.


Selecting an SVG as an Image Field value

AFAIK the jpg/png/gif limitation is hardcoded in the image field, you can't solve this (only) with configuration.

SVG Image allows .svg files in core's image field. You can use the standard image formatter with it (or better: you must use the standard image formatter, it will not work with Focal Point or similar)

SVG formatter uses the file field and provides an SVG formatter for the file field.

Both also work with media entities, but I've not tested them with IMCE yet.


Ensure you have the Field UI module enabled.

If you go to Structure > Content Types > Event > Manage form display (admin/structure/types/manage/event/form-display) then you can change the form widget that is used there.

The Date and time widget which is the default has no configuration available. However, you can also use the select list widget which allows you to specify Date part order and Time type.


You may want to try the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interested in. As part of the report design, indicate which export formats you want to allow for exporting the data included in it. Typical export formats that are supported are CSV, XML, HTML, XLS, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "content to be exported". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.


Which module should I use to visualize my Google Analytics Data using the Google Charts engine?

Seems to me that Google Analytics Reports is the solution for this, no? Those "reports" do include charts also (not just tabular data).

If you rather want to create some charts yourself, consider the Comparison of Charting Modules as a possible place to do start from, to find the module that best fits your needs. Possible alternatives that might work for this specific question are the Chart module, or the Charts module, though there are other alternatives in that comparison that might be a better fit for this case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Disclosure: I'm the author of the comparison and modules Chart and Charts, I hope this does not violate the site's policy on self-promotion.


Drupal 7 drop down menu not showing on other pages

To clarify:

Go to Structure/Menus;
Select the menu with the non-expanding menu item (ie. Main menu);
Select the List Links tab if not already;
Click the "edit" link for the non-expanding menu item - the "Show as expanded" button is there.


Can recurring initial payment period be changed after purchase is made?

According to the official documentation

  Recurring process

  When an order containing a Recurring product is purchased for the
  first time for the current user, by default the module reacts on
  "Order is paid in full" event, a Recurring entity will be created
  associated with that product for the current order.

  On a cron event, the recurring entities with past due dates are
  retrieved and an order is created for each recurring entity associated
  with the recurring product and customer.

  Note: When this cron event runs it's the time to trigger the payments
  or use another technique to build a queue of payments.

  All this process is driven through Rules so most of it is modifiable

So from reading this, looks like all you gotta do is check the recurring entity that was created for that particular order and see if the due date is 1 month from now or if it's still 1 year from now. If the latter, then edit it and change the due date to 1 month from now.


Preferred way of loading a specific entity revision

Currently the preferred way is to get the storage instance (EntityStorageInterface) for the entity type from the EntityTypeManager and then use its loadRevision() function. For example, you could do this for a node:

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

Previously to this you would get the storage instance from the EntityManager like this:

$node_revision = \Drupal::entityManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

This still currently works however it has been deprecated in favour of the first method. The change record relating to this is at https://www.drupal.org/node/2549139

The old way, which still currently works in Drupal 8 but is also deprecated, is the function entity_revision_load(), which is also available in drupal 7 via entity_revision_load() in the Entity API module.

This function replaces the use of conditions to load old entity revisions.
You can see the history of this change in the Drupal core issue about Remove deprecated $conditions support from entity controller.

The way you would use this function as per the original question is:

$old_revision = entity_revision_load('node', 123);


My javascript is making the drupal admin menu disappear. Not sure how though

Drupal comes with jQuery so you don't need to add it. You should use https://drupal.org/project/jquery_update when trying to use a newer version of jQuery; doing it the way you are currently can cause unknown side effects.


How is it possible for CSS code to be in a false directory but still be used?

I can't find how he can link CSS files to a theme thats not even located in the sub-theme folder.

He's not, the system is doing that part.

When you have CSS aggregation enabled, Drupal concatenates all the relevant files together per-page (bit more complicated than that actually, but for the sake of argument that'll do), and those are served instead of multiple originals. Compressed versions are also created for browsers that support it, yes.

If this is messing with you, just pop to the Performance settings page at admin/config/development/performance, switch off CSS aggregation, reload your page, and check the source again. You'll now see links to the original, un-merged CSS files within the theme.


In which cases should I not call user_access() in a form submission handler?

I did a little detective work to find when that user_register_form() code was committed and then traced the corresponding issue.

From comment #21 there:

  The problem is that you can't form_alter out the admin behavior without rewriting the submit handler from scratch.

So I guess the approach you use just depends on whether you want to allow your access checks to be altered by other modules without them having to override your submit handler.


Custom Node Template not inheriting page.tpl.php

You cannot do this with those templates.

Only one "page" template will be used.   You could try using one "page" template, and one "node" template:  https://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

but the node template won't allow you to modify the page template.


Are there any pitfalls pointing config sync to profile's config/install?

No, I don't think that is a good idea. default configuration is something else than the config sync folder. For example exported config has a UUID and system.site has a site UUID while default config shouldn't.

They are two different use cases. default config is for installing new sites and the config export is to deploy configuration between different installations of the same site.

What you might want to look into is https://www.drupal.org/project/config_installer, a simple installer that allows to install based on an config export/sync folder.


Restrict Users from creating + editing higher level accounts, but still able to create + edit lower level accounts

I finally Discovered the Role Delegation module, which provides the exact functionality described above. Apparently Role Assign also does a similar trick.

Both, however, allow the assigning of multiple roles to a single user, rather than forcing a single role. This allows a user to apply multi-layered permissions to a single user.

If there's any way to force a single role choice, it would be perfect.

Update

I tweaked my copy of the Role Delegation module to show radio checkboxes instead of conventional checkboxes. It doesn't inherit settings like 'default role for new users', but it avoids this multi-user issue.


Drupal 7: Webform Gmap Location

https://www.drupal.org/sandbox/drecksau/2096563

  This module adds «Gmap» component to Webform.
  This component allows you to mark the location using the Google map.
  Also below the map can be displayed autocomplete address field.


If your only concern is to have different passwords you can use drush sanitize to change all passwords afer importing the DB into dev environment.

drush sql-sanitize --sanitize-password=devpassword

This changes all users password to 'devpassword'.

The command also sanitizes all user emails (so your dev site will never send mails to real users).


How can I add classes to the rendered "body" field on a content type?

note:I have tested it in my machine and it works 100%

the Hook_preprocess_node is gonna be executed before the rendering of any node of any content-type, you have to apply your logic here but be sure to apply it only of the body field exist otherwise you'll get an error if some content type doesn't have this field, then inject the updated dom into the node.html.twig template using the $varaibles that has been passed by ref to the current hook:

<?php
/**
* Implements  hook_preprocess_hook
*/
function test_preprocess_node(&$variables){
 // 1. Getting the current node.
 $node = $variables['node'];

 //2. Apply this logic to all nodes that have a body field
 if( $node->hasField('body')){

   //3.Get the body field
    $body = $node->body->value;

    //4.Apply som logic on the body field
     $body = updateBodyDom($body);

   //5.injecting the result into the node template (ex: node.html.twig)
   $variables['body'] =  $body ;
 }

}

function updateBodyDom($body){
 $DOM = new DOMDocument();

 $DOM->loadHTML(mb_convert_encoding($body, "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NODEFDTD);

 $anchors = $DOM->getElementsByTagName("a");

 foreach ($anchors as $anchor) {
   $existing_classes = $anchor->getAttribute("class") ? $anchor->getAttribute("class") : "";
   $anchor->setAttribute("class", "button {$existing_classes}");

   //kint($anchor-> getAttribute('class')); die();
 }

 $content = $DOM->saveHTML( );
 return   $content;
}

in your templates folder create node.html.twig, to render the
injected body :

{{ body }}