How should I insert a row into a database table created by another module? I'm attempting to insert a row into a table created by another module. This module was enabled in a previous hook_update_N(); I want to insert a row into the table with another hook_update_N() or the same one. Using two hook_update_N() works when the updates are ran at different times but if both updates are ran at once the second update fails because the table does not yet exist. I have tried using sleep() but that seems problematic.

/**
 * Enable commerce fees
 */
function mymodule_update_7004($node) {
  module_enable(array('commerce_fees'));
}

/**
 * create compliance fee
 */
function mymodule_update_7005($node) {
  // wait for commerce_fee table to be created
  sleep(10);
  if (db_table_exists('commerce_fees') == TRUE) {
      db_insert('commerce_fees')
    ->fields(array(
      'name' => 'non_compliance_fee',
      'title' => 'Non-compliance Fee',
      'display_title' => 'Refundable Non-compliance Fee',
      'description' => '',
    ))
    ->execute();

    // Clear the necessary caches and rebuild the menu items.
    commerce_fees_reset();
    entity_defaults_rebuild();
    menu_rebuild();
  }

  else {
    drupal_set_message('table commerce_fees does not exist');
  }
}

I recommend using DrupalUpdateException to make update 7005 fail if the table doesn't exist so that it can be ran again when the table has been added, or at least notify the web builder that the table doesn't exist and needs to be worked on.


Best builtin way for footer generation What would be the drupal 7 options to generate the footer links?

Writing the links by hand could lead to 404 errors if links change...

It's fairly simple:

Create a menu at http://mysite.com/admin/structure/menu/add
Add some links to it
Go to http://mysite.com/admin/structure/block and assign the automatically generated block for your new menu to your theme's footer region.

If your theme doesn't have a footer region you can add one by adding a line like the following to the theme's .info file:

regions[footer] = Footer

And then edit page.tpl.php to add the new region wherever it sits best in your HTML:

<?php echo render($page['footer']); ?>


Writing to a drupal table form javascript as fast as possible I have a table in my Drupal database this is simply a name value pair for each entry. I need to write to this table from javascript and get back as soon as possible. My first attempt was to create a menu endpoint that looks like this:

  $name = $_POST['propertyName'];
  $value = $_POST['propertyValue'];
  $result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
  $record = array(
    "property" => $name,
    "value" => $value
    );
  $primary_key = !empty($result) ? array('property') : NULL;
  drupal_write_record('global_properties', $record, $primary_key);

I hit this endpoint from JavaScript using a dojo.xhrPost.

Sadly speed is quite important for this operation and it is taking me around 1000ms to get back from my post (I would like to be around 100ms).  What would be a faster way to write to the Drupal table?

I am running this page on a server running MAMP Pro.

If you have zero concerns about user verification and data validation (seems to be the case given the example code) then I would post to a custom script that just boots up the database and does the write. Note that drupal_write_record is only available at the full bootstrap level.

Example code below:

/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Boot up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

// Load up code for drupal_write_record().
// Untested and might break stuff as we are not at a full bootstrap.
require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_write_record('global_properties', $record, $primary_key);

If you do care about user verification and server side data validation and thus need a full drupal bootstrap but the client does not care about what is returned then httprl's httprl_background_processing() function might do what you need. Example of this workflow below.

/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Cut The Connection.
require_once DRUPAL_ROOT . '/sites/all/modules/httprl/httprl.module';
httprl_background_processing();

// Fully Boot Up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Do various user checks here.

// Run Example code.
$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

drupal_write_record('global_properties', $record, $primary_key);

What the above example will do is return ASAP to Apache but drupal/php will run in the background. If the above example doesn't work there is one other option using HTTPRL in order to get a background worker running.


Drupal 7 "Panel Nodes" Content Pane Contextual Filter Does anyone know how to set up a taxonomy-based contextual filter (argument) for a Views Content Pane that is going to be displayed in a "Panel Node" (from the "Panel Node" module that comes with Panels) tagged with the same taxonomy term?

I think I am missing something about how "Panel Nodes" works. I don't get the option for a term ID unless I add a "Relationship" to the taxonomy field in Views. Then I can set the Contextual Filter to the term ID, but it does not work consistently. If I set the "Argument Input" for the pane to "From Context", it works in Views preview with an argument, but it's blank on the actual Panel Node (if the Pane even shows up to be added). If I set it to anything other than "No Argument", it doesn't work at all.

When I use an argument to preview the Content Pane in Views, it works as it should. But on the "Panel Node" page, it's blank. I don't think the argument is making it to the pane.

Some background:
"Panel Nodes" is a module that comes with Panels and it creates this Panel-ified content type, but I'm finding very little documentation on how to use it. Panel Nodes are not in Page Manager and so you cannot set a context for them there.

I have a client that could use Panels in their Drupal 7 site just for one particular kind of content type. For this particular use case, the the "Panel Nodes" way of generating the content is the most intuitive for the client (enter a title, body, an image into a node add form, and then click on the Panels Layout and Panels Content tabs right from the node form; I believe this is a similar model to the way http://drupal.org/project/panelizer is supposed to work).

I urge you not to use Panel Nodes. Panel Nodes are being deprecated in favor of Panelizer. The largest hurdle to getting rid of them is that I need to complete the upgrade path. I suggest that you

Move to Panelizer, following the upgrade path issue if you already have Panel Nodes.
If necessary, repost a new question with regard to Panelizer.


Custom theming: How to list multiple content types in the same page and use regions too I created two content types: articles and press releases and I want to display those in the same page. I also am developing a custom theme.

So I created a view for that with the machine name press_release_list, created a template for it: views-view--press-release-list.html.twig and it works perfectly.

The problem is, I cannot make use of regions. I mean, I have content and side_menu regions and I want to add a twitter feed to the side menu. I add the block through "block layout" menu, it can be configured to be displayed on article and press release nodes however there is no option for the view I created...

I'm quite new to Drupal so what would be the best way to do this, is there a way to display the block on the view or is there a better option than creating a view?

In block layout the visibility for content types works only, if the content type is a route match. That means, you have requested a node with that specific content type through the url.

It does not work for nodes that are displayed as result of a view.

To configure the visibility for a view you can define in the tab "Pages" the url of the view or a pattern of urls, that matches multiple views.


hide the author information from the non-member I use Drupal-7.14 and the default theme,Bartik 7.14.
I added "my content type" as a new content type.
Then I could see a new content foo by the url hostname/content/foo.

The content foo shows the author and the date
because I checked

Structure > Content Types > my content type > edit > Display Settings > Display author and date information.

Only the date should be shown from logouted users.
The author should NOT be shown for logouted users.

How can I hide the author information from the non-member.

If you copy the node.tpl.php file from the templates directory and create a node--mycontenttype.tpl.php file you should see the following around line 91:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>

Simply change it to this:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php endif; ?>

<?php endif; ?>

The $logged_in variable is a node template variable that has the value of TRUE if a user is logged in.

In this snippet you're just saying if the user is logged in, then display the submitted information.

Don't forget to clear your caches!

EDIT

Apologies, I've read the question properly now.  The following should do what you want.

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php else: ?>
      <?php print $date; ?>
    <?php endif; ?>

<?php endif; ?>

This will display the entire submitted by text for authenticated users, and just the date for anonymous users.


How to exclude recursive module dependencies? Is there a way to exclude dependencies of dependencies? For example:
my_module.info contains
dependencies[] = views

dependencies[] = ctools

my_sub_module.info contains

dependencies[] = my_module

On the module display page my_sub_modue will have my_module, views and ctools as dependencies. I know this is the desired outcome in 99% of all situations but I was curious to know if there were a way to have only my_module (or items explicitly stated in the info file) as the dependency for my_sub_module.

Thanks

In my opinion, the best is have always in mind solid and stable solution.

If you have this problem you should change your design, not your code.

Your module should have a display, and your submodule should have a display who modifies your module's display.


Do I need BOTH jQuery wrappers or just one? [Drupal 7.43]
[Production Linux Environment]
[Omega4 Sub-Theme]
[jQuery-Update-Module-7.x-3.0-alpha3]

(Some Questions) I am using jQuery on my website to accomplish several fixes:

Make iPhones respond to Hover Events.
Add a Div-wrapper to enclose a group of Navigation-Links.
Create an Accordion Navigation Drop-Down.
Stop Google-Maps-Windows from scrolling in Mobile environments, eclipsing the regular page scroll.

I have integrated jQuery using the MyTheme-Info strategy.  That is, that I have added the script-tag of the fixes individually to the MyTheme.info file.  Then I have uploaded the corresponding Fix-01.js files to the server.  Basically, this seems to be working, but I have some questions and these concern the BONUS weirdness that Drupal adds to the already amply weird jQuery itself.

I know that I have to wrap the "Fix-0x.js" files in the code:

Code Wrapper #1

(function ($) {
   //Some amazing code here
}(jQuery));

As I understand it, this allows jQuery to use the '$' symbol without clashing with other libraries that also use this same symbol.

I know that jQuery also MUST wait for the DOM to load before the script can have any access to the elements of the DOM.  Often this is done with the  code:

Code Wrapper #2

$(document).ready(function() {
    //Some amazing code here
});

Or sometimes it is written:

Code Wrapper #3

$(function() {
    //Some amazing code here
});

The question is, does the first jQuery wrapper (Code-Wrapper #1) include the Document-Ready function or not (Code-Wrapper #2).  Do I have to wrap the jQuery in BOTH wrappers?  I know that Code-Wrapper #2 and Code-Wrapper #3 are equivalent.

does the first jQuery wrapper (Code-Wrapper #1) include the Document-Ready function or not (Code-Wrapper #2).

No it doesn't.

  Do I have to wrap the jQuery in BOTH wrappers?

If you need DOM ready, yes you do, but in Drupal 7, they suggested Drupal.behaviors. See https://www.drupal.org/node/756722#behaviors


Include Entity Reference values to term page Solr results I would like to index the value/s from EntityReference, to be included in Solr results.

Example, My entityreference field has nodes "Foo" and "Bar" in "Lorem Ipsum" taxonomy term.

I'm using Solr to render my Taxonomy page.

Is there a chance to include "Foo" and "Bar" to my "Lorem Ipsum" Solr results and sorted properly (in order)?

So it is like merging Entity Reference values and Solr results.

Here's what I did to merge entity reference nodes to Solr results (Solr-generated taxonomy terms)

I did a _term_load()_ on _theme_preprocess_search_results()_ to pull all the entities from entity reference field and load them using _entity_load()_ and get the renderable array by using _entity_view()_ and render it by render().

After assigning those referenced nodes into a variable, I printed the variable in search-results.tpl.php above the _$search_results_.

It should display the referenced nodes into Solr page, above the actual Solr results.

To prevent displaying the node twice, I filtered all nodes from entity reference field not to show in current Solr page.

foreach ($term->field_article_reference[LANGUAGE_NONE] as $key => $val) {
  // Exlclude items that is already in term's entity reference field.
  $excluded_ids[] = $val['target_id'];
}
foreach ($excluded_ids as $excluded_id) {
  $query->addFilter('entity_id', $excluded_id, TRUE);
}

To maintain the total number of rows, here's what I did.

// To get rows variable subract 11 from the total number of reference
// items, first page should start with first item 0.
// Start variable should be the product of $rows and the page number, if
// page number exists. And it should always shows 11 total rows.
$total_rows = 11;
$param = drupal_get_query_parameters();
if (empty($param['page'])) {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = 0;
  $query->addParam('start', $start);
  $query->addParam('rows', $rows);
}
else {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = $rows * $param['page'];
  $query->addParam('start', $start);
  $query->addParam('rows', $total_rows);
}

Note: Maximum items from reference field should not be equal nor more than to the total number of rows.


How built in functions like theme_field() are called in drupal? I have function theme_field() in my field.module. But I don't know how it's getting called. I have searched entire drupal project for the function calling statement . But I couldn’t find it. How this function is getting invoked? Please advice.

function theme_field($variables) {
//    print_r($variables);
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Consult hook_theme($existing, $type, $theme, $path).

It is called via theme() which can be called directly or indirectly on a render array

Each module that introduces a theme element will define a base implementation (what you are looking at in your question) for theme and other modules can override it if they wish.

Look at field.default.inc in Field module, line 212:

$info = array(
          '#theme' => 'field',
          '#weight' => $display['weight'],
          '#title' => $instance['label'],
          '#access' => field_access('view', $field, $entity_type, $entity),
          '#label_display' => $display['label'],
          '#view_mode' => $view_mode,
          '#language' => $langcode,
          '#field_name' => $field['field_name'],
          '#field_type' => $field['type'],
          '#field_translatable' => $field['translatable'],
          '#entity_type' => $entity_type,
          '#bundle' => $bundle,
          '#object' => $entity,
          '#items' => $items,
          '#formatter' => $display['type']
        );

Theme will then go through this process below to determine whether to render via template file or theme function (screenshot from page 82 of Drupal 7 Module Development).


Hide whole edit content link column to users I'm using drupal 7 and have a view with column edit content link. I want to hide a whole column edit to users and only administrator who can see that column.
How can I achieve that without coding since U don't have the permission to access that.

I already tried using Field Permission module but i can't find the solutions either..

Set up multiple page views displays with the same path.

You can clone your page views display to accomplish this.

Keep their path settings the same.

In the regular user one, remove the Edit field. Be careful that you are only editing "This page (override)" and NOT "All displays."

In the admin views display, under Page Settings > Access, restrict your admin view to role=admin.

Re-order the views displays so the most restrictive (admin) views display is first.

To reorder the displays, look for the item "edit view name/description" in the upper-right corner of the screen and expand it to select "reorder displays" - this will take you to a screen where you can drag and drop the views displays. After you put yours in the right order, click "Apply" then save your view.

Hope this helps.


Create a content type node programmatically I have a content type called ip_range and i was trying to create a node programmatically . I tried the follows :

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
    $data = array(
      'type' => 'ip_range',
      'title' => '192.168.7.100/24',
      'field_ip_range_gw' => '192.168.7.100',
      'field_ip_range_hidden' => '',
      'field_ip_range_blocked' => '192.168.7.200',
      'field_ip_range_access_type' => 'Blocked',
      'field_ip_threshold' => '20',
      'field_ip_range_sec_zone' => 'C2',
      'field_ip_range_vlan_name' => 'Network58',
      'field_ip_range_vlan_tag' => '4054',
      'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);

    $node->save();

But its not creating any . Any idea ?

UPDATE

Its creating the node . But its creating as anonymous user . So i cant see it in front end . That was the problem . How to create it as a admin user ?

Try this Code in MigrateContentController:

<?php

namespace Drupal\migrate_contents\Controller;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

class MigrateContentController extends ControllerBase {

 function migrateContent() {
 $updated = 0;
 $data = array(
   'type' => 'ip_range',
   'title' => '192.168.7.100/24',
   'field_ip_range_gw' => '192.168.7.100',
   'field_ip_range_hidden' => '',
   'field_ip_range_blocked' => '192.168.7.200',
   'field_ip_range_access_type' => 'Blocked',
   'field_ip_threshold' => '20',
   'field_ip_range_sec_zone' => 'C2',
   'field_ip_range_vlan_name' => 'Network58',
   'field_ip_range_vlan_tag' => '4054',
   'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
 );
 $node = Node::create($data);
 $node->save();
 $updated++;

 return array(
   '#markup' => $updated,
 );
 }
}

  Inside your_module.routing.yml

migrate_contents.migrate_node:
  path: '/migrate-contents'
    defaults:
    _controller: 'Drupal\migrate_contents\Controller\MigrateContentController::migrateContent'
    _title: 'Migrate Contents'
  options:
    _admin_route: TRUE

Note: Clear the cache before proceeding.


Drupal validation for nested field element I have written some custom validation for each element in a form. I use the following method to display errors. It automatically highlights the required fields.

form_set_error('field_athletes_male', 'Athletes Male field is required.');

My problem is that there are nested element names like this:

 field_coaching_programme[und][0][field_organisation_delivered_by][und][0][value]

The validation message is shown successfully but the element is not highlighted.

Its working now, code as follows

form_set_error('field_coaching_programme][und][0][field_organisation_delivered_by', 'Organisation delivered by field is required.');


Pagination in search results I have installed search configuration module to alter pagination on search results. I've set the pager limit in Configuration > Search settings > ADDITIONAL NODE SEARCH CONFIGURATION > RESULTS to 3 (which should trigger pagination), but no pagination is appearing when I am logged in whereas when I am logout, it is showing pagination having 2 items per page instead of 3.

This is, presumably, by design. If you look at Search Config's query alter function, you can see that the function returns (without limiting results) if you're you're the superuser. Hence, when you're logged in with UID = 1 you will not see the pagination.


Module for managing permissions on per node basis integrated with shopping cart or checkout Hey I'm looking for a way to manage specific users access to specific nodes in Drupal. I'm wondering which modules I can use to accomplish this.

To elaborate:

Lets just say I have 20 stories on my site that cost 5$ each to access. Users need to sign up, and then they pay $5 for each story they want to have access to.

I need to manage the individual user's access to specific nodes automatically after they are paid for...

Anything you can point me toward would be helpful

Thanks

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

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

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


Restricting access to specific nodes for specifc users? Using drupal 7 I have implemented hook_node_access but am having real trouble figuring out how to go a step further and achieve the following using hook_node_access_records and hook_node_grants.

For a given content type ('submission') I want to limit users with a particular role ('curator') and an additionally set field in their user profile ('location') to see only nodes that have a specific matching field value set ('location').

So in this case curators from London can only see submissions to the gallery in London rather than see all 'submission' nodes.

Update

I have made some progress here in my understanding. See the code below. My question now is can i do the following to check set a realm and grant id that i can use to lock specific users out?

Below I am trying to set a lock such that any user who has the grant id cannot access the node (this will be a subset of people within a given role) and for everyone else I just want the sites normal configured access permissions to apply.

function hook_node_access_records($node) {

$grants = array();

if ($node->type == 'submission') {

    $grants[] = array(
      // Say this node is in our realm.
      // By convention we prefix the name of the realm
      // with the module name.
      'realm' => 'submission-permissions',
      // Define the grant id - users in the realm must
      // have this grant id to access this node.
      'gid' => $node->field_location[LANGUAGE_NONE][0]['target_id'],
      // Users who match cannot view the node.
      'grant_view' => 0,
      // Users who match cannot update the node.
      'grant_update' => 0,
      // Users who match cannot delete the node.
      'grant_delete' => 0,
      // In the case another module provides exactly
      // this access record, the one with the highest
      // priority wins. Usually leave this as 0.
      'priority' => 100,
    );
  }

}

/*
 * Implements hook_node_grants().
 */
function hook_node_grants($account, $op) {

    $grants = array();

    $role = is_string($account) ? $account : $account->roles[4];

    if (($role == 'curator') && ($op == 'view')){

        // Get the currently looged in users accounts details
        $user_fields = user_load($account->uid);

        $location = is_string($user_fields) ? $user_fields : $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        if (!empty($location)){

            $grants['submission-permissions'][] = $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        }

    }

    return $grants;

}

I had to do something similar in a project last year and ended up using Taxonomy Access Control (TAC). If you make your location field a taxonomy and use the same taxonomy field on your user profile and content type, you can set perms for your curator role relative to the taxonomy term. It has to be enabled on a role by role basis so it won't impact any other roles on your site.


Update remaining points in different site once purchase through points method I am using userpoints module. What I need to do is once the purchase is done through points methos, update the remaining points in different drupal site.

I have tried for webservices. I have created web services which will update the remaining points in other site.

I have gone through the code and found function uc_userpoints_payment_uc_order() 'all\modules\userpoints_ubercart\uc_userpoints_payment\uc_userpoints_payment.module' where it updates (uc_userpoints_payment_payment) or refund the points (uc_userpoints_payment_refund). So here (in these two functions), I want to call webservice.

Could anyone please throw some light and point me in right direction?

You can call web service using hook_uc_checkout_complete. it takes action when checkout process is completed.

Please refer uc_cart api


Javascript does not work when signed in or when comments are open This is my info.yml file.

name: tnt
description: Drupal 8 starter theme
type: theme
core: 8.x

libraries:
  - tnt/global-styling

regions:
  header: 'Header'
  primary_menu: 'Primary menu'
  breadcrumb: 'Breadcrumb'
  content: 'Content'
  sidebar_first: 'Sidebar first'
  footer_first: 'Footer first'

This is my libraries.yml file.

global-styling:
  version: VERSION
  css:
    theme:
      styles/style1.css: {}
  js:
    js/js1.js: {}
  dependencies:
   - core/jquery

This is my JavaScript file.

$(document).ready(function() {

  alert("Here I am");

});// end ready

This works fine unless one of these conditions is true.

User is signed in
User is on a page where comments are open

Obviously, I had much more complicated JavaScript code, but I reduced it to something simpler to illustrate the point.

I am currently using Drupal 8.1.10.

How do I get this to work when users are signed in and/or comments are open?

What am I doing wrong?

To get the jquery alias $ working in drupal, you have map it like this:

(function ($) {
  $(document).ready(function() {
    alert("Here I am");
  });
})(jQuery);

The document ready function is not the best option, better use Drupal.behaviors and once():

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How to redirect to user organic group on login I am trying to redirect the user to a page for which he is an organic user, and I want this redirect to happen after user login.

I am trying to use the hook_user_login() to make this redirect. However, I have found that when I inspect the $user object when it hits that hook, the $user->og_user_node field is empty. When I look at the user's edit screen (or when I inspect it with devel), it does have associated groups.

How can I retrieve a user's groups to make this redirect?

Since you are using code to do this you should be able to use og_get_groups_by_user to return that information. This will return all groups of either the active user or the $account object that you pass to the function.

You can also use Rules to do this without code pretty easily. There is a rule export on this page to help get started if you want to go that way.

Just to add: the place you are looking for the og group should be under og_membership I think, not og_user_nodes but that's off the top of my head :)


Drupal paid subscription manager where nodes are removed upon expiration I would like to charge my users to post content. For example, 1$ per node/ week that it's visible.

Now I know there are many subscription modules. But how can I manage a subscription system with re-occurring payments, which also automatically interacts with my website and makes changes in real time. For example - how can I have nodes 'expire' after 2 weeks if the user only pays for two weeks.

Are there any combination of modules people would recommend to use to implement such a system?
I was thinking of Ubercart, UC Node Checkout, Node Published, however these are D6 modules and i've been on D7 for a while.

You want Commerce License, a framework built exactly for that. You can write a custom license type that creates / deletes the node when the license status changes (and it would be a good candidate for a generic contrib).

The recurring side is handled by Commerce License Billing.

EDIT: There is now a Commerce License Node project too, doing what I described.


Where to use the php functions when adding fields to existing nodes? I'm new to Drupal and PHP. I've found many answers on stackexchange to the question of bulk adding fields to existing nodes. I need to add a field, like a tag or date (for future facet filtering), to existing nodes. I've been successful with creating a content type and setting up the default fields for users, but now we'd like to figure out how to do this if the nodes have already been created. The VBO module may be the best answer, however, we may have a few hundred of these nodes.

I see plenty of great example code, however, I am unsure of where to use this code. Do I do this on phpmyadmin? I'm more familiar with SQL, but I've read advice here that SQL should only be used if very familiar with Drupal. I'm using Drupal 7.

Fields are attached to Entities, not Nodes. So the field is either attached to bundle that is your node (for all nodes, pre-existing or not), or it hasnt been attached to that bundle yet.

You can use field_info_field and look at the element bundles to see if your given field is attached to the given Entity. If it isn't you can use field_create_instance to add the field to your entity.

You can get a list of all entity types and inspect their bundle types with the bundles key returned from entity_get_info by calling $site_entity_list = entity_get_info(NULL).

Entities and fields are cached, so be sure you use something like drush cc all to be sure you're looking at up-to-date values for all these function calls.

EDIT:
You use these functions and PHP from essentially a small php script. Such business logic could be in a small module with hook_update_n() for instance. Or, you could use Drush and write a very simple PHP snippet using hte above 3 functions and some loops and call it using drush like:
drush php-script your-script-filename.php


Implementing a search and results page in the admin interface I'm trying to implement a search and results form in the admin interface but I am having trouble getting the search function and pager working.

[1] The pager is not showing at all. I've got this working using db_select for the query but I'd like to use a solr query. How can I get a pager to display?

[2] The form submission is not working as expected either. On submission the page is redirect to the correct url but an error message is displayed: The requested page '/admin/monitor/custom/search/?q=foobar' could not be found. Do i have to declare a separate menu route /admin/monitor/custom/search/% to handle searches?

Many thanks,

function custom_menu(){
    $items['admin/monitor/custom/search'] = array(
      'title' => 'Custom',
      'description' =>'Custom search form',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('custom_form'),
      'access arguments' => array('administer site configuration'),
    );
    return items;
}

function custom_form($form, &$form_state){

    $table = build_results_table();

    $form['keyword'] = array(
      '#type' => 'textfield',
      '#description' => t('Search database by keyword'),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Go!'
    );

    $form['results'] = array(
      '#markup' => $table,
    );

    return $form;
  }

function build_results_table($search_term){

    // perform query using Solr Search API
    // page number from $_GET('page')
    // search limit from a variable set by another module
    $results = query_database();

    $header = array('Firstname', 'Middlename', 'Surname');

    $rows = //... build rows from $results ...;

    $table = theme('table', array(
      'header' => $header,
      'rows'=>$rows,
    ));

    pager_default_initialize($table);
    $table .= theme('pager');

    return $table;
}

function custom_custom_form_submit($form, &$form_state){

    $keyword = $form_state['values']['keyword'];
    drupal_set_message(t('Showing results for %keyword',
    array('%keyword' => $keyword)));

    $form_state['redirect'] =
    '/admin/monitor/custom/search/?q='. $keyword;

}

Drupal only has only pager implementations for DB queries, but you can use the pager system manually for data in external sources. There are a couple of examples on the pager_default_initialize() docs that should get you started.
Anything other than q as the param name should work - Drupal uses q as the path param in its rewrites, so it's probably trying to find a route of foobar in your example.


How to redirect to edit page on node create? I am trying this code in my custom module but it does not redirect to the node edit page.

 function mymodule_entity_insert(EntityInterface $entity) {
   if ($entity instanceof \Drupal\node\NodeInterface){
        $id=$entity->id();
        return new RedirectResponse("/node/$id/edit");
      }
   }

When not in a Controller call the send() method on the RedirectResponse object.

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


Dynamically loading terms in a term reference tree from a huge taxonomy so users may select nodes as options I'm trying to create a form that uses a bushy taxonomy of about 30,000 (max depth is ~9) terms to allow users to select multiple nodes from the tree.  The Taxonomy Term Reference Tree Widget fits the functionality I need perfectly, but with the size tree that I'm using each expand/collapse or select event takes a couple of seconds to complete, which isn't acceptable in terms of performance.

I'm new to drupal, but haven't been able to find a widget that can perform this task quickly. Are there any D7 widgets or modules that can accomplish this task? It seems that if I were able to have the widget not load all of the children all at once that performance might increase, but I can't say I'm sure.

You can try some contrib modules:
Hierarchical Select

  Module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy. Demo

Simple hierarchical select

  Defines a new form widget for taxonomy fields to select a term by
  "browsing" through the vocabularies hierarchy.

You can use it with High-performance JavaScript callback handler

Also you can try https://www.drupal.org/project/views_jstree


Custom module error, does'nt show on the page I am new to drupal, so basically i have made a simple registration form. The problem is when i go to the registration form it shows a blank page .

i have made 3 files by the name of my custom module -registerme i.e.-

1.registerme.info

name = Register Me
description = A custom registration form
package = Drupal 7 Development
core = 7.x
files[] = registerme.module

2.registerme.module

<?php

function registerme_menu()
{
$items['registerme/newform'] = array(
  'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => 'registerme_newform',
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
 );
return $items;
}

3.And finally i have registerme.newform.inc

<?php
function registerme_newform(&$form_state)
{
$form = array();
$form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details')
);
$form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name')
    );
$form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );
$form['account details']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );

$form['account details']['pass'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => TRUE,
    );
$form['account details']['pass'] = array(
    '#type' => 'password_confirm',
    '#description' => t('Enter the same password'),
    '#size' => 15,
    );
$form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
);
$form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
);
$form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Register Me'),
 );
 return $form;
}
function registerme_newform_submit(&$form, &$form_state)
{
dsm($form_state);
}
function registerme_newform_validate(&$form, &$form_state)
{
// Some validation to be done on fields.
}

where i am doing wrong getting errors like

Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in
    menu_get_item() (line 479 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: call_user_func_array() expects parameter 2 to be array, null given in
    menu_execute_active_handler() (line 516 of
     C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
      C:\webserver\Apache\htdocs\Starter\includes\menu.inc).

The form dislpays a blank page when i click on the menu listing Register Me and the url is
    localhost/Starter/?q=registerme/newform

Error in hook_menu implementation ! See right code below.

function registerme_menu() {
  $items['registerme/newform'] = array(
    'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('registerme_newform'), // Should be array !
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
  );
  return $items;
}

function registerme_newform($form, &$form_state) {

}

function registerme_newform_submit($form, &$form_state)
{
  dsm($form_state);
}
function registerme_newform_validate($form, &$form_state)
{
// Some validation to be done on fields.
}

Clear menu cache before checking !


How to hide language switcher block if node has no translation? Having a bilingual site here. Some nodes are translated and language switcher works fine. But the switcher block also shows up on nodes which aren't translated. Then the untranslated language link has a different styling.

How can I hide the switcher when there's no (other) translation of the node? I looked up variables in all preprocess functions without finding any indicators. What do I have to look for? And how then can I hide the switcher?

In template.php add:

/**
 * hide language switcher if en-gb is not set
 */
function MYTHEME_links__locale_block(&$vars) {
  // made conditional if other languages are added later
  if(!isset($vars['links']['en-gb']['href'])) {
    unset($vars['links']['en-gb']);
  }
  // here is the condition
  if(count($vars['links']) <= 1) {
    return '';
  } else {
    return theme_links($vars);
  }
}


How to override the ['search_distance'] in Location: Distance / Proximity Views in a custom module After looking at the location module. I couldn't find any way to override the 'search_distance' parameter by creating a custom Form.

dose anyone know how to override this variable by using a custom module? .

I do have a map that is already searching proximity by zip code. it uses php code to determine the  latitude, longitude.

I want to add the 'distance' selectbox next to the zipcode and filter it by (25 miles, 50 miles, 100 miles) like that.

Please note: the below Form for filtering is written in a custom module. so I'm looking for php code.

I haven't had much experience with Location module. This feature is supported out of the box with Openlayers module. I would recommend checking out that module.

I have done a similar sort of thing for one of my clients. I had to hide the distance fields as they didn't want that. If you view source you can see those fields in HTML.

http://biopetonline.com.au/stores


How do I remove the “submitted by” text on Views in drupal 7 How Can I remove the "Submitted by" Text on Views in drupal 7. I know How to do this on pages, webforms. but how on views?

Since the QA didn't care to explore on his found solution.

Assuming your view displays teaser texts / full posts, go to the content type settings (e.g. /admin/structure/types/manage/page for Basic page) and disable the option "Display author and date information." under Display settings.


D7 Views 3 Blog Archive Block I need to build a "blog archives" block with Views 3. I've seen (and am currently using) the solution at Archive block for nodes using Views, but this method doesn't allow specific enough paths.

Following the linked method, the summary output relies on the selected context filter. For example, if you use Content: Created Year+Month, your links turn out like base_path/YYYYMM - no separation between month and year. Likewise, if you use the Content: Created Year or Content: Created Date contextual filters you get a string output... not that great for organization.

Is it possible to generate a link path like base_path/YYYY/MM instead of a mixed string? I have attempted to create this solution using aggregation, count and grouped Views fields with no luck.

You'd have to create 2 views, one which takes Year argument with path base_path/yyyy and another that takes 2 arguments with path base_path/yyyy/mm

And you have to create a custom module which defines a hook_block_info and hook_block_view. This block will basically read your node table for blog type posts, and build links to the 2 views you created above, structured in Year > Month hierarchy. I'm not sure if there's an easier way to achieve this.


how to add to html.twig from a node twig file? I need to add the article image to the post shared on facebook and twitter, this is done by meta tags added in the  as shown below

<head>
  <head-placeholder token="{{ placeholder_token|raw }}">
  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">

  {# RIGHT HERE  #}
  <meta name='og:image' content='{{ file_url(element['#object'].field_image.0.entity.uri.value) }}'>
  <meta name="twitter:card" content="photo" />
  <meta name="twitter:site" content="@nestle" />
  <meta name="twitter:title" content="Article Picture" />
  <meta name="twitter:description" content="A description" />
  <meta name="twitter:image" content="{{ file_url(element['#object'].field_image.0.entity.uri.value) }}" />
  <meta name="twitter:url" content="{{ base_path }}" />
</head>

I need to add meta tags in the  in the html.html.twig file, the problem is those meta tags depend on the article being shared because I need to get the URL of the image, I cannot figure out how to do it such that a block of code written in the node.html.twig file would be placed in the  in the html.html.twig file.

WHAT I TRIED
i tried adding a block in start of node file and extending the html.html file
node--article.html.twig (start of file) :

{% extends "html.html.twig" %}
{% block metablock %}
  <meta name='og:image' content='{{ file_url(element['#object'].field_image.0.entity.uri.value) }}'>
  <meta name="twitter:card" content="photo" />
  <meta name="twitter:site" content="@nestle" />
  <meta name="twitter:title" content="Article Picture" />
  <meta name="twitter:description" content="A description" />
  <meta name="twitter:image" content="{{ file_url(element['#object'].field_image.0.entity.uri.value) }}" />
  <meta name="twitter:url" content="{{ base_path }}" />
{% endblock %}

then calling this block from the html.html file like this:

  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">

    {# RIGHT HERE #}
    {{ block('metablock') }}
  </head>

But this gives an error

  The website encountered an unexpected error. Please try again
  later.Twig_Error_Syntax: A
  template that extends another one cannot include contents outside Twig
  blocks.

I tried putting the rest of code in node--article inside a block, this does work but the metablock block gets placed in the start of every article viewport (Not what I intended) I need it to be placed only in the head tag.

Hope I was clear enough, to summarize, How can I place meta tags in the head from the node--article.html file, not the html.html file.

You're going about it the wrong way, you cannot affect other Twig template files, it needs to be done way before you get to Twig. Everything you want to can be done using the Metatag module:

Supports a large number of commonly used meta tags, including the page title, canonical URL, description, etc, and for Facebook's Open Graph, Twitter Cards and Dublin Core via included submodules (see full list)


Why is session.cookie_lifetime set to 23 days? As far as I understand the session lifetime at Drupal is limited by session.gc_maxlifetime setting is by default set to some 2.3 days.

Then what is the use of session.cookie_lifetime being set to 23 days?

Here is the snippet from settings.php:

/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

Please assume that I've set both session.gc_probability and session.gc_divisor  to 1 just for the sake of this question.

ini_set('session.gc_maxlifetime', 200000);

This value is for the server.
It is a settings for Session Garbage Collection.
If the users last visit happened before 200000s then this session is eligible for garbage collection.
Since it is GC, the session value may be discarded and not compulsory. If a GC action happens after the session was made eligible for the GC, it will be deleted.

ini_set('session.cookie_lifetime', 2000000);

This value is for the browser.
This is the absolute maximum time till which a browser can keep this cookie active.
A 0 value here means immediate or when the browser is closed.

To answer your question in particular.

If the user doesn't hit the server back in 2.3 days, his session will be deleted when the session garbage collection runs.
If he keeps on hitting one page on the server every 2.2 (less than 2.3 days) then his session will stay active. But it can be active only until 23 days from the time the session was first generated.
So what that means is session.cookie_lifetime is the absolute maximum lifetime of a session.


Theming a content type What's the best way to theme a content type? Is there an effective way? Can I just use my page template, resave it with a different name and do it that way?

It depends on what you want/need. Not only for content types, for theming generally; my suggestions:

For little/cosmetic changes(font, color etc.) and basic layout settings you can use node-type-yourcontenttypename class and style with CSS.
For moderate+ structural and visual needs you can use Views, Context, Panels  etc. alone or combined(and CSS of course).
For the things you can't achieve without dirtying your hands; you can create special template files for pages, nodes, block, views etc.
For the things you can't achieve with above ways; you can hack core, module, theme files. But this would be last and worst way to go.

You can do lot of things with 1, most of things with 1+2 and almost everything with 1+2+3.


Admins that only control a subset of users I am creating a page where users pay to create and edit their custom content.

These clients need to use multiple accounts with certain edit-rights - so they need their own people-management.

These are my requirements in that respect:

Each client-admin belongs to an organization that can have multiple members
Each organizatin "owns" certain content
Each client-user can edit content of his organization but only if the client-admin has granted him these rights

Is there a way that I can create admins that only control a subset of users?

(I found the https://drupal.org/project/administerusersbyrole module, but with that I would need a new role for each client. Is that a good solution? )

It looks like you're looking for Organic Groups.

[Organic Groups] Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

It is a fairly complex module, but I think it is very well suited for your use-case.


hook_user_presave at user registration, how to get field_data_field (set to auto increment) to take a new and unique value I'm trying to force a parallel identifier (to match up legacy system requirements) to correlate to uid by means of a field_data_field_foo table.

The field_data_field_foo was created in the Field UI and because I couldn't see any UNIQUE and AUTO_INCREMENT options I set them both for the column field_data_field_foo.field_foo_value in phpMyAdmin.

I assumed this would be enough to force the issue, but in development I setup a hook_user_presave() function in my custom module and with a break point inside it, for $account->field_foo I just get undefined....

field_foo   Array [1]
    und Array [0]

Because this is something that must be assigned uniquely and I'd like to assign at the point of registration should I be using a different hook? Or is there something else I'm missing?

Btw, it might be something more basic in Drupal that I'm missing as I'm not that experienced with it atm - i.e. due to the nature of this project, I've yet to spend time learning nodes and the like.

Here's what I did in the end...

First I added the field to the user registration form, as one thing Drupal is great at is processing information - I did notice errors being caught so I might have to check that out.

Then I used hook_user_presave() and (managing the unique id creation seperately) passed that, overriding any existing value or adding a value if none existed.

(full details are here: Editing user submission of user registration form with hook_user_insert() and $edit)

I will still have to manage away the users ability to insert an identifier by hiding it through CSS/JavaScript etc. but because hook_form_alter() wouldn't edit the user registration form after repeat attempts this seems the most expedient way of solving the problem.


How can I remove Features modules from a site without affecting functionality? I have inherited a site that makes heavy use of Features, and this constrains what I can do to permissions and creates dependencies that don't otherwise exist.  Something as simple as turning off the overlay becomes a mystery.

Is there some way I can remove these features and give back control to the database and to dependencies declared in non-Feature modules? I'd sure like to be able to adjust permissions by visiting the usual permissions UI and making the change as per usual.

I see there is a Features Tools module that appears relevant, but it does not seem to address things like roles and permissions.  And it's a bit discouraging to think that an additional module might be necessary just to de-Features a site.

When you are absolutely sure there is no custom code in the feature module you can safely recreate the feature by going to /admin/structure/features and then change permissions and/or disable modules such as the Overlay module that are declared as a dependency in the feature.

You can recreate the feature and remove the unwanted components:

Go to /admin/structure/features
Click the 'Recreate' button next to the feature
Uncheck all dependencies or other components that you don't want in the Feature.
Click the 'Download feature' button.
Replace the Feature module in your modules folder.

When you are not sure there is any custom code in the feature module do this on a local environment and check all changed code via Git to make sure only the components you deselected are removed from the feature module.


Views suggestion preprocessor template.php and views-view-field--suggestion.tpl.php working in harmony? This is tricky to explain properly...

I have a view, and I want to override the output of one of the fields, so I created a template.tpl.php file, called:

views-view-field--frontpage-fold--page--field-video-background-files.tpl.php

I at first had the logic in that file, and everything worked as expected. Great!

Then to conform with best practice, I moved the logic part (that was at the start of my .tpl.php file), to a theme function override thingy. This looks like:

function MY_THEME_views_view_field__frontpage_fold__page__field_video_background_files(&$variables) {

And that works fine... With an exception.

THEY DON'T WORK TOGETHER!

Depending on how I fiddle around with clearing caches, and using views 'Rescan Template Files' button, I either get one working, or the other. Not both.

The result of this is that it's impossible to separate my logic into a template.php file and pass variables to my .tpl.php file.

Does anyone have any idea why this might be?

I'm fairly new to Drupal, and have found the following pieces of information, but don't quite understand what they're saying...

https://stackoverflow.com/questions/10433853/drupal-7-preprocess-views-not-working
https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates/2387782#2387782
https://www.drupal.org/node/939462

Can anyone clear this up for me, and suggest a solution?

I think what you are looking for is:

function MY_THEME_views_view_field__frontpage_fold__page__field_video_background_files_preprocess(&$variables, $hook) {

Note the addition of _preprocess at the end of your function name.

https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7


How to send e-mail in users selected languages I have created two users and my site supported two languages(English,Spanish).
In every 5 hours CRON will be run,I have wrote a custom module and every CRON run users are getting Emails thats fine.
But here is the problem is Emails are not sended to users prefered languages,it takes admin default language and sended to users.

I have installled multilingual module also.

I want Emails should be in users prefered languages only.

Code:-

function sendmail($from, $to, $firstname, $message, $user,$language) {
  $module = "my_mail_example";
  $key = "mail_example";
  $language = user_preferred_language();
  $send = TRUE;
  $params = array(
    'body' => $message,
    'subject' => 'Hello from Bright Ideas'
  );
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  $current_messages = $user -> field_reminder_messages_received[LANGUAGE_NONE][0]['value'];
  $updated_messages = $current_messages.'\r\n'.$logmessage;
  $edit = array(
      'field_reminder_messages_received' => array(LANGUAGE_NONE => array(0 => array('value' => $updated_messages, ), ), ),
    );
  user_save($user, $edit);
}

Cron runs as the anonymous user, so any emails sent by cron will use the site's default language.

Your code snippet has the following:

 $language = user_preferred_language();

This is wrong.  It will get the preferred language of the anonymous user, not the user you're sending the mail to.

Instead: figure out the recipient's preferred language:

$userobj = user_load($user);
$language = user_preferred_language($userobj);

Now, you can send mail with the correct language:

$result = drupal_mail($module, $key, $to, $language, $params, $from, $send);


Delivery Date Changes Price field value with New Custom Field I got project with following requirements:

The customer should be able to select delivery date(date popup) in the checkout form.
The administrator can set special delivery date, in configuration settings.
If the customer select a delivery date that matches with special delivery date, the prices will change.
There are 2 price field in 1 product reference. The default price field and custom special price field.
Price value will change according to the delivery date that the customer selected.

For example:

Case 1:

The admin set Special date to be: Feb 14, 2016
The customer selected delivery date: March 2, 2016
The final product price uses the default price field value.

Case 2:

The admin set Special date to be: Feb 14, 2016
The customer selected delivery date: Feb 14, 2016 (match)
The final line item product price will use the value that was set in the custom price field.

What would be the workaround with this one. I feel stuck with my module. I was thinking if I need to use rules instead. Thanks in advance.

Rules will be the best option in the above mentioned cases. You can use "data validation" to compare both fields and set value of the "product price" field accordingly


CSS for Display Suite Fields not applied I'm attempting to place text next to the top of images inline for a content type using CSS on fields through Display Suite with a built-in layout in Panels (Two column bricks)

I am using a subtheme for the professional_theme.

I have tested and ensured the style sheet is over-ridden to my subtheme
I have inserted the css shown below (and tried several other css codes)
I have inserted the css names into the CSS Classes of Display Suite
I tried applying the styles to several different fields as well as
the region independently and together.

That all being said I think there is extra CSS code being inserted that is throwing off the style being pulled in but I have no idea where it is coming from.

The code below displays Source Code with the CSS style I applied to the image and a text field:
The names of the only styles I applied are: .floatleft .floatright

Are you the Kind to be Kind

Tuesday, October 27, 2015 - 09:30

You are in charge of your own destiny, don’t try to control theirs.

CSS CODE: Keep in mind that I have tried other CSS codes

.floatleft {
clear: both;
vertical-align: top;
float: left;
padding: 4px 10px 4px 0;
}

.floatright {
clear: both;
vertical-align: top;
float: right;
padding: 4px 0 4px 10px;
}

Any help is greatly appreciated. I tried finding CSS documentation for Display Suite with little luck.
WO

First of all, remove the . from your classes in your HTML code, e.g. you should have
 and not
.

If you want to have one element next to another by using float, your combined element's width should be smaller than their container's. And since both your image and the text are inside divs and a div has 100% width by default, you have to specify a smaller width to each.

.floatleft {
    float: left;
    width: 40%;
}

.floatright {
    float: right;
    width: 30%;
}

Just change the widths accordingly.


Updating from 7.34 to 7.35 after successfull update, drush status shows version 7.34? Recently i tried to upgrade my site from 7.34 to 7.35 everything when successfully but when i go to status report or executing drush status command it shows that im still on drupal 7.34.

These are following screenshots: Result of drush up --security-only (same with drush up drupal)

And this screenshot shows drush status just after the update:

Any suggestions whats wrong?

Thanks in Advance
Tee

This is a file permissions issue.  See:

Can't update drupal core to 7.27

Drush should give an error message here, instead of pretending to work.


Unset the "please wait" in drupal commerce I've got a product with different taxonomy like "S" "M" "L".
When you change the size in the display product, it shows the ajax div
"Please wait..."
I've tried

function bartik_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
unset($form['attributes']['field_size']['#ajax']['progress']['message']);
}

If I have a look at it with dms($form) I see attributes -> field_size -> #ajax -> callback(commerce_cart_add_to_cart_form_attributes_refresh)

There is not message. How can I get rid of it?

Thanks in advance.

A simple way could be to hide it with CSS, but what is displayed by Drupal is actually configurable. The throbber with the Please wait... message is the default behavior but you can change it to a number of things. What you need to look at is the #ajax['progress'] attribute.

Usually #ajax['progress'] is not set in the form, and Drupal will add the default throbber with the Please wait... message in the JavaScript that handle the ajax request. The solution it quite simple, all you need to do is to set it like this:

$form['element']['#ajax']['progress'] = array('type' => 'throbber');

It will kill the message and only show the throbber. There are a number of ways to configure what Drupal does to show the user progress - you can read all about it in the link above.


Change "Add new node" and "Add existing node" button labels in inline entity reference forms I am using inline entity forms to allow users to add or reference existing location content to event content from the front end and am very pleased with how this works. I would really like for the buttons to be labeled slightly different here with the labels reading, for example, "Add new location" rather than "Add new node" which is currently a bit confusing for users. Is this possible, even if this was a theme hook that only changed the label in the front end? The solutions for Drupal 7 don't seem to work in 8.

Turns out this is really easy. Under "Manage form display" in your content type, make sure that the widget is set as Inline entity form (simple or complex) and check "Override labels" then define your node type label.


Panels, panel node print header and footer I use Panels module and I've created Panel page, where I inserted Panel nodes.

Problem: Panel nodes have their own header and footer html tags that are printed. How to remove them? Any way to make it without custom template in code?

I should use min-panel. Panel page and panel node both have page structure.


Migrate addressfield: Call to a member function import() on a non-object in migrate/includes/migration.inc on line 696 also posted to Migrate issue queue as a support request

I am importing users and data from csv with a Migrate Group. The initial user creation and some additional data in other tables in working fine.

I have read everything I can find on Google about Migrate and Addressfield, and some of it is 2 years old and confusing. For example, Migrate has deprecated $arguments for field mappings, sub-fields are mapped with colon notation. Also, I am adding the Addressfield migration to a group so it gets the correct uid from the completed user migration, so posts about direct csv imports are not helpful.

I am getting a message when I migrate (with drush)

PHP Fatal error: Call to a member function import() on a non-object in /var/www/[site]/sites/all/modules/contrib/migrate/includes/migration.inc on line 696

I put a drush_print_r on that line

drush_print_r($this->destinationValues);drush_print_r($this->sourceValues);

the output of drush_print_r just before the error is

stdClass Object
(
    [entity_id] => 483
    [field_user_address] => Array
        (
            [0] => US
            [arguments] => Array
                (
                    [administrative_area] => NY
                    [first_name] => [actual first name]
                    [last_name] => [actual last name]
                    [locality] => New York
                    [postal_code] => 10028
                    [premise] =>
                    [thoroughfare] => [actual address]
                )

        )

    [revision_id] => 483
)

stdClass Object
(
    [Row] => 1
    [Type] => M
    [Prefix] => Miss
    [FirstName] => [actual last name]
    [MiddleName] =>
    [LastName] => [actual first name]
    [StaffNotes] =>
    [ColumbiaAffiliation] => Alumna/nus
    [ProfessionalAffiliation] =>
    [AddressLine1] => [actual address]
    [AddressLine2] =>
    [City] => New York
    [State] => NY
    [ZipCode] => 10028
    [Country] => Array
        (
            [0] => US
        )

    [TelephoneNumber] => [actual phone number]
    [Email] => [actual email]
    [Birthday] =>
    [ID] => [actual ID]
    [Descriptor] => [A] A: EN07
    [GraduationYear] => 2007
    [SchoolAffiliation] => EN
    [csvrownum] => 1
    [migrate_map_hash] =>
)

my field mappings:

$this->addFieldMapping('field_user_address', 'Country');
$this->addFieldMapping('field_user_address:administrative_area', 'State');
$this->addFieldMapping('field_user_address:locality', 'City');
$this->addFieldMapping('field_user_address:postal_code', 'ZipCode');
$this->addFieldMapping('field_user_address:thoroughfare', 'AddressLine1');
$this->addFieldMapping('field_user_address:premise', 'AddressLine2');
$this->addFieldMapping('field_user_address:first_name', 'FirstName');
$this->addFieldMapping('field_user_address:last_name', 'LastName');

and in prepareRow():

$row->Country = array($row->Country);

I gave up with the Addressfield Migration Class and decided to do a db_insert -- and it worked!

Not only works, but because I register the insert in the prepare() function of class SchoolMigration (where I was already using db queries) it also rolls back!

<?php
/**
 * @file migrate_users.migrate.inc
 * Our own hook implementation.
 */

/**
 * Migration classes for migrating users and user fields
 *
 * see Migrate handbook: https://drupal.org/migrate
 * and http://www.verbosity.ca/working-drupals-migrate-module
*/

/* useful functions for debugging using drush migrate commands:
drush_print_r($row);
drush_print_r($this->destinationValues);
*/

/**
 * Implements hook_migrate_api()
 *
 * Returns 'api' => 2 for the 7.x-2.x branch of Migrate.
 * Registers the migration classes for the 7.x-2.6 branch of Migrate (including
 * 7.x-2.6+xx-dev).
 */

function migrate_users_migrate_api() {
  $api = array(
    'api' => 2,

    // Migrations can be organized into groups. The key used here will be the
    // machine name of the group, which can be used in Drush:
    //  drush migrate-import --group=MigrateMembers
    // The title is a required argument which is displayed for the group in the
    // UI. You may also have additional arguments for any other data which is
    // common to all migrations in the group.
    'groups' => array(
      'MigrateMembersGroup' => array(
        'title' => t('Import Member Users'),
      ),
    ),

    // Here we register the individual migrations. The keys (MigrateMembers_Step1,
    // etc.) are the machine names of the migrations, and the class_name
    // argument is required. The group_name is optional (defaulting to 'default')
    // but specifying it is a best practice.
    'migrations' => array(
      'MigrateMembers' => array(
        'class_name' => 'MigrateMembers',
        'group_name' => 'MigrateMembersGroup',
      ),
      'GraduationYear' => array(
        'class_name' => 'GraduationYearMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'School' => array(
        'class_name' => 'SchoolMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'SchoolID' => array(
        'class_name' => 'SchoolIDMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
    ),
  );
  return $api;
}

/**
* Abstract class as a base for all our migration classes
*/

abstract class MigrateMembers_Basic_Migration extends Migration {
  public function __construct($arguments) {
    // Always call the parent constructor first for basic setup
    parent::__construct($arguments);
    // Avoid known line ending issue: drupal.org/node/1705850
    ini_set('auto_detect_line_endings', TRUE);
  }
}

/**
* User-only migration
* (and creates $row (Row) with user id to key other tables in subsequent migration classes)
*
* The data file is assumed to be in
* sites/all/modules/migrate_users/data_sources/
* the columns in the csv must be in the same order left-to-right as the $columns array below
* every row in csv must have a unique id in the first column (can be ascending numbers, for example)
*/
class MigrateMembers extends MigrateMembers_Basic_Migration {

public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = t('Import an CSV-file (only "User Account"-fields)');
  $columns = array(
  // Format: ('Fieldname', t('Description'))
      0 => array('Row', t('Row number (must be unique)')),
      1 => array('Type', t('S = Student M = Member')),
      2 => array('Prefix', t('Mr. Mrs. etc')),
      3 => array('FirstName', t('First Name')),
      4 => array('MiddleName', t('MiddleName')),
      5 => array('LastName', t('Last Name')),
      6 => array('StaffNotes', t('Staff Notes')),
      7 => array('SchoolNameAffiliation', t('SchoolName Affiliation')),
      8 => array('ProfessionalAffiliation', t('Professional Affiliation ')),
      9 => array('AddressLine1', t('Address Line 1')),
      10 => array('AddressLine2', t('Address Line 2')),
      11 => array('City', t('City')),
      12 => array('State', t('State')),
      13 => array('ZipCode', t('Zip Code')),
      14 => array('Country', t('Country')),
      15 => array('TelephoneNumber', t('Telephone Number')),
      16 => array('EMAIL', t('Email')),
      17 => array('Birthday', t('Birthday')),
      18 => array('SchoolID', t('SchoolID')),
      19 => array('Descriptor', t('Descriptor')),
      20 => array('GraduationYear', t('Graduation Year')),
      21 => array('SchoolAffiliation', t('SchoolAffiliation')),
  );

  // TIP: delete ", array('header_rows' => 1)" in the next line, if the CSV-file has NO header-line
  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationUser();
  $this->map = new MigrateSQLMap($this->machineName,
  array('Row' => array( // this field is used to connect user to other tables
          'type' => 'varchar',
          'length' => 6,
          'not null' => TRUE,
          'description' => t('User\'s Member-ID') // description never used
        )
       ),
  MigrateDestinationUser::getKeySchema()
  );

  // Mapped fields

  $this->addFieldMapping('name', 'EMAIL')
    ->defaultValue('')
    ->description(t('Name (User Account)'));
  $this->addFieldMapping('mail', 'EMAIL')
    ->defaultValue('')
    ->description(t('Email address'));
  $this->addFieldMapping('init')
    ->defaultValue('')
    ->description(t('Email address used for initial user-account creation'));
  $this->addFieldMapping('pass', 'PASSWORD')
    ->defaultValue('asdf')
    ->description(t("User's password (plain text)"));
  $this->addFieldMapping('is_new')
    ->defaultValue(TRUE)
    ->description(t('Build the new user (0|1)'));
  $this->addFieldMapping('roles')
    ->defaultValue(6)
    ->description(6 . t(' = "member"'));
  $this->addFieldMapping('theme')
    ->defaultValue('')
    ->description(t("User's default theme"));
  $this->addFieldMapping('signature')
    ->defaultValue('')
    ->description(t("User's signature"));
  $this->addFieldMapping('signature_format')
    ->defaultValue('filtered_html')
    ->description(t('Which filter applies to this signature'));
  $this->addFieldMapping('created')
    ->defaultValue(time())
    ->description(t('unique timestamp of user creation date'));
  $this->addFieldMapping('access')
    ->defaultValue(0)
    ->description(t('unique timestamp for previous time user accessed the site'));
  $this->addFieldMapping('login')
    ->defaultValue(0)
    ->description(t('unique timestamp for user\'s last login'));
  $this->addFieldMapping('status')
    ->defaultValue(1)
    ->description(t('Whether the user is active(1) or blocked(0)'));
  $this->addFieldMapping('timezone')
    ->defaultValue(t('Europe/London')) // 'America/Los_Angeles', 'Europe/Berlin', 'UTC', ... from drupal.org/node/714214
    ->description(t("User's time zone"));
  $this->addFieldMapping('language')
    ->defaultValue(t('en')) // e.g.: 'en', 'fr', 'de', ...
    ->description(t("User's default language"));
  $this->addFieldMapping('picture')
    ->defaultValue(0)
    ->description(t('Avatar of the user'));

  // Other handlers
  if (module_exists('path')) {
    $this->addFieldMapping('path')
       ->defaultValue(NULL)
       ->description(t('Path alias'));
  }
  if (module_exists('pathauto')) {
    $this->addFieldMapping('pathauto')
    ->defaultValue(1)
    ->description(t('Perform aliasing (set to 0 to prevent alias generation during migration)'));
  }
  // Unmapped destination fields
  $this->addUnmigratedDestinations(array('role_names', 'data'));
  }
}

class GraduationYearMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = 'Add data to field_data_field_graduation_year';
  $this->dependencies = array('MigrateMembers');
  $table_name = 'field_data_field_graduation_year';

  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationTable($table_name);
  $this->map = new MigrateSQLMap($this->machineName,
    array('Row' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
       )
     ),
    MigrateDestinationTable::getKeySchema($table_name)
    );

  // Mapped fields
  // add uid from completed MigrateMembers migration
  $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
  $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

  // Insert Graduation Year value
  $this->addFieldMapping('field_graduation_year_value', 'SchoolAffiliation')->sourceMigration('MigrateMembers')
    ->defaultValue(date("Y"));

  // set some defaults from the schema
  $this->addFieldMapping('delta')
    ->defaultValue("0");
  $this->addFieldMapping('entity_type')
    ->defaultValue("user");
  $this->addFieldMapping('bundle')
    ->defaultValue("user");
  $this->addFieldMapping('language')
    ->defaultValue("und");

  $this->removeFieldMapping('path');
  $this->removeFieldMapping('pathauto');
  }
}

class SchoolMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_member_school';

    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_member_school';
    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
         )
       ),
      MigrateDestinationTable::getKeySchema($table_name)
      );

    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('field_member_school_tid', 'SchoolAffiliation')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');

  }

  public function prepareRow($row){
    // convert 3 letter codes to ISO 3166-1 standard 2 letter codes http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Current_codes
    // TODO:
    // 1 - check for full list of country codes in old data
    // 2 - many records with US addresses do not have a foreing country code, not the USA country code
    // 3 - What are INO SAF SWD?
    switch ($row->Country)
      {
        case 'AUS': // Austria
        $row->Country = "AT";
        break;
        case 'BEL': // Belgium
        $row->Country = "BE";
        break;
        [more mappings]
        default :
        $row->Country = "US";
        break;
      }

  }

  function prepare($entity, stdClass $row){

    // delete rows added by MigrateMembers
    $num_deleted1 = db_delete('field_data_field_member_school')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();
    $num_deleted2 = db_delete('field_data_field_user_address')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

      switch ($row->SchoolAffiliation)
      {
        case 'AR': // Arts
        $row->SchoolAffiliation = "91";
        break;
        [more mappings]
        default :
        $row->SchoolAffiliation = "NULL";
        break;
      }

    $this->destinationValues->field_member_school_tid = $row->SchoolAffiliation;

    $fields = array('entity_type' => 'user', 'bundle' => 'user', 'deleted' => 0, 'entity_id' => $this->destinationValues->entity_id, 'revision_id' => $this->destinationValues->entity_id, 'language' => 'und', 'delta' => 0, 'field_user_address_country' => $row->Country, 'field_user_address_administrative_area' => $row->State, 'field_user_address_sub_administrative_area' => '', 'field_user_address_locality' => $row->City, 'field_user_address_dependent_locality' => '', 'field_user_address_postal_code' => $row->ZipCode, 'field_user_address_thoroughfare' => $row->AddressLine1, 'field_user_address_premise' => $row->AddressLine2, 'field_user_address_sub_premise' => '', 'field_user_address_organisation_name' => '', 'field_user_address_name_line' => '', 'field_user_address_first_name' => $row->FirstName, 'field_user_address_last_name' => $row->LastName, 'field_user_address_data' => '');
    db_insert('field_data_field_user_address')->fields($fields)->execute();
  }
}

class SchoolIDMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_SchoolID';
    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_SchoolID';

    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
           )
         ),
        MigrateDestinationTable::getKeySchema($table_name)
      );

    // add uid from completed MigrateMembers migration
    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

    //this assignment does not find the SchoolID; it is set in prepare()
    //$this->addFieldMapping('field_SchoolID_value', 'SchoolID')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");
    $this->addFieldMapping('field_SchoolID_format')
      ->defaultValue("plain_text");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');
  }

  function prepare($entity, stdClass $row){
    // delete rows in table added by MigrateMembers
    $num_deleted = db_delete('field_data_field_SchoolID')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

    //
    if ($row->SchoolID) $this->destinationValues->field_SchoolID_value = $row->SchoolID;
    else $this->destinationValues->field_SchoolID_value = "NULL";
  }
}


Populating file fields with an http-request with the Services module and a REST Server (Drupal 7) I need to add content trough a node.create and one of the fields in the content type I am adding is a file field.  So far I have been able to get my Services module set up with REST server to accept user and node resources and I have been able to make http-requests to  add content containing text fields.  Now I need to expand on this to work with a file field but I have not been able to find any resources about creating nodes that contain file fields.  I am wondering how would this be done?  Would it be done in one pass or two?  Would I upload the file with a first post then do the association next?  Does anyone have any good resources related to this topic?

Currently services doesn't offer the ability to add a file to a node in ONE method call, but thats easily within the scope of what services can offer, its just not in services core.

Currently you can make a request to create a file and get the returned FID, then you can process to submit a node with the field structure for a file field.

Which is something like

{"nid":1, "field_image":{"und":[{"fid":2}]}}

Forgive me thats very rough, but you can can use devel to look at an already existing node with an image attached and mimic that in your submission and it will work.

The current process is:

POST to /file

get returned FID

PUT to /node make sure to have nid and field_* in the correct structure or it won't stick.


How do I increase time of slide in jcarousel? I want to increase the timer of the slide by 4 seconds so that each slide should be visible for 4 seconds. How can I do this?

Try this. Click on "View Transition Advanced Options" and into "Timer delay" set time in milliseconds as shown in below image.


How to call hook_theme_suggestions_HOOK_alter twice, if node is shown twice? What I want to do is show the contact person responsible for a language in two different regions simultaneously, but with different twig templates.
I therefore have two regions: footer and sidebar
I have a node type of Contact Person (contact_person) with several fields and I create one content of this node type per language (using Only One module)
I started with creating a View which get's me the correct content, but with two blocks. This gave me the same issue. I tried to circumvent this issue by creating two Views (Contact Person (Footer) and Contact Person (Sidebar)) each with one block display.
I changed the system names in the views to be block_sidebar and block_footer instead of the default block_1 for added clarity.
I used these blocks in the Block Layout, where I added both blocks to their respective regions.
If I examine the theme suggestions, the blocks behave as expected
For Sidebar:
block--views-block--contact-person-sidebar-block-sidebar.html.twig
___________________________________^^^^^^^_______^^^^^^^
For Footer:
block--views-block--contact-person-footer-block-footer.html.twig
___________________________________^^^^^^_______^^^^^^
But when I examine the node theme suggestions, the are the same
For Sidebar AND Footer:
node--view--contact-person-sidebar--block-sidebar.html.twig
___________________________^^^^^^^________^^^^^^^
if the Sidebar block get's rendered first.
If I swap the blocks in their regions (Sidebar Block goes inside the Footer region and Footer block inside the Sidebar region) and clear all the caches, the footer block is rendered first and so the theme suggestions changed for both of them:
node--view--contact-person-footer--block-footer.html.twig
___________________________^^^^^^________^^^^^^
These suggestions seem to generated in the Views module itself
// File core/modules/views/views.module
// ...
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function views_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['elements']['#node'];
  if (!empty($node->view) && $node->view->storage->id()) {
    $suggestions[] = 'node__view__' . $node->view->storage->id();
    if (!empty($node->view->current_display)) {
      $suggestions[] = 'node__view__' . $node->view->storage->id() . '__' . $node->view->current_display;
    }
  }
}
// ...

If I try to debug this I discovered that the hook_theme_alter function is only called once for the node. I isn't called a second time, because the hook_theme_suggestions_HOOK_alter was already called for this very node.
How can I say Drupal that I want these suggestion alter function to be called a second time, if one node is shown a second time on the same page?

Nodes are rendered only once per view mode and then are cached. So the easiest solution would be to configure different view modes. Which makes sense in this case, these are in fact two different displays of the same node. Another benefit, you don't need this hook, because view modes have theme suggestions out-of-the-box.


How to implement a duration field? I am constructing a content type that will 'wrap' a video, either youtube, vimeo or file upload. One of the fields required is a 'duration' field. Obviously a requirement is also for the videos to be sortable in a view based on that field.

How would I go about doing that? A format of H:i:s or i:s would be prefered in a textfield as an input method.

Posting my comment as answer - Check for HMS (Hours Minutes Seconds) Field module.

  Displays a integer formatted as Hours, Minutes or Seconds.
  The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provides developers a way to add their own format.


Using breadcrumbs with multiple menus for one link In my website I have 2 menus; the Main Menu and the Header Menu that I use for quick links.

I have 1 page that is linked in both menu.

When I'm on that page, the breadcrumb (and other menu-related blocks) use the hierarchy of the quick-link menu.

In my node the menu configured is the Main Menu and I added the link manually to the Header Menu.

Is there any way to give a weight to different modules?

Thanks!

Multiple Node Menu might do the trick:

  This module modifies the "Menu settings" in standard node editing form
  to allow managing multiple menu links to a node. The Drupal standard
  behavior is to only care about a single menu link for anode, all other
  menu links must be added through menu administration.


How can I add products to cart programmatically? I have a form adding an item to the basket in the form of a table n x m where
n and m are taxonomy terms of two different taxonomies ('type of the insert' and 'insert size').

In each cell the user can enter the number of items, with the n-th 'type of the insert' and m-th 'size'.

Form I create myself in the template-based taxonomy vocabularies. How can I add products to cart programmatically?

To add particular product id you have your product id and current user id you can easily do.
Send the Product id and user id to this function this will add your product to the user cart.

This is the custom function used. The main part here is the commerce_product_line_item_new() and commerce_cart_product_add() this will add the product to that particular user cart.

function add_product_to_cart($pid,$uid=0){
    global $user;
    $uid = isset($uid) && !empty($uid) ? $uid : $user->uid;
    $line_item = commerce_product_line_item_new(commerce_product_load($pid));
    commerce_cart_product_add($uid, $line_item);
}

Hope this will help :)


Adding an existing node as a translation I have many articles in original (English) language and they're all translated to 3 languages - however, the translations were created as new nodes (and not by clicking "Add translation" in the Translation tab).

Is it possible to somehow relate the translations with the original English article or do I have to manually redo it all by clicking "Add translation" in the Translate tab of each node and adding the translations?

You can do this in code by reading the field values from the three translated nodes and add them as translation to the english node:

$node_en->addTranslation($langcode1, $node1->toArray());
$node_en->addTranslation($langcode2, $node2->toArray());
$node_en->addTranslation($langcode3, $node3->toArray());
$node_en->save();

This is for demonstration only, you can loop through the languages and get the langcode from the node.

The problem is that at the moment the translated nodes and the english node have no connection in the database. If you have some data in the nodes that do match, you can do a entity query and loop through the results.


Export selected view rows and selected columns to excel I use VBO export module and Views Bulk Operations module to export my view results to CSV. This works fine. The user can also make a selection which rows to export.

Is there a solution to let the user also select which columns (which view fields) will be exported to CSV?

To export just a particular column or number of particular columns you would change the view itself. To preserve the original one, just copy the view export only the column(s) you need and delete the temporary view.


Is there any alternative to OpCache? I have a hosting with suPHP handler which doesn't support opcache. I want to start working on Drupal 8 sites which highly recommend opcache.

Is there any alternative to opcache? Should I change my hosting?

Any properly configured opcode cache should work. Notice that Drupal only currently checks for PHP Opcache in its requirements. Some people have got Drupal 8 working with XCache, for example.

APC is really not the way to go. It exists in a backwards-compatible way in PHP 5.5 and as a token-based data cache (still useful, but it isn't an opcode cache in that configuration).


Cannot get articles or custom content types to load on front page I am new to drupal. I have Drupal ver 8.5 installed on my local MAMP.

Unfortunately, though I am following a tutorial that is using version 7.28 (perhaps this is the issue). I cannot get my recently made articles OR custom content types to show on my front page.

a.) I have ensured that my URL under Front page > "Basic Site Settings" is blank.
b.) I have ensured that all my articles have "Promoted to front page" checked under the Promotion Options Tab.
c.) I have ensured that all my custom content types have "Promoted to front page" under the Promotion Options Tab.

What am I doing wrong?

By default, in a fresh Drupal 8 installation, your homepage is populated by the frontpage view. Make sure that your homepage URL under admin/config/system/site-information is /node. That is the default URI of the frontpage  view.

You can find the definition of that view under admin/structure/views/view/frontpage.

If you need a guide about the Views module, you can find it on Chapter 9. Creating Listings with Views.


Views Slideshow - How to add link on Pager that can link to original page? Views Slideshow on Drupal 7 has a feature that can “Activate Slide and Pause on Pager Hover”. How can I add link on Pager, so when click, it actually link Pager to original piece of content?

Having a look at the views slideshow code it seems that all the sections of the views slideshow are easily themed.

In the views slideshow module there is a themes folder with template files that can be overridden.

Though there is not a template file for the pager, instead there is a function in the file views_slideshow.theme.inc. The function you are interested in is probably theme_views_slideshow_pager_widget_render($vars) and this can be overwritten.

In your themes template.php copy and paste this function and rename it to MYTHEME_views_slideshow_pager_widget_render($vars), (replacing MYTHEME with the name of your theme).

You should then be able to modify it in any way you like.


Do I need to download migrate upgrade module if use drush command? Migration Drupal 6 to Drupal 8.

My Drupal 8 site is located at /domains/example.com/public_html/drupal8site

Step 1: Install Drush

Step 2: Browse my drupal site cd /domains/example.com/public_html/drupal8site

Step 3: Use drush command drush migrate-upgrade --legacy-db-url=mysql://user:pass@12.34.56.78/d6db --legacy-root=http://example.com

If I using Drush migrate command above, do I still need to download the Migrate Upgrade module? If yes, where should the module file located?

No. You don't. In Drupal 8.1.3 This module is part of the core.

To have the full list of drush upgrade commands you would need Migrate tools  module though.

See here for more details.


footer block through custom module and fetch node image field in Drupal 7 I want to create footer block through custom module and want to add five images through node.Five images should change one by one after one hour.

Can anybody tell me how to do this ?

<?php

function chat_block_info() {
  $blocks['chat_footer'] = array(
    'info' => t(' FOOTER'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

function chat_block_view($delta = '') {
  $block = array();

  switch($delta) {

    case 'chat_footer' :
      $block['chat_footer'] = array(
        '#markup' => chat_footer_block('footer'),
      );
      break;
  }
  return $block;
}

function chat_footer_block($parm) {
 if ($param == 'footer')
 {
   $node = node_load(11111);
    $uri_top = $node->field_footer_image['und'][0]['uri'];
    $alt_top =$node->field_footer_image['und'][0]['alt'];
   $image_top = theme('image_style', array('style_name' => $footer_chat,
        'path' => $uri_top,
        'getsize' => TRUE,
        'alt' => $alt_top,
        'title' => "IMG"
      ));

}

}

To accomplish this I would probably use a combination of hook_cron() to check in every hour, persistent variables to track the last loaded image (see variable_set and variable_get) and the great Ajax Blocks module so that your block is refreshed without having to rebuild the entire page each time.