Views: Combine Fields Filter "OR"? How do I combine two fields using the Views Global: Combine Fields Filter using an "Or" statement? For example, if my  filter combines Field A and Field B and my content is has Field A->Option A, Field B-> option C, it would show up when my filter is set to A OR C.

Desired results:

Field A
 - Option A
 - Option B
 - Option C

Field B
 - Option A
 - Option B
 - Option C

Combined Filter select Menu: Option A
 Expected result, content shows.

The default behavior seems to require that value is present in both field not either.

This was accomplished using Operator "CONTAINS" vs default "IS EQUAL TO"

I set a custom group and inputted values manually and had the operator set to contains, so for example if I select "Option A" in my filter and piece of content with either field a or field b with "option a" selected would show up.


How to get real thumbnails (not onthefly scaled down large originals) in grid from media gallery depending on certain tag using views I would like to use Views to display, in a block, real thumbnails of images uploaded using tools based on the Drupal 7 Media Gallery module in a grid of images with a certain tag.

By real thumbnails, I mean either cropped small images of the original or the entire original reduced in size. This kind of thumbnail is efficient at loading. I do not want thumbnails which are simply the browser's on-the-fly scaling down of the original.

I worked it out: here's my solution: http://groups.drupal.org/node/183909 credit to Drupal Gardeners Moderator Staff @mstef, @Jeannie.Finks, @Sara.Roy @mongolito404 (on groups.drupal.org/media ) for providing the basis and hints.


Minimizing the time taken for entity_load while using for apachesolr indexing I am working on a site with a specific node type that has close to 50 fields, most of which are taxonomy term references, a couple of node references and a few conventional text and integer values. Almost all of them accept multiple values.
While indexing the nodes with apachesolr I observe that most of the time in the indexing process is consumed by calls made to entity_load function, almost 3.5 - 4 minutes for loading 200 nodes when checked with timer based logging while the total indexing takes about 50 seconds more (4.5 minutes overall).

Adding a custom 'status back' with hook_apachesolr_entity_info_alter to query and return the node status directly instead of loading it, I was able to negate the entity_load in one instance, however another function apachesolr_index_entity_to_documents() where the drupal node to solr document conversion takes place had entity_load calls consumed more time since they could no longer use the cached result of the status callback.

My aim is to reduce the time taken for indexing to at least half of what it currently which now is completely dependant on the time taken by entity_load. Since entity_load is one of the critical aspects of Drupal 7 around which functions like node_load/node_load_multiple are derived from I'm unable to find a different option to proceed or determine ways to improvise entity_load usage.

Note: The site functions such that these nodes get created almost all the time and none of the fields can be pruned out, negating the option of pre-loading the entities. Also the site uses entity cache module with memcache

I'm hoping to get suggestions on improving the node load time programatically with entity_load or using alternative approach to load the respective entities to bring down my indexing time.

You could very well form an array of the nodes to be indexed after the query execute and do a single entity_load instead of doing a entity_load for each and every node separately and I hope that will reduce the time and below is the patch that could help you

Index: apachesolr/apachesolr.index.inc

--- apachesolr/apachesolr.index.inc     (revision 9348)
+++ apachesolr/apachesolr.index.inc     (working copy)
@@ -636,9 +636,21 @@
     $query->condition('aie.entity_type', $entity_type);
   }
   $query->range(0, $limit);
-  $records = $query->execute();
-  $status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
+  $records = $query->execute()->fetchAll();
+  foreach ($records as $node_record) {
+    $entities[] = $node_record->entity_id;
+  }
+  $arr_entity = entity_load($entity_type, $entities);
+  foreach ($records as $record) {
+    $record->status = $record->status && $arr_entity[$record->entity_id]->status;
+    $rows[] = $record;
+  }
+  // Commenting as we have already used the entity_load
+  /*$status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
   foreach ($records as $record) {
     // Check status and status callbacks before sending to the index
     if (is_array($status_callbacks)) {
@@ -651,7 +663,7 @@
       }
     }
     $rows[] = $record;
-  }
+  }*/
   return $rows;
 }

As you have said most of your fields are taxonomy term it is idle that you check the term_load method and also whether the term_data table is properly indexed.


Creating field on each node I want to add a field on each node which links to a particular page where module's controller will act. I want to actually add a link at bottom of node, and I want to do this programmatically. But I am not able to start, and I am very new to this.

Any ideas or suggestions to get me started? Or give me some reference in Drupal core modules or some other type of sample code to do so?
I have done this till now to add the link:

function module_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode) {
if (TRUE) {
  $entity->content['links']['module'] = array(
      '#theme' => 'links__entity__module',
      '#links' => $link_builder->buildLinks($entity),
    );
 }
}

but till now got no success. Am I using correct hook?Also I think that now the question makes sense.

If you have a link field added in your content type then there is no need to render the field programmatically. As I understand with your comment, you need to add field value programmatically.  So in drupal 7 it was hook_node_insert and in drupal 8 it is hook_ENTITYTYPE_insert.

So in drupal 8 your hook_node_insert will look like following :

function hook_node_insert(Drupal Core Entity EntityInterface $node) {
  // Change node object how you wanted.
}

Helpful Links :

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

http://www.drupalcontrib.org/api/drupal/drupal!core!modules!node!node.api.php/function/hook_node_insert/8


How to start migration with migrate module I'm trying to make the migrate module to work, but I can't find where the dashboard is located.

In this url: www.foo.com/admin/content/migrate

I have the list of all available content that can be migrated into the DB (screenshot below).

However there must be another screen where you can actually initiate the import process.

I've tried this other url: www.foo.com/admin/content/migrate/dashboard

But it gives a 404 page not found error.

Any suggestions?

Is the Migrate UI module active? If yes, please try to clear the menu cache.


how to create user view with last login zero or never logged in I am trying to create user view for those user who never logged in. For this i need a filter as last login is equal to zero.
Any body knows how to select filter as last login is zero.

When i used Operator equal to zero it shows a message
Invalid date format.

Yes, after long search i got a suitable answer
If i put in operator is equal to value 1970. it gives me result
basically 1970 consider as a zero value.


How to print the drupal username -without a link to it- inside the node profile? So far the only thing that works is $name wich prints the username with the link.

I´ve tried $account->name, and it won´t print anything at all (I´ve tried $author and $account_name; too, without any luck).

I want to print the username inside their profile usernode in a Drupal 6 installation, but don´t want to print it with the link to it, just the username.

Thanks for your help!

I do not have the exact answer you are looking for.
However I'd use get_defined_vars() in all template files to list the defined variables.

In case you are not a programmer, here's the code.

<pre>
<?php
  print_r(get_defined_vars());
?>
</pre>

http://php.net/manual/en/function.get-defined-vars.php


Invoke javascript in hook I have create a hook to alter page funcionality. It's posible invoke javascript function in hook.
          I test this function but i had this error -->  Call to undefined function alert()

      function catalogo_preprocess_node(&$vars)
      {
        alert("hello");
      }

D7 you can try function drupal_add_js

function hook_preprocess_node(&$vars){
  drupal_add_js(drupal_get_path('theme', 'your_theme') . '/js/my_script.js');
}

D8 You need define one or more (asset) libraries, add a *.libraries.yml file to the root of your theme folder

library_name:
  version: 1.x
  js:
    js/my_script.js: {}

Attaching a library in a preprocess function

function hook_preprocess_node(&$variables){
  $variables['#attached']['library'][] =  'your_theme/library_name';
}


How to adding our own sorting to a view on Drupal? I have develop a drupal view with table format.

Here table rows are Name and Date.
I am sorting a Name column with default sorting in views,it's working fine.
But when user click on views page automatically views page redirected to default sorting in views.
Here problem is when user click on sorting with (asc/desc) that order permanently store in database.

how can we achieve this.

You could alter your view query with hook_views_query_alter to add your custom sorting.

<?php
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function mymodule_views_query_alter(&$view, &$query) {

  //simple example: change the order of the master display
  //if you want to do it only  on a certain display add something
  // like  "&&$view->current_display == 'panel_page_1'"
  if ($view->name == 'VIEWNAME') {

    //to find out what the fieldname ist: use devel and add your desired field as
    //first filter ( =>orderby[0]). install devel and uncomment the next line
    //dpm($view->query->orderby)

    $view->query->orderby[0]['field'] = "CASE FIELD_NAME WHEN 'apple' THEN 1 WHEN 'zebra' THEN 2 WHEN 'banna' THEN 3 ELSE 4 END";
  }
}
?>


How to get monthly node view count? I have a site where we want to send out information to "owners" of certain pages to tell the users how many page views the page got in the last month.

I think this could done 2 ways:

A module that keeps the a monthly count of page views. I have looked at Statistics Counter module but it seems to simple. It resets as soon as the new month starts. So if I wanted to send information for the last month it would lost as soons as the next month started.  Any other modules that keep this information for past months?  Or maybe I should just write a very simple module that would write the old month count to a history table before it gets reset.
Let Google analytics handle this. Either through custom code or a module query Google analytics with path, and date range.  Is there module does this already?

Other ideas on how to do this?

Thanks for any help on this

I haven't tried this yet, but https://drupal.org/project/google_analytics_sync might get you part of the way there.


Drupal 7 Taxonomy term display page I am trying to display my content in Alphabetical group for a specific content type.

What I did?

Added a vocabulary "Category"
Added a term(Myterm) inside this vocabulary.
Added a field in content type and put the relation with this vocabulary and the default option is the term name.

This is working fine. Now I want to show up the Myterm page the content alphabetical group. For your information I used Pathauto module to create the taxonomy term url. So my current url is domainname.com/MyTerm

This page showing the results which are belongs to MyTerm term. I want to just display the Alphabetical group and each group will contain the content whose title starting with this group. Please guys advice me how to implement this. If any contributed module is available, please advice. Thanks in advance.

e.g. Suppose my requirement is like below:

[A]
Amazing Video
A good tutorial
Award wining software
[B]
British Council
Be right back
[C]
Case discussion
Content privacy
....

I think what you would like to achieve is like a glossary.

You can by default create a glossary with views. How to do this is best explained or shown in this video.

If you want to show each of these on one page, i think you need to have some kind of a special field to group your results by. For this, try to the Views PHP module. Make a field where you grab the first letter of each term, and group by this (for example).


Customizing taxonomy Term page with sticky articles I am trying to create an educational website. I have created terms as

History, Science, Biology, Mathematics
and Mathematics term, sub-term as Algebra, Trigonometry

I want to create a separate page like frontpage for each term with few posts sticky at top. For example When someone clicks on History then a page with teaser view of Articles like "About history", "Books for history", " Preparation Guide" will be top on that page list and all other nodes tagged with History term will come below these three posts.

And how can I set no of total posts of History term page as 10?

I am new to drupal and not able to find right modules. Stuck in this issue for 2 days, any help will be appreciated.

You can create a custom module and implement hook_menu_alter for taxonomy terms.

In your custom callback you then filter by your taxonomy and intercept the ones you want and pass the rest to the default handler.

On the ones that you intercept you then render a custom view for that taxonomy. That view will just be a normal default view (no page) with an attachment as well. You set the attachment to the top of the other view and show teasers. The other view will show links only with an offset to not show the teaser nodes as well. Your view will be constructed with appropriate contextual filters that you will pass.

Your MODULE.module file:

function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] =   $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MODULE_taxonomy_term_callback';
  $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'MODULE') . '/includes';
  $items['taxonomy/term/%taxonomy_term']['file'] = 'MODULE_callbacks.inc';
}

Your MODULE_callbacks.inc file (located at MODULE/includes):

function MODULE_taxonomy_term_callback($term, $callback) {
  $function = __FUNCTION__ . '_' . $term->vocabulary_machine_name;
  if (function_exists($function)) {
    return $function($term);
  }

  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return $callback($term);
}

// one for each vocabulary
function MODULE_taxonomy_term_callback_TAXONOMYVOCABULARYMACHINENAME($term){
  $view = views_get_view('VIEW_MACHINE_NAME');
  $view->set_display('default');
  $view->set_arguments(array($term->tid));
  $view->pre_execute();
  $view->execute();
  return $view->render();
}

You View(s) will be as follows:

Contextual filter: Content (taxonomy in question)

When the filter value is not available

Provide default value: Taxonomy term ID from URL
Load default filter from term page.


user_login_finalize() logins the user, but I remain anonymous I'm using user_login_finalize() in my code to login a user (right before the review page), and this works because I can see the log in drush watchdog-list. However, it only works behind the scenes: the browser session remains anonymous. The browser has a new anonymous session though.

It's almost like a new PHP thread is spawned for the user instead of using the old one (thus, Drupal logs the user and spawns a new thread, so the user is still anonymous even though Drupal has logged the old user). I don't know whether it does that, but that's what it looks like.

I know this doesn't help you per se, but I'd like at least to know how to debug that. I'm really lost there.

FWIW, here is the drush watchdog-show 66341 for the login:

 Wid        :  66341
 Type       :  user
 Message    :  Session opened for dsdsdsdsdsdsdsdsdsd@sdsdsds.com.
 Severity   :  notice
 Location   :  http://test.lxc:81/checkout/11
 Referer    :  http://test.lxc:81/checkout/11
 Hostname   :  192.168.120.1
 Date       :  08/oct 16:20
 Username   :  dsdsdsdsdsdsdsdsdsd@sdsdsds.com

More information: I'm using the following code where I call user_login_finalize:

global $user;

$account = new stdClass();
$account->is_new = TRUE;

$edit = array(
  // More to come later, but this is the only constraint
  'name' => 'some random name',
);

$user = user_save($account, $edit);

// Checking $user here, it has the correct UID of a new user.

user_login_finalize();

You mean that the user remains anonymous in the browser session, right? (In Drush, you must pass -u uid on every invocation to specify the user, because Drush is stateless.)

Make sure that the Drupal session cookie is being set in the browser.  If, for example, you set the cookie in the secure context (https) and then redirect to http, the cookie will be inaccessible, and the user will remain anonymous.

Edit: user_login_finalize requires a $form_state parameter; see: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_login_submit/7  It's hard to see which fields of the form state are relevant, since it is just passed to user_module_invoke.  However, if you compare what is in $form_state during a normal Drupal login, and supply the same information in your function, then it should work fine.


How to programatically change image style of images gathered by view? I have a view that collect fields of some content type and one of those fields is image field. I can set image style for that image from view editing page and that image in every row will have that same image style.

Now I need to set different image style for some rows. I.e. first row image should have style "ep1", second "ep2" and third and fourth "ep3".

What I tried so far is pre-processing image field like this:

function hook_preprocess_views_view_field(&$variables)
{
  $view = $variables['view'];
  $field = $variables['field'];

  switch ($view->id()){
    case 'view_id':
      switch($field->field) {
        case 'image_id':
          $rowIndex = $variables["field"]->view->row_index;

          $variables['field']->options["settings"]["image_style"] = 'thumbnail';
          break;
      }
      break;
  }
}

This way I can collect row number, but setting this "thumbnail" style is not working. On front-end I'm still getting image style set from view.

Then I tried preprocessing image formatter like this:

function cr_common_preprocess_image_formatter(&$variables) {
  if ($variables['image']['#style_name'] === 'style_to_change') {
    $variables['image']['#style_name'] = 'thumbnail';
  }
}

And this way style really is changed, but I don't' have info on current view row so it can be used only for setting random image styles or something.

You could try a different approach, via the Views UI, adding the same image field 3 times, and assigning each of these different image styles.

Add a View result counter field, this will let you know the row number.

Then on template/twig file print image field that was assigned x image if counter (this is the twig variable name for View result counter) equals y.


How to generate more than one pdf from a node? I need to generate two or more PDF from the same node with different templates.
e.g.: from a reservation page of a accomodations site I would generate a PDF for client, a PDF for owner and a PDF for agent

I'm currently using Print module.

How can I do?

Print module doesn't support choosing multiple templates and content from the page. You'd have to create a custom module for that which isn't a trivial task.

If you can't code, maybe you can restructure your Reservation page in a way to use different Content types that reference each other (Entity reference). One CT for client info, the other for owner info and a third one for agent info.

You can use Views to display all that info on one page, all together. But Print module would apply to each node separately, so you'd be able to have that separate.

It may be that info you want to show overlaps between PDFs. You'd have to come up with a custom solution for anything more complicated like that.

Maybe you can combine different solutions for different PDFs.

Check out Entity Print, Printing any Drupal Entity to PDF.


How to change label pass field on registration form I need to change the password field label on the registration form. Name and Email I changed through hook_form_alter and password does not work. Help me!

$form['account']['name']['#title'] = 'Имя пользователя/Login';
$form['account']['mail']['#title'] = 'E-mail адрес/E-mail';

Here is the soluition (need to clear the caches):

function MYMODULE_element_info_alter(&$type)
{
    // dpm($type);
    // assuming it's a password_confirm type
    $type['password_confirm']['#process'][] = 'custom_pass';
}

function custom_pass($element)
{
    $element['pass1']['#title'] = 'Пароль / Password';
    ...

    return $element;
}


image 404 error (via JSON:API) My 'gatsby develop' command fails as image files (coming from Drupal 8) are returning a 404 error - I don't understand why (this is new)
== Details: ==
JSON:API (which Gatsby uses to build the site), uses this URL:
https://dev-tuckel.pantheonsite.io/jsonapi/file/file
it provides this image URL:
https://dev-tuckel.pantheonsite.io/sites/default/files/2020-08/mckenzie%20falls.jpg
Which returns a 404. There are at least 3 other images that are returning a 404 error - this is strange.
== Investigation: ==
In: content> Files:
the file is 165.17 KB, which is strange, as I ussually upload higher quality images.
it also says it has 1 "use count", however the "entity" field is empty (again, not usual)
I cleared the Admin > Performance cache (thinking it's may a thumbnail / cache file error).
The site is hosted in the free dev tier of pantheon.
Prior: I was not working on Drupal at the time of failure, I was working on Gatsby code.
If you have any ideas, it would really help because I'm stumped.

I was able to delete the files via JSON:API (thank god that exists) using Postman.
The FIDs were: 1,2,8,9 - indicating that the files were very early on in the development of the site. I think they may have belonged to article content types that were recently removed (and therefor orphaned) - however I was still able to build the gatsby sites after this.
However, I think it was straight after I deleted the .cache folder from the Gatsby build that I had this issue, so it's possible that I had the images cached, they were then orphaned (during deletion of the 'article' content type.). Although I would have expected that Drupal would have done appropriate deletion of files and records when removing a content type.


Adding custom form to form_alter -- help please I've been trying for awhile to add a custom form to a custom module so as to make it show in drupal profile Edit page. Using the normal $form['submit'] messes up the other forms in the page, so tried to use $form['#submit'][] and append the second submit handler, but still no luck. Hoping someone can see what i am doing wrong.

Here is the code i have so far:

function custom_module_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'user_profile_form' && user_access('delete mods', $form['#user'])) {

$modlist = getcurrentmods(); // this function returns an array of usernames

$form['modlist']['mods'] = array(
'#type'=>'select',
'#options' => $modlist,
'#multiple' => false,
'#weight' => 30,
'#size' => 10,
'#id' => 'modlist',
'#prefix' => '
',
'#suffix' => '
',
 );

$form['#submit'][] = array(
'#type' => 'submit',
'#value' => t('Delete'),
'#submit' => array('_modlist_delete_callback'),
'#weight' => 32,
'#attributes' => array(
    'class' => array('submit-inline'),
),
'#ajax' => array('callback' => '_modlist_delete_callback',
'wrapper' => 'dropdown-modlist',
'effect' => 'fade',
'method' => 'replace',
  ),
 );

  }
}

The dropdown with the user list shows up fine, however the submit button doesn't.

Anything with a # preceding it isn't an element, it's a property. Properties are not rendered.

To fix, just give your submit button a unique key without the #, e.g.

$form['foo_submit'] = array(
  '#type' => 'submit',
  ...
);


How to display products without selling them (or using the typical ecommerce modules)? I am working on a project with drupal 7. My drupal experience is limited and Im a bit stuck on how to achieve a good structure.

The site will have products like wine, sherries and spirits. Each of these product types will have subcategories. (example: like red / white wine) Within these subcategories there will be certain brands of wines.

Since the website is focussing only on displaying the products and not selling them, I really do not want to use any ecommerce software, or modules.

Preferably I would like the products to be a content type. There is a little catch to it. All categories, so in the examples above; wines, sherries, spirits BUT ALSO red / white wines should have a description and a image.

Can anyone shed some light on how to create this in drupal 7. I have searched a lot but I'm not sure what the right approach would be. Thanks!

The easiest way to achieve this without using "commerce" modules are taxonomy and vocabularies, using the Entity Reference Module.

A  simple workflow to achieve this would be:

1).Create the corresponding Vocabulary with the desired term structure from admin/structure/taxonomy/add, for example:

Wine

Red

Brand #1  etc.

2). Create The Content Type with the desired Fields

3). In the content type, add an "Entity Reference" Field, assigning it to the vocabulary

4). Create your products (Add content)

5). Create Views to customize the display of each page depending on the term level (using filters)


What Drupal development environments are available besides XAMPP? I am using XAMPP for almost 2 years. Recently i found some articles that suggests that XAMPP is loading some extra libraries/dlls which is not required for a Drupal development environment.
Is there any other options that i can adopt for Drupal development besides XAMPP?

I found nginx.

I think it's best if your local development environment matches the environment of the servers your site(s) are actually hosted on as much as possible.  I've used XAMPP with Drupal and I haven't ever had problems relating to extra libraries being loaded.

That said, if you're looking for a Drupal-optimized solution, Acquia, the company run by the founder of Drupal, provides a Dev Desktop which allows you to set up and host Drupal quickly on Windows or OS X.  This works similarly to XAMPP but it's easier to set up.  (Warning: Acquia's Drupal distribution is slightly different than the standard Drupal from drupal.org.  However, you can easily replace the Acquia Drupal distribution with the one from drupal.org if you want.)

For a different approach, you can try Drupal Quickstart, which is a Virtualbox VM that includes an install of Ubuntu Linux pre-configured with (as per the project page):

  Support for Drupal 7 and Drupal 6
  Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
  Firefox (with developer plugins) and Chrome
  Drush, drush make, and custom drush commands
  Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
  Netbeans and Eclipse, configured with XDebug
  XHProf and Webgrind profilers. Emails logged as files
  cvs, subversion, git, bazaar

This is the "whole development environment in a box" solution.


How do I incorporate a browser file search into a Drupal form? This question extends a previous one. The previous answer stated that the pop-up window to search the user's computer for a file to upload is called using .  I am not certain how to make the call from within the form_submit function and have searched the core code for an example without success.  I know that add content has a widget to add an image file, but I cannot find the code generating it. I even did a file search for the word "Browse" which is the title of the button without finding a single file.

Does anyone have an example of how I would direct a call to a browser function from within the Drupal form?  OR Does anyone know where the add content form widget for adding a file is at?

To output a file select form element in a Drupal form, you simply add a file or managed file element.

$form['upload'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file')
  );
)


Feature creation of Print module for path to print stylesheet Using the print module, I need to create a Feature to deploy in order to set the path to the .css file to my themes directory on my production site.

In Features, what do I need to check to make sure I get these settings?

When creating the Features, the closest thing I can find is a checkbox under permissions:

Thanks

You also need strongarm enabled to export the path variable. Then it will be available as print_css variable.


How to remove orphaned actions if you get not authorized access as uid1? I get this error 1 orphaned actions (views_bulk_operations_archive_action) exist in the actions table. Remove orphaned actions

But when I click Remove orphaned actions I get You are not authorized to access this page..

And I'm logged in as UID1 user.

Can this be solved via drush?

Relative path /admin/config/system/actions shows a list of the actions available in the site.

If a site has orphaned actions, then relative path /admin/config/system/actions/orphan will provide the opportunity to remove them.

If you enter relative path /admin/config/system/actions/orphan and get redirected (automatically) to /admin/config/system/actions/manage, then that is an indication that there are no orphaned actions.

And if everything else fails, and you're willing to take the risk (+ a backup of your database first!), you might want to give it a try to edit the Drupal database using an SQL which looks like so:

delete from actions where aid = "views_bulk_operations_archive_action";


Rules sending email to profile2 users I am new to drupal. I have installed profile2 module and created one profile named as "Travel Agency". Now I want to send different mail to this user when he/she registered with my site as "Travel Agency". so I have created a Rule for this and it is working it is sending a separate mail which has been setted for the Profile2 user or Travel Agency users.

My rule information is as follows:

Event: After saving a new profile

Condition: Data Comparison .. Selected data: profile2:type equals Travel Agency

Action: send e-mail

The problem is that along with this email it is also sending the email which has been sent to user when he/she registered as Normal user with my site.

Please guide me on this. Thanks for the answers in advanced.

You could go to admin/config/people/accounts and uncheck "Require e-mail verification when a visitor creates an account." Then create a new email rule for users who are not "Travel Agency". If you still need to require e-mail verification before the user logs in then check out the Mail Control module.


Trying to make a filter taxonomy menu with multiple vocabularies I'm currently having trouble getting a taxonomy menu to act as a product display filter.  Actually I think I may need multiple menus as my products need to be filtered by: category, price, and color. I can do the filters separate, but they need to stay active together such as a filter with a category of 'all' and a price of 0 to 99 and color of red.  I am hoping to get this working somehow with views rather than recoding, but that is an option as well.  I'm still a little new to Drupal, and this is my first Drupal commerce kickstart site.  Using Drupal 7 and commerce kickstart 1.

I think that you mean "taxonomy vocabularies" when you say "taxonomy menu". Because actual menus like the navigation are not really suitable for this task.

Scince you are using Commerce Kickstart, you can simply use multiple Search Blocks as Filters and join their results. The View "Display Products" that comes with Commerce Kickstart by default actually has already a Block with the "Price" Filter on it.

I am assuming that your product display already has fields for the Term references to your taxonomy vocabulary. Also assuming you have not changed these settings yet, go to Administration » Configuration » Search and metadata » Search API » Product display » Fields and select the fields of your product that you want to filter for. Then reindex them and go to Administration » Configuration » Search and metadata » Search API » Product display » Facets, select your new fields and edit their display (e.g. checkboxes for color and ranges for price). Make sure you select "AND" as an operator if you want to have the products that match every filter.

Once you have that, go to Administration » Structure » Blocks and put the newly created blocks on the sites you need them on (e.g. /products)


Drupal user points and commerce I have 3 products: A, B and C. After the user buy the product A, I want to give the user 5 points, for B 10 points and C 20 points.

How do I do this with rules?

Add a new rule with some name, e.g - Award Userpoint for Product A.
In event select "Completing the checkout process".
If you want to award userpoint only if payment has been done in full, then after going forward delete the "Completing the checkout process" & add another action "When an order is first paid in full".
Add condition "Order contains a particular product", put the SKU of the product A. User operator & quantity as per your requirement.
Add a action named "Grant points to a user", in data selector choose "commerce-order:owner" & set the points which you want to award.

Done...this is how I am doing.


Add t('String to be translated') to your database I've altered a form where I set the save button text to t("Buy Product");

But how can I make sure that I can translate this string in admin/config/region/translate/translate ?

I've tried to add this

$conf['locale_custom_strings_en'][''] = array(
 'Buy Product' => 'Koop Product',
);

to my settings.php but no result. How can I make sure the string in my code can be translated in drupal itself?

Every single string passed to t($string) function will be added to the database, and you can find it in the path you montioned above "admin/config/regional/translate/translate"

clear the cache, and search it again with help of filters existing on the admin translate page.

[EDIT]

First of all a must have module in multilangual sites is the internationalization module, it's a powerfull and helpfull module...

But the most important thing in your case is that before you can see your string in the transltion page:

you must enable(switch to) the desired language
visit the page that contain that needle string
visit again the translation interface.

That's it you will find your string ;)


Complete project package I have been working on a D8 project and been wondering what the best course of action would be in order to produce a complete project package that can be easily set up in a new drupal installation. The theme part is pretty straightforward but what about all the specific content types that accompany a project with a specific theme? Is there a way I can have those being created on theme installation?

You can add the needed configuration files of the content types and fields needed for the site in a folder named config/install in your theme directory. These configuration gets imported when we install it.

for eg: if you want to create a content type test when your theme is installed

Create a file node.type.test.yml in your_theme/config/install folder paste the code in it

langcode: en
status: true
dependencies:
  module:
    - menu_ui
third_party_settings:
  menu_ui:
    available_menus:
      - main
    parent: 'main:'
name: test
type: test
description: ''
help: ''
new_revision: true
preview_mode: 1
display_submitted: true

Easy method is to

create the content types and fields form backend
export the configuration
Take the newly created files from it and remove the line uuid from it
paste it in your theme folder


Unable to edit custom block without administrator permissions I created a content type "landingpage" and a user role "editor". I enabled layout builder for this content type and enabled the option to overwrite the the layout for individual pages.
As Admin I can easily add custom blocks to the layout and afterwards I*m able to edit those blocks oder delete them.
As Editor, however, though I a am able to add custom blocks, I neither can edit my own blocks nor am I able to remove them.
I granted the editor role following permissions:

Admin blocks
Custom block: Manage display
Content - Landing page: Configure layout overrides for content that the user can edit.
Create and edit custom blocks
Manage Layout Builder Modal

Im using Drupal 8.9.14
Has anyone an idea to solve my problem?

To edit the blocks in layout builder, the user needs to have permission to use contextual links.


Trouble theming Ubercart's cart page (Drupal 7) using hook_theme Ubercart's uc_cart module offers a 'cart' page which I'm willing to have a theme/template. What I did is added following in mymodule_theme():

    'uc_cart_view' => array(
        'render element' => 'page', // IS THIS CORRECT?
        'template' => 'cart', // Located in mymodule/templates/cart.tpl.php
        'path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),

But No luck!

My Question:

Shall I have some other value for render element key? Or shall I have a variables entry? I tried with variables with an empty array instead of render element entry but no luck.

Here goes some more information about Ubercart's uc_cart module so that you can help me solving this issue:

For Your Consideration

Portion from uc_cart_menu:

$items['cart'] = array(
    'title' => 'Shopping cart',
    'description' => 'View/modify the contents of your shopping cart or proceed to checkout.',
    'page callback' => 'uc_cart_view',
    'access arguments' => array('access content'),
    'file' => 'uc_cart.pages.inc',
  );

So I figured out I should use my custom template for uc_cart_view. This uc_cart_view() is a function in *uc_cart.pages.inc* page, I've pasted the function here for your convenience.

Any help on what I'm doing wrong?

uc_cart_view() is not a form builder; it is a page callback. As such, theme_uc_cart_view() is not automatically called for uc_cart_view(). It is the page callback that needs to call the necessary theme function, or refer it such as in the following code.

  if (empty($items)) {
    return array(
      '#theme' => 'uc_empty_cart',
    );
  }

What you can do is the following:

Implement hook_menu_alter() to alter the page callback invoked for http://example.com/cart.

function mymodule_menu_alter(&$items) {
  if (isset($items['cart'])) {
    $items['cart']['page callback'] = 'mymodule_cart_view';
  }
}

Implement the page callback to output the content as you want it to be.

I cannot suggest the code to write for mymodule_cart_view(). Looking at the code used from uc_cart_view(), I notice the main part is the following one.

  // Load the array of shopping cart items.
  $items = uc_cart_get_contents();

  // Display the empty cart page if there are no items in the cart.
  if (empty($items)) {
    return array(
      '#theme' => 'uc_empty_cart',
    );
  }

  $build = array();
  // Load through the cart panes...
  foreach (uc_cart_cart_pane_list($items) as $id => $pane) {
    // If the pane is enabled...
    if ($pane['enabled']) {
      // Add its output to the cart view.
      $build[$id] = $pane['body'];
    }
  }

What a page callback can return, in Drupal 7 is:

a string containing the markup to output
an array accepted from drupal_render(), such as the following ones

$build = array(
  '#theme' => 'node',
  '#node' => $node,
  '#view_mode' => $view_mode,
  '#language' => $langcode,
);

$block = array(
  '#markup' => '<em>' . t('There are no rows matching the selected criteria') . '</em>'.
);

$styles = array(
  '#type' => 'styles',
  '#items' => $css,
);

As side note, in your theme definition, the template filename cannot be "cart"; as the template file is for "uc_cart_view" you can report it to be "uc_cart_view" or "uc-cart-view." Any other filenames are not accepted, from Drupal.


Export and Import Taxonomies and Extra Fields I created extra field in Login Form, I Installed even Extra Module (address) and create Taxonomies

Now I want to Export these configurations to another Drupal. This Drupal is the Clone of the main Drupal.

I Tried to use import/export Configuration (admin/config/development) But I have several error during import ( shortcut and error Ajax 500 )

I don't have active and staging folder (link)

Is it correct to use Conguration Management to export Module and Taxonomies?

According to this drupal link

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'


How can I upgrade ONLY Drupal core with composer? I knew that Drush make files were being phased out, but I kept using them, because in my opinion Composer isn't the best package manager in the known universe.  It updates too much or too little, has uninformative error messages,
and takes a lot more ram than necessary.  Don't get me wrong, I still used composer, but not for Drupal core updates, because those are more important and sometimes security releases.

But, in 8.4, Drush 9 is required, and in Drush 9 make files don't work at all.

My concern is this: I have some wildcards in my composer.json similar to the ones mentioned in this issue: https://www.drupal.org/node/2609568 which tell composer where to find my modules' composer.json files.  Yet, when I run

composer update drupal/core --with-dependencies

Whether or not I run it --with-dependencies, it will always go into the merge-plugin include paths and update all of those packages as well.  Now, if my site is out in production, I would like an easy way to update core and core's vendor files WITHOUT updating a bunch of contrib modules' libraries which I do not care about.  What if core releases a security update?  I want to be able to conveniently update core and only core quickly.  With Drush make, this was simple.

Has anyone figured out a way to do this with composer?

I do two things.

I use webflo/drupal-core-strict in my composer.json to make sure the same tested core dependencies are the ones used in my project.
I pin both drupal/core and webflo/drupal-core-strict to an exact Drupal version so I can regression test and know exactly what I am deploying.

So, my projects looks like

"require": {
    "drupal/core": "8.3.6",
    "webflo/drupal-core-strict": "8.3.6",
    "composer/installers": "^1.2",
    "drupal-composer/drupal-scaffold": "^2.2",
    "cweagans/composer-patches": "~1.0",
    "drush/drush": "~8.0",
    "drupal/console": "~1.0",
},

And where there is a new core version, I composer update drupal/core webflo/drupal-core-strict and then double check the lockfile.


How can I migrate the Domain publishing settings for nodes via SQL? I am using Drupal 7 and Domain Access (latest stable versions).

In my source site, there are nodes with "Domain access options", "publish to.." then a number of selected domains.

I migrate the data in the node_access table, mapping the old nid to the new nid using the migrate_map_xxx table.

However when I view a Node which has rows in the node_access table, publishing the node to certain domain id, the relevant box is not ticked on the node edit page.

When I rebuild permissions, the rows of data I migrated into node_access disappear and the node is still published to just the default domain (three other rows were inserted into the node_access table, now there is just one).

How can I migrate the publishing options for nodes from one DB to another?

OK, I figured it out... The domain_access table is the one I need to migrate the data from and to.

Key is to rebuild permissions after updating the domain_access table, so the node_access table is updated with the latest domain publishing options.

So I executed the following SQL to migrate the old domain_access records in to the new DB, then update with the new nid values from the migrate_d2d mapping table:-

delete from destinationdatabase.domain_access
    where nid in (select destid1 from destinationdatabase.migrate_map_blognodearticle);

CREATE TABLE IF NOT EXISTS destinationdatabase.domain_access_tmp LIKE destinationdatabase.domain_access;

INSERT INTO destinationdb.domain_access_tmp (nid, gid, realm)
SELECT nid, gid, realm
FROM sourcedatabase.domain_access
where sourcedatabase.domain_access.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

UPDATE destinationdatabase.domain_access_tmp AS ds, destinationdatabase.migrate_map_blognodearticle AS new
SET ds.nid=new.destid1
WHERE ds.nid=new.sourceid1
and ds.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

INSERT INTO destinationdatabase.domain_access (nid, gid, realm)
SELECT nid, gid, realm
FROM destinationdatabase.domain_access_tmp;

Then ran drush eval 'node_access_rebuild();


Risks to set permissions 777 I set permissions 777 to /www/sites/default/files folder and all subfolders. I did this because Drupal 7 would not let me save content. Drupal said me: The specified file temporary: //filetXbwF7 could not be copied, because the destination directory is not configured correctly.

Originally, these folders have the permission 755. But that did not work.

What risks are there to set permissions 777?

Thanks in advance!

Some things you should check:

Check if the owner of the sites/default/files is the proper user and groups. The user and group usually is www-data, but it depends on your webserver.
Since you mention temporary folder, you should check if the temporary directory at admin/config/media/file-system section of administrator interface is configured properly.

  What risks are there to set permissions 777?

It is a very very bad practice. There are tons of materials on the net you can look at, but long story short: Setting the permission to 777 means that anyone can write and execute anything in that folder, including malicious codes.


Render admin pages (forms) alongwith their admin theme from within a custom theme I am working on an already set up site where the custom theme was created very much manually and the head-region markup, incl. logo, main menu, user menu, etc. are manually rendered with a particular set of CSS based on twitter bootstrap. The admin theme was left alone, so it doesn´t have those head-region markup. But I do want admin pages/forms to seamlessly be rendered with the custom styled head-region. I tried isolating the css used in the head and added it to the admin theme´s page.tpl. This proves quite disastrous, since a hell lotta css conflicts come up, esp. because of bootstrap.css.

One lousy way would be to add element specific resets. But perhaps there´s a way to shield/wrap the head and the form so that they can still coexist on the same page with their own baggages of css+js?

Theme nesting is not implemented in Drupal. Too much risk of CSS conflicts, and HTML and CSS does not provide any way of isolation except for iframe. There is, quite literally, no way to write an universal solution. So you may:

Implement resets as you need. Probably hard, but still infinitely easier than any attempt to make solution universal and foolproof.
Trim the admin theme to remove footer, sidebars etc, and open admin pages in iframe
Prepare your own theme in a way that will render admin pages in a convenient way, "borrowing" code from admin theme you like (probably it's GPL, so you are allowed to do it).


create order - drupal commerce I'm developing an eCommerce website using Drupal Commerce.
I've been asked from my management to allow several users to use the 'create order' page in the admin store section (orders page) to stimulate sales.

The 'create order' page is sufficient by itself, but adding a product (line item) isn't that friendly, so I need to figure out a way to develop a 'browse products' function that'll allow me to add products to the order I'm creating.

Is there an easy way to do so? Maybe creating an all new 'create order' page? If so, what is the best appraoch without changing the drupal core code?

Of course you can create custom order form and page in new custom module. I think you understand drupal 7 FORM API, so you have to create new page with form.
You can process form values (i mean in form submit funtion) using entity API.

To create an order for current user:

global $user;

$order = commerce_order_new($user->uid, $status = 'pendig', $type = 'commerce_order');
commerce_order_save($order);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

To add billing info:

$profile = new stdClass();
$profile->type = 'billing';
$profile->uid = $user->uid;
$profile->status = '1';

$profile->commerce_customer_address['und'][0]['country'] = $your_country;
$profile->commerce_customer_address['und'][0]['locality'] =$your_locality;
$profile->commerce_customer_address['und'][0]['postal_code'] = $your_postal_code;
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;
$profile->commerce_customer_address['und'][0]['first_name'] = $first_name;
$profile->commerce_customer_address['und'][0]['last_name'] = $last_name;

commerce_customer_profile_save($profile);

$order_wrapper->commerce_customer_billing = $profile->profile_id;

Then you can add products to this order:

Presume that $products is an array of arrays of products ids and quantity of this product user is buying (EG.

$products = array(
array('product_id' => 22, 'quantity' => 1),
 array('product_id' => 23, 'quantity' => 3),
);

foreach ($products as $item) {
$product = commerce_product_load($item['product_id']);
$line_item = commerce_product_line_item_new($product, $item['quantity'], $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper->commerce_line_items[] = $line_item;

}
//to save line items and billing info in your order
commerce_order_save($order);


What is the difference between a view mode and a style plugin? It is possible that you can define the difference between a view mode and a style plugin. As far as I understand a view mode defines what fields are outputted and a style plugin decides how to render those fields. However, is a style plugin always connected with a panel?

I'll give this a shot.

A view mode is a concept that exists for entities. A node has for example the view modes Full content, Teaser and RSS.
And as you say different view modes can have different settings. An image might be just an URL in the RSS view mode and a large rendered image in the Full content view mode. It is also possible to have different order and visibility settings for each field in each view mode.

A Panel region or a Panel pane has something called a Style setting, this is also a Style plugin. There are styles such as No style, Rounded corners etc. Changing style will change the markup that surrounds your region or pane. In most cases the Style setting for the pane is something you do not change.

But to answer your question, yes a region or a pane always has a set "Style" and that Style is by default set to use the style plugin "No style".

A style plugin is a concept that also exists in Views. Under the setting Format in Views you have the option to choose between Style plugins such as Grid, HTML list,
Jump menu, Table and Unformatted list. When you choose a different style plugin the markup surrounding and in between each row changes.


How to hide node title while in edit without automatic nodetitle module? Actually in hook nodeapi(op:presave) I'm setting my own custom title so I want to hide the title field from the node edit form.

It does not work if I use automatic nodetitle module since it is also changing the title.

What is the best way to hide the title without using automatic nodetitle module?

Use hook_form_alter and unset($form['title']) in a custom module (since the node create / edit form will usually be displayed in your admin theme this will be a better approach than adding the function to your themes template.php file.

So create a module with a basic mymodule.info file.

Create a mymodule.module file and add:

function mymodule_form_alter(&$form, $form_state, $form_id) {

   // 1.NODE TYPE FORM
   if ($form_id == 'NODE_CONTENT_TYPE_node_form') {
     unset($form['title'];
   }

 }


Add interval to current date and dispay result in views I have a field in one of my content-types that contains a interval (using the interval module). I have configure the field so that the user can select how many years a curtain certificate should be valid.

How can I add this interval to the current year and count how many results I got using views?

Have you tried the Views Calc module?

The other option would be to use the Computer Field module but that could be risky as you enter PHP code into the field.


jQuery code in Drupal I have this code, but I don't know how to wrap it in Drupal.

 $(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 100) {
        $('.bottomMenu').fadeIn();
    } else {
        $('.bottomMenu').fadeOut();
    }

});

I've already activated the .js file and added the detail in .info, I can see it from the firebug that is ok, but from firebug console I can see that I have syntax errors.

From Drupal website I can see an example:

(function ($) { // Here code javascript })(jQuery);

Can someone show me how the code above should look like into Drupal? Thanks.

Here you go:

(function($) {
  Drupal.behaviors.yourCustomName = {
    attach: function (context, settings) {

      $(document, context).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 100) {
          $('.bottomMenu').fadeIn();
        } else {
          $('.bottomMenu').fadeOut();
        }
      });

    }
  };
})(jQuery);

Be sure to read the docs.


How do I set administrator menu to be the same as this Drupal 7 menu? I upgraded my site from Drupal 6 to Drupal 7.

The administrator menu is looks differently with Drupal 7 aministrator menu.

How do I set it same as the default Drupal 7 menu?

Drupal 7 administrator menu after upgrading

I want it became this administrator menu

To disable the menu shown in your first image, go to Structure > Blocks and disable any menu blocks you don't want to display (e.g., Management, Navigation, User). (Thanks, @leymannx!)

To have the menu shown in your second image, enable the core Toolbar module.


Trying to display or render values from links field within paragraph field base on its current language I'm currently using Drupal 8 Paragraph and I'm trying to figure out how I can display or output the url and title of a link field from within a Paragraph base on the current language via preprocess. Here is a snippet of the code I'm working on.

function iom_preprocess_paragraph(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

function _generatePrimaryLinkElement($currentNode, $entity, $title, $url) {

    $attributes = new Attribute(['class' => ['menu-item']]);

    if ($entity && ($currentNode->id() === $entity->id())) {
        $attributes['class'][] = '-active';
    }

    return [
        'attributes' => $attributes,
        'link' => [
            'attributes' => new Attribute([
                'href' => $url,
                'class' => ['link']
            ])
        ],
        'title' => $title
    ];
}

function _preprocess_primary_links_paragraph($paragraph, &$variables) {
    // Current page node
    $currentNode = \Drupal::request()->attributes->get('node');
    $activeLanguage = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $links = [];

    foreach ($paragraph->field_link as $link) {
        $entity = _loadEntityByUri($link->uri);

        $title = $link->title;

        // If there is an entity and the title is not set of the link
        // use the entity title instead
        if ($entity && !$title) {
            $title = $entity->title->value;
        }

        $links[] = _generatePrimaryLinkElement($currentNode, $entity, $title, $link->getUrl()->toString());
    }

    $variables['label'] = $paragraph->field_label->value;
    $variables['links'] = $links;
}

    {{ label }}

        {% for link in links %}

                {{link.title}}

        {% endfor %}

Below is some general purpose code I wrote to solve this problem across a lot of code.  It can take either a standard /node/## path or an alias and convert it to the desired language.  It assumes you are using prefixed language URLs and 'en' is the default language. If FL URL can not be found, the same URL is returned.

/**
 * Utility function to take a standard drupal path or alias and convert to the specified language alias path.
 *
 * @param string $path Root relative standard path, e.g. /node/### or english alias, e.g. /my/view and the like.
 * @param string $langCode  Language code for the resulting url. If not specified current language is used.
 * @param boolean $testPrefix If true, the input URL will be tested to see if the language prefix is already there.
 * @return string
 */
function my_i18n_language_url( $path, $langCode=NULL, $testPrefix=FALSE ) {
  if ( empty($langCode) ) {
    $langCode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  }
  // Optional check to see if url already has language prefix.
  if ( $testPrefix ) {
    $languages = \Drupal::languageManager()->getLanguages();
    foreach ( $languages as $code => $lang ) {
      if ( strpos($path, "/{$code}/") === 0 ) {
        return $path;
      }
    }
  }
  // If in alias format convert to node/### format.
  if ( strpos($path, "/node/") !== 0 ) {
    $url = \Drupal::service('path.alias_manager')->getPathByAlias($path,'en');
    if ( $url == $path ) {
      // Maybe it's a view
      try {
        $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
        if ( $url == $path ) {
          return $path;
        }
      }
      catch ( Exception $e ) {
        watchdog_exception('my_i18n', $e );
        return $path;
      }
    }
    $path = $url;
  }
  $url = $path;
  try {
     $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
  }
  catch ( Exception $e ) {
    watchdog_exception('my_i18n', $e );
    return $path;
  }
  $url = my_i18n_language_prefix($langCode) . $url;
  return $url;
}

/**
 * Utility function to get a language prefix based on the current page language.
 *
 * @param string $langCode  Optional - defaults to current language
 * @return string
 */
function my_i18n_language_prefix( $langCode=NULL) {
  $manager =  \Drupal::languageManager();
  $default_lang = $manager->getDefaultLanguage()->getId();
  if ( empty($langCode) ) {
    $langCode = $manager->getCurrentLanguage()->getId();
  }
  if ( $langCode == $default_lang ) {
    return "";
  }
  return "/{$langCode}";
}


Extreme slow Views rendering time On my Drupal 7 site I have some heavy performance problems. I found out (with XHProf) that the cause of that problem are some Views. The strange thing is: not the query build time nor the query execute time are to slow, but the views rendering time:

Query build time    4.83 ms
Query execute time  3.29 ms
View render time    1175.82 ms

The view is complicated because it has 7 relations. So that its build and execute time is as long as it actually shows up in the example above, is what one would expect. But the rendering can not depend on the complexity of the query, right? But only on the complexity of the resulting array or something else.
So, my question is, where to start to optimize View render time?

ps.: If the view is cached it much faster. But I have to optimize its over all execution time, when it's not cache or can't be cached.

Views can create real bottleneck for scaling and often cause great head ache by becoming resource hungry if not optimized well. Especially the use of Left Joins instead of Inner Joins, the default pagination in views and features like Distinct are major causes for the same.

The below code is a quick sample implementation which probably could fix the join issue in a view.

/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

Also, check if you can enable views cache. You can set the interval to something based on your update frequency or try to clear views_cache when something is updated on the site.

Use of views_litepager instead of the default page can also help, if you are using pagination in views.

There are several things you can do. You could read this detailed post on the topic for a more detailed understanding.


Different rankings in a view based on geolocation I'm currently building a site which has a ranking table.
I'd need the rankings to be different based on geolocation so what i'v done so far is building a different view for each country.
So the question is - how do i display them based on the session's location? (different home page and navigation for different countries)

Any explanation would be more than welcomed.

Edit: I'm using Zen theme.

I think Smart IP module is help you to solve your query.

OR

Check IP Geolocation Views & Maps or Session Cache API module.


Is it possible to have an entity with fields, which doesn't use bundles? I have an entity (using entity API) for which I would like a fixed number of fields (and would prefer to use fields and the API rather than just creating properties) - it makes no sense to make a bundle - but do I need to create a bundle nonetheless to allow fields to be attached?

I'm thinking this is the case since field_attach_instance takes a 'bundle' value in the array to pass in (and field_config_instance contains the bundle column).

Technically, yes! For each entity type you must have a bundle.
Since bundle is the implementation of entity type. If you define your entity type without a bundle the bundle will be of the same name with entity types. For example user entity doesn't have a separate bundle so it uses the default one with the same name of entity type.

Please go through this and this for details.


user tabs customization I have a site built with Drupal 7, and I allowed the authenticated users to see the other profiles. Till now, every thing was OK; the problem is when they click on the name of a user. They see the tab "account" by default, and I wanted them to get the tab "video" or blog entries instead.

I have the view, edit, video, account tabs, and I used the tab tamer in order to reorganize the theme, but the "Account" tab is still the default one.

How can I make the "Video" tab the default one? Where can I change it?

Please check my site.

I am unaware of any module that does this for you. So, you'll need to use a little bit of code to tweak things. What you need to do is implement hook_menu_alter() in a module to alter the way the tabs are organised. In particular, you will need to swap the menu type of the default tab and your video tab. The types in question are MENU_LOCAL_TASK and MENU_DEFAULT_LOCAL_TASK; i.e., change the default tab to MENU_LOCAL_TASK and your video tab to MENU_DEFAULT_LOCAL_TASK which should set the latter as the default. More information on these constants are provided on the hook_menu() page.


Using Features to create module with nested field collections I'm using Fred Parke's method to create a content type module by first building the content type and then turning it into a feature and exporting it. It works perfectly well, except for when I include field collections that are nested, one inside another. The exported source code doesn't seem to include those, even when I manually select the field_* types for export.

Is it possible to export nested field collections in a feature? If the answer is yes, how can I achieve this?

At this stage, I'm looking at doing it in Wordpress and embedding the result in an iframe, which should tell you how desperate I am.

Turns out I was running into some limitations in the Features export module (including some obscure bugs) and a misunderstanding of part of the return result for hook_node_info.  All it took was three solid days of debugging and I got it working.  So this one can go away now; given its limited usefulness, I don't mind if an admin wants to just delete the whole question.


Checkbox title as link I want to make the checkbox title as link with target _blank but this doesn't seem working.

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => l(t('Approve conditions'), 'node/10'),
  '#required' => TRUE,
);

So the approve conditions should be a link

That code doesn't work on Drupal 8 because l() has been removed from Drupal 8. The correct code for Drupal 8 is closer to the following one.

use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => Link::fromTextAndUrl(new TranslatableMarkup('Approve conditions'), Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']]))->toString(),
  '#required' => TRUE,
);

Alternatively, you can put the link in the description.

use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => new TranslatableMarkup('Approve conditions'),
  '#description' => new TranslatableMarkup('By clicking this checkbox, you approve the conditions', [':conditions' => Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']])]),
  '#required' => TRUE,
);

Keep in mind that, as said in the comments for l() and url() are removed in favor of a routing based URL generation API, if the shown code is used in a class using the StringTranslationTrait trait, instead of the TranslatableMarkup class you use $this->t().


How to resolve my database connection error when using the Wordpress Migrate module? I have a Drupal8 site and I've installed the Wordpress Migrate module and it's dependencies for migrating a Wordpress site to Drupal8.

When I start to import the exported XML file from Wordpress, I get this error:

The website encountered an unexpected error. Please try again later.

When I checked the error messages pages I found this:

  Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: migrate in Drupal\Core\Database\Database::openConnection() (line 361 of /media/mosama/Content/test_poc/drupal8_2/core/lib/Drupal/Core/Database/Database.php).

Any solution for this?

Solved!
By adding anothe data base configuration with ['migrate'] in settings.php under the default database like this

$databases['migrate']['default'] = array (
  'database' => 'NAME',
  'username' => 'USER',
  'password' => 'PASS',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);


How to theme a view that displays content from a relationship? I have a page for Organization. Each organization has a Featured Person field which is an unlimited node reference to the Person content type. The organization can have many featured people. I also need to be able to customize the markup for each view-row and therein lies my problem.

I set up the view according to another question. The view is able to select and display the correct Person data only when Show: Content. AFAIK, this does not let me customize the markup for each row because the rendered markup is sent directly to the template.

If I change to Show: Fields in order to get more control over the theming, the view will display the fields related to the organization, not the people (since I am on an organization page, and the contextual filter is set to the organization id, I suppose).

How do I set up my view so I can display the relationship content (Featured People) and still customize the template for each row or people?

With Show: Field, each individual field can be toggled to any of the relationships in the view. It is similar to Show: Content and Show: Rendered Entity except the dropdown list is buried one step further down.

Switch to Show: Field, and edit each field and set the dropdown list to the Featured Person relationship. Then, go about your theming just as you would with any other fields template.


How to handle Dev and Production servers having different file structure I know you are not supposed to do this, but for reasons beyond my control the location of my web root is different on my Dev and my production server.  As a result everytime I copy the database from my production server to my Dev server, all of my modules become confused and point to the wrong file location. What is the recommended way to handle this?

If you are using Drush you can run the following commands to fix the module path problem, if you are using multisites then make sure you are in the sites/mysite.com directory (this must not be a symlink) before running these commands.

Drupal 6

drush eval "module_rebuild_cache();"
drush cc all

Drupal 7

drush eval "system_rebuild_module_data();"
drush cc all

(though as I've not tested I'm not sure this is needed on Drupal 7 anymore)

If Drush is new to you then here is the description from the Drush project page:

  Drush is a command line shell and
  scripting interface for Drupal, a
  veritable Swiss Army knife designed to
  make life easier for those of us who
  spend some of our working hours
  hacking away at the command prompt.


Drupal installation in nginx subdirectory I have a new application that will be made of 2 frameworks yii and drupal 7

Yii framework will be in the root (/)

and drupal will be in a sub directory called admin (/admin)

I have a problem how to config it in nginx,drupal doesn't work,it gives me access denied,or just the home page and no link works

This is my configuration file in nginx

server {
        listen 80;
        server_name demo.example.com;
        root /home/www/example;
        index /index.php;

        location / {
                if (!-f $request_filename) {
                        rewrite ^(.*)$ /index.php?q=$1 last;
                        break;
                }
        }
        location /admin {
                root /home/www/example/admin;
                index  index.php index.html;
                try_files $uri $uri/ @rewrite;
        }
        location @rewrite {
                rewrite ^/(.*)$ /admin/index.php?q=$2 last;
        }
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include        fastcgi_params;
                index /index.php;

        }
         location ~ /\.ht {
                deny  all;
        }

}

I had a similar scenario, but in my case I didn't need to define again the root folder for the Drupal installation as you do on location /admin.

In my case I only needed to add the nginx directives for the Drupal path:

location /admin {
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^ /admin/index.php;
}


No commerce_price field in product after Kickstart I installed Commerce Kickstart 7.x-2.35 and I'm doing a Ubercart Commerce migration (from my current Drupal 6 site) using the Commerce Migrate Ubercart module. When migrating first products I don't see the prices and get an error message:

  Notice: Undefined property: stdClass::$commerce_price en
  commerce_product_line_item_populate() in line 1394 of the
  commerce_product_reference.module.

During migration the old Ubercart price (sell_price) is correctly mapped to commerce_price.

When checking Product Display type I don't see any price field, the only fields I see are product title, url, body, category and reference. Should I manually add a price field commerce_price? How to do that?

The commerce_price field should be on products referenced by the display. Typically what happens is an importer will migrate all product entities first (which corresponds to each SKU in the remote system) and then set the product reference field value of a product display to point to those product entities. The SKU is unique, so it can be used as unique ID to reference displays to SKUs when you don't actually know product IDs.


A deleted module is appearing in getEditable('core.extension') Using Drupal core 8.9.6, created a custom module called wdocsApi. I wanted to rename it, so I uninstalled it and created wdocs_api. The problem is, when I try to install the new one, I get the error

Drupal\Core\Extension\Exception\UnknownExtensionException: The module wdocsApi does not exist. in Drupal\Core\Extension\ExtensionList->getPathname() (line 522 of core/lib/Drupal/Core/Extension/ExtensionList.php).

I tracked it down to Drupal/Core/Extension/ModuleInstaller.php where a call is made to $extension_config = \Drupal::configFactory()->getEditable('core.extension'); and my old module is returned in the list of modules.
What can I do to erase any remnants of the old one from my database?

There is many reasons for this and most likely the rename hapend before was completely uninstalled...
Here is a few examples of how to make sure its gone for good:

run the following somewhere
 \Drupal::service('module_installer')->uninstall(['wdocsApi']);

or Just

run drush cex to export the active config

Open up core.extension.yml  and delete the reference to  "wdocsApi"

run drush cim to import the config


View for Entity Reference reverse, backwards forwards The need is to present in a landing page a view of all pages that do reference to this landing page. So, this view will search in other content type, to find in a reference field that contain same id.

Landing page content type have several nodes children.

Page content type have a Entity reference field_back_parent for a node parent

Content types
Landing page (1) parent,
  Page (2) child,
  Page (3) child,

I would like to this using UI in admin. So, no entityQuery in this opportunity.

No additional module need to be installed.
No coding needed. Just site building for Drupal 8.
First we need to check if our content types are ready.

Landing page content type, don't need any change.
Page content type need a field of type Entity reference.

Add field -> Add a new field = Reference Content

Then in Edit tab chose your kind of content type (parent)

After Save you will get...

Now go to admin/structure/views and + Add view

In this case we are going to check the option to create a block

In ADVANCED

Add Relationship for our field_back_parent in Page content type. This important to connect the two content types.

You need to tick Require this relationship.

In ADVANCED

Then Add Contextual filter for our current content type Landing Page. In this way, we will get our actual node id to be used in the view. So, now we can find only the pages that have same node id in field_back_parent.

So find by ID (Content)

Select the relationship name.

Check Provide default value -> Content ID from URL

Then you will get something like this:

In Relationship you must to have the word Content in the rightside

This is the result of our settings

If you click in Update preview you will corroborate that it doesn't display anything.

You must to add the node id from parent. In our case is the node 2 from Landing page.

Other way for reference https://mushtaqtahir.com/blog/4/drupal-8-reverse-entity-reference-in-view

I hope that this info help you.


How do Organic groups and virtual sites relate to each other? I just want to know that a site which is built in Openscholar, a LMS for Drupal.

Therefore, how organic group is tied up with virtual sites? Also I want to know the the Views module's role in such circumstances.

I am not sure about openscholar but what organic modules can do about virtual sites-

With help of organic group you can declare an entity as a "group" or call it context, an example could be a sports site with group as "cricket"
With help of og you have permission granularity in context to group, so a user can have access to all post which comes under a "group" in our example "cricket" being totally unaware of other groups, can say "hockey"
With in group you can have group specific roles, a user who can admin cricket group but still can not do anything on hockey group.

So each group can be seen as fully functional site in itself - virtual site

Note: Domains have nothing to do with og, it's just a matter of context switching


is installing a module on a live site ill advised? I am trying to install Code Per Node on my website.

All i have to do is ad content types that would accept HTML5 webgames.

There would be theming involved.

Is this a no go?

I successfully installed modules on sites with thousands hits a day. Maybe even an hour. And I must tell it's not wise, from the point of my experience. Sometimes you have no choice (installing captcha on the spam wave when client forbids technical break), but way to many things can go wrong. If your site has any significant number of visitors and you care about your reputation, either:

Install module on a copy of your site
Put your site in maintenance mode
Add .htaccess "maintenance mode" screen
Sync files
Sync data

Or simplier, but with longer break:

Put your site in maintenance mode
Add .htaccess "maintenance mode" screen
Install module

That way if your site dies, visitors will see nice static html screen saying "Sorry, technical break" and you will be able to revert from backups.


Move the location of "Notify user of new account" from bottom to custom section of admin/people screen? Is it possible in Drupal 7 to move the location of "Notify user of new account" checkbox from the bottom of the page to another location on the admin user screen? I have a custom module with hook_form_user_alter. I have no problem hiding it from appearing, but I didn't know if I could move it to another location on the form and how would I go about doing that if it can be done.

If I recall correctly, it's $form['notify']. So you should be able to do this:

$form['notify']['#weight'] = -999;


How to create a horizontal views slideshow of content in views? I want to create a content slider in drupal 6 similar to what exists here

I am using views 3 on my site.

You can use Views Slideshow module for this.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

You can read tutorial here: http://drupal.org/node/755010

Demo: http://drupalmultimedia.org/slideshow


How to establish a condition to show another view if the first view has no results? I have some blocks with views that show upcoming events of different categories. Now, if one category has no results, how can i trigger another views-block with another category (that is normally not displayed)? I was trying to get this done with the context-module, but i have only the possibilty to create a context IF a view is shown...

Try to write a php code, in your view UI, in the textarea for behavior when no result :

print views_embed_view( 'your_other_view_name', 'default');

NB : enable PHP filter module


How to query the Database logs and create summary reports and/or charts of them? Is there a module for querying and creating summary reports of the Database logs?

I need something that can create an equivalent of SQL Group by queries on the Database logs, eg, group by type, severity, count, IPs etc, and create views and possibly graphs on them.

The Views Watchdog module might be useful.

  The Views Watchdog module extends the Views module and allows to
  create customized lists (pages, blocks, feeds) of watchdog entries.

Combine it with the Charts module and a bit of custom code and you should be able to get a wide array of reports.


Drupal Commerce Shipping I have configured my clients online Vineyard store to display a flat rate up to £50 and free shipping thereafter.  However they are now selling Vineyard Tour vouchers which are free to ship.

I am trying to set up a condition whereby:

If the cart only contains a vineyard tour voucher or if the order is over £50 make the shipping rate free.
or

If the cart contains any other product (as well as a voucher) and is less than £50 standard shipping rate of £8.50.

Any help would be appreciated.

Best

Tom

You can use a combination of the modules Rules Bonus Pack, Conditional Rules, and Commerce Rules Extra to create condition loops to compare a data value and set the shipping type in the actions.

Ex:
Event = When calculating shipping

Condition = If cart contains item of type X

Action = add IF > Order total is greater than $50 > Add line-item: Free shipping

     add ELSE > Add line-item: Standard shipping


What is the purpose of sites.php and how does it relate to settings.php? What is the purpose of sites.php and how does it relate to settings.php?

I have done a lot of web searches and looked at the comments in these files, but cannot find a simple explanation.

Looking at conf_path() should help clarify the relationship here. conf_path() builds the default subdirectory (inside the sites directory) Drupal will goto for settings.php (and other site-specific configurations). It's default search behavior can be overridden with sites.php.


Get raw URL from field link I have set up a node--home_page.tpl.php template with the following:

  <a href="<?php print render($content['field_primary_section_link']); ?>">

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

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

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

I want the anchor tag to contain the raw URL from the field_primary_section_link but it is pulling in everything around it. I just want the plain URL but am unsure how to do. Any help would be appreciated.

You can dump $content['field_primary_section_link'] using var_dump() or if you have devel module installed in your project you can use dpm() and you'll see a bunch of arrays there and check the raw url that you need.


How do I give access to only specific roles to buy at my store? I have a platform with roles for moderators, editors, teachers and students. Only student roles should be able to buy courses and the other roles should not be able to buy courses or see any of the commerce store information e.g. cart etc. How do I set their permissions? All roles still see "cart" in the menu bar. Am I missing a setting in permissions? There doesn't seem to be a permission for cart, only checkout permissions.
What am I missing?

Solution

After a few nights of sleeping on it I believe I have a solution. I tested it and so far it works. But please let me know if you experience any issues with my solution below.

Step 1

a) Install Roles For Menu module (has a stable releases for this project are covered by the security advisory policy.)

b) Install the Path Access module together with the Chain Menu Access API (which is needed to install the Path Access module)

Step 2

a) Go to your menu links in the user menu admin/structure/menu/manage/user-menu (or wherever your 'my cart' link is located) and set the required roles to show and hide for that menu item.

b) Go to admin/config/people/pathaccess and add the paths that you wish to deny access to per role.

Now the roles who don't have access to any of these paths get an access denied page and those who do have access will just be able to use the store as intended.


How to unpublish all nodes of a user after is assigned a role? I am interested on this scenario:
After a user is assigned a role,all his published nodes get unpublished.
I am interested in doing this with rules and VBO.
I tried but no luck.
I used :Event:User profile is update
Action:Load all node with VBO.
Seems I am missing something.Anyone help?
thanks

I would instead create a Views Loop using the Views Rules module. You can create a view and have the rule loop through all the rows that the view outputs.

Edit:

  For Example, I want to send an e-mail to all user's attached to a node
  registration. So I needed to do the following:

  Create a view with a Rules Display. Field: User E-mail. Contextual Filter: NID (Screenshot: http://i.imgur.com/rcvdMyn.jpg).
  In the Views Rule Settings - Parameters: I specified the parameter's label and name, that wil need to match the Views Loop Data
  selector (Step 4) for the Views Contextual filter. (Screenshot:
  http://i.imgur.com/MFA7mxk.jpg)
  In the Views Rule Settings - Row Variables: I specified which field should be enabled for Rules, and how it should be passed back to
  Rules. (Screenshot: http://i.imgur.com/U7fkzjj.jpg)
  I then created a Views Loop in my Rule matching the Parameters and Row Variables in my view (Screenshot: http://i.imgur.com/hGziOtK.jpg)
  I then created the action "Send mail" under the Views loop using the now available token that was specified in the View. (Screenshot:
  http://i.imgur.com/chlKc7x.jpg)

And that's it. If you want to test your output rather than your unpublish action. I would recommend using the action "Show a message on the site".

In your case your contextual filter is most likely your UID and NID as your field. I used my example as a proof of concept.

Edit 2:

Exported View:

$view = new view();
$view->name = 'waiting_list_user_list';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Waiting List User list';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Registration */
$handler->display->display_options['relationships']['registration']['id'] = 'registration';
$handler->display->display_options['relationships']['registration']['table'] = 'users';
$handler->display->display_options['relationships']['registration']['field'] = 'registration';
$handler->display->display_options['relationships']['registration']['label'] = 'User Registration';
/* Relationship: Registration: Registration to Node */
$handler->display->display_options['relationships']['registration_related_node']['id'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['table'] = 'registration';
$handler->display->display_options['relationships']['registration_related_node']['field'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['relationship'] = 'registration';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['label'] = '';
$handler->display->display_options['fields']['mail']['alter']['trim_whitespace'] = TRUE;
$handler->display->display_options['fields']['mail']['alter']['strip_tags'] = TRUE;
$handler->display->display_options['fields']['mail']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['mail']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'registration_related_node';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Registration: State entity */
$handler->display->display_options['filters']['state']['id'] = 'state';
$handler->display->display_options['filters']['state']['table'] = 'registration';
$handler->display->display_options['filters']['state']['field'] = 'state';
$handler->display->display_options['filters']['state']['relationship'] = 'registration';
$handler->display->display_options['filters']['state']['value'] = array(
  'waitlist' => 'waitlist',
);

/* Display: Rules */
$handler = $view->new_display('views_rules', 'Rules', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_parameter'] = array(
  'nid' => array(
    'enabled' => 1,
    'type' => 'integer',
    'label' => 'nid',
    'name' => 'nid',
  ),
);
$handler->display->display_options['rules_variables'] = array(
  'mail' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'token',
    'label' => 'User: E-mail',
    'name' => 'mail',
  ),
);

Exported Rule

{ "rules_waiting_list_e_mail_after_registration_deletion" : {
    "LABEL" : "Waiting List E-mail after Registration Deletion",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "REQUIRES" : [ "rules", "rules_i18n", "registration" ],
    "ON" : { "registration_delete" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "registration:state:name" ], "value" : "complete" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "registration:entity-id" ] },
          "PROVIDE" : { "entity_fetched" : { "node_id" : "node_id" } }
        }
      },
      { "VIEW LOOP" : {
          "VIEW" : "waiting_list_user_list",
          "DISPLAY" : "views_rules_1",
          "USING" : { "nid" : [ "node-id:nid" ] },
          "ROW VARIABLES" : { "mail" : { "mail" : "User: E-mail" } },
          "DO" : [
            { "mail" : {
                "to" : [ "mail" ],
                "subject" : "test",
                "message" : "Test",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


What's the proper way to create a new page option? I want to show comments of a node on a separate page instead of on the node page.
Since this is just a "comment archive" and not active I would like a simple solution without a big module or a lot of code.

I can "hack" the node--mytype.tpl.php page to show comments when the "?archive" is in the URI:

    $uri =  check_plain($_SERVER['REQUEST_URI']);
    if (strpos($uri, '?archive') > 0){
        print render($content['comments']);
    }
    else {
        print l('View Comment Archive', $uri.'?archive');
    }

This works fine, even with the comment pager. I'm curious what the "proper" way in Drupal would look like.

The easiest way to to use Views.

You can create a view over Comments, or you can make a view over Content and then add a relationship to the node's comments.  There are advantages and disadvantages to both.  You just need to play with them to see what works best for your situation.

With either method, you can use any of the normal means for adding a view to you site.


Why is the replacement not happening when using the Search and Replace Scanner module? I am using Search and Replace Scanner module to perform replacement of links in my website. When I run this module, It says replacement successful  and 250 fields are replaced. My site includes English and Dutch as well.But when I see in the database its not at all reflecting, No changes in the links. I referred this but no success. Give some other suggestions to achieve this.

I tried Drush Search & replace, it works awesome, but I dont want to replace all the links, only body content links should get replace. This filtering option is not there in Drush Search and Replace.

Any suggestions?

Your scenario sounds similar to what is described in issue # 2616640.

Have a look at Comment nr 6 in it for an explanation for what may be causing it, i.e.:

  It looks like the module assumes that the field content to replace is set to the same language as the node.

Probably your best bet is to try the patch attached to Comment nr 18.


Create a View of Books I'm using the core Book module for organizing meeting notes and documentation. How do I create a list of books with the views module? That is, I'd like a list of only the top-level Books, not all the book pages.

An example of what I want in core is at admin/content/book which looks like this:

Thus far, all I've been able to get is a hierarchical list of books and all book pages. Current view:

Create a taxonomy term and defined in your content type
Use Simple hierarchical select or Hierarchical Select to create new term when you add new book "book name is taxonomy term"
Create a view using taxonomy term and select those terms whose parents has value = 0


Uncaught TypeError: Only on Drupal edit pages I'm using the BigSlide.js sliding menu on my drupal site, which i've built into the theme,  and it works fine on every page, apart from on /edit/ pages. E.g. user/%/edit.
When clicking the target menu button nothing happens - the menu should slide out from the left.

In the chrome console i'm getting:

  Uncaught TypeError: undefined is not a function

As you can see from the image above it's referencing bigSlide.js, I've tried updating jQuery to 1.9 with the Jquery update module as i'm using 1.7 and that didn't help, and i've made sure all my JS files are being loaded on /edit/ pages.

What could be the problem?

Here's the issue spot within bigSlide.js

Any help much appreciated.

I had installed the dev version of jQuery Update 7.x-2.3+15-dev, which allows you to specify different versions of jQuery for normal and administrative pages:

I'd done this because I had previously required jQuery 1.5 for something in the backend. It appears /edit/ pages are considered 'administrative' pages - (which seems odd to me)  and therefor were using 1.5 which broke the bigSlide.js menu.
Changing the admin pages back to 1.7 fixed the issue.


Is it possible to build a complete web site with Drupal 7 without using contributed modules or Hooks? Is it a good programming practice to add your own hooks in a template.tpl.php or is it best practice to make all the changes possible into a custom module?

It depends on the site's requirements. If you want to create a site only for content listing, you can simply change in template files to make it as per design. But you must keep your theme in sites/all/themes directory.

But generally the requirements are not so simple. The modules are contributed to make the better user experience. If you are asking this question for the better performance of site, then you should maintain your site with drupal standard.

The things to keep in mind :

Use contributed module rather than writing custom module.
In some case if you have to write custom module, then use drupal functions and API rather than core PHP functions.
Always keep your site (drupal/modules) updated with security releases.


Exposed filter shs (simple hierarchical select) in a custom template I don't see anywhere how to print this exposed filter in a custom template.

The problem was I did't add filter- in front of the filter name. Now it works with:

print $widgets['filter-{filter_name}']->widget;


Author handling node view access? First post here! ;) I'm not getting any help from the Drupal forums on this, maybe someone can help me out...Does anyone know of a module that I can use so that an Author can allow access to a user requesting access to the Author's node.
The setup would be like this:
1. An Author would create a private node, but viewable in teaser form.
2. Any Authenticated user could then request access to the node/full view.
3. The Author would then have a queue, say in their own user environment, where he/she could approve or deny access to the node/full view for the requesting user.
Thank you very much!

I was thinking about building a simple access system, but that would be like re-inventing the wheel.

Take a look at content_access in combination with ACL. The flexiaccess might be another option.