How to always show Poll results on most recent poll block? I want to make a block that shows a poll that shows the results and with a link to vote to that particular poll.
It seems that the default most recent poll shows the results if the user doesn't have the right to vote and the voting options if it has the rights...

How can I control this?

From memory you can configue poll blocks using the Views module. At any rate, using Views you will be able to create a new block that displays votes. You can then add a footer to the block with a link to the poll node so users can vote.

There's plenty of documentation about using Views:

http://drupal.org/project/views


Doubt with display a query using Custom Field Module in View I have installed the CustomField module.  I have a view and I'd like to add a new column in a table in the view.  The content of this column is a result of a query to a table different to node.  Is this possible with this module?

I am using Drupal 6.

You can set up relationships in views to pull data from other tables should you have to.  There's a screencast from Drewish here on how they work and how to set them up.

Basically, you'd need to set up a relationship based on a part of the current data in the row.  After this, more data is exposed to you in the fields section of views.

If I'm misunderstanding your question and you'd just like to embed a view withing a view, then check our the Views Field View module.

  This module allows you to embed a view as a field in a view.

  This view can accept arguments from fields of the parent view using
  tokens.


Where to add my merchant gateway using ubercart? I am trying to figure out how to add the gateway of my merchant so I can accept credit card payment.

I have given a URL by my merchant and I can redirect to this URL easily using my own PHP code, but I can't find a way to integrate it using Ubercart.

Example gateway is https://test.mymerchantgateway.com/ECN/eng/payment/payForm.jsp.

So that when my customer checkout it will be redirected to the url above and when the payment is successful it will return to my website using the "successUrl" like:

<input type="hidden" name="successUrl" value="http://mydomain.com/success.php">

I am using Drupal 6, if that makes any difference.

There are lots of modules that actually does this. You will need to do some custom coding and integrating with Ubercart. It's been a while since I did this and it also depends on your Ubercart/Drupal version. But you can checkout the quickpay module for drupal 6 integration example.

The typical way of doing these kinds of things, is to create a form and auto post it with javascript to the payment gateway url with all the params needed. It's up to you to send the correct params along and up to the gateway to redirect back. But answering those questions won't be drupal or ubercart related.


Custom Views Bulk Operation using Batch API I am using Views Bulk Operation for updating custom value. I created a custom Operation using hook_action_info. How can I use Batch API with my custom action if I have to Operate on maximum nodes.

Go to VBO settings (when editing the view, next to Style: Views Bulk Operations) and for your operation select the "Use Batch API" radio button under "To execute operations".


Why is file_create_url() returning inconsistent values? I'm experiencing an inconsistent behaviour in Drupal 7 on the function file_create_url(). I have one field collection with 4 fields in it. On the first field the function provides the correct file url. For the other 3 fields it displays only first part of url. How can I get rid of this?

Here is my code:

<video controls="controls"  autoplay="autoplay" poster="<?php print file_create_url($content["field_poster"][0]["#item"]["uri"]); ?>" style="width:100%"   >
  <source src="<?php print file_create_url($content["field_mp4"][0]["#item"]["uri"]); ?>" type="video/mp4" />
  <source src="<?php print file_create_url($content["field_webm"][0]["#item"]["uri"]); ?>" type="video/webm" />
  <source src="<?php print file_create_url($content["field_ogg_theora"][0]["#item"]["uri"]); ?>" type="video/ogg" />
</video>

And here is the result: field_poster is fine but the others fail;

<?php print_r($content["field_poster"][0]); print_r($content["field_mp4"][0]); ?>

leads to...

            Array
(
[#theme] => image_formatter
[#item] => Array
    (
        [fid] => 288
        [uid] => 1
        [filename] => Transgourmet_Waldputen_MASTER.jpg
        [uri] => public://Transgourmet_Waldputen_MASTER.jpg
        [filemime] => image/jpeg
        [filesize] => 65241
        [status] => 1
        [timestamp] => 1440456242
        [type] => image
        [rdf_mapping] => Array
            (
            )

        [image_dimensions] => Array
            (
                [width] => 1008
                [height] => 573
            )

        [alt] =>
        [title] =>
        [width] => 1008
        [height] => 573
    )

[#image_style] =>
[#path] =>
)
Array
(
[#theme] => file_link
[#file] => stdClass Object
    (
        [fid] => 289
        [uid] => 1
        [filename] => Transgourmet_Waldputen_MASTER.m4v
        [uri] => public://Transgourmet_Waldputen_MASTER.m4v
        [filemime] => video/x-m4v
        [filesize] => 34256348
        [status] => 1
        [timestamp] => 1440457177
        [type] => video
        [rdf_mapping] => Array
            (
            )

        [display] => 1
        [description] =>
    )

)

Is it possible that is has to do with the mime-types?

Thanks in advance.

For each of the video files, this (for example):

$content["field_mp4"][0]['#item']['uri']

should be this:

$content["field_mp4"][0]['#file']->uri

Change #item to #file and change the syntax to reference an object instead of an array.


Issue using search_api_ranges with search_api_ajax I have set up search_api_solr - integrating search_api_ajax, facetapi and search_api_ranges into the results for a better flow.

I keep hitting an issue with regards to search_api_ranges where initially, for example; when a search runs on a taxonomy view which returns indexed nodes with the tag 'toyota', the link is always originally structured as:

mysite.com/car-tags/toyota/field_car_price/%5B1000%20TO%202000%5D

When clicking this, a 404 page not found is returned.

However! If I run the search again, this time clicking around the other facets - seeing the ajax working nicely, it's as if something triggers the ranges api, and each link is now:

 mysite.com/search_api_ajax/taxonomy/term/2/field_car_price/%5B1000%20TO%202000%5D

When clicking this, the ajax works fine.

Anyone come across this before?

The issue is related to Search Api ranges module. There is already a patch for similar problem.

Kindly check patch at https://drupal.org/node/1987232 or use the updated module. I hope it will help for you.


How to remove ul li formatting from list of attributes in Ubercart order email template? I would like to update my customer order email and printable invoice so that each product line item looks like this:

1 x SHIRTRED | Red | Tshirt

1 is the quantity ordered
SHIRTRED is the SKU
Red is the attribute option that was chosen
Tshirt is the product name

I have already updated my uc-order--customer.tpl.php code to look like this:

<b><?php print $product->qty; ?> x </b> <?php print $product->model; ?> | <?php print $product->title; ?> | <?php print $product->details; ?>

The attribute options are printed as a ul list, which causes them to wrap to the next line below the other info for this product. I would like to remove the ul li formatting from the product's attributes in the customer order email and the printable invoice so that the info can be on a single line/table row. I found this in uc_order.module:

$product->details .= theme('item_list', array('items' => $attributes));

Would I just change 'item_list' to something else in a template.php function? If so, what would I change it to? If not, how else can I accomplish this change?

Thanks!

Not exactly what I was asking for, but I did find a workaround that works for the most part. I copied the uc-order--customer.tpl.php  file into my theme dir and added css for the ul to the head in that file. (display: inline-block and a few padding, margin, and list-style styles). The only issue now is the emailed order invoice. The CSS doesn't follow along into the email, so it's a bit of a mess. Open to any suggestions on how to handle that, or a better way overall.

EDITED TO ADD: I ended up copying the product line items from the uc-order--admin.tpl.php file. The attributes therein are not styled as a list, so it was a breeze to use that code.


How can I determine in the body of a hook implementation what hook it is implementing? I have a functional understanding of what the hook system is and how to use it in Drupal, but would like to deepen my knowledge. Normally when writing a hook, I know exactly what hook I'm using, because I've looked up what hooks were available, chosen one that suits my need, and implemented it. Sometimes though, I have a situation where I look at the THEME HOOK provided by the debugging output in the HTML, and I write a hook for that, and maybe add a couple of specifiers. For example, if I see this debugging output:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   x page--user--edit.html.twig
   * page--user--555.html.twig
   * page--user--%.html.twig
   * page--user.html.twig
   * page.html.twig
-->

I might implement a hook for page__user__edit. If I am in my theme called my_theme, I know I can go into my theme file my_theme.theme and implement the hook there, and that if I do I should begin the hook with my_theme_preprocess. So all together my hook should be my_theme_preprocess_page__user__edit, and I test it, and it works, and that part is all good.

Where my confusion comes in is when I go to specify parameters or document the function. What parameters does the function take? What hook does it implement? I am usually able to guess on the parameters, since usually it is (&$variables), but sometimes they are different. Ideally I would like to look up exactly what parameters the function takes based on the documentation for the hook, rather than trying to guess, but looking up the documentation for the hook can require some guesswork itself if you don't know what hook you are implementing. Some hooks are hook_preprocess_whatever, others are template_preprocess_whatever. Other times, like for a block, I wrote the hook my_theme_preprocess_block but it turns out this is not implementing hook_preprocess_block, it is implementing hook_preprocess_HOOK (or so I believe). So, once I have written a hook implementation (i.e. my_theme_preprocess_block or my_theme_preprocess_page__user__edit), how can I definitively know what hook I have just implemented?

Currently, I just Google a few different plausible-seeming hooks that I might be implementing, and if one of my guesses is correct or I get close enough that Google gives me a suggestion, I'm all set. In the case of the hook above, I'm able to find documentation for a template_preprocess_page function, and no such hook_preprocess_page function. Sometimes the results of this Googling process are less clear though, and leave me uncertain of what hook I have just implemented (like for the block - hook_preprocess_HOOK is very generic, how can I be sure I'm not implementing something more specific that I just missed in my Googling?). So if there does exist a way to definitively tell what hook you are implementing using a debugging tool or something, I would very much like to know about it.

I've tried using kint($variables) inside of my hook implementation (e.x.

function my_theme_preprocess_page__user__edit(&$variables) {
  kint($variables);
}

) but the closest thing I could find in there was theme_hook_original, which for the above gives 'page', so doesn't resolve these ambiguities about what hook I'm implementing.

Or, if there doesn't exist a way to tell what hook you are implementing with a debugging tool, is there a better way to figure out what hook I'm using other than what I'm doing? I'm open to suggestions on any level, including ways I should revise my workflow, something I should know about the difference between template_preprocess_whatever and hook_preprocess_whatever functions that if I knew that thing I wouldn't be confused, or whatever else. Thanks!

Where my confusion comes in is when I go to specify parameters or document the function. What parameters does the function take? What hook does it implement?

Preprocess hooks are only provided a single parameter: $variables. The hook that you're implementing is literally hook_preprocess_HOOK. The HOOK part of it is the identifier for the theme entry, as defined in a hook_theme() implementation somewhere.

So if you have this:

function MODULE_theme() {
  return [
    'foo' => [
      'variables' => [],
    ],
  ];
}

Then, by convention, you can implement hook_preprocess_hook like so:

/**
 * Implements hook_preprocess_HOOK() for foo templates
 */
function MODULE_preprocess_foo(&$variables) {
  // ...
}

Note the docblock; the convention is to use for XXX templates, where XXX is a description of the item being preprocessed. If you search for _implements hook_preprocess_ in the core folder, you'll find a lot of these as examples.

  So, once I have written a hook implementation (i.e. my_theme_preprocess_block or my_theme_preprocess_page__user__edit), how can I definitively know what hook I have just implemented?

By definition, you already know :) You created the function with a certain name, so you know which theme entry you're preprocessing variables for.

  like for the block - hook_preprocess_HOOK is very generic, how can I be sure I'm not implementing something more specific that I just missed in my Googling?

Because there can only ever be one theme entry for a given identifier, you won't run into this problem.

  something I should know about the difference between template_preprocess_whatever and hook_preprocess_whatever functions that if I knew that thing I wouldn't be confused

Hopefully, along with the above, this will clear things up:

template_preprocess_HOOK is, again by convention, used by the module implementing the theme entry, to provide the base variables. It's always run first, before hook_preprocess_HOOK is invoked, so it helps those defining theme entries to ensure important variables and processing are done up front before the rest of the system gets involved.
hook_preprocess_HOOK is essentially for other modules to preprocess the variables, rather than for the module implementing the theme. There's nothing to stop that module from implementing hook_preprocess_HOOK as well (it's just a naming convention and no special checking is made), but it could be undesirable to do that if some initial processing needs to be done, a la template_preprocess_HOOK.


Views : Output the field as link - not showing the field properties properly I want to output an image field as a link in views. I've seen many tutorials but get stuck at one point.

I already added the link on top of the image field. By clicking on the image at rewrite results I could check "output this field as a link" - but checking will not give me the fields properties where I could fill in the link field details - as shown in the below screenshot

Do you know what I'm missing?

Here's a picture of it.

Check this thread: https://www.drupal.org/node/1494860

Basically, upgrade to latest version of cTools and set the admin jQuery version to 1.5 via jquery_update.


How to add metatags to a view? I need to add rel=canonical meta tags to some views. There are a couple of sandbox modules for the metatag module but I'm looking for a more simple solution.

Couldn't I just use views_php and drupal_add_html_head()?

Try the Context Metadata module. It can add metadata to node and non-node pages. The following metadata tags can be set according to a context: Title, Description, Keywords and Canonical URL.


Using jquery mmenu, how to close one submenu when I open another submenu? I'm building a (Drupal 7.5) site where I use mmenu (Mobile Sliding Menu) module to create the menu. When I click the trigger, the main menu items appears. Some of the main items have a submenu. When I click the trigger for those submenus, the submenu opens, so far so good.

When I then click another submenu trigger, that submenu opens, but the previously opened submenu stays open as well. What do I need to change to have only ever one submenu open at any one time (i.e. triggering a new submenu closes one that was opened before)? There is no setting for this in the mmenu configuration (drupal module), and no instructions on this on the mmenu website (http://mmenu.frebsite.nl).

Many thanks for any help on this.

The easiest method I can think of is to use JS or jQuery to trap the click for every sub-menu item then, onclick, cache a reference to the clicked item, then programmatically close all of the open sub-menus with a loop, skipping the clicked item.

Try something like this:

(function ($, undefined) {

  // Execute once the DOM is loaded.
  $(document).ready(function () {
    // List of expandable sub-menu items.
    var subs = $('.mm-subopen');

    // Iterate through each sub-menu item...
    $(subs).each(function () {

      // Set up onclick handler...
      $(this).click(function () {

        // Cache reference to clicked item.
        var clicked = this;

        // Iterate through list of sub-menu items...
        for(i=0,c=subs.length;i<c;i++) {

          // If current item is not the clicked item...
          if (subs[i] !== clicked) {

            // Get reference to parent <li>, then remove the mm-opened class.
            var parent = $(subs[i]).closest('li');
            $(parent).removeClass('mm-opened');
          }
        }
      });
    });
  });
})(jQuery);

You might need to modify for nested sub-menus, but I hope this helps!


How can I remove the default generated  tags in view's result? I am using a views in my drupal web site. I have set 'style' to 'Unformatted' and 'Row style' to 'Fields'

Also I have Rewrote the output of the field with my HTML tags.

But I have a problem in the result.
Every row is located inside a [div] tag
for example the first row is located in

How can I setup the view in order to remove this extra [div] tag ?!?!?

I don't need this wrapper.

The easiest thing to do is copy the template files from "sites/all/modules/views/theme/" into you theme (I normally make a "views/" subdirectory).

If you want to make this change for all themes, edit "views-view-unformatted.tpl.php".

If you want to just change that view, edit the view then click on the Theme: Information link.  It will show the template suggestions for the view.  Copy
If you want to make this change for all themes, copy "views-view-unformatted.tpl.php" to the proper name, and edit that file.

In both cases, make sure you clear the Drupal caches to make sure the system finds the new files.


Can't connect to DB while installing Drupal 8 Can't connect to DB while installing Drupal 8. DB is located on localhost acording to direct admin but i can get to DB only when using ip address  in advanced options of drupal installation otherwise i get: SQLSTATE[HY000] [2002] No such file or directory. With ip entered it says  following message: SQLSTATE[HY000] [1045] Access denied for user on server.......

I have tried different  users and db that i have created on server (granted all permissions). No luck.

I have no problem logging to that DB with that user using phpmyadmin.  What does it seem to be the problem ?


How can I load all Media of a certain type? I am trying to load all media items of a certain type but I can't find how to.

Is there a way to set a filtering type on something like

$media = Media::loadMultiple();

Or do you have to load all media and then filter manually?

If you use entity query you can filter the entities by type before uploading them.

$ids = \Drupal::entityQuery('media')
  ->condition('bundle', 'YOUR_TYPE')
  ->execute();

$medias = Media::loadMultiple($ids);


Is it possible to have "pseudo-nodes"? Is there a way to expose content from other databases to Drupal so Drupal sees them like nodes? Importantly, this should work without making actual node entries in the Drupal database.

This would mean writing a module which specifies how to translate my proprietary content into Drupal node format, so one could write theming functions for that content, or use the Views module on it, etc.

Currently my module just displays the content directly on its own, without bothering to provide seamless Drupal integration into Views.

It really depends on what you are trying to accomplish.

If you need any Drupal feature, like commenting and tagging, or want to integrate with modules like Fivestar or Flag, then you need a node (or other entity).  If you want to get into the theming system, then I think you have no real choice.  The way I normally accomplish this is to have a hook that runs hook_node_load, does a call out to the remote system (either REST or direct DB), and then builds up a data structure and sticks it somewhere in $node.  You then have some preprocess functions to make the data available to the node templates, or you have a hook_node_view to get the data into the $node->content render array.  The next time I need to do this I will likely try to use the Field Storage API with content types defined by hook_node_info.

With this approach, the only thing the node is really used for is to have a $nid / $vid pair available to the rest of Drupal for other modules to work.  The content type that you are using typically only needs on field in it to store the primary key in the remote system.  I usually also copy over the title to the node to make it easier to identify in the admin UI.

Though all of this may seem hard, it is actually pretty straightforward and mostly easy to implement if you are familiar with the API.

Just remember that what you need to do now may not be what you want to do in the future.  Preparing for this by having true nodes available may make better sense in the long run.


Attempting to merge in an array of items into Twig classes I have a Twig template where I'd like to merge in an array of items as classes. So far I have this code:
{% set classes = [
  'media',
  'media--type-' ~ media.bundle()|clean_class,
  not media.isPublished() ? 'media--unpublished',
  view_mode ? 'media--view-mode-' ~ view_mode|clean_class,
] %}

 {% for item in content.field_category | children(true) %}
   {% set classes = classes|merge(item) %}
 {% endfor %}

<section{{ attributes.addClass(classes) }}>

etc...

Note that {% for item in content.field_category | children(true) %} is using Twig Tweak.
In this case for example, item represents term values for each item in plain text as:
Nature
Travel
Architecture

and then with <section{{ attributes.addClass(classes) }}>, I'd like the set classes as well as my custom classes to all be merged together. However, I am getting an error:
Notice: Array to string conversion in Drupal\Core\Template\AttributeArray->__toString() (line 73 of core/lib/Drupal/Core/Template/AttributeArray.php).

So this tells me, I did not merge the array of items properly but I am lost after this, not sure how to fix it. My guess is, I need to do this without a for loop somehow?

Twig's merge filter expects an array as an argument, not a string.
Updating your for loop should resolve:
{% for item in content.field_category | children(true) %}
  {# Merge classes array with an array with one item, item #}
  {% set classes = classes|merge([item]) %}
{% endfor %}


$_GET['q'] for all entities I have this code.

     if ($_GET['q'] == 'entity/bundle'){
        unset($css[drupal_get_path('module', 'system') . '/system.base.css']);
 }

Which I use in template.php to unset css on certain pages, but I want to have code (in this case unset css) to run on all entity pages for example entity/bundle/1, entity/bundle/2, entity/bundle/3. How can I get this to apply to all entity pages. I need something like entity/bundle/% or entity/bundle/* or maybe there is another way.

Context add assets seems to be a good solution for this https://www.drupal.org/project/context_addassets


drupal 7 workbench: Can I limit different users/roles within a particular section via taxonomy? drupal 7 workbench: Can I limit different users/roles within a particular section via taxonomy?
If I setup 2 roles Author and Editor and I assign different users with the same role (i.e. Author) but assign them to a different section via taxonomy (i.e. Northeast region or Southwest region).  Once this is done will users with Northeast region taxonomy and Editor role only see "Needs Review" documents within the Workbench section created by Author user that have the matching Northeast region taxonomy?

You use the submodule of Workbench, called Workbench Access to limit users to a "sub section" of the content based on Taxonomy or Menu path.

  Workbench Access creates editorial access controls based on
  hierarchies. It is an extensible system that supports structures
  created by other Drupal modules.

  When creating and editing content, users will be asked to place the
  content in an editorial section. Other users within that section or
  its parents will be able to edit the content. A user may be granted
  editorial rights to a section specific to his account or by his
  assigned role on the site.

There is a great documentation page and associated web video for Workbench Access on configuration within the project page.


Drush fails "unable to copy" to drush-backups? When I run $ drush pm-update I receive an "Unable to copy" error.

  Unable to copy /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to /home/ec2-user/drush-backups/opencall/20150422140414/drupal.               [error]
  Unable to move /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to /home/ec2-user/drush-backups/opencall/20150422140414/drupal.               [error]
  Failed to backup project directory /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to

Any thoughts? I'm sure it will run if I use sudo but that has other undesirable consequences.

Think I've solved it.

Looks like someone previously ran Drush in the sudo environment and that had the effect of setting permissions to 6226 all over the place.

Updated manually and fixed permissions as I went.


Inject variables from Controller to Blocks? I have a Product module that implement's an entity, a Repository, a Controller and 2 Blocks

The problem is, in the product page, I'm querying the entity in every block and also in the Controller. I'm trying to find a way to query ONLY ONE TIME, and then pass the result to the 3 parts (Blocks and Controller).

So for example, I have:

class SidebarProductBlock extends BlockBase {

  $repository = new ProductRepository();

  $product_id = $route_match->getParameter('id');
  $productObject = $repository->getProductByProductId($product_id);

  // Some more processing and return
}

class StoresGridProductBlock extends BlockBase {

// Here I query AGAIN

  $repository = new ProductRepository();

  $product_id = $route_match->getParameter('id');
  $productObject = $repository->getProductByProductId($product_id);

  // Some more processing and return
}

// And in the Controller I query AGAIN.

How can I manage to query the database just one time and use pass the result in all 3 parts?

The Blocks are always rendered in the same page

You can't inject variables from a controller to a block.

Generally it would help to put the repository in a service, so that you don't have to instantiate it multiple times and are able to cache product objects queried before.

In this case you don't even need to call the repository in each controller/block, because Drupal upcasts entities to objects in routes and you can get the object directly from the route match, as long as the product entity is using the standard way to generate entity routes with param converter.


Ajax error every time open view i want to create new view but every time i make selection like user, content etc. i got this error

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /dru/system/ajax StatusText: Internal
  Server Error ResponseText:  registrar_frameset({ a_id: 48873,       //
  edit this to pass your portfolio ID, drid:
  'as-drid-2416478692338427'});     // edit this to pass your Domain
  Registrant ID

I would comment this, but I do not have the reputation. If you are using jQuery Update module, make sure it is set to 1.5 for the admin pages.


what can replace hook I am a newbie into Drupal.

what else other than module name can replace 'hook' from any hook function in Drupal?
For ex.
"myModule" replaces hook in hook_form_alter and defined as 'myModule_form_alter'

Any alter hook and preprocess hooks that is defined inside a module can also be defined inside the theme as well. So if you are using Bartik theme you can open the Bartik's template.php file and use

function bartik_form_alter(){}

UPDATE

Checking the Is it possible to define hook functions in template.php instead of the module? can also be helpful.


drush - which folder for install on VPS / root server (newbie) good evening,

new to drupal - I want to install drush on my linux root-server, which  runs OpenSuse Linux my friend does the root adminstration.

What is aimed: i want to work on all my drupal domains - but i guess that i do not need root access. Can anyone please tell me which folder I should use to install drush?

Do you need to have my file structure? Well if so, i  can give you later this week.

Well a friend told me to take $HOME/local/drush, but cant we put it anywhere;
we just need to make sure that drush is in our $PATH. See the README.

or what is with this hint top take the domain path like so

/var/www/vhosts/mydomain.com and echo $HOME gives me /root.

So would I create a 'local' directory in /root and install drush there

so the path would be /local/drush/drush.php?
I am not just asking from a drush point of view but also from a server file structure point of view ie that I think I am not allowed to upload stuff to some server directories.

But wait - i do not want to have all root rights - is this doable?!
Can i install drush into the www-directory where all the domains are rooted!?

Thanks for any and all help - it will be greatly appreciated as allways.
zero-your drupalnovice

hi there just an update:

if someone wants to update the sites trough the terminal?

in that case:

I don't think it's matter where we put it, we could put it in the root if we'd like, once installed after pear-chanell....

http://drupal.org/project/drush

we can update any site on our

srv/www/htdocs

we just have  to get inside the htdocs/site1 and type drush sm update
do our things and get into our new site htdocs/site2 and do whatever we want to do there with drush too.

and the best thing is: one install works on all our sites.

that rocks yeah

You didn't say much about the distribution you're using. but i would suggest searching for a package for your Linux distribution. Installing it that way usually is the safest and easiest. There is one for Debian/Ubuntu and Gentoo as far as i know.


Query with multiple where clause I have a query that works fine with one where clause however when I add AND it doesn't work, can someone please tell me what I'm doing wrong?

$args2 = array(':name' => $existingproductIDfield);
$args3 = array(':vid' => '6');
    $result2 = db_query('SELECT * FROM taxonomy_term_data WHERE name = :name', $args2 .'AND vid = :vid', $args3);

    if ($result2->rowCount() > 0) {
        foreach($result2 as $row) print_r($row);

    }

Parameter replacement is done all in one go, and you just need to provide a single associative array of args to db_query() for those replacements:

$args = array(':name' => $existingproductIDfield, ':vid' => 6);

$result2 = db_query('SELECT * FROM taxonomy_term_data WHERE name = :name AND vid = :vid', $args);


Limit total quantity of products across user's entire order history I am trying to limit a user's total quantity of products across their entire order/purchase history based on a field on that product. For example, if Can of Peanuts has a limit of 3 per user, then the user should not be able to buy 3 then place another order for 3.

Does anyone have any recommendations for ways to accomplish this?

Use hook_form_commerce_cart_add_to_cart_form_alter()

<?php
mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id)
{
  /*code*/
}
?>

Then, inside the hook, use entityFieldQuery to get list of orders for this user

For locating the "currently selected product," you can use the form_state variable:

<?php
$current_product = $form_state['default_product'];
?>

Finally, you'll want to iterate over each order and use entity meta data wrappers to wrap the orders so you can iterate over the line items, looking for matching products.

<?php
foreach ($orders as $order_id => $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
  }
}
?>

The final final round would include looking to see if the line item is attached to the product and then counting the number of products this person has purchased.

Unfortunately, while you might be able to construct an SQL statement that does most of the heavy lifting (instead of iterating over all the user's orders and line items), it would require much more intimate knowledge of your particular store architecture.


How to Rename "Request new password" link? We want to rename the "Request new password" text on a Drupal's login page to some custom text.

In the user.module file, I see that this text is hard coded

if (variable_get('user_register', 1)) {
    $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  }
  $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  $form['links'] = array('#value' => theme('item_list', $items));

Is there any other way of renaming this text rather than modifying the Drupal core?

The String Overrides module is a good suggestion if you have many strings, or need to constantly alter them, but you can also achieve this by editing the string overrides section of your settings.php file.

Simply uncomment the section so it looks like this:

$conf['locale_custom_strings_en'] = array(
  'Request new password' => 'MY CUSTOM TEXT FOR A NEW PASSWORD',
);


Setting admin theme using Profiler I'm using Profiler to create a Drupal 7 installation profile, which works great -- however, it doesn't set Seven as an admin theme, and thus falls back on Bartik (The default theme).

Is there any way to set the default admin theme within Profiler?

One way to accomplish this is to use Strongarm to set the admin theme variable as part of a Feature.

Given that the "Standard" Drupal installation profile creates a lot of other stuff that won't be in a custom installation profile -- Basic Page and Article content types, for instance -- I've created a Feature with all those and added the Admin Theme Strongarm variable as part of that.

That said, leaving question open in case somebody knows how to set the Admin theme as part of a Profiler makefile.


Bootstrap sub-theme with responsive and off-canvas menu module I've created a custom Bootstrap sub-theme and am replacing the default Bootstrap menu with the Responsive and Off-Canvas Menu Module but seem to be running into a string of problems.

No matter what settings I select, the Mobile "Burger" icon is always showing on the page. I thought it would hide depending on whether the horizontal menu was being shown or not by default. I know I can manually hide this with media queries in my CSS but just not sure if that's the optimal method.
I have no idea where the Off-Canvas portion of my menu is coming from? There doesn't seem to be a twig template for it. How is this being generated?
Also, when the off-canvas menu is being used, for some reason it's placing carats next to each link as well as the default arrow to show there is a sub-menu. Is this carat coming from the Bootstrap theme template files? Also, when I click to view the sub-menu items in the off-canvas view, none of the sub-menu items are listed at all like they are on the default horizontal view. Why is this? The off-canvas menu doesn't seem to be able to locate any sub links for some reason.

Has anyone used both Bootstrap and this Module together to shed some light on this for me and if there were any complications that you encountered as well, if any?

Turns out the Bootstrap menu--main.html.twig file was causing the issue. I just created a theme override for it and made it just the default Drupal menu code and all is working properly now.


How do I connect vocabularies and filter them to be depend on each others? The vocabularies I use are:

TV Channels
TV Shows

The "TV Channels" vocabulary includes 6 terms, where each term represents a TV Channels (e.g. channel<1>, channel<2>, channel<6>).

The TV Shows vocabulary includes 30 terms, where each term represents a TV Show, but not all of them belong to a one TV Channel, but some of them belongs to channel<1>, and others for channel<2>.

I've already created a content type, and added various fields for these vocabularies using term references.

How do I make a filter? When I choose the TV channel from the filed, and then move to the next filed for the TV Show I should only find the ones belonging to this TV channel, and not the whole TV shows from all the channels.

This is a very clever idea, but will it allow me to list all TV Show episodes when I click on any given TV Show link?

Also about the main presenter, how can I add it to the content type the same way?

My point is to find a way to list contents in the website as a whole by:

TV channel
TV show
Main presenter and guest
Topic
Date of broadcasting

So I've created various taxonomies like the following:

I created a vocabulary for each one of the above first four items.
I added terms for each one of them:

TV Channel vocabulary
TV Show vocabulary
Main Presenter & Guest
Topic

I have installed these modules:

Chaos Tool Suite
Form Elements - Hierarchical Select
Panels
Taxonomy Menu
Views

I added a content type with these fields:

TV Channel
TV Show
Main Presenter
Guest
Topic
Broadcasting Date: This one I need to make it in a pop up calender way so if I click on any given date to list all episodes for various TV Shows from any given TV Channel.

The first five fields are term reference fields.

The alternative solution is to add a single vocabulary "TV" and make it two level. In first level all the "channels" will come and "shows" will be added as a child term (second level). Now for reference use "Hierarchical Select" module.


How do I use API versioning? I'm using the Services module to produce a REST API.  According to the official documentation, there is a way to version services resources.  I believe version here means supplying a single API (e.g. example.com/api) and allowing clients to specify which version they want per resource with headers.

So I think that means that these two requests would return different results, despite living at the same URL:

Version 1.0:

POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json

Version 1.2:

POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json
services_system_set_variable_version: 1.2

I cannot make this work for the life of me.  Here are the steps I took:

Enabled the system/set_variable service

Added the following code to mymodule.module (cribbed directly from services.versions.api.php)

.

function _system_resource_set_variable_update_1_1() {
  $new_set = array(
    'help' => 'Create a node with an nid test',
  );
  return $new_set;
}

function _system_resource_set_variable_update_1_2() {
  $new_set = array(
    'help' => 'Create a node with an nid optional prams.',
    'args' => array(
      array(
        'name' => 'name',
        'optional' => TRUE,
        'source' => array('data' => 'name'),
        'description' => t('The name of the variable to set.'),
        'type' => 'string',
      ),
      array(
        'name' => 'value',
        'optional' => TRUE,
        'source' => array('data' => 'value'),
        'description' => t('The value to set.'),
        'type' => 'string',
      ),
    ),
  );
  return $new_set;
}

Cleared cache
Attempted to use the system/set_variable service with postman.
Saw that the system/set_variable service was working

Attempted to use the system/set_variable  service without arguments, per _system_resource_set_variable_update_1_2
Saw that arguments were still required

So what am I doing wrong here?  I'm pretty sure I followed all the instructions.

Quote from services.versions.api.php

  For clients that want to request a specific version they need to pass a certain header

  services_RESOURCE_METHOD_version = version
  as an example, services_system_set_variable_version = 1.2
  @see ServicesVersionTests for code examples

Make sure to use set acceptable Content-Type.

Content-Type: application/x-www-form-urlencoded

GET /v1/status HTTP/1.1
Content-Type: application/x-www-form-urlencoded
API-KEY: AAAAAAA
TOKEN: VVVVVVV
services_status_index_version: 1.1
Host: local.mywebsite.com
Connection: close
User-Agent: Paw/3.0.16 (Macintosh; OS X/10.11.6) GCDHTTPRequest


Patch method sample code REST API I am working on web services in drupal. I have created a sample module for get method to expose the data using web services. I have not found any sample code for the patch method.
code for get method:

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

I am novice to drupal. I did not find any example for patch method. Can any one usher me or provide a sample code for patch method.

It's actually quite simple. You only have to do like this:

public function patch() {
  // Write your code in here.
}

The patch function uses the canonical link just like get.

 * uri_paths = {
 *   "canonical" = "/path-to-endpoint", // Used for GET, PATCH and DELETE.
 *   "create" = "/path-to-endpoint/post" // Used for POST.
 * }

To get the request object, I think that you can use $request as first argument like this:

use Symfony\Component\HttpFoundation\Request;

public function patch(Request $request) {
  // Write your code in here.
}


How to prevent drupal 7 from saving a node I have a dummy form that will act as a main switchboard for all my content types. For example:

My starting point in the form fill up process starts with the 'Enter basic categories' node type where user specifies the categories in a taxonomy hierarchy:

Classifieds
  -Autos
    -Aston Martin
  -Computers
   -Desktop
   -Laptop
  -Jobs
A user then selects any of the terms and the page now redirects to the appropriate content type form, e.g. computers_node_form

The thing is that Drupal saves this Enter Basic Categories Node Form data that I no longer needed.

Is there a way to cancel or prevent Drupal 7 to save the first content type before the redirect? Any suggestions?

So basically, you don't want a form for content entry, but you want a form to streamline the user navigation - right?

You can probably alter the node form (implementing hook_node_submit for instance) to stop it from saving data, but I recommend against it. The essence of a node is that it is site content, so it doesn't make sense to have a node form that doesn't save a node to the database.

You can build a custom form that does exactly what you want it to do by implementing hook_menu (to choose the url for your form) and a custom form generating function. See form_example.module for examples of custom forms.


Embedded Media Field Video: Output both Video Flash Object and Video Thumbnail in Node Display? I would like to be able to access both the Video Flash Object, as well as the Video Thumbnail filepath from the Node Display. Please let me know if I can provide more info, not sure anything else is relevant! Thanks!

Clarification: Basically I want to be able to be able to output both the video with a custom resolution, and the thumbnail through an imagecache preset, from either a custom module, or within template.php. Essentially I would hope to end up with both the final video HTML and image HTML as individual objects or php variables, so I can then output them wherever I like from within the relevant node.tpl.php. I'm assuming there's a simple theme() function I can use for both of the above. The embedded video at this time can come from either Youtube/Vimeo.

One way to do it is to set the video field display mode to full video under /content/types/CONTENT_TYPE/display then add the thumbnail via theme_emvideo_video_thumbnail() as a variable using themename_preprocess_node(&$vars) in your theme's template.php -OR- print it directly in your node.tpl

The trick to theme_emvideo_video_thumbnail(($field, $item, $formatter, $node, $no_link = FALSE, $options = array())) is to provide all the right parameters. Especially $options

e.g.

<?php
  // code adapted from emvideo.theme.inc
  // ignore the <?php tag

  $system_types = _content_type_info();
  $field_name = 'field_video'; // the machine name of your video field

  $field = $system_types['fields'][$field_name];
  $field['widget'] = $system_types['content types'][$node->type]['fields'][$field_name]['widget']; // get CCK widget data. includes all formatting settings

  $options['return_url'] = TRUE; //return URL
  $options['raw'] = TRUE; // return image path. Otherwise node path is returned

  print theme('emvideo_video_thumbnail', $field, $node->{$field_name}[0], 'video_thumbnail', $node, FALSE, $options);

In template.php

<?php
// change MYTHEME with the theme's machine name or use phptemplate
function MYTHEME_preprocess_node(&$vars) {
  if ($vars->type == "mynodetype") {
    // see code above
    $vars->video_thumbnail = theme('emvideo_video_thumbnail'...);
  }
}

Then <?php print $video_thumbnail; ?> where you need it in node.tpl.php (-OR- use the first code block directly in the node template)

Hope it helps.


Drush @sites not implemented in drush 9 Since drush 9 (drupal 8.4 requirement), alias @sites does not seem to be implemented anymore (or yet ?).

$ drush @sites cr
The alias @sites could not be found.

Is this a way to get the same behavior that does not consist of typing my 300 alias in a config file ?

Waiting something similar, I wrote this small script I called "drall" you may adapt:

#!/usr/bin/php
<?php

// Path to sites.php file.
include('web/sites/sites.php');

$done = [];
$argv = $_SERVER['argv'];

array_shift($_SERVER['argv']);

$parameters     = implode(' ', $_SERVER['argv']);
$commandPattern = "drush --uri=:key $parameters";

foreach ($sites as $key => $site) {

  if (count($argv) > 1 && !in_array($site, $done)) {

    $command = str_replace(':key', $key, $commandPattern);
    echo "Executing command `$command` on $site\n";
    `$command`;
    $done[] = $site;
  }
}

Use example:

$ ./drall cc render
Executing command `drush --uri=xxxxxxx cc render` on default
 [success] 'render' cache was cleared.

Hope there will be some @sites behaviors later, that was helpfull.

Although from this issue it doesn't look like it:

  Drush 9 no longer supports executing a single command on multiple sites with alias lists (@A,@b,@c) or @sites. Neither of those syntaxes are available in any context. You may still use drush sa @group to see all aliases in a group; that is the only context in which Drush recognizes alias lists.


webform: redirect to modified result page After somebody submits a webform, he should be redirected to the "webform
result" (which is standard generated, but only accessible by clicking the
"webform results" tab as an admin).
My module needs to hook into the "webform results", and add some simple custom PHP
calculations on top of that "webform result" (for example: if two
radio-elements have a certain value, a warning is displayed on top of that
result page)

Any ideas ?

cheers

You have do some customization for this, use hook_form_alter().

Create a custom module.
Create a result page in that module.
Alter the webform.
Do the calculation.
Sent the data to result page and show.

Example:

function  MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_') === 0) {
    // webform_client_form_ (change this id with your form id)

   $form['#submit'][] = 'changeform_form_submit';

  }
}

function changeform_form_submit($form, &$form_state) {
  ... your submission logic ...
}


How do I add CSS & JavaScript to ? I want to add the following code in my  section of the front page using a Drupal 8 sub theme of Bartik.

Can anybody help how to do it? What is the best way to do it in this new twig version of theme? Where is page.tpl?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="stepcarousel.js"></script>

On you THEME.libraries.yml:

global-styling:
  version: VERSION
  header: true // <--- To the header!!!
  css:
    theme:
      css/mystyle.css: {} // if you want add custom css
  js:
    js/stepcarousel.js: {}
  dependencies:
    - core/drupal // for use drupal.js
    - core/jquery

On you THEME.info.yml:

name: THEME
base theme: Bartik
...
libraries:
  - THEME/global-styling
...

and Clear Cache

  Where is page.tpl?

Here: core/modules/system/templates/page.html.twig

If you want use it, copy to theme folder inside templates, like this:

 THEME
   templates
     page.html.twig

Change all you want and Clear Cache


How to create a rule that checks an extra profile field created with the core profile module? I have a Drupal 7 site with the Honeypot module installed. Honeypot removes or prevents many spam registrations, but not all. I have extra fields added to the profile e.g. 'profile_field1'. I'd like to build a rule using the Rules modules that either deletes an account or prevents it from being created if the content of the 'profile_field1' doesn't match a certain regular expression.
I cannot find how to create a rule that can handle an extra profile field.
What I'd like to create:

'before saving a new user account'
if profile_field1 does not match RegExPattern
then prevent account from being created

I can find how to create a condition based on the 'regular' fields in the account (such as the name), but I cannot find how to test for the extra fields.

Update 1: the field 'profile_field1' is part of the Users profile, i.e. the Drupal Profile module is enabled. This module is part of D7 and similar in functionality to drupal.org/project/profile (for D8). It's found in [drupal]/modules/profile. Configuration settings are in admin/config/people/profile.

Update 2: I checked in the database. There is no table called 'profile_field1'. The info is in 'profile_field' which defines all fields and in profile_value, which contains all values.
So, e.g. profile_field1 would be fid=1 in table profile_field. Then user 5 (uid = 5) would have a record in profile_value with fid = 1, uid = 5, value = 'content of field'.

Update 3: With the suggestions in the answer I was able to migrate the information from the old Profile to the Profile2 fields. Write up is here: https://www.drupal.org/node/2916659

Update 4: At least I can create a Rules rule now. Just wondering if this is the best:

{ "rules_prevent_spam_registration" : {
    "LABEL" : "Prevent spam registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "account-unchanged:profile-personal" ],
          "field" : "field_profile_field1"
        }
      },
      { "AND" : [
          { "text_matches" : {
              "text" : [ "account-unchanged:field-profile-field1" ],
              "match" : "<regexPattern>",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [ { "entity_delete" : { "data" : [ "account-unchanged" ] } } ]
  }
}

With the limited info provided in your question, the best bet is that you cannot test for that extra field because you forgot to add a Rules Condition like "entity has field" (related to your profile_field1 field). So add that Rules Condition first (as your very first Rules Condition), and then try again.
For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.
Update:
As per your updates to your question, I now understand that you're using the deprecated (core) profile module. This is a quote from its .info file:

; The Profile module is deprecated, and included in Drupal 7 for legacy
; purposes only. By default, the module will be hidden from the UI unless you
; are upgrading a site that uses the Profile module to extend user profiles.

Because of that, I doubt that there is a way to use the Rules module to check "if the content of the 'profile_field1' doesn't match a certain regular expression" (as in your question). Mostly because the Rules Condition like "entity has field" (=  typical prereq to configure these kinds of Rules Conditions) will not have any effect for such profile_field1-field. Maybe not the answer you would want to hear/read, but I'm afraid it explains that what you're asking for cannot be done with Rules.
Plan-b:
Give it some thought to consider switching to the Profile 2 module. Quote from its project page:

Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!
Features
... Thanks to the foundational entity API the module integrates well with Rules ...

If you do, pretty sure my original answer (= add a Rules Condition like "entity has field") will turn out to be the solution for what you try to achieve.


How to disable webform select box with jQuery without resetting selection value to default I have a webform, below's a section of the form (the selection field)

<select id="edit-submitted-bring-alcohol" name="submitted[bring-alcohol]" class="form-select">
    <option value="yes" selected="selected">Yes</option>
    <option value="no">No</option>
</select>

I now use jquery to dynamically setup this field.

if (age < 19) {
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').prop('disabled', true);
}

This works great. When user entered their age, this method automatically change the selection to 'no' (if they are under 19), and disabled by itself.
However, the problem I have now is that the submitted value I received is 'yes' when the selection field is disabled (apparently it chooses the default value).

So could anyone help me out?

You can do this by removing the 'selected' attribute first, and setting the new selected attribute, prior to disabling.

e.g:

if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').prop('disabled', true);
}

Here's a jsfiddle link for tinkering: http://jsfiddle.net/AwUwt/

Edit: Alternatively, you can just hide the select box

if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').css('display', 'none');
}


How to build an url to access filtered view? From a first view I need to dynamically build an URL to add a link to another filtered view named gallery_details.
I created a tpl template for my view where I build the URL like this one:

  http://www.example.org/?q=gallery-details&field_main_categorie_value=Anciens&field_categorie_value=dessin&page=2

where field_main_categorie and field_categorie are the two used filters.
When the two filters are "exposed" it works, but if I uncheck the exposed filters, this URL become invalid.
I don't want to let the user to directly select the filters on gallery_details, also a solution may be to hide the exposed filters in gallery_details view.

I guess that there is a better solution.

Have you tried using Contextual Filters in your view? It sounds like they do what you want.


How to access the user's email field with Field Permissions? This is a sort of sequel to my previous question How to hide specific fields and the according label in a view, based on field permissions?. One of the fields I'm displaying in my view is the standard User: Email field. I'd like to hide this field in my view except for the administrator and the user himself/herself.

How can I do that? I can't find a way to access the field with the Field Permissions module. If someone could show me a way to do that (my previous question is solved), this question would be solved.

Or is the Field Permissions module not suitable for this situation?

I think your issue here is a duplicate of this one:
https://stackoverflow.com/questions/2727513/drupal-show-hide-fields-in-view

The two solutions are:

in the field template, display the content depending on the user role
or
create two views displays, one for each of your user role


New action for Views Bulk Operations I'm trying to add some custom actions to my Views Bulk Operations, but for some reason, they don't appear in the list.

This is my code (got it from Drupal.org, so I guess this is a working code...)

function publication_action_info() {
  return array(
    'node_unpublish_action' => array(
      'description' => t('Unpublisedh node--'),
      'type' => 'node',
      'configurable' => FALSE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
    'node_unpublish_by_keyword_action' => array(
      'description' => t('Unqsdfqsdfpublish node containing keyword(s)--'),
      'type' => 'node',
      'configurable' => TRUE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
  );
}

So what's wrong with my code or logic to make this thing to work?

Here is the way, I found for D7...

/**
 * Implementation of hook_action_info().
 */
function MODULE_action_info() {
   $action = array(
    'MY_ACTION_NAME' => array(
      'label' => t('MY ACTION LABEL.'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
 );
 return $action;
}

/**
 * Action function for MY_ACTION_NAME.
 */
function MY_ACTION_NAME(&$entity, $context = array()) {
  // Your code here.
}

Now just add the action MY ACTION LABEL in VBO list.


Installing new module in Drupal 8.3.2 link is not exist in xampp I installed drupal 8.3.2 in xampp (localhost). But i can't add new modules like themes,image slider etc.. What I want to do?

Just download zip unzip it and paste folder to xampp\htdocs\modules. It should be working then.


How to create a pager to display next article in particular taxonomy? How to create a pager to display next article in particular taxonomy? I can not find any module.

I tried to do this with a view. I created a view that display all content from article and add a pager, but then i've got another problem (cant related this with another view from home page that display image and title from all articles and navigate to chosen article)

Sorry for my english.

I have view that displays fields (image and title) from articles with taxonomy term (e.g. Shapes) like this:

When i click on image i go to this article:

but I dont know how to do pager like on this picture that could navigate me to next article:

You can accomplish this with the contrib module Flippy. It will allow you to add pagers for specific content types. Hope it helps.

  Flippy is an ultra-simple module that generates previous/next pagers
  for content types. On the Node type administration screen, you can
  turn Flippy on or off for each content type. It'll generate a unique
  pager for each content type, so you can page through Articles or page
  through Blog posts, but you can't page through all nodes on the site.


How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)? I know how to email using Rules when a field in a node is changed and add conditions for particular fields whether they were changed.

But I would like the email to contain the info which field(s) exactly were changed and from/to which value.

E.g., I have a content type with 20 fields. Then I create a node and populate all the fields. Now I want to change two fields in the node (e.g., "First Name" and "Age").

I'd be happy to receive the following email:

The following was changed in "Node name":

"First name" changed from "John" to "George".

"Age" changed from "35" to "76".

Some of the ingredients you'll need for a possible solution to make this work:

The Conditional Rules module.
Rules Actions "Add a variable" and "Set a data value".

Read on for more details ...

Here is a rule, in Rules export format, which is a prototype of what you're trying to get to work:

{ "rules_notify_admin_of_selected_field_updates" : {
    "LABEL" : "Notify admin of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "Field changes applied to a node:" },
          "PROVIDE" : { "variable_added" : { "field_changes" : "Added variable" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Optionlist changed from \u0022[node-unchanged:field-optionlist]\u0022 to \u0022[node:field-optionlist]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Free Format Text changed from \u0022[node-unchanged:field-free-format-text]\u0022 to \u0022[node:field-free-format-text]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Field changes in node with nid=[node:nid]",
          "message" : [ "field-changes" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the above rule:

It showcases updates to (only) 2 fields, i.e.:

a selection list field with machine name  field_optionlist, and a few possible values.
a free format text field with machine name field_free_format_text.

The Rules Actions "Add a variable" is to create an appropriate variable.
The Conditional Rules module allows for including like "Rules Conditions" within the Rules Actions.
Using "Set a data value" we append what's appropriate to that variable.
In the end (last Rules Action), we make Rules send an eMail with an extremely basic eMail body: the content of the variable we populated in the previous Rules Actions.

Assuming that you enabled the Conditional Rules module, you should be able to import the rules example above in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names).

Homework:

Extend the prototype from 2 to 20 fields (= sames as except ...).
You may want to improve the formatting of the eMail body, eg add some relevant HTML tags in it to make it more readable. Maybe also its subject, etc.

Voilà, happy (Conditional) Rules-ing!

PS: Would be nice if you could use a Rules "loop" to iterate over all 20 fields in a single loop, similar to what is shown in the answer to "How to create a rule to send an email to a list of selected email addresses?". However I'm not aware of anything in Rules to do so.


How to add the admin role to Drupal 7 after upgrading from Drupal 6? In Drupal 6 there was a module called Admin Role which allows you to make a superadmin role (same rights as superuser). This function is now in core (as of Drupal 7). So if you install Drupal 7, you get three roles by default: anonymous, authenticated, administrator.

However, when upgrading a site from D6 to D7, this new admin role is missing. How do I add this role or convert an existing custom role to be the admin role?

You can set an admin role in admin/config/people/accounts or by going to Configuration -> Account Settings under "People" label.

The help text under the select box says:

  This role will be automatically assigned new permissions whenever a module is enabled. Changing this setting will not affect existing permissions.

So remember to assign the existing permissions to this new role! But whenever a module is enabled and new permissions are created, this role will automatically be granted those.

To create new roles you go to People -> Permissions (tab) -> Roles (secondary tab)


How to disable redirection to the node after node form submission I have a node form exposed in the front-end to allow visitors to add their organisation to the list of partners. Below the form, I have exposed view block with the list of existing partners.

When a visitor enters a new organisation to the list I want the form just to add a new node type "partner" and reload the page/block without redirecting to the node content (node/[node ID]).

At the beginning I ed taxonomy terms instead and it worked as it should, now I want to achieve the same with node entity.

I have tried various solutions but none of it works correctly and I didn't find much by googling it.

For example, this is not functioning:

function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id == 'node_partners_form') {
    $form_state->disableRedirect(); // This is not functioning
  }
}

This does not work either:

function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id == 'node_partners_form') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'THEME_node_form_submit';
      }
    }
  }
}

function THEME_node_form_submit($form, &$form_state) {
  $form_state->setRedirect(Url::fromUri('internal:/node/1')->toString());
}

=> Error: Route /partners does not exist.

Value of attribute action in the exposed node form is correct and therefore I think the proper solution should be elsewhere then altering form properties - probably it has more with the Drupal behaviour after adding a new node.

<form action="/en/partners">...</form>

Thank you for the comment 4k4. Unfortunately, I didn't have enough time to find a proper solution so I just changed the redirection URL to the same content where the form is exposed.

function THEME_node_form_submit($form, FormStateInterface $form_state)  {
    $node_id = 1;
    $form_state->setRedirect('entity.node.canonical', array('node' => $node_id));
}

I'll try to find a more appropriate solution if I'll have some extra time before deadline :)


how to put arguments into contextual filters In this post http://drupal.org/node/228959 says that i need to add an code to the argument of view2,

I add a contextual filter in views 3, but where is the spot to place the following code?

if (arg(0) == 'user' && is_numeric(arg(1))) {
    return array(arg(1));
}

There's a comment in that article down below with a code to import for D7 and Views 3.

If you import that code into your Views 3 and then study the Contextual Filters and the Relationships you should get a good idea on how to achieve this.


Drupal 7 Apache solr - how to index pages content instead of nodes content I have a drupal 7 website with pages that include multiple nodes and I use Apache Solr as search module. It works but the results are very messy.

This is a page structure exemple:

As you can see, I have multiple nodes defined on my page. I'd like the indexer handles the content as page content but not like node content. In other words, I don't want the indexer handles this page as an addition of nodes but like an unique content.

In this case, I'd like to get a page URL as result but NOT multiple node URLs.

I hope it's clear enough.
Thanks

If I get you right, you don't want to show nodes in search results which are only used to be referenced to from another node, correct?

First of all, you need to define which Content Types should be indexed by SOLR. For this go to your SOLR settings page and untick all Content Types you don't want to show up in your search results.

After this done, I would highly recommend you to install the Display Suite module. This Module allows you to create different View-Modes. Built in and among many others which are available when you enable them, is the "Search Index" View-Mode. After enabling it for your Content-Type you can set it up the way SOLR should index it. So in your case probably the best would be to show the full content of the referenced node in the search index.

I hope this brief hints and tipps will help you ... To explain the Display Suite with all its possibilities is not possible in one post, but you really should try it.


content type doesn't editable from UI There is a way to prevent the editing of my custom contet type from UI?
I have created my custom content type programmatically and I added a few fields and field groups.
The content type and fields must not be editable by UI but only from code.
I have tried to use the property 'locked' in hook_node_info() but without results, the content type is editable yet.

For ordinary users, you can just disable the "Edit any content" permission for the type in the Node section of Administration » People » Permission GUI:

However if you also need the to prevent user #1 (the default Administrator role) from editing, this will not work, since access controls are not enforced for that user.  Instead, you can implement hook_menu_alter() to override the access callback for the node edit page, and provide your own instead:

function MYMODULE_menu_alter(&$items) {
  $items['node/%node/edit']['access callback'] = 'MYMODULE_node_edit_form_access';
}

function MYMODULE_node_edit_form_access($node) {
  $type = is_string($node) ? $node : $node->type;
  if ($type == 'my_type') {
    return FALSE;
  }
  return node_access('update', $node);
}

(Please note that user #1 should normally be trusted to not do anything stupid, so you should not usually have to use access control tricks to restrain user #1.)

Alternatively, you prevent anyone (including user #1) from editing any field (e.g. the body field) by disabling access the field hook_form_alter.  You can do this with any field that makes up the content type.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['body_field']['body']['#disabled'] = TRUE;
    $form['body_field']['body']['#value'] = $form['body_field']['body']['#default_value'];
  }
}


Theme a contact form I'd like to theme a contact form in Drupal 8.
I'd like to put divs around form elements (using bootstrap).

I also want to put some classes on certain elements (submit button, the form itself).

You can simply theme every form how you want. I don't like the method by @rpayanm, cuz it hard to maintane and hard readable, with big forms this is not the case, just single wrapper and simple structure.

Every form trying to use theme equals their machine name. You can find this template name in $form['#theme'] just by alter, it is always (or in most times) same as form id machine name. What you need to do is register template for it. You need to implement hook_theme(). You can write it in CUSTOMMODULE.module or in THEMENAME.theme. Theme key must be the same as in $form['#theme'], so its automatically use it, otherwise you need to add new one via form alter.

/**
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'FORM_ID_THEME' => [
      'template' => 'custom-form-template-name',
      'render element' => 'form',
    ]
  ];
}

Drupal pass $form variable with form.

Then you must create custom-form-template-name.html.twig (with your template name from hook_theme()).

The minimal template is

{{ form }}

You also can print every field from form where you want

{{ form.field_name }}

Here you can do whatever you want with markup.

You also can pass additional data to template by implementing template_preprocess_TEMPALTENAME

function template_preprocess_FORM_ID_THEME(&$variables) {
  $variables['example'] = 'This is added via preprocess';
}

And then use in template

{{ example }}

  {{ form.first_field }}

  {{ form.second_field }}

  {{ form.submit }}
  {{ form.preview }}

{#
Don't forget to add printing form special info at the end.
Without this data form will not working propertly.
#}
{{ form.form_build_id }}
{{ form.form_token }}
{{ form.form_id }}

I think this method is more fliexible, clean and powerful.

P.s. sorry for my english, hopes someone edit and fix my mistakes :)

Example of complex form using this method.


Update button for each line item in cart (drupal 7 commerce) The update cart button in drupal commerce updates all quantities at once. Since on my site there will be very lengthy lists of line items in the cart, I would like to have an update cart button for each line item (see screenshot, red column). How can that be done?

This is pretty simple to explain but building this will probably give you some headaches.

create a views handler (for the update button)
add the button in the cart view
done

Now the tricky part is building the form handler, you should take a look at commerce_line_item_handler_field_edit_delete which almost does what you need (only it deletes an item instead of saving it).

Since you only need to update the quantity you need to find out line item id and the new quantity. Load the line item and then update it. You don't need to update the order itself, commerce should handle everything when the order is updated.


$base_url and $THEME_ARRAY using together I have this in settings.php:

$THEME_URLS = array(
  array('/optoelectronics','sky'),
);
foreach ($THEME_URLS as $info) {
  if (strpos($_SERVER['REQUEST_URI'], $info[0]) === 0) {
    $conf['theme_default'] = $info[1];
  }
}

I have two domains each based on a different theme. The issue is that I'm trying to use part of the old theme for just these two sections but the other theme is entirely based on SKY and if I make any modifications to the css or create a page-optoelectronics.tpl.php, then both sites receive the modifications, which I don't want.

So I duped the theme "sky" and changed all appropriate names and such to 'optotemp' but as I mention above, Drupal still disregards the "http://www.site.com" part and switches to 'optotemp' when it sees /optoelectronics.

So I found $base_url which returns the full path, including the host.

I'm a little rusty with the combination of an if/else command and including the array above in one fell swoop.

I want to say: If the absolute path is http://www.sitea.com/optoelectronics use theme optotemp. Otherwise, use the default theme. This command would then mean by default that http://www.siteB.com/optoelectronics would still use the theme assigned to that domain via the domain access module, which is Sky.

In other words, www.sitea.com has a new entire theme, but two sections of www.sitea.com will need to use optotemp but www.siteb.com uses sky.

I need help on knowing the syntax to get this right.

var $usOrEuro = $base_url;
if ($usOrEuro == 'http://www.sitea.com/optoelectronics'){
  $appliedTheme = 'optotemp';
}

$THEME_URLS = array(
  array($usOrEuro, $appliedTheme),
);
foreach ($THEME_URLS as $info) {
  if (strpos($_SERVER['REQUEST_URI'], $info[0]) === 0) {
    $conf['theme_default'] = $info[1];
  }
}

This should do it:

$hosts = array('sitea.com', 'www.sitea.com');
if (in_array($_SERVER['HTTP_HOST'], $hosts) && $_SERVER['REQUEST_URI'] == '/optoelectronics') {
  $conf['theme_default'] = 'optotemp';
}


Building a employee directory I am new to drupal but long time programmer. I'm trying to figure out how to create a directory similar to the one here (http://studentunion.okstate.edu/directory). Using feeds i can get the info to import but every entry goes into its own node. So question is using feeds how do i get all the entries to display on a single page.

Since you've got each employee in his/her own node, you can use views to show pages or blocks/panels with all employees (or certain employees depending on the filters you set on the view).


Exposed filter for file field I have a content type with several file fields. I have a view listing nodes of that content type. Now I want to add an exposed filters for each file field to let users filter only those nodes which have a file attached to corresponding field (or not have, whatever they choose).

So, I see choice options like this:

Any
Has file attached
No file attached

Is there a module for this? Or my only way is to write a custom Views filter?

Answering to myself :]

Add a new filter for, say, field_file:fid, make it exposed and choose Is not empty operator.

It will not work :D It is a known Views issue. Luckily, comment #70 in that issue has a patch to fix this operator behavior, apply it and enjoy :)


How can you prevent a Webform from going to a confirmation modal if remote post handler fails in a service response? I have a webform with a single handler - an extended remote post handler that sends the submission to an external service. The entire form loads in a modal dialog and has two wizard steps.
This service can return a 200 (with confirmation id and date) or 400 (and any number of errors).
How can I either:

Prevent the submission on error from the service, and reload the form to try again (with values retained)
Change the confirmation message to reflect that something went wrong, and either reload the form fresh with that appended or just have a link in the modal that goes "back to form"

I have looked at a few other questions like:

Trigger redirect after Webform Remote Post Handler posted successfully
How do I pass a response from a Webform custom handler back to Drupal to display on the confirmation page
Override webform confirmation and email message if token data is missing

I can't get them to work. preprocessConfirmation() is never triggered in my handler, I don't see other examples or where that would be called. How are we supposed to implement that effectively? If there was an error saving the data to the remote service, I either want the user to try again, or just delete the webform submission in Drupal and start over.

I believe it is too late to halt the Webform with validation errors once it is past the validation phase ie. in postSave(). If you are expecting validation errors on user input however, then you could move the service call to WebformHandlerBase::validateForm() and then save the service response in the $form_state object if you need it.
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    parent::validateForm($form, $form_state, $webform_submission);

    try {
      $response = $this->doServiceRequest()
    }
    catch (\Exception $e) {
      $form_state->setErrorByName('foo', $e->getMessage());
      return;
    }

    // Save service response output.
    $webform_submission->setData($response->getData() + $webform_submission->getData());
  }

Note: This probably goes against the design of the RemotePostWebformHandler, but I think it could work..., or you could directly extend WebformHandlerBase instead.


How to deploy a site? I have Drupal 8 website created with composer. I put all files to my remote server in the sitename/www/ but my page won't load. I receive such an error:

  Fatal error: Class 'Drupal\Core\DrupalKernel' not found in /home/bx273629/drupal8.com.ua/www/index.php on line 16

I think it is because I created that website with the Composer. Does any body know how to deploy correctly such a websites?

Website perfectly works locally!

I have such an error:

  'Fatal error: require(): Failed opening required '/home/bx273629/drupal8.com.ua/www/../vendor/autoload.php' (include_path='.:/usr/local/pear/php56') in /home/bx273629/drupal8.com.ua/www/autoload.php on line 17'

And on the line 17 of these file I have such a string:

return require DIR . '/../vendor/autoload.php';

It is from the outer folder which was installed with composer.

I had faced this problem a while ago. After lot of research, I found that running
composer install from the site root resolves any problem.


Can a title of a node not be associated with a url? I want to create a node with multiple urls.  I don't want the title of the main node to be a url.  Right now the main node is being pulled up in a list view through taxonomy.  When I create multiple nodes for the main node, it shows up multiple times in the taxonomy list as the same item.

I want the main node to show up once in the list with all the "sub-nodes" clickable in the main node's summary view.  Hope this makes sense.

When I create multiple nodes for the main node

What exactly are you trying to accomplish here? How do you create multiple nodes of the "main" node, how are they related to each other?

CCK has a node reference field, you should use that to make the relationships explicit and go from there.


How can I back up my Drupal site? My site crashed the other day, and I was wondering if anyone could tell me how I can back up my site, so that if something ever goes wrong again, I could still have a working copy of my site.

Try the Backup and Migrate module:

  Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.


Nodes they have reference to the nodes of current user I use node reference and want to display with views to the user only the nodes they have reference to its nodes :

A*<----B

^----C

E**<-----D

*: node created by the current user.

**: node created by an other user.

The views for current user will only show : B,C.

I assume you already have the view. In it under 'Advanced' add a contextual filter on Content:Author:UID. When you configure the filter select 'Provide default value' under 'When the filter value is NOT available' and set the Type to 'User ID from currently logged in user'. This will limit the display to nodes the current user created.

EDIT:

Misunderstood. If you are trying to create a list if nodes which reference the current node (eg, view displayed as a block when the page is displayed) the method is the same. Create a view of the nodes, and a Contextual filter on the Node Reference field. The default value type should then be set to 'Content ID from URL'. This will limit the list to those nodes which refer to the current node.


Screenfly alternative for testing Drupal 8 sites For Responsive screen testing I am using Screenfly (http://quirktools.com/screenfly/).

Drupal 8 can not be displayed inside an iframe (see link, par. 9). This is the reason why Screenfly can not be used to test Drupal 8 sites by default.

Are there any alternatives to Screenfly for responsive screen testing?

With Google Chrome CTRL + SHIFT + I also known as right click >> Inspect

Once the Developer Tools is open, then CTRL + SHIFT + M or click the 2nd icon

With Responsive, you can resize to whatever you want by dragging the right border


Is registering the path 'node/%/ajax' bad practise? Would anyone say that registering the path 'node/%/ajax' would be bad practise, potentially causing trouble for other modules that takes the easy path to implement AJAX functionality on node links?

I've got a node type which has a lot of AJAX functionality, and it would be an easy and obvious solution to simply handle AJAX callbacks via this link as Drupal does all the work for me on links such as 'node/19/nojs' where 'nojs' would be replaced by 'ajax'. Fallback to non-js browser would be taken care of by itself.

My concern is that it might be stupid to "occupy" this path for a single node type, and that it is a too obvious path to occupy with regards to other modules?

I wouldn't say it's bad practice as such, but I always go under the assumption it's good practice to prepend paths with your module name, e.g.

node/%/mymodule_ajax

That way you can be pretty sure that you won't run into any issues with other modules that don't follow the same convention.

For the record I don't think I've ever come across a module that implements the node/%/ajax path, but if you're at the start of your implementation and can change the path easily, I'd go with adding your module name to it.

It'll mean some extra work on the JS side, but if you want to be as sure as possible that you won't get path conflicts in the future, I think it's your best bet.


problems usings new custom theme I have created a custom theme for my website. Now, I've started getting some strange problems.

After installing Profile2 module, I am not getting view & edit option but it work fine if I use Bartik theme.

Another problem is that if an authenticated user logs in, his defalut home page changed to 'user/18' & couldn't able to access front page (as defined in page--front.tpl.php). But this works fine in case of Bartick.

I don't know what did I miss in my new custom theme. Any suggestions?

You must have forget to render $tabs variable in your custom theme. You have to render it before you render your $content in page.tpl.php

Example from my page.tpl.php --

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

        <?php if ($tabs): ?>

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

        <?php endif; ?>
        <?php if ($title) : ?>

                <?php print $title; ?>

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

<?php endif; ?>

Structure your page.tpl.php like this by rendering $tabs variable before title, clear the cache & you will have tabs..


How to get the number of pages in a view template? I'm trying to get the number of total "pager" pages with a view by using the views-mini-pager.html.twig. Here is my code so far...

{% if items.previous or items.next %}

            {% if items.previous %}
                {% if items.current %}
                    {% trans %}
                    Page {{ items.current }}
                    {% endtrans %}
                {% endif %}
                    ←{{ items.previous.text|default('‹‹'|t) }}
            {% endif %}
            {% if items.next %}
                {% if items.current %}
                    {% if items.previous %}
                    {% else %}
                        {% trans %}
                        Page {{ items.current }}
                        {% endtrans %}
                    {% endif %}
                {% endif %}
                {{ items.next.text|default('››'|t) }}→
            {% endif %}

{% endif %}

I want to have something like this

And currently, I can only get the current number page which ends up like this ...

I have searched for the variables inside of views-mini-pager.html.twig and I have not found the number of pages.

My question is...

How can I get the number of pages total? So I can display it at views-mini-pager.html.twig

For instance, if I view is divided into three pages I want to display "Page 1 of 3"

Mini Pager doesn't give you that information. It's designed to not execute a count query. It just knows that there's at least one additional result (because it actually queries 21 if you show 21).


Why is my taxonomy term name no longer outputting? I have created a custom node with a field where you can select one tag from a list of a custom taxonomy term (location)

I was originally using this to print out the name of the selected tag for the node:

echo $field_location[0]['taxonomy_term']->name;

However it has since stopped working (it now outputs NULL). All I have done since is remove an unrelated field in the content type.

Now when i do a var dump of $field_location all I get is:

  array(1) { ["und"]=> array(1) { [0]=> array(1) { ["tid"]=> string(1) "1" } } }

Wheras before I had a load of extra stuff like the name of the tag etc...

Anyone have any ideas what's happened?

Go to Structure > Content types > Article > Manage display, for Article for example. If your field is in Hidden section (bottom of the page) then change Format of this field to other than Hidden.


How to change the revision uid on node save I need to change the revison uid of 7000 nodes on a site. So I am using Views Bulk Operations to perform this action, by publishing or saving the the 7000 nodes concerned. Then I use the hook_node_presave to update all contents. But unfortunately, the field revision_uid isn't properly updated. By cons the field log is properly updated..

$field_uid = field_get_items('node', $node, 'uid');
    if($field_uid){
         $node->log = $node->uid;
         $node->revision_uid = $node->uid;
    }

The revision id is still the one I'm using to make this operation (1 to admin..). How can get around this problem??

You'll have to impersonate a user while performing your operation:

<?php
//Save current user data/session
global $user;
$original_user = $user;
$old_state = drupal_save_session(FALSE);

$field_uid = field_get_items('node', $node, 'uid');
    if($field_uid){
         // Load new $user data
         $user = user_load($node->uid);

         $node->log = $node->uid;
         $node->revision_uid = $user->uid;
    }

// Fail safe - if your code fails session won't be saved
$user = $original_user;
//Rever to old user and save session
drupal_save_session($old_state);
?>

References:

http://drupal.org/node/1082292
http://firedev.ro/blog/node-revision-when-doing-nodesave-gets-currently-logged-users-uid


Why is theme.inc looking for view template in calendar module So I am working on updating a drupal site that was very out of date, I have updated everything to the latest versions. When I updated the Calendar module things started going awry, now most of my views don't display anything. I'm assuming this error is the reason:

Warning: include(__custom_path__/sites/all/modules/calendar/views-view-fields.tpl.php): failed to open stream: No such file or directory in theme_render_template() (line 1525 of __custom_path__/includes/theme.inc).

I've searched and while there are numerous potential fixes none have worked. The last one I tried, adding a empty version of the views-view-fields.tpl.php and that only creates a different error where theme.inc can't find calendar.views.inc because it look for it at the path calendar/calendar.views.inc instead of calendar/includes/calendar.views.inc

Why is it looking for this in calendar instead of views? What can I do to fix this?

I cannot reproduce this myself but take a look at

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

It is an old ticket but is for the  7.x-2.x-dev branch and basicly it says disable your module remove the module directory and reinstall it so something like

Will disable the module.

 drush dis calendar

Will uninstall the module (if the module has a uninstall hook)

drush pmu calendar

Remove the directory

rm -rf __custom_path__/sites/all/modules/calendar

Most likely not necessary but wont hurt but will rebuild the registry and clear all cache

drush rr
drush cc all

Download the newest version of the module

drush dl calendar

And enable it.

drush en calendar

It should remove all traces of the old calendar and add a clean copy/install.

I would also do a drush updatedb just to double check if after all that everything is still in order.


Need help wiith a Drupal Migration I have a task to do a Drupal migration and was given a database backup and a backup of all the web files. It was a Drupal 7 site but I have no further information as to what modules and themes were used. I need to get it up and running on Windows IIS6 enviroment with FastCGI and ISAPI Rewrite running with a MySQL 5 backend. This is a staging environment.

I have
1. rebuilt the database in MYSQL from the sql dump
2. unpackaged the web files into the webroot
3. configured settings.php to point to the DB

and all I got was WSOD so I added

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

to the beginning of index.php to get a better handle on errors

I got "Fatal error: Call to undefined function: user_access() in menu.inc"
so I checked the system table but

system.module
node.module
user.module
filter.module
block.module

All check out- with status="1" and correct filepaths in data- e.g. module/system/system.module etc.

I have then tried truncating the cache (went directly in to the DB) and tried

TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

this caused a slew of PHP Warnings that eventually righted itself as cache started rebuilding.

Am now in state where the page only shows multiple instances of one warning.

Warning: array_merge(): Argument #2 is not an array in theme_get_setting()
(line 1461 of C:\Sites\public_html\includes\theme.inc).

But now having finding any info on how to proceed from here. Apologies as this my first time doing a Drupal migration.Do have a copy of all the original backps so I can start agin from scratch as necessary.

I would suggest you to use drush and try rebuilding registry using Registry rebuild because there might be modules file path issues (conflicts) while migrating.

After you put all files in place and database imported. try this,

Download Registry rebuild module.
now run drush rr on your drupal installation directory. [ if it is multi-site then your working directory should be inside sites/example.com/ ]


How can I add the Schema.org type 'BreadcrumbList'? I want to add the Schema.org type BreadcrumbList for my website.

I have installed Schema.org module, but I'm unable to find any option there.

I tried using the Easy Breadcrumbs module, but it does not have the Schema.org type BreadcrumbList.

I have checked on the Schema.org website and there in example given for JSON-LD.

function yourtheme_breadcrumb($variables) {
  $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']);
  }
  else {
    return t("Home");
  }
}


Where is the view menu? When I want to see the wishlist of user 1, for example I go to http://localhost/drupal/user/1/wishlist. And I successfully get a well organized page.

But I don't see any items in the hook_menu() that describes this. How does it work?

Though there is hook_views_api(), I am not sure whether it is the place for view.

function commerce_wishlist_menu() {
  $items = array();

  $items['user/%user/wishlist/delete/%'] = array(
    'page callback' => 'commerce_wishlist_delete',
    'page arguments' => array(1, 4),
    'access callback' => 'commerce_wishlist_access',
    'access arguments' => array(1, 4),
    'type' => MENU_CALLBACK,
  );
  $items['admin/commerce/config/wishlist'] = array(
    'title' => 'Wishlist configuration',
    'description' => 'Configure wishlist',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('commerce_wishlist_admin_form'),
    'access arguments' => array('administer wishlists'),
    'file' => 'commerce_wishlist.admin.inc',
  );
  $items['wishlist-actions'] = array(
    'page callback' => 'commerce_wishlist_operations',
    'access arguments' => array('view own wishlist'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Some pages are generated entirely through views, bypassing the code. You can set the menu link and path in the view's settings. The navigation to that page would then be completely independent of the code.

If the page was created when you installed someone else's module, I would guess that the view is embedded into the site through code, and the path can be set that way as well. In that case, the path would be set in an array with something like this:

$handler->display->display_options['path'] = 'user/%/wishlist';

Contained in a function utilizing hook_views_default_views.

You can tell where the view is generated on the admin/structure/views page, where under each view title it tells you either: "In database", "In code", or "Database overriding code."
I'm assuming that the wishlist page is a view. So, if your page doesn't appear on the views admin page, then it's a different problem.