Commerce functionality using Domain Access + i18n I have several sites using modules Domain Access and i18n, using Drupal 7. I am completely newbie to commerce, and have read about the options of modules Ubercart and Drupal Commerce.

However, I want to have the flexibility of Domain Access, so I would like to have a store section which is different for any domain (at the least) and possible different for any domain-language combination (less likely).

What would be the best option of the above modules? Are they both compatible with Domain Access? How do I need to install Drupal, first the commerce or better (I guess so) the Domain Access + i18n and, after that, the module ( I had great problems with a module related to Domain Access just because of the order of installation, with no even the developer knowing what had happened or if it was a bug after all ).

The answer to your question: Can a Drupal Commerce catalog show different domain-aware products? is "yes." Mostly because Drupal Commerce simply uses content and Views to build catalogs, so if you can get Drupal to do something, Drupal Commerce is most likely along for the ride.

But I want to dig a little deeper to help you understand the problems you will uncover as you try to build something like this. Drupal Commerce 7 works on 2 levels (the version for Drupal 8 is much different):

1) Node level - Content with a title, a url, and published settings are best kept as nodes in Drupal 7. That suits Drupal Commerce well, since if you want to display a product, you must do it with a product reference field on a node. Most of the content related to specific products (a specific size/color/configuration) are actually injected fields. Injected fields get replaced automatically using ajax when an attribute field (size/color/configuration) is changed. This presents the biggest challenge for domain/translation.

2) Entity level - Lots of things in Commerce are simply implemented as custom entities. This includes products (not product displays), Orders, Line Items, etc. Products are the most likely to give you problems. For example, if you set a product display (node) to be certain domains, and products to be other domains, what do you expect to happen?

The Domain Access module is built to work with nodes exclusively. While some effort has been put into making a generic entity solution, it has many failings, most of which include a buggy and bloated data-entry interface. If I were to build such a thing, it would require a few patches to make it useable and understandable to the "store administrator."

For translation, you have a similar problem. You will need to decide whether you want to be able to translate certain fields (titles, description) or entire nodes/entities (a complete copy of the about us page, including attachments).

Most likely, you will want field-level translation. In that case, product pages that use product-level content (pictures or description that are a part of the attributes, like color/size/configuration) have a difficult problem to solve. The node would need to bring in a translated version of fields, and (optionally) bubble up product-level (read: entity-level, not node level) translated versions. If this sounds confusing, it's because it really is. We have multiple sources of content, all that would require some form of field-level translation.

The good news is, you can confirm this works in a matter of minutes with commerce_kickstart version 1 plus your domain and translation modules of choice. Note that field-level translation is supported by search_api, which means that your catalogs that should respond to domain and language, is possible and works without patches (this was not always the case).

The bad news is, while this is relatively easy to build as a demo, in practice, the resulting mess of products, translations, and page-level content becomes very hard to represent in a administrative interface in such a way that your average non-drupaler would know what's going on. For example, lets say you have a tshirt shop that sells shirts in two colors and two sizes. How do you describe to your store administrator that the color "red" is a taxonomy term that needs to be translated because it's connected to products which are connected to the page they are on? It's 3+ levels deep. Quite an abstract problem.

Your question isn't really suited for a "how to" because there many variations on your request that would completely change how I would set up the underlying information architecture. Something else you might consider adding to your architectural plan would be a comprehensive way to deal with multiple currencies in the face of domain/translation combinations.

// Edit: Here are some module recommendations:

I wouldn't use Domain Access if you are trying to control product visibility with domains. It's too messy. It's much easier to simply create a taxonomy term and then build a custom views condition that compares the taxonomy term with the actively requested domain. I have built one store where this was a take-away after months of development.
I recommend https://www.drupal.org/project/entity_translation for field level translation
You will still likely need https://www.drupal.org/project/i18n for menu and taxonomy (attribute) translation.
I highly recommed you tell your designer you need an interface that helps selecting a domain, a language, and a currency. Or some combination. At the end of the day, there isn't one easy way to do this, especially important to nail the mobile-responsiveness of your visual solution. (Drop-downs don't make as much sense on a phone).


How to load a customer profile from address module I'm using Drupal 8 with the module Commerce  and I have an issue with the customer address.

I'm developing an export custom module in D8, and I'm stuck trying to load the profile (to access billing and shipping address) of a customer.

I'm not able to access this data from the custom module. And there is no documentation about the address pluggin ( https://www.drupal.org/project/address )

I have tried to load the order and the user data but there is no relevant field that helps  me to achieve this.

Can anyone give me a hint?

Thanks in advance.

you can try get profile by order and can try the code below:

$order_id =1;
$entityManager = \Drupal::entityTypeManager();
$order = $entityManager->getStorage('commerce_order')->load($order_id);

get address by field billing_profile

$address = $order->billing_profile->entity->address->getValue();


Content Type no showing fields I have been trying to created a content type programmatically in Drupal 7. I notice that I should use the hook_node_info to generate the content type with the title and to add the body I should use the  node_add_body_field. I have been follow the examples modules ￼

So this is what I got as my code ...
non_recruiter.module

<?php

/**
 * Implements hook_node_info().
 */
function non_recruiter_node_info() {
  // We define the node type as an associative array.
  return array(
      'job_template_2' => array(
          'name' => t('Job Template 2'),
          'base' => 'job_template_2',
          'description' => t('A content type for posting your jobs.'),
          'title_label' => t('Job Template 2'),
          'locked' => TRUE,
      ),
  );
}

/**
 * Implements hook_node_type_insert().
 */
function non_recruiter_node_type_insert($content_type) {
  if ($content_type->type == 'job_template_2') {
      $body_instance = node_add_body_field($content_type, t('Job Description'));
        $body_instance['display']['non_recruiter_list'] = array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
    );

    // Save our changes to the body field instance.
    field_update_instance($body_instance);

    // Create all the fields we are adding to our content type.
    foreach (_non_recruiter_installed_fields() as $field) {
      field_create_field($field);
    }

    // Create all the instances for our fields.
    foreach (_non_recruiter_installed_instances() as $instance) {
      $instance['entity_type'] = 'node';
      $instance['bundle'] = 'non_recruiter';
      field_create_instance($instance);
    }
  }
}

/**
 * Implements hook_form().
 */
function non_recruiter_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

function _non_recruiter_installed_fields() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'cardinality' => 1,
          'type'        => 'text',
      ),
  );
}

function _non_recruiter_installed_instances() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'non_recruiter_quantity',
          'label' => t('Quantity required'),
          'type'        => 'text',
          'widget'      => array(
              'type'    => 'text_textfield',
          ),
          'display' => array(
              'non_recruiter_list' => array(
                  'label' => 'hidden',
                  'type' => 'hidden',
              ),
          ),
      ),
  );
}

So I took what they did and modify the code base on what I want.

My Goal is to have a content type that have the following fields...

Job Title (title)
Job Description (body)
Quantity (text)

But I'm doing something wrong because the fields are empty. If I try to add new content using this content type this is what I got ...

An empty content type, without any fields.

Here is some extra information of how my Manage Fields & Display looks like..
Manage Fields

Manage Display

So, can anyone tell me why my fields are not showing up in my content type ?

/**
 * Implements hook_node_info().
 */
function non_recruiter_node_info() {
  // We define the node type as an associative array.
  return array(
      'job_template_2' => array(
          'name' => t('Job Template 2'),
          'base' => 'job_template_2',
          'description' => t('A content type for posting your jobs.'),
          'title_label' => t('Job Template 2'),
          'locked' => TRUE,
      ),
  );
}

/**
 * Implements hook_node_type_insert().
 */
function non_recruiter_node_type_insert($content_type) {
  if ($content_type->type == 'job_template_2') {
      $body_instance = node_add_body_field($content_type, t('Job Description'));
        $body_instance['display']['non_recruiter_list'] = array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
    );

// Save our changes to the body field instance.
field_update_instance($body_instance);

// Create all the fields we are adding to our content type.
foreach (_non_recruiter_installed_fields() as $field) {
  field_create_field($field);
}

// Create all the instances for our fields.
foreach (_non_recruiter_installed_instances() as $instance) {
  $instance['entity_type'] = 'node';
  $instance['bundle'] = 'job_template_2';
  field_create_instance($instance);
}
  }
}

/**
 * Implements hook_form().
 */
function job_template_2_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

function _non_recruiter_installed_fields() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'cardinality' => 1,
          'type'        => 'text',
      ),
  );
}

function _non_recruiter_installed_instances() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'label' => t('Quantity required'),
          'type'        => 'text',
          'widget'      => array(
              'type'    => 'text_textfield',
          ),
          'display' => array(
              'non_recruiter_list' => array(
                  'label' => 'hidden',
                  'type' => 'hidden',
              ),
          ),
      ),
  );
}


How do I disable cache in my entityQuery? I created a preprocess function in my recipe node page, inside that function I want to get 3 random recipes everytime the user accessess the page.

I have this code:

function sometheme_preprocess_node__recipe__full(&$variables)
{
    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'recipe')
        ->condition('status', 1)
        ->addTag('sort_by_random')
        ->range(0, 3)
        ->execute();

    $variables['random_recipes'] =  \Drupal\node\Entity\Node::loadMultiple($nids);
}

But I notice that the recipes doesn't random because of Drupal cache system.

I don't want to turn off the overall cache system of Drupal for perfomance purposes.

I just want to disable cache programmatically when I get the random recipes.

You'll need to make this an un-cachable block and place it on your template file, otherwise, you would have to turn off page caching.

But unless this is the only thing on that page, and there isn't something else in here worth caching, then you could alternately turn off caching for this specific page(s).


How to display fields from different entities in views In my project, i need to create a view that displays fields created in the profile 2 module and a field from the core registration form (Username) in the same table. Please how can this be done? I plan to filter users using the username field. and other values provided via the profile 2 fields.

Thank you.

Start with either the base table of user entity or profile 2 entity, then just add a relationship in views to the other. It is found under the "advanced tab" in views.


Help me understand this Fatal error: Call to undefined function EntityDefaultMetadataController::bundleOptionsList() With updated modules to recent releases,
Recently this error started appearing when executing 'Modify entity values' in views bulk operations. It happens on all the views in the site.
Indications where to start digging is much appreciated.

Fatal error: Call to undefined function EntityDefaultMetadataController::bundleOptionsList() in /home/cdt/public_html/sites/all/modules/views_bulk_operations/actions/modify.action.inc on line 173

The static method EntityDefaultMetadataController::bundleOptionsList() is a part of Entity API module that VBO is dependant upon. One of your modifiable entity properties needs this method to retrieve options for the modify operation.

You need to debug why this method isn't available. It's defined in entity.info.inc and should be included if the Entity API module is enabled.


Avoid repetitive API calling in form rebuild while submitting I am calling external API in form build function. While submitting form gets rebuild and call external API again.

How can I avoid repetitive API calls in the form's build function? I used form_state->set() but it's doesn't seem to be working.

You can test whether the form is currently rebuilding using the FormStateInterface::isRebuilding method:

if (!$form_state->isRebuilding()) {
  // Contact the API
}


I am unable to install module for my Drupal 7 I am a newbie to Drupal and was trying to develop a website. I am in need of modules to enhance and when trying to install them , it throws the following error.

  Warning: ftp_login(): Login incorrect. in FileTransferFTPExtension->connect() (line 59 of ..)
  Check Username and Password

My username and password are perfect. Can someone please help??

The alternate way to install module is to download the module and untar/unzip the files under /drupal/sites/all/modules/

Using Admin UI you can enable the module.


Display webform results data in a Google Chart I'm trying to display webform results as Google Charts. I'm doing this on the theme layer by overriding theme_webform_results_analysis() on my theme's template.php file and using the Chart module. Drupal 6.22, Webform 6.x-3.11.

The webform analysis page normally shows the data in a table, so I'm trying to hack apart the arrays for that table to pass stuff into the Chart API.

EDIT: I figured out how to use var_dump and found that the better approach might be to get up in the $row_data and $questions arrays separately (instead of using the $rows array that I had in the first version of this question, which was a mashup of both arrays).

EDIT #2: I think I've discovered how to grab each piece of the original $questions and $row_data arrays (see below - the foreach in the other foreach). So now I need to get those pieces into proper arrays (1 per question) and find a way to iterate through all of those.

Here's what I've got in template.php:

/**
 * Output the content of the Analysis page.
 * @see webform_results_analysis()
 */
function mytheme_webform_results_analysis($node, $data, $sids = array(), $analysis_component = NULL) {

  foreach ($data as $cid => $row_data) {

    if (is_array($row_data)) {

      // get the questions, put them in an array
      $questions = array();
      $questions[] = array('data' => check_plain($node->webform['components'][$cid]['name']));

      // this will print everything out in the right order - it really needs to
      // make an array for each question that looks like $test_chart below
      foreach ($questions as $question) {
        print $question['data'] . '
'; // questions
        foreach ($row_data as $key => $value) {
          print $value[0] . '
'; // labels
          print $value[1] . '
'; // results
        }
      }

      // Set up the chart
      $chart = array(
        '#chart_id' => 'webform_analysis',
        '#type' => CHART_TYPE_PIE_3D,
        '#size' => chart_size(658, 250)
      );

      // not real data here, this just shows the format I'm shooting for
      $test_chart = array(
        'option 1' => '12',
        'option 2' => '45',
        'option 3' => '122'
      );

      // separate the above array into labels and values, add a percentage to the label
      foreach ($test_chart as $key => $value) {
        $chart['#data'][] = $test_chart[$key];
        $chart['#labels'][] = strip_tags($key) . ' (' . round($test_chart[$key], 2) .  '%)';
      }
      // pick some colors
      $chart['#data_colors'][] = 'b0c73d';
      $chart['#data_colors'][] = '667323';
      $chart['#data_colors'][] = '221f1f';

      $output = chart_render($chart);
    }
  }

  if (count($row_data) == 0) {
    $output = t('There are no submissions for this form.');
  }

  // return the data that goes into chart function, just for testing
  // return $chart_data;

  // someday, this might return a set of webform charts. right now it returns the fake test chart
  // return $output;
}

There is another Drupal charts module that provides support for webforms: http://drupal.org/project/fusioncharts

Fusionchart has a little sub-module called fusioncharts_webform


Avoid combining products in cart With Drupal 8 / Drupal Commerce 2, I can't find a way to disable product combining in cart (same products in cart appears on the same line with quantity > 1). In my use case I never want this to happen.

I found that in

/modules/contrib/commerce/modules/cart/src/Form/AddToCartForm.php

...we have a submitForm method which calls

$this->cartManager->addOrderItem($cart, $order_item, $form_state->get(['settings', 'combine']);

So it seems like my form needs to have a combine variable set to FALSE.

How could I set this variable or override

public function addOrderItem(OrderInterface $cart, OrderItemInterface $order_item, $combine = TRUE, $save_cart = TRUE);

...in

/modules/contrib/commerce/modules/cart/src/CartManagerInterface.php

...to define the default value of $combine to FALSE ?

Thanks

I could achieve this by implementing hook_form_alter on add to cart form (in a custom module) and setting combine like this :

$form_state->set(['settings', 'combine'], FALSE);


Adding JavaScript before drupal.js I am trying to add jQuery to my page (it is not being added by default). The file is adding to the page but after drupal.js causing the error:

SCRIPT5009: 'jQuery' is undefined
drupal.js, line 5 character 1

The code that adds drupal.js to the page in common.inc

...
'misc/drupal.js' => array(
          'data' => 'misc/drupal.js',
          'type' => 'file',
          'scope' => 'header',
          'group' => JS_LIBRARY,
          'every_page' => TRUE,
          'weight' => -1,
          'preprocess' => TRUE,
          'cache' => TRUE,
          'defer' => FALSE,
        ),
...

In my module hook_init I have:

  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'cache' => TRUE,
  ));

I would think with a lower weight it would load before drupal.js?

The header of the page contains the following scripts:

<script type="text/javascript" src="http://mysite.com/misc/drupal.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/misc/jquery.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/misc/jquery.once.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/default/files/languages/nl_c9aC92_wtuULa79-hTFcGPM53oqk1yKwciOa_Q3yO28.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/lang_dropdown/msdropdown/jquery.dd.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/lang_dropdown/lang_dropdown.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/devel/devel_krumo_path.js?mqdxrf"></script>

In the end I got it working by changing the code to:

  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));
  drupal_add_js('misc/jquery.once.js', array(
    'group' => JS_LIBRARY,
    'weight' => -19,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));

This then meet the rules on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

First by scope, with 'header' first, 'footer' last, and any other scopes provided by a cust om theme coming in between, as determined by the theme.
Then by group.
Then by the 'every_page' flag, with TRUE coming before FALSE.
Then by weight.
Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.


How do I display articles in sticky footer? Not sure if i am going about this the right way but my intended goal is this:

Create a sticky footer that displays:

In Section 1(Left section) a Link to Latest magazine issue.
In Section 2 (Right Section)
A. Either show the latest Archived Articles.
B. Allow a user to input or select their own desired archived article.

Can I use a view to display this, or should I use a block? If I can accomplish this with a view, what should my approach be?

if you number of archive and data in this block all always this (not need generate dynamic)  you can  create them  with 2 static block that their link  redirect user to a page that data was generated by views,(views page ).

and if you block data is not static and you want they generate dynamically I suggest you use views block(this mean a view with block display).

I think this link can help you it describe how to create a block that show month name and when click on each month  related data  according to the that month fetch by view.


Displaying multiple node add forms using panels and contexts I'm using panels to create a single page that will display multiple (different) node add forms. Within panels, I use contexts to activate the node add forms I'm using and then put the forms in as content. However, the resulting page shows only the first node add form and then displays "Form" and "Form goes here" in place of the Title and fields of the second node add form.

Is there a fix for this? Or another way to display multiple node add forms within a page?

I doubt that panels can handle it.

I would try creating a custom page with hook_menu and outputting all the forms on it via a page callback like
   $output = drupal_get_form('foo_node_form');
   $output .= drupal_get_form('bar_node_form');
   return $output;


How to Add a quertystring to a link using jquery I have a set of links on my page and some of them start with /mypath, like this

I need to add a querystring to the links that start this way, so the result is something like  with the '1234' being the node id of the node we're currently viewing.

I've sucessfully passed the nid into my js file using drupal settings.  The only part of this I can't get to work is putting the original link in where you see the second attr('href').

My code is as follows:

    $('a[href^="/mypath/"]').attr('href', attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid);

Instead of that second attr('href') I've tried a number of things and can't figure out what it should be.

You've got nothing to hook onto for that second attr() as you're not storing the result of the jQuery call in a variable.

I'd advise using a loop instead:

$('a[href^="/mypath/"]').each(function(index, element) {
  var newAttr = $(element).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(element).attr('href', newAttr);
});

That will catch any link on the page that matches the path selector.


Using DATE_FORMAT in a select query I am migrating the custom code of d7 to d8 while doing I am using db_query in d7 where as in d8 I am using

\Drupal::database()->select('node_field_data', 'spmw')
            ->fields('spmw', ['id', 'created' => 'DATE_FORMAT(created, "%H:%i")'])->execute()->fetchObject();

I am getting error as

1054 Unknown column 'spmw.DATE_FORMATcreatedHi' in 'field list': SELECT spmw.id AS id, spmw.DATE_FORMATcreatedHi

You can try \Drupal::database()->select->addExpression().

For you, below code might be useful.

\Drupal::database()
  ->select('node_field_data', 'spmw')
  ->fields('spmw', ['id'])
  ->addExpression("DATE_FORMAT(created,'%H:%i')", "created")
  ->execute()
  ->fetchObject();


Create a filterable, sortable admin view that produces front end block The goal is to produce a single block to go on the homepage with 5 linked terms from a single taxonomy vocabulary. These terms would be selected and then ordered in an admin interface by a content administrator. The taxonomy vocabulary itself my have 30-50 terms.

I thought I could create an admin view with an exposed form to select the terms and then apply draggable views to the results, but I am having trouble combining the exposed form and draggable views. I am also having trouble turning the results into a block.

Happy to ad more info if this is vague, but all of the views I have set up have been so wrong I did not want to waste anyones time by posting them here.

Would views / exposed filters / draggable views be the right way to go about this or is there a better way? I'd rather not install something huge like panels to make this happen.

Another way to do this would be to install
https://www.drupal.org/project/term_queue

This contrib module gives you all you need.

Here is a screenshot, admin interface to the right, front-end block to the left.

The module provides a block automatically, for each term queue, you simply need to place it.

Good luck!


Load nodes with a fields condition I have node type called online_users.
The node type has a field called field_website_id.
I would like to get the nodes that has a specific field_website_id.

I have try to make the following action but gets an error:

function get_list_of_users($site_id) {
$query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'users_online')
  ->propertyCondition('field_website_id', $site_id)
  ->execute();
  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }
}

The error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'node.field_website_id' in 'where clause': SELECT node.nid AS
  entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type
  AS entity_type FROM {node} node WHERE (node.type =
  :db_condition_placeholder_0) AND (node.field_website_id IS NULL ) ;
  Array ( [:db_condition_placeholder_0] => users_online [:entity_type]
  => node ) in EntityFieldQuery->execute() (line 1140 of /Applications/MAMP/htdocs/Drupal/includes/entity.inc).

What is the right way to do this?

To filter by fields you should use fieldCondition() method instead of propertyCondition()

function get_list_of_users($site_id) {
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'users_online')
    ->fieldCondition('field_website_id', $site_id)
    ->execute();
  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }
}


How to share a D8 configuration without the UUID limitation? How can I share a Drupal 8 configuration (content type, custom view/menu/block, etc.) with another website without the UUID limitation?

Each site has a unique UUID, and refuses to work with the configuration file of another website. It's a big problem that doesn't allow users to share their configuration with the world.

The best way is to use the features module which is pretty stable and useful. You can even bundle specific configs and install them later on any website as a module (thus not needing to install the module there).


Obtain the total (count) of the contents associated with a nested taxonomy (only in the parent taxonomy) It is possible to count the contents associated with a nested taxonomy in Drupal 8 views, but the difference of this is that the taxonomies are of two levels.

For example:

I have these taxonomies:

Now, I have three created contents in which I associated the terms of the taxonomy, I stay like this:

I need something like this:

What I need to get in the view is, the total post associated with the parent taxonomy.

For example, I would like to see something like:

Backend: 2

Frontend: 1

What I have tried so far only shows me the totals independently(using aggregation), for example:

Backend - Post One - Total: 1

Ruby- Post One - Total: 1

Backend - Post Two- Total: 1

Python- Post Two- Total: 1

Frontend- Post Other- Total: 1

Is it possible to do this in Drupal 8 views?

I tried something similar I think, here's my code but keep in mind it's not perfect.

first get alle the terms

$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $node_storage->loadMultiple();
$node_tags = [];
foreach ($nodes as $node) {
  if ($node->hasField('field_terms')) {
    foreach ($node->get('field_terms')->getValue() as $value) {
      array_push($node_tags, $value);
    }
  }
}

after that you count all the terms

foreach ($node_tags as $key) {
  if (isset($count[$key['target_id']])) {
    $count[$key['target_id']]++;
  }
  else {
    $count[$key['target_id']] = 1;
  }
}
arsort($count);

then (and this still needs a lot of work) you search for them

$tags = $terms_storage->loadTree('tid');
$i=0;
foreach ($count as $key => $c) {
  foreach ($tags as $tag){
    if($tag->tid == $key){
     //here you can get the $tag->tid
     //you can get $tag->name
     //time used = $c
    }
  }
  $i++;
}

if you want to get the other terms

foreach ($tags as $tag){
  if(!array_key_exists($tag->tid,$count)){
   //here you get the same info
  }
}


jQuery Dialog, passing html to dialog I am looking for a method to pass html to jquery dialog. Without success.

I try:

Drupal.jqui_dialog.html(messages);

And

        Drupal.jqui_dialog.open({
              data : messages
        });

But it doesn't work.

If you have the jQuery UI library with dialog activated on your site, you should be able to do

$('<div>' + message + '</div>').dialog();


Commerce RRP translation The special price attributes provided by Commerce Exra Price Formatters are not translatable. Especially RRP. I cannot change the translations of these fields. I can write the label in the display dialog but it is not changeable depending on the site's language. How can I solve this problem?

For bugs like this, it's best to do a quick search of the module's issue queue. There are two issues, one with a patch that appears to do the job!

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


How to display the weekly view in manage availability in rooms_availability? I installed the Rooms module, and enabled all dependencies. Now when I edit a bookable unit and when I click in "manage availability", I can edit availability per month.

But I do not want a monthly view, I want weekly view. And I want to select the availability per hours/days.

Is that possible? And is there any other way to do this? Or is there another change in the code?

I'm not aware of a way to display a weekly view. But as per your "... is there another change in the code ...", it seems like it should be pretty forward to transform the 3 months view to a single month view via rooms_three_month_calendar.tpl.php.

To actually do so, remove line 2 (with class="month1") and line 4 (with class="month3") from this part of that tpl file:

After doing so, it should look like so:

Still not exactly a weekly view, but at least you already got rid of 2/3 of the days you don't want to see, right? And hence leaves 3 times as much space for the current month view.

Note: By not removing the backward / current / forward links in that tpl file, you should still be able to easily navigate to another month.


What's the correct way to redirect the user when a Batch API job finishes? I've got a form that starts a batch job. What's the right way to redirect them after it finishes? Calling drupal_goto() in my finish function?

You can set 'redirect' in hook_batch_alter().
For example:

$batch['form_state']['redirect']['path'] = 'cart';


How do I add a form to the block? I want to add a configuration form for a block. The form's style is the following:

    one year (label)    input text box value    eg:$10
    two years           input text box value
    three years         input text box
    500 accounts        input text box
    1500 accounts       input text box
    2500 accounts       input text box
    image:              can upload an image

How do I do it? I should write a module to get that.

How do I design the table, which is used to store the input box value and image value.
How do I design the fields?
Which hook should I use?

You can use a combination of the Webform module and Views.  Create a node with the form you want using the webform module and you can then create a block with Views for that particular node.


Creating a menu structure based on Content Types Alias I have imported in a bulk of content via a CSV Feed Importer (see Migrating content from older custom CMS). It worked splendidly. I was even able to take in each of the pages old URL and create an path alias for each page. Now I would like to rebuild the menu structure and it would be a certain help if I could create a menu structure based on all of the path aliases.

Is there a module to accomplish this?

I have never seen a module that does that, but you could try Import HTML. More details from the module's project page:

Import an old existing, static HTML site structure into the Drupal CMS as structured nodes!
Allows an admin to define a source directory of an existing traditional static HTML website, and import (as much as possible) the content and structure into a drupal site.
Source files will be stripped of exisiting chrome and navigation elements before being inserted as nodes.

As alternative, I would use the https://www.drupal.org/project/menu_editor module to quickly build out the menu structure of the already imported content.


Filtering referenced nodes where logged in user is a member I am trying to set up a view of referenced nodes (entity reference field) of the current viewed (group)node.
So when a node is viewed i like to filter all the nodes that point to the current node.

Using the node id from url in contextual filter gives no problems.
So far so good.

However i like to only display those referenced nodes where the current logged in user is a member of.

Is this possible using views?

Ok Organic Groups. I got a long way with the following recipe. Unfortunately I could not set up an identical environment to yours.

1 Add a Contextual filter on "OG membership: Group ID".

2 When the filter is not available Provide default value "The OG groups of the logged in user ". Leave the concatenator as "+".

3 Under More check "Allow multiple values"


What is the pattern '' referred to in Drupal speak? Is the pattern  used to denote the front page in Drupal referred to as token or something else? Does it exist in Drupal 8?

According to this Drupal 8 issue queue, <front> is a "special token." Yes, it still works in Drupal 8.

Reading the whole issue queue will give you some insight into the core developers' thought processes as they decided whether or not to support this legacy Drupalism in Drupal 8. They had a lot of good reasons to drop support for it, but they erred on the side of caution and left it in.

You can also try it for yourself in a Drupal 8 site; it definitely still works!

Help text for adding a menu link says:

  Start typing the title of a piece of content to select it. You can also enter an internal path such as /node/add or an external URL such as http://example.com. Enter <front> to link to the front page.

I guess you might want to give more weight to Clive's comments above, since his answer is based on the actual code and comments in Drupal core. Technically, all strings processed by index.php are considered "paths" and the ones that resolve to valid destinations are "routes." (Under the hood, Drupal 8's routing system is based on the routing provided by the Symfony HTTP kernel, and is used to connect paths to controller logic.)


Need help to work with videos and FFMPEG I am building a website that people upload a video and then they can cut a piece of the video. I am using FFMPEG.

I know how to do this using pure PHP, but since my website is based on Drupal, I prefer to use the Drupal modules.

I saw PHP FFmpeg and FFmpeg Wrapper modules that work with FFMPEG.
I would like to know is there any advantage in using these modules or using the pure PHP is preferable? Can these modules save the clipped videos as a node or not?

Thanks in advance.

The only advantage these modules is assistance in managing your dependency on FFMPEG and how you want interface it in PHP code.

PHP FFMPEG is a helper module for managing a dependency on the PHP FFmpeg library. If you want to use the PHP FFmpeg library, and require a Drupal module that will ensure your module has FFMPEG available to it, this module will help.
FFmpeg Wrapper is a handful of custom functions that interface with FFMPEG via PHP's passthru() function. If your PHP environment can execute passthru() and you want some basic functions to execute some ffmpeg console commands, this module will help.

Both are API modules that don't provide any other integration with Drupal.


Allow to login with e-mail As follow up to my previous issue, I think it would be nice to allow email address to be set as username for login. Or at least don't require username field and default it to use email address. This is a use case for Facebook login which allows email address be used as username for login.

When I try to run

{
"name": { "value": "test05@gmail.com" },
"mail": { "value": "test05@gmail.com" }
}

I am getting response

{
    "message": "Unprocessable Entity: validation failed.\nname: The username can not be an email address.\n"
}

My module Login with Email only should solve that:

  This simple Drupal 8 module allows users to log in exclusively with
  their email address from the standard login form.

  Setup:

  Just enable the module.

  Recommended Modules:

  This module is based on the Login Email or Username module:
  https://www.drupal.org/project/login_emailusername


How to create a slideshow of different views? I am trying to create a slideshow of different Views.

I am thinking that the "view field" might work with "views slide show" - possibly sending the "view result counter" through as an argument. I am struggling though as I'm not sure this is a readable contextual filter when it reaches the "view field" view.

Can anyone point me in the right direction? If the "view result counter" is readable, what contextual filter should I add in the "view field" view.

Your current approach will not work because View Fields View will insert the same view for each and every row/slide.

Here is what you need to do. For example: You want 4 slides.
Create a Slideshow View of Articles or something that has 4 or more content. Then set the view results to 4, so it only shows 4.
Now add a Global: View Result Counter and exclude from display.

Add a Global: Custom Text and for text put:
[counter]

In your view preview you should see numbers
1
2
3
4

Now we are going to override these (the custom text), and replace them with views in template.php (located in /sites/all/themes/yourtheme/) add the following code:
function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 1) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_1');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 2) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_2');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 3) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_3');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 4) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_4');
  }
}

replace yourtheme with the actual name of your theme
replace view_slideshow_name with the name of your view slideshow.
replace view_name with the name of the view that you want to show
replace block_1 with the machine name of your view

Lastly, in Drupal, clear/flush your Cache to see the changes.

Note: The changes will show up when you see the slideshow in your page and not in the view preview.

Forgot to mention that you need to uncheck provide/add wrappers and classes.

Also, for both of your fields, do as below

It seems odd that you have to list the block name of the view you want to insert but not the block name of the view you are overriding.

That's because in my case I did not plan to add more blocks or pages to my view. When you do not specify, it affects all pages or blocks that are from your view.
But if you want to be specific here is how:
function bartik_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "rotator" && $view->current_display == 'block_1' && $vars['fields']['nothing']->content == 1) {

    $vars['fields']['nothing']->content = views_embed_view('checking_home', 'block_1');
    }

  else if ($vars['view']->name == "rotator" && $view->current_display == 'block_1' && $vars['fields']['nothing']->content == 2) {

    $vars['fields']['nothing']->content = views_embed_view('home_outstanding_issues', 'block');
    }

}


Portable content types I'm used to leverage Bundle Copy to import/export content types with Drupal 7. One of my expectations with Drupal 8 is that I could theoretically achieve this with CMI. On the Bundle Copy project page it's also mentioned that "Bundle Copy is in Drupal 8 Core CMI!" so it all looks promising.

However, due to UUIDs and CMI's focus being on supporting content staging across multiple instances of a same site, it doesn't seem that obvious to create a generic content type that you would export on N number of sites.

For instance, take a photo gallery content type. Once you've created it and that you're happy with everything, you probably don't want to go through the same hassle again and would likely prefer to simply import the YML files onto the active configuration dir via CMI's single import tab (by manually copying the content of your YML files) or via the Synchronize tab (by making YML files available under the staging dir).

I thus wonder if a) I've missed something and b) if yes, what's your recipe for portable content types, if any?

It should be possible to take most relevant config files (content type, fields, displays, ...), create a module, put them in the config folder of it and install that module on any site you want. Or the same with an install profile, I made some relatively successful* tests there by throwing all config of an actual site into an install profile and was able to install it.

You can also manually edit them, as long as you're not doing in the active storage.

Problematic are for example config files that contain a mix of things. Translation settings for example, which are stored in a single yml file for all entities and bundles, or rest.module settings, all enabled resources are also in a single file. So you would have to write code that manually updates that configuration in hook_install().

* Relatively successful, which means I had some troubles with config that referenced content (custom blocks, default images of image fields) but I think that can be sorted out.


How to wrap a custom content page with HTML tags? I have a mini-panel in which I add custom content panes. I would like to turn these content panes into buttons. I am able to apply some CSS to turn them into a block, by adding a css class via the "CSS properties" option in each pane's settings. But how can I make a link out of them?

There is no option to add HTML around a pane. And I really want the entire pane to be a link, not just the stuff in it. I could artificially insert HTML into the pane to create a link-block that would fill up all the space, but then I'd have to create other CSS properties to apply to this element, it would just be cumbersome.

I'm still on Drupal 6. Any help would be appreciated.

Could you put an  tag inside the pane, and then with CSS give it a width: 100% and height: 100%, effectively filling the mini-pane?

To be specific, your html inside the pane would look like:

This Is A Link

And your CSS would look like:

a.mini-pane-link {
    display:block;
    width: 100%;
    height: 100%;
}

(You might want/need to put a few extra selectors in front of the a.mini-pane-link)


How to show all template suggestions for a page without using Devel Themer? For some reason the Theme developer module doesn't work on my site (whenever i activate it and navigate on my site it just shows a white page with written "Jump to main content"), but all I want to know is which TPL files are being used to render my current page.

I know that if i put print_r($variables["theme_hook_suggestions"]); in preprocess_html or preprocess_page functions (or any other preprocess function for what it matters) I'll be able to see the suggestions for the html.tpl.php and page.tpl.php files respectively, but i actually need to go deeper and see all the template suggestions that are being checked to render the current page.

Is there any way to do this without using the Theme developer module?

You can put this in your settings.php
$conf['theme_debug'] = true;

This outputs html comments on your page which will help you with debugging how the theme suggestions are selected.


Update manually installed modules I have installed Drupal Commerce 2 through composer as mentioned in

https://docs.drupalcommerce.org/commerce2/developer-guide/install-update/installation

after that, I have installed a few modules and a Barrio (Theme) directly through drupal admin interface.

Can I still update them through composer?

I have tried to update with ~/composer.phar update drupal/block_class --with-dependencies, but I am getting the following output.

  DrupalProject\composer\ScriptHandler::checkComposerVersion
  Package "drupal/block_class" listed for update is not installed. Ignoring.
  Loading composer repositor
  Updating dependencies (including require-dev)
  Nothing to install or update
  Generating autoload files
  DrupalProject\composer\ScriptHandler::createRequiredFiles

Can I still update them through composer?

No, Composer can only manage packages that have been installed through Composer.

You could always add it to the "require" section of your existing composer.json (manually or by executing composer require), then Composer will know about it.


Drupal 7 theme for specific page I have one page mortgages/%/view that needs to have it's own custom theme. I have the HTML created and it's ready to go. In my 'mortgage' module I have a mortgage.tpl.php file with this HTML in it.

My hook_menu looks like this:

function mortgage_menu() {

  $items = array();

  $items['mortgage/%/view'] = array(
    'page callback' => 'mortgage_callback',
    'page argument' => array(3), //pass 3rd argument of url -- 1. drupal 2. mortgage 3. %
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
 }

Then my callback function and mortgage_theme function look like this:

function mortgage_callback() {
 return theme('mortgage');
}

 /*
 * Implementation of hook_theme().
 */

function mortgage_theme(){
  return array (
    'mortgage' => array (
      'template' => 'mortgage' ,
      'arguments' => array(),
    ),
  );
}

This successfully calls my mortgage.tpl.php file into my mortgage/%/view page. HOWEVER, it only displays in the middle of my "content" section instead of correctly overriding the theme. Obviously this isn't correct.

How would I get this mortgage.tpl.php file to be THE theme file for this specific page?

e/ Mortgage is NOT a node. It's a custom module which allows users to get a full page view of mortgage details.

In your module

function custom_theme($existing, $type, $theme, $path){
      return array(
        'mortgage_page' =>  array(
          'template' => 'theme/mortgage',
          'render element' => 'page'
        ),
      );
    }

function custom_preprocess_page(&$variables, $hook) {
  if ( preg_match("/mortgage\/.*\/view/", drupal_get_path_alias($_GET['q'])) ) {
   $variables['theme_hook_suggestions'][] = 'mortgage_page';
  }
}

Check for path alias to be correct and change theme_hook_suggestions to your theme.


Why does the count of the Menu badge not decrease after page is viewed? I have created a view, which shows activity logged by Message module.

I then created a menu badge which shows the numbers on the menu item. - In start, when there is no activity, it shows 0, After there is some activity it shows the count, but when the page is viewed the count remains the same and does not decrease or disappear.

When the whole activity page is viewed, the numbers should disappear.

Part 1 - It does seem to work as designed

Since your question is about a "Menu badge", I'm assuming you are using the (great!) Menu Badges module to create such badge, whereas you also created a view (using the Views module).

To make it all work, your view should show the number of rows corresponding to the "activity logged by the Message module" (as in your question).

And the view seems to be OK if there is no activity (it shows "O").
However, if the count remains the same later on, then it must be because the result of your view doesn't change either. If you want that number produced by the Menu Badges module to change, then you must make sure that the view produces the correct number. So if that number doesn't change, it is about sure (not just probably ...) because something in the filter of your view is not correct. Like does your view only select the rows which have some kind of "new activity" indicator? If not, what other filter do you have to make that number decrease?

So IMO this is not a bug in the module, but rather just a customization error in your view (head over to Part 2 for more details on that).

Part 2 - What you're missing in your view

I think Part 1 of my answer is "the" answer to your question, but here is an attempt to also, partially, answer your additional comment (which is really a new question I think):

  If there is new activity, the number does increase, but do not decrease or disappear as in case of private messages. What I have understood so far of menu badges is that you have to put something in the fields section and turn on aggregation so that it knows what to count. Currently I am using Message:Message ID in the field. What filter I should use?

Not sure where the "private messages" refers to (I'm just going to consider that as "a" type of messages). But you're right about that "you have to put something in the fields section and turn on aggregation so that it knows what to count": that is the "clue" about what the Menu Badges is all about. Let's consider the Message View (where the below screenprints originate from) that comes with the Message module, i.e.:

Here is a screenprint with the design details of that view:

If you'd use the Add button for "fields", and then filter the available fields for "Message:", you would only get these fields:

Language
Message ID
Render message (Get text)
Rendered Message
Timestamp
Type
User uid

Obviously, none of these fields contain any information if it is yes or no a "new" message. So that's what you're missing and why out-of-the(-message)-box you cannot get this to work. To better explain this (what you're missing): have a look at the "tracker" view (disabled by default), which has the fields "Content:Has new content" and  "Content:Has new comments". Those are 2 perfect fields to use if you want to use Menu Badges to get notified whenever there is new content, or new comments.

A possible compromise, and maybe partial solution for your scenario could be that you'd use the Timestamp field as your filter. E.g. if you'd filter it like "only the ones from the last 24 hours", that should have some effect.

Part 3 - How to get it to work anyway

There is a way to get this to work anyway ... Because messages are fieldable. So simply (hm, hm) add a boolean field like "Message is new" (Yes/No). It'll then also show up in the list of fields you can select from in your view (in the list of available fields as in Part 2). And with that you have a perfect solution for what you're trying to get to work.

However, there is one more challenge left: add appropriate logic to maintain the value of that boolean field. If you wonder how to do that (also), just ask a new question.


Menu links not working in Ubuntu (D7) I had a site in Windows installed inside xampp.  I copied the same site's folder and database from windows-xampp installation to Ubuntu's www folder (Lamp) . The menu links are not working now. localhost/sitename directs to the homepage . But when I click on any menu items , it says

  The requested URL /sitename/latest/11 was not found on this server.

I could not figure out if this is problem of localhost or menu or database?

I can't even login because users/login is also not working.

Any suggestion or any links to the articles that I should read to solve this problem  would be great. Thank you .

My suspicion is that Drupal's .htaccess URL rewrite directives have been disallowed in your Ubuntu installation of Apache. If it were a bootstrap or database connection problem, you would not be able to see the front page either.

Ordinarily, Drupal prevents Clean URLs from being activated if not supported by the server. In this scenario, of course, that test was done in the Windows installation. Ensuring rewriting support in the target server is at the top of the migration checklist.

The quickest way to see if Clean URLs is the culprit is to try browsing to localhost/sitename/index.php?q=user/login ; if that page does come up, you will need to enable rewriting in your web server.

See http://drupal.org/node/1186762#comment-5424052 for some instructions on checking your Apache configuration to make sure it allows Drupal to rewrite URLs in its .htaccess file.

If you can confirm that the .htaccess file is being read, rewrite directives have been allowed in Drupal's installation directory, and that mod_rewrite is active, and still see problems, I would check next for a corrupted menu table.


Activate menu item with preprocess_page function Hi my international friends!

I work in Drupal 7.38.

If the current page belongs to a specific content type, I want to activate a specific menu item.
By to activate a specific menu item I mean that this menu item has the class active.

I try to do this with preprocess_page() function within template.php. It does not work :(.

Here is the code.

function MY_THEME_preprocess_page(&$vars) {
  if( !empty($vars['node']) ) {
    switch ( $vars['node']->type ) {
      case 'machine_name_my_content_type':
        menu_tree_set_path('machine_name_menu','path_menu_item');
        break;
      default:
        menu_tree_set_path('machine_name_menu','path_menu_item');
    }
  }
}

I have also tried a variation. Instead of putting:

menu_tree_set_path ('machine_name_menu' 'path_menu_item')

I put menu_set_active_item ('path_menu_item')

Nothing works!

Can you help me. Thanks in advance.

I would suggest looking at the Menu position module


Unlimited TextFields with Form API I'm creating a Block Plugin with a form. I'm able to create the standard form with various input field types. Like so.

    $form['text_field_1'] = array(
        '#type'          => 'textfield',
        '#title'         => $this->t('Entry 1'),
        '#default_value' => $this->configuration['text_field_1_submit'],
        '#size'          => 60,
        '#maxlength'     => 10,
    );

    $form['text_field_2'] = array(
        '#type'          => 'textfield',
        '#title'         => $this->t('Entry 2'),
        '#default_value' => $this->configuration['text_field_2_submit'],
        '#size'          => 60,
        '#maxlength'     => 10,
    );

This works but I can't anticipate how many entries the user may need, so I'd like users to be able to add multiple field entries in the same way that you can in a content type field.

Is this possible?

This is not a form API level feature, it's field/widget API.

For a custom form, you have to build it yourself with an add more button that uses #ajax to add more elements. A full code example would be too complicated for an answer, but you have to keep track of the count in $form_state, on pressing of the button increaes it, rebuild the form and then return the new elements.

See https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.2.x for more documentation, a quick tutorial that I found: https://www.sitepoint.com/using-ajax-forms-drupal-8/


How to generate block with Views, Entity Reference and Taxonomy Terms I have a site with content types: book-page & ride.

These are organized so that each book-page displays several rides (using Entity Reference), and each ride is tagged with several taxonomy terms.

I'd like to create a block which displays links to other pages whose rides share a taxonomy term with any of the rides on the current page.

Looking at the table structure I can see that the following query will yield the desired results (for node id 9).

SELECT DISTINCT your_page.title
FROM node my_page
INNER JOIN field_data_field_rides my_page_rides ON my_page.nid = my_page_rides.entity_id
INNER JOIN node my_ride ON my_page_rides.field_rides_target_id = my_ride.nid
INNER JOIN taxonomy_index my_ride_terms ON my_ride.nid = my_ride_terms.nid
INNER JOIN taxonomy_term_data my_term ON my_ride_terms.tid = my_term.tid
LEFT JOIN taxonomy_index your_ride_terms ON my_term.tid = your_ride_terms.tid
INNER JOIN node your_ride ON your_ride.nid = your_ride_terms.nid
INNER JOIN field_data_field_rides your_page_rides ON your_page_rides.field_rides_target_id = your_ride.nid
INNER JOIN node your_page ON your_page.nid = your_page_rides.entity_id
WHERE my_term.vid = 2
  AND my_page.nid = 9
  AND (your_page.nid IS NOT NULL AND your_page.nid != my_page.nid)
  AND your_page.status = '1'
  AND your_page.type IN ('book')
  AND your_page_rides.entity_type = 'node'
  AND your_page_rides.deleted = '0'

My question is - can the same thing be done through the Views UI using a Relation?

I'm using D7 with Views 3.

Many thanks to @flocondetoile for responding, but I think the problem I posed was a join too far for Views. That is, whereas @flocondetoile needed to join:

parent-node -> child-node -> parent-node

I needed to join:

parent-node -> child-node -> taxonomy-term -> child-node -> parent-node

Try as I might I could find no way to do this directly in the Views UI. I did though find an elegant solution which I share here in case anyone else finds it useful.

Step 1

Save your query as a database view, i.e.,

CREATE VIEW view_name AS ...

Step 2

Describe your database view (or table) to the Views module. This is done by implementing hook_views_data (you can find the Views version in node.views.inc). It's a big method, but not too scary. In effect you just build up an array of meta-information about your database view. I based mine fairly closely on the code in node.views.inc. This step is described in some detail on this blog page, which also includes a worked example. Be sure to check out the slides linked at the bottom of the page.

Step 3

Views will now know about your custom database view/table. You can query it directly.


When using the StringTranslationTrait in a service why should you inject the 'string_translation' service aswell? I was reading the code comments in the StringTranslationTrait trait and saw the following:

  If the class is capable of injecting services from the container, it
  should inject the 'string_translation' service and assign it to
  $this->stringTranslation.

So I created a simple service, used the StringTranslationTrait, injected the string_translation service and assigned it to $this->stringTranslation. I found that when I don't inject the string_translation service the $this->t() function still works as I expected.

Why should one inject said service into his own service? Is it good practice or are there other benefits such as speed? The comments in the StringTranslationTrait file offer no explanation.

My service for completeness:

<?php

namespace Drupal\wow\Service;

use Drupal\Core\Url;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Class RedirectService.
 *
 * @package Drupal\wow\Service
 */
class RedirectService {

  use StringTranslationTrait;

  /**
   * The redirect object.
   *
   * @var \Symfony\Component\HttpFoundation\RedirectResponse
   */
  private $redirectResponse;

  /**
   * RedirectService constructor.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $stringTranslation
   *   The string translation service.
   */
  public function __construct(TranslationInterface $stringTranslation) {
    $this->stringTranslation = $stringTranslation;
  }

  /**
   * Sets the redirect.
   *
   * @param string $routeName
   *   Drupal route name to redirect to.
   * @param string $message
   *   Message to show after redirecting. If not provided no message will be
   *   shown.
   * @param string $messageType
   *   Message type of message shown after redirecting.
   */
  public function setRedirect($routeName, $message = NULL, $messageType = 'status') {
    $uri = Url::fromRoute($routeName);

    if ($message) {
      drupal_set_message($this->t($message), $messageType);
    }

    $this->redirectResponse = new RedirectResponse($uri->toString());
  }

  /**
   * Gets the redirect object.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   The redirect object.
   */
  public function getRedirect() {
    return $this->redirectResponse;
  }

  /**
   * Returns the response object.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response object.
   */
  public function send() {
    return $this->redirectResponse->send();
  }

}

If you didn't inject the string translation service into $this->stringTranslation, the trait would get it from the static \Drupal wrapper

  /**
   * Gets the string translation service.
   *
   * @return \Drupal\Core\StringTranslation\TranslationInterface
   *   The string translation service.
   */
  protected function getStringTranslation() {
    if (!$this->stringTranslation) {
      $this->stringTranslation = \Drupal::service('string_translation');
    }

    return $this->stringTranslation;
  }

and this should be avoided in OOP code. The main reason for this is to be able to inject mock-up services for code tests.


Conflict between Corolla and Panels? Wanting to use a mobile savvy html5 theme, I currently chose Adaptive Themes "Corolla", however I have noticed over the past 3-4 days that when I now attempt to add any content to Panel, the Panel interface just hangs and shows the blue 'timer' graphic and goes no where even after 10 minutes. If I revert back to say Bartik and or standard theme it works as expected. Since I'm 'upskilling' with a view to future employment, I would like to know what causes such issues now of for future reference, what is is hanging on for?

Of course, cosmetically Corolla can be changed for a custom HTML5 theme, but an answer would be helpful. I'm running a webdev Ubuntu LAMP stack on a home webdev box using pure apache so no wamp/xammp etc. The webdev box emulates a live production server for future commercial projects.

The module versions are:

cTools: 7.X.1.0 alpha#1 (doesn't matter if it is later).
Panels: 7.x.3.0 Alpha#2
Views: 7.x.3.0 alpha#1

I have tried a number of the above versions and I have multiple D7 projects on my LAMP box, and it makes no difference so I have concluded it is Corolla, even with the latest strain. I have no desire to go down to Drupal v6.
Thank you.

Paul B.

I'm running Pixture Reloaded, another Adaptivetheme and I use Panels for nearly everything on my site and have experienced no such problems.

I have used both the 2.x and 3.x series with no incidents.

I doubt your problem is Corolla; from your post, it is clear you are still running alpha versions of Panels and Views.  These modules have had stable and security releases for D7-- Views is now version 3.3.  You really need to keep your modules up-to-date when there are security releases

Update all your modules to the latest versions (or at least Ctools, Views, and Panels), run update.php, and then do this:

Enable Corolla.
Clear the cache twice.
Go to the Corolla theme settings page.
Click save.  (It doesn't matter if you make any changes.)
Clear the cache twice again.

This will ensure that all the files that are automatically generated by Corolla have been rebuilt properly and should fix the problem.


how to add menu item from tags? I am new in Drupal,
and I am creating  a library the library has subject, each subject select from a list that referenced to a taxonomy.

  I want each subject become an item in my menu and when click on it
  show that tag result.

I'll post my comment here as an answer also so this question can be closed.

If you want a taxonomy vocabulary and it's terms to be represented in a menu you can use the module Taxonomy menu. It synchronizes changes in your taxonomy tree to a menu of your choice.

  Transforms your taxonomy vocabularies into menus with ease!


Both language menus show up Currently I'm working on a 6-language website and all content obviously needs to be translated, including menus. For this, I have enabled i18n_menu and i18n_select (as I had a little experience on the latter regarding this issue), translated the originally French node to English, and both menu items show up when I go to English translation of the node. Any ideas?

There are several discussions on drupal.SO about this, including this  and this one on drupal.org; but none seemed to resolve my issue.

I suppose you added the french menu item before you added additional languages to your Drupal. Then it is very likely that it was saved using LANGUAGE_NEUTRAL as language and therefore will appear within all languages.

To fix this, go to the menu's item list on admin/structure and manually edit the menu item. You should find a drop down for the language within the edit form. Make sure to choose the appropriate language here and save the item.


How to create custom field in ubercart 3.x checkout page? I want to customize checkout page and remove/add some fields from client information.
How can I do it?

I found the Extra Fields Checkout Pane module.

  This module allows an administrator to define additional (billing and shipping) address fields as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.
  This module has been developed and tested with Ubercart 2.6.


use multi level/chain of entity reference fields to create a list of nodes using views I have 3 content types: Outline, Chapter and notes.

Chapter and Notes have 2 entity reference fields chap_outline_reference and note_outline_reference respectively referring to outline.
On the chapter nodes i want to populate a jump menu of all the notes referring to the same outline as the chapter.
I'm using Views 7.x-3.13 and Drupal 7.41.

I created a block view using the following relationship:

Entity Reference: Referencing entity ( for chap_outline_reference)

Entity Reference: Referenced Entity ( for note_outline_reference) and i'm using the above relationship in this relationship.

I am unable to figure out the contextual filter.
I tried using Content:nid with either of the above relations, but that didn't work.

Any help would be highly appreciated. Thank You.

For everybody stuck in a similar situation and not having advanced knowledge; this is how I solved it:
I broke the problem into 2 views and used "view field view" module to connect the 2 views.

In the first view; i used a relationship(entity referencing) and contextual filter(Content:nid) to reach the nid of the outline from the chapter nid.

In the second view; i used a relationship(entity referenced) and contextual filter(Content:nid) to reach the nid of the notes from the outline nid.

Using the Global: view field (from view field view) module I substituted the Outline nid for the contextual filter (Content:nid) in the second view.


Views Page Not Appearing in Search Results Using the views module, I've created a page (view) that contains a certain content type. This page doesn't show up when searching the site.

Is this expected behavior? Is there any way to make the page show up in a search?

Instead of creating a page view, I've created a block view and added it to an actual page (content). This works in my particular case and allows the site to index the page to show up in a search. It may not be fancy but I don't have to add a module to make it happen.

Thanks to user cilefen who answered my questions and got me here.

To answer the first of two questions: Yes, this is the expected behavior. Views pages are not indexed by Drupal core search.

For the second, Drupal core search is limited. More is possible by using Apache Solr search integration.
According to https://www.drupal.org/node/2570521, https://www.drupal.org/project/apachesolr_nan is an example of a module that may do what you need. But you would need access to a Solr server.


Services user/login and system/connect I would like to know the difference between user/login and system/connect.

system/connect

  Returns the details of currently logged in user.

user/login

  Login a user for a new session

To login a user you will use user/login service call... Once user is logged in if you would like to pull logged in user details you will use system/connect service.. You can see above details in services module help section


How do I create a administration page (with overlay) through the UI I would like to add an administration page (with overlay) to my site (not programatically). I assume the basic process is:

Create a 'basic page'
Set the path to /admin
Set permissions <-- How do I do this???  I can't see how do I
restrict the page??
Configure overlay - Is it automatic?
Add page to admin menu.

I'm stuck on 3, but I could probably use help on 4 and 5.

Thanks!

You're probably looking for the Overlay Paths module:

  This is a simple module that enables site builders to use the built-in Overlay for non-admin pages.

However, if the path you've got for the node is under /admin I'm pretty sure that if you configure permissions properly you won't need that module; the overlay should pop up automatically. You'll need to give your users the "Use the administration pages and help" permission, as well as the one to actually use the overlay.

As it's a node, whatever node access solution you have in place will determine the access beyond those two permissions.


What data type to use for Commerce price field in a rule with a Views Loop (Views Rules)? I want to create duplicates of some Commerce Products with the goal of giving these products a new Product type. With great help (How to change the product type of selected Drupal Commerce products (without direct DB updates)?), I have managed to use the Views Rules module to create a Views loop that should iterate through a selection of Commerce Products and duplicating them (creating new entities) with the new product type.

All fields except one accept the data type "Text", and the variables created looks like [sku:value], [title:value] and so forth.

The problem is that I keep getting PHP errors like this:

  Unable to create entity commerce_product": Invalid data value given.
  Be sure it matches the required data type and format. Value at
  commerce_product()->commerce_price: .

... telling me that the data format for the Commerce price field is wrong though. I have tried using "text" as data type (and also "Price", "Commerce product" etc.).

Whatever I do in the action part of the Views loop, I keep getting a numeric field for the price (I can't just paste [price:value] in the field). I can switch to "Data Selection input mode", and add something like commerce-price:base-price (if I use Price as data type for the price field in the variable settings for the Rules View in question) but that also ends with a PHP error like I described above.

What to do with the variable for the commerce price here?

EDIT: this is the price field I get in the Action part of the Views loop, no matter what data type I assign to the price field in the Rules View, including Integer (in the variables configuration). I have also tried to add an action that converts the price into an integer jag before the action that creates the new entity. If I switch to Data Selection there are no price fields to be found.

And if I toggle to Data Selection mode this is what I get. No price field can be selected.

It really seems impossible to use the price field in a views loop.

Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

  The price field is and will continue to store price amounts as integers ...

So give it a try to use "integer" for your Commerce price field. If needed, also use a Rules Action like "convert the data type" (of that price field) to convert your actual input to an integer.


Theming a custom form I have themed Drupal7 forms, cannot do the same with 6 ...

I have:

function _my_form() {
    $output="";
    $form=drupal_get_form("my_form");
    $output=theme("my_form",
        array(
            "element"=>array(
                "my_form"=>$form
            )
        )
    );

    return $output;

}

function MYMODULE_theme()
{
    $themes = array(
        'MY_form' => array(
            'template'=>'my_form',
            'variables' => array('element' => NULL)
        )
    );
    return $themes;
}

If i do a var_dump($element["my_form"]) in my_form.tpl.php i only get a superlong string with the html form already rendered, while i expected to have an array with all the single form fields... what am i doing wrong?

i think you should return a  render array in your theme function
  array('render element' => 'form')


Hiding group_group field programmatically I am trying to hide the group_group (request membership) field for organic groups based on a radio button. Here is what I have done that doesn't work:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $menu = menu_get_item();
  $path = drupal_get_path_alias();

  $node = node_load($menu['page_arguments'][0]->nid);

  // field_show_group_group is radio button
  if($item['field_show_group_group'][LANGUAGE_NONE]['value'] === 0) {
    dsm("Just show the subscribe button - NOTHING to do.");
  }
  else {

    dsm("hide button");
    $instance = field_info_instance('node', 'group_group', 'community');
    $instance['widget']['settings']['og_hide'] = FALSE;
    $instance['settings']['behaviors']['og_widget']['access_override'] = FALSE;
    unset($instance['widget']['settings']['og_hide']);
    unset($instance['settings']['behaviors']['og_widget']['access_override']);
    $form['group_group']['#access'] = FALSE;
    $form['group_group'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    unset($form['group_group']);
    unset($form['group_group']);
    $menu['page_arguments'][0]->group_group['und'][0]['value'] = 0;
    unset($menu['page_arguments'][0]);
    $item['group_group'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    unset($item['group_group'][LANGUAGE_NONE][0]['value']['#access']);
    $node->group_group[LANGUAGE_NONE][0]['value']['#access'] = FALSE;

}

These are all possibilities I couldn't think of, which of course for some reason don't work. I searched the whole internet for this including drupal.org, drupal.stackexchange, google and stackoverflow. Can you help?

You should be able to hide the group_group field with the $form['group_group']['#access'] = FALSE; this is used by the Hide checkbox on the field settings page and this is how it works.

However, if you testing as an anonymous user maybe you have this issue: https://www.drupal.org/project/og/issues/2278003 there's a patch which fixes the access itself.


Get path alias from NID (or node object) I have a node object, and I am trying to use it to get a given path in Drupal 8.

There was drupal_lookup_path() in Drupal 7 but I'm not seeing any equivalent or documentation for Drupal 8.

What's the new "Drupal" way to get a path from a node object?

Would it be something simple like $node->get('path')?

This seems like a simple question, but I'm just absolutely not finding any documentation on it.

Notice I do not want the path alias for the current path; I want the path alias for an arbitrary node, given a node object or a node ID.

To get the path for a node id use AliasManager::getAliasByPath:
Drupal 8
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);

As per the new change record in Drupal 8.8.0 and above path.alias_manager is deprecated and path_alias.manager is introduced.
New syntax is as follows :
$url_alias = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid, $langcode);


Alter element_info and troubleshoot changed elements Ubercart defines the following uc_price type in uc_store_element_info:

$types['uc_price'] = array(
  '#input' => TRUE,
  '#size' => 15,
  '#maxlength' => 15,
  '#autocomplete_path' => FALSE,
  '#process' => array('ajax_process_form'),
  '#element_validate' => array('uc_store_validate_number'),
  '#theme' => 'textfield',
  '#theme_wrappers' => array('form_element'),
  '#field_prefix' => $sign_flag ? '' : $currency_sign,
  '#field_suffix' => $sign_flag ? $currency_sign : '',
  '#allow_negative' => FALSE,
  '#empty_zero' => TRUE,
);

Assume I want to allow negative prices by setting #allow_negative to TRUE. (Maybe this is a bad idea, but play along.) Maybe I will need to replace the #element_validate array with a custom function as well.

From reading the API documentation here: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_element_info_alter/7.x it looks as if making a custom module and implementing hook_element_info_alter should let me do this. I made a module called customcode and implemented the following function:

function customcode_element_info_alter(&$type) {
  drupal_set_message('Altering uc_price');
  if (isset($type['uc_price'])) {
    $type['uc_price']['#allow_negative'] = TRUE;
  }
} /* end hook_element_info_alter */

but this does not work. Maybe this does not work for obvious reasons but I am pretty confused, and web searching (on this site and elsewhere) is not clearing up my confusion. I could easily believe I am specifying the array element incorrectly, but without troubleshooting information it's difficult to figure out what is going on.

Here are some questions:

How do I see the value of the $type array? When troubleshooting other forms I have used print_var or dpm, but those do not do anything here. I do not understand at what point this code is executed and how to display output from it. The drupal_set_message displays nothing.
Is hook_element_info_alter the way I want to modify this element? If not, what approach should I take? I obviously do not want to hack the Ubercart module unless there is no other choice.
If so, is creating the function with the name I have chosen (customcode_element_info_alter) correct? When I use hook_form_alter I need to include the original form ID in the name. I do not understand how this hook knows enough to alter the data in uc_store_element_info.

Thanks for any help you can offer.

The underlying problem was caching. I thought I had cleared cache, but apparently not.

Here are answers to my questions:

As suggested above, use watchdog() to see the value of the $type array. Here is a (probably dangerous) snippet:

watchdog('customcode', 'uc_price after mod: <pre>'.
print_r($type['uc_price'], TRUE) . '</pre>');

hook_element_info_alter is how I want to modify the element, and the function should replace hook with the name of the custom module.

It looks as if all hook_element_info_alter hooks are called after all type elements are defined somehow, but I am still fuzzy on this.

I am not certain when hook_element_info_alter is called, but it appears to be called early (there is no need to visit the form in question) and it appears to be cached for a long time.

My strategy of setting #allow_negative to TRUE was in fact the right approach, because the validation function uc_store_validate_number takes this into account. Otherwise I would have had to unset the validation function and replace it with a custom one.


Migrate Entity Validation I am trying to migrate some data with the migrate api in a custom entity called Seller.

Each seller has an email address with a constraint "UniqueField" which checks, that the email address is just entered once. If i try to import a seller with an existing email address, the seller will be created although the email already exists.

So my question is: Doesn't the migration api consider the entity validation or how can I do this?

One solution for the problem would be to write a custom process plugin for the email address, but it would be nice, if the entity validation would check this automatically.

There is an open core issue to add validation to content entities: https://www.drupal.org/node/2745797

With that patch, you can enable validation thusly:

destination:
  plugin: entity:node
  validate: true


How do I assign a new role to all the existing accounts on the site? I have more than 300 users in my site. I want to assigned them a new role I just created.

How do I achieve this?

One option would be to do it via the GUI (admin/people) where you can select all the shown users with the uppermost checkbox and then under 'update options' add the role you want. If it's a one time thing for ~300 users then this is probably the quickest way to handle it.

For a programmatic approach the user_multiple_role_edit() function can be used. You need to pass the user id-s as an array, the operation and role id to the function and it'll do the rest for you. You can get the role id by checking the edit link of the wanted role via the GUI (admin/people/permissions/roles).

To get all the user id-s and assign them the role you could use the following example (modify where needed):

$result = db_query('SELECT uid FROM {users}');
$uids = array();
foreach ($result as $record) {
  if ($record->uid == 0) continue;
  $uids[] = $record->uid;
}
user_multiple_role_edit($uids, 'add_role', 4);


How to resolve my timeout during import of my Drupal database using phpMyAdmin? I downloaded my Drupal database (in MySQL format, and using phpMyAdmin) from my new web site. I am attempting to import it using phpMyAdmin on my local Win 7 computer running Acquia Dev Desktop. It generates a script timout on Drupal table cache_menu with 31 rows imported.

I started the import again. This time the row count in cache_menu is 62. I've been doing this for hours! The row count goes from 31, 62, 93, 124, 155, 186, ... about 30 rows each time. The odd thing is that only 66 rows exist in cache_menu on bluehost.

Here are the versions of software involved:

Bluehost mysql version 5.5.42-37.1-log InnoDB
Acquia mysql version 5.5.42-37.1 InnoDB

Bluehost phpmyadmin version 3.5.8.2
Acquia phpmyadmin version 4.3.7

I tried the suggestions as described in "Maximum execution Time in PhpMyAdmin". Unfortunately, these suggestions resulted in Internal Server Error.

Any idea what's going on?

Skip processing rows in cache tables
For any of the cache-tables, there is no need to actually import them in your dev environment. So it is OK to just skip those rows during your import. That might help to get around this issue. FYI: clearing the cache in the site where you are exporting from, before performing the export is another way to avoid such rows being imported (might help also).
Use module Backup and Migrate
Another possible work around, you may want to consider using the Backup and Migrate module. Here is a quote from its project page:

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

Refer to the readme.txt that comes with the module for details to get you going.
Your local environment is Win 7, though your hosted website probably runs in "some other OS" (Linux? Something else? consider clarifying in your question also ...). So that implies potential extra challenges (because of differences in the OS-es. I've had good experiences with Backup and Migrate between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.


How to get view pager url in node page? How to get pager url in node page ,actually what i want i am creating a view block with listing of nodes with ajax in view exposed filter,because exposed filter doesnt work without ajax,the problem i am facing when i am clicking pagination of view url is not creating like /system-manager/central-ordering/?page=1 .

Also used quick tabs where i am showing view as block in tab.

What i want when user click on the node in view page to see the node content ,i am placing there back button but on clicking back button everytime its going to pager 1(/system-manager/central-ordering) ,not on the same pager from where its clicked(/system-manager/central-ordering?page=3) .

Is it possible to add pagination in view url argument with ajax?

If your intent is showing node content by clicking on node title or similar, you can use the Views Reference Filter filter instead of the Exposed filter. It basically filters one View display with another display. You create one display with a list of node titles, another view display showing node content and add the special filter to the second display. This makes for a very nice user interface for instant filtering.

You can use this answer to a similar case to compare and follow steps: Filter a view by clicking on a link on another view


Twig debug statements not appearing Still new to Drupal, but I've read over the docs countless times and can't figure this out.  I'm not seeing Twig's debug comments. I am using a sub-theme of 'Bootstrap 3'. Running on local environment in Windows (XAMPP).

In /sites/default/services.yml

debug: true
auto_reload: true
cache: false

I've cleared the cache more times than I can count.  I've also tried, unsuccessfully, making various changes to settings.php as well, however since these changes aren't in the docs I'm guessing they shouldn't be required for enabling debug statements.

go to sites/default/services.yml

and write in the proper indentation with spaces as below..

parameters:
  twig.config:
    debug : true
    auto_reload: true
    cache: false

*remember to follow the same structure as above

If not working clear cache from back-office :
http://your-drupal.com/admin/config/development/performance


How to hide a field in a comment in hook_comment_view programatically? My comments have a field called 'Extra'. I'm trying to hide it when the user who's viewing the comment wrote it. This is my custom module:

function mymodule_comment_view($comment) {
  global $user;
  if ($comment->uid == $user->uid){
    unset ($comment->field_extra);
  }
}

Why isn't this working and what's the correct way to achieve my goal?

hook_comment_view(), along with most of the other entity view hooks, are typically used to add properties onto the entity object.

If you read the source for comment_build_comment(), $comment->content[] has already been built up by the time the view hook gets invoked.  So, messing with the field directly has no effect at this point.

You want to implement a template_process_comment() in your theme, or you can implement a module (which technically makes it an instance of hook_preprocess_comment().

Implement this, and then dpm($variables) inside it.  Figure out what you don't want, and then unset() it.  If the variable is printed directly from the comments template, this is is directly in $variables.  If it is in the content section, then unset the proper key in $variables['content'], which is a render tree.


Drupal 8 settings.yml file doesn't reflect changes So I'm trying to define some additional values in my settings.yml file, but none of my changes are reflected in the code. The config object has the same values in it. I've tried drush cr and other measures to clear the cache, but nothing works.

yml files are just imported on module install time.

If you need runtime changes, during development, have a look at
https://www.drupal.org/project/config_devel


Loading default image from a node field in page.html.twig I want to print the default image of a node field into the page.html.twig template file in Drupal 8. On doing my research the easiest approach I could find was

{% if node.field_image.entity %}

{% endif %}

This works if I load an image in the field but not otherwise with the default image of the image field. I want to use the above code to print the default image that I pick for this image field. Currently the above method gives  for the default image

How can I access the uri value of the default image in the src of the image tag above. Is there any other way to print the default image of a node in the page.htm.twig preferably from within the template layer as I don't have any experience with preprocess functions etc.? My objective is to have a static image which is the same throughout the content type.

Here's one approach, using a helper method. It assumes you have access to the loaded node entity ($entity), and would like to get either the set, or default image for a given image field. I've also left comments and links that explain why Drupal::service('entity.repository') is being used, and how I discovered the way in which the Image module loads the default image settings.

    /**
 * Get the set or default image uri for a file image field (if either
 * exist).
 * @param $entity
 * @param $fieldName
 * @return null|string
 */
function get_image_uri($entity, $fieldName) {
  $image_uri = NULL;
  if( $entity->hasField($fieldName) ) {
    try {
      $field = $entity->{$fieldName}; //Try loading from field values first.
      if ($field && $field->target_id) {
        $file = File::load($field->target_id);
        if ($file) {
          $image_uri = $file->getFileUri();
        }
      }
    } catch (\Exception $e) {
      \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
    }

    // If a set value above wasn't found, try the default image.
    if (is_null($image_uri)) {
      try {
        $field = $entity->get($fieldName); // Loading from field definition
        if ($field) {
          // From the image module /core/modules/image/ImageFormatterBase.php
          // $default_image = $test->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
          $default_image = $field->getSetting('default_image');
          if ($default_image && $default_image['uuid']) {
            // $defaultImageFile = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']));
            // See https://www.drupal.org/node/2549139  entityManager is deprecated.
            // Use entity.repository instead.
            $entityrepository = Drupal::service('entity.repository');
            $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
            if($defaultImageFile) {
              $image_uri = $defaultImageFile->getFileUri();
            }
          }
        }
      } catch (\Exception $e) {
        \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
      }
    }
  }

  return $image_uri;
}


Unable to create a view of type solr search I have installed the apachesolr , views and apachesolr_views modules but I am unable to create a view of type solr search.
Is there something i am missing? Because the apachesolr_views provides views integration of apachesolr.

Any Help?

Steps:

Install the modules that you have mentioned
Install and configure Apache Solr in your server
Configure Apache Solr server in the apachesolr module settings
Add a view. Select Apache Solr localhost server (or the name that you have given to your Apache Solr server configuration in apachesolr settings) in the Show dropdown menu when creating the view.

Steps for installing and configuring Solr:

Download the .zip file from http://lucene.apache.org/solr/ (you might want to try with version 3, although it has worked for me with 4
Unzip in a folder in your machine
Copy all the contents from sites/all/modules/apachesolr/solr-config/solr-3.x/ to apache-solr/example/solr/conf/ in the folder you created in step 2
Start the server with running java -jar start.jar

Check in the admin section of your Drupal site if the server is found and working.


add value to shipping service I am using flat rate shipping service and I want to add a value to shipping service price, I know drupal commerce  has a rule for this job, Add an amount to the unit price , but when I want to complete it  I don't know what is should enter in  Line item section ?

I try below one by one

commerce-order:commerce-line-items:0
commerce-order:commerce-line-items:1
commerce-order:commerce-line-items:2
commerce-order:commerce-line-items:3
commerce-order:commerce-line-items:4

but no one work. exactly what this mean, I want add value to only line item that is shipping type, I search google but didn't get any example or something similar this.

appreciate any lead an suggestion about what I should enter in line item ?

You are editing the component rule for the flat rate. Instead, you'll want to create a shipping pricing rule.

http://youtu.be/trLydGpimD4?t=10m7s

In that video, I show you how to set up a shipping pricing rule that only runs on a particular flat rate service ... I've linked for you to jump to the part of the video that walks you through that.

The two conditions you're looking to add:

Entity has field (it should have the shipping service field)
Data Comparison (the shipping service field should equal whatever flat rate you want to tweak)

Josh


Frontpage is a menu item...title won't change When I access site via / or /fp, I always get 'Home', this only happens for the home page...How can I change the title?

$items['fp'] = array(
    'title' => 'Front Page',
    'page callback' => 'rocdocs_main_view',
    'access arguments' => array('access content'),
    'title callback' => 'rocdocs_main_view_title',
    'type' => MENU_CALLBACK
);

function rocdocs_main_view_title()
{
    return 'THIS IS A TEST';
}

Just deactivate the predefined menu link and add a new one - use

<front>

as path.

In Drupal 7 and 8 go to

Home > Administration > Structure > Menus > Main menu > Add link

Drupal 7

See tooltip for details (using Rubik Theme)


How to use multiple styles for Nice Menus? I'm having two Nice Menus, both are displayed in my website's top bar. I created a default CSS layout for them and everything looks quite nice. However, I'd now like to change the layout of the second menu's parent a bit.

How can I set up this alternative style?

Each Nice Menu can be addressed in CSS using its name. For example I have a Nice Menu called "Product Menu" and by looking at the html of my page I can see that my menu has the following classes

nice-menu
nice-menu-right
nice-menu-menu-product-menu
etc..

You can use the nice-menu class for all Nice Menus, the nice-menu-right class is the type of menu it is set as (Right, Left, etc.). You can also customize each menu individually by addressing it in CSS using the nice-menu-menu-MENU-NAME