How to use mmenu without breaking core Overlay How can I use mmenu jquery library without breaking core Overlay. Overlay works, but when I do a page refresh (F5) the overlay is blank. When I prevent the mmenu library from loading it works again.

I load the library in hook_preprocess_html in my custom zen theme:

drupal_add_css(drupal_get_path('theme', 'zen_sub') . '/css/mmenu/jquery.mmenu.all.css');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/mmenu/jquery.mmenu.min.all.js', 'file');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/zensub.js', 'file');

I then add the menu to the zen theme in hook_preprocess_page through a preprocess variable:

$menu_left = menu_tree_all_data('main-menu');
$menu_left = menu_tree_output($menu_left);
$menu_left = drupal_render($menu_left);
$vars['mmenu_markup'] = array(
      '#markup' =>
        '
' . $menu_left . '
',
);

And finally I include placeholders for the menu, as well as the preprocess variable in my page.tpl.php

 <?php print variable_get('site_name', "ZenSub");?>

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

And Finally this is my js file (zensub.js) to set it all in motion:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.zensub = {
        attach: function(context, settings) {
            $('div#menu-left').once().mmenu({
               offCanvas: {
                   position: "left",
                   zposition: "front"
               },
               header   : true
            }, {
                // configuration object
               classNames: {selected: "active"}
            });

        }
    };

})(jQuery, Drupal, this, this.document);

You should consider using Mobile Sliding Menu. It could save you a lot time and pain.

  The mobile sliding menu module integrates the mmenu jQuery plugin for
  creating slick, app look-alike sliding menus for your mobile website.


I need to add title of specific nodes in a select box I would like to have the title field of specific Nodes from a Content Type show up in a Select Box on a Webform.  Technically, it should not grab all of the nodes titles of that content type, it should only grab specific ones (that I'll need to mark somehow), so am thinking I'll need to create a vocabulary and assign this to the nodes somehow, but than I'd like to be able to use this taxonomy term to grab the titles of these nodes only.  Is this even possible?  Is there a module that ties into the webform that can do something like this?  Or perhaps a better way to go about doing this?

Depending on your requirements could try drupalising your webforms a little so that you could use all the lovely field based modules.

If you elected to use entity form, instead of webform, then you should be able to use a normal entity reference field or a views derived field (eg entity reference view widget) on your form.


Translate the allowed values list of an entity access field? I have a field of type: Entity access field.

In my allowed values list I have:

public|Public
community|Community

I have all of the core translation modules enabled:

Configuration Translation
Content Translation
Interface Translation
Language

I cannot find where in the administrative interface to translate these. Can they be translated in the interface?

As @4k4 already said in his comment, if you have the Configuration Translation module enabled, you simply go to your-site/en/admin/structure/types/manage/your-content-type/fields and select the list field you want to translate (see screenshot below).


Programmatically schedule the execution of a component I have found the function rules_scheduler_schedule_task() under the rules module which supposedly does exactly what I want, but I have trouble interpreting how the function arguments are built. The arguments of that function are an array with the following keys :

config: The machine readable name of the to be scheduled component.
date: When the component should be executed.
identifier: User provided string to identify the task per scheduled

And finally :

state: A rules evaluation state to use for scheduling.

I don't have any trouble with the first three arguments, but what is the meaning of the later (state) ? Is it where I put the arguments of the components ?
Could someone provide an example ?

I know this is an older post, but I had the same problem, and found this post. I found the answer so maybe someone can use it later:

$state = new RulesState();
$state->addVariable('variable_name', $variable, array());
// 3rd parameter is called $info it must be an array, but i don't know it's function

$task = array(
'identifier' => 'unique_id_of_scheduled_task',
'date' => time(), // timestamp
'config' => 'id_of_the_rule_component_to_run',
'state' => $state,
);

rules_scheduler_schedule_task($task);

So you have to create a RulesState object and pass in that in place of the 'state' parameter.
I had to do this because in Rules I couldn't get the timestamp I wanted when I was configuring the "Schedule component evaluation" action.


Views - adding relationship adds duplicate row for each relation Sorry if the title is a little vague, I don't know how else to describe it in the space.

I have a view that shows Drupal Commerce
orders. I am trying to add the SKUs of each product in an order as a field for filtering reasons. However, when I add a relationship to reference line items in the orders, I end up with duplicate rows, one for every line item in an order. I've tried aggregation and making queries distinct, neither of which do what I want.

Do this:

Add relationships:
1. Commerce Order: Referenced line items
2. Commerce Line item: Referenced products

In Other set Set Aggregation to Yes

Include fields:
1. Commerce Line Item: Line item ID, set aggregation to COUNT and tick Exclude from display
2. Commerce Product: SKU, set aggregation to COUNT and tick Exclude from display.

Add a Filter criteria:
1. Commerce Product: SKU. Expose it to the visitor to your liking, and leave aggregation type to Group results together.

Now you will have only one row returned with no duplicates and you can filter SKU


How do I set filters to reset automatically on new search? I have a search and some filters on a drupal 7 site. If I search a term, for example "stuff", and there are 30 results, I can click a checkbox filter (let's call it FilterA) on the side and narrow my results down. But now if I type "things" in the search bar and submit it, FilterA is still clicked when the results come up. I need for all the filters to be unchecked when I perform a new search. I've gone through I feel every setting in the view and all the search and filter settings and still nothing. Thank you for any help you can provide.

To fix this I created a new block and inserted this code:
<script>
    //unchecks all checkboxes
    function clearCheckBoxes(){
        var uncheck=document.getElementsByTagName('input');
                    for(var i=0;i<uncheck.length;i++){
                        if(uncheck[i].type=='checkbox'){
                            uncheck[i].checked=false;
                        }
                    }
    }
    //this function makes sure that new searches aren't hindered by filters set for previous searches.
    jQuery(function(){
        if(typeof(Storage) !== "undefined"){
            //retrieve what's in search box and remove whitespace
            var currentsearch = document.getElementById("searchbar").value;
            currentsearch = currentsearch.trim();

            //if search box has a value that differs from the session storage search value then filter checkboxes are unchecked and url is sanitized of categories
            if (currentsearch.length > 0){
                if (sessionStorage.getItem("squery")) {
                    let oldsearch = sessionStorage.getItem("squery");
                    if(currentsearch !== oldsearch){
                        clearCheckBoxes();
                        location.pathname = 'simplepathname';
                    }
                }
                // set session storage search value equal to current value
                sessionStorage.setItem("squery", currentsearch);
            }
        }
    });
</script>


How to display a message according to the country of the store? On Drupal 8, I installed Drupal Commerce 2
I want to modify the TWIG file of the products to show "Made in France", if the store country is France and made in Belgium, if the store country is Belgium.
How to display a message according to the country of the store ?
I would like to do this in the products TWIG file and in the stores TWIG file.
There is certainly a condition to be met but I do not know which one.
commerce-store--online--full.html.twig :
  {% if  (how to make the condition to check the store country) FR %}

        ENTREPRISE FRANÇAISE

  {% elseif (how to make the condition to check the store country) BE %}

        ENTREPRISE BELGE

  {% endif %}

For commerce-store--online--full.html.twig it should looks like:
  {% if store_entity.address.country_code == FR %}

        ENTREPRISE FRANÇAISE

  {% elseif store_entity.address.country_code == BE %}

        ENTREPRISE BELGE

  {% endif %}


How to set a node reference programmatically? I'm creating a new node and attempting to the values of the fields programmatically. I cannot seem to figure out how to set a value for a node reference field, the widget type is autocomplete and it is set to unlimited values.

Here is my code to create the new node and an entity metadata wrapper

// Create the communication node and set the current user as the author
$new_comm = entity_create('node', array('type' => 'comm', 'uid' => $uid));
// create a wrapper for the new communication
$nc_wrapper = entity_metadata_wrapper('node', $new_comm);
// then I set some other field values via the $nc_wrapper

I cannot seem to set the value for the node reference field field_comm_relationship. I have tried all manner of setting the value including the following ($oc_wrapper wraps a different node type that also has a node reference):

I tried inserting it straight from the $oc_wrapper

$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

I tried using the set method

$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value());

I tried both of the previous while accessing the actual nid value

$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value()->nid);

and

$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value()->nid;

I tried to make the input an array

$site_nid = ['und' => [ 0 => ['nid' => (int) $oc_wrapper->field_call_site_ref->value()->nid]]];
$nc_wrapper->field_comm_relationship = $site_nid;

I tried using the node_load function instead of EMW

$node = node_load('node', $nc_wrapper->nid->value());
$site_nid = $oc_wrapper->field_call_site_ref->value()->nid;
$node->field_comm_relationship['und'][0]['nid'] = $site_nid;
node_save($node);

As suggested I do call save() later in my code, but it's not making it there because it hits a fatal error. For instance if I run this code

$nc_wrapper->field_comm_relationship = (int) $oc_wrapper->field_call_site_ref->value()->nid;

I get this error

EntityMetadataWrapperException: Invalid data value given.
Be sure it matches the required data type and format.
Value at node()->field_comm_relationship: 713511. in EntityMetadataWrapper->set()
(line 122 of /vagrant/sites/all/modules/contrib/entity/includes/entity.wrapper.inc)

After updating the value in your entity metadata wrapper you need to be sure to also call the save() method to save your change. See this documentation on drupal.org.

Since you have an object, and not an id, the following should work.

// Set value for a single value field.
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

or

// Set value for a multivalue field. Make sure to pass an array of objects.
$nc_wrapper->field_comm_relationship = [$oc_wrapper->field_call_site_ref->value()];

or

// Append an additional value to a multivalue field.
$nc_wrapper->field_comm_relationship[] = $oc_wrapper->field_call_site_ref->value();

and finally

// Save the host entity.
$nc_wrapper->save();

If you have ids, check out this answer. You can get an id instead of an object from the entity metadata wrapper like $oc_wrapper->field_call_site_ref->raw() instead of ->value();

Additional info for entity metadata wrappers can be found in this Death to Field Arrays! article.


Set height and width of image field being rendered with views PHP The context: drupal 7, views, views PHP, rendering some fields with PHP because there's no other way.

$nodo = node_load($row->nid);
$strmn  = '
';
$strmn .= '
';
$image = field_get_items('node', $nodo, 'field_image');
$preout= field_view_value('node', $nodo, 'field_image', $image[0]);
$linko= url('node/'. $nodo->nid);
$strmn .= '' . render($preout) . '';

After a lot of googling I've been able to write this.

It's very probably crude but it works, except I can't find a proper way to set height and width for the image. I don't want to create a style in drupal, it would be no good as it won't be used anywhere else. I also don't want, if at all possible, to rework my code to do something like:

$image = theme('image_style',array(
    'style_name' => 'mail_image_big',
    'path' => $image_obj['uri'],
    'attributes' => array('style' => 'border:1px solid #aaa;')
  )
);

Because my php is sketchy at best and the knowledge of the drupal API is null. Every change costs me a lot of time and energy because, honestly, I lack the basics and I'm not sure of what I'm doing until I do it right.

Finally: how do I set the $display array in field_view_value so that height and width are set the way I want them in my output html? I can't find an example or a list of valid properties I can set in the $settings array to save my life. :)

The context: drupal 7, views, views PHP, rendering some fields with
  PHP because there's no other way.

There definitely is another way, you're just not aware of it, this article was written 5 years ago:

  As of this writing, 44,497 site maintainers have read that warning and
  chosen to ignore it. They’ve chosen to put their PHP into a
  non-revisioned, difficult-to-access place, and to enable PHP input in
  a module that was never designed for security. They’ve left their site
  at risk of a very difficult to diagnose and even harder to fix WSOD.

I suggest that you fully read and understand that article and rethink your position about there being no other way.

  Because my PHP is sketchy at best and the knowledge of the drupal API
  is null. Every change costs me a lot of time and energy because,
  honestly, I lack the basics and I'm not sure of what I'm doing until I
  do it right.

Welcome to Drupal, it's a steep learning curve and if your knowledge of PHP is poor then you stand no chance of being able to understand Drupal, perhaps you could edit your question or provide a comment of what you're trying to achieve? I'm always surprised that beginner Drupalers dive straight into coding their way round a problem before investigating whether there is a non-code solution.

Finally, who cares whether an image style is going to be used anywhere else or not? It's not they are hard to set-up or cost anything.


How to fix floated elements extending height of non-floated elements within a single zen theme region? I'm updating a site built on D7 with a 7.x-56 zen sub theme. The theme is laid out with responsive horizontally stacked content regions. I've created a custom blog content type, and three views blocks based on taxonomy, archive, and recent posts, but I'm having trouble with the layout of the individual blocks within the content region.

What I want is the three blog content filter blocks stacked and floating to the right, while the blog itself is floated left. I've more or less pull this off, but floating and clearing the blocks to stack on top of each other, but the issue I'm having is that they are somehow influencing the height of the first blog post. .

So, why are the floated elements influencing the views row's height and how can I fix this? You can see a live version of the site here live site. Should I add a sidebar region here? or is there a css fix for this? For context, page is a view constructed from a custom content type, and the filter views are placed using the context module with equal row height of -9.

So, the simplest approach ended up being adding another region to the theme. I made sure to add the region within the content region div to facilitate alignment, this gave me a container to float the block divs altogether with the clear: both declarations messing with the internal layout of the content region.


Why is a content type's node twig template being used by taxonomy term? New to Drupal (using drupal 8) .. please bear with me.. I 've tried to find an answer, but I couldn't...

I have created a content type, say 'course' that holds info about a particular course.  I have successfully created and placed a twig template, node--course.html.twig and through there I can control the layout of all dynamically created courses.

So far so good .. However, that course is linked to a simple taxonomy (entity reference) which has only two terms, say 'theoretical' and 'classical'.  Say that this value is held within field_course_direction.

Now the problem .. When I output any course I use my node--course.html.twig and somewhere I have something like:

Direction: {{ content.field_course_direction }}

So I get the appropriate value (say 'classical') as a link, which points to a view of all courses under 'classical'.

The problem is - that page which is something like 'my-site.com/taxonomy/term/37' for me, again uses the node--course.html.twig template, and as a result comes up really weird with some HTML stuff I dont want there.

I have enabled twig debug, and in the HTML source I indeed see the 'X' next to the template .. But why is that happening? What does this have to do with my 'course' content type? Why is that template being picked up? Is it because of the relationship between them? ...

I 'm quite confused .. Obviously I haven't understood how templates should be named and used, but still I can't get why that view has anything to do with a specific template such as node--MY_CONTENT_TYPE.html.twig ....

Thanks a lot for your patience and time ..

PS - I could replace my code with something like:

Direction: {{ node.field_course_direction.entity.label }}

and thus get only the 'raw' value, in this case a simple string saying 'Classical' without the link, but this is not what I want/ask .. I ask why is that template being picked up by a page that seems completely irrelevant to me ...

A view can show content or fields. The taxonomy term view shows content and this means it renders each node in a node template. If you don't want that the template of the full node display is picked up by the view use different view modes, which you can append to the template name:

node--course--full.html twig
node--course--teaser.html.twig

teaser is the view mode the taxonomy term view uses by default. You can change this to a custom view mode if you want to style the nodes displayed here in a different way than in the front page view which uses teaser as well.


How to test if memcache is working? After successfully enabling it, how do you know it's working? And how do you know how much better performance is increased?

In homepage of https://www.drupal.org/project/memcache it says:

A module that provides a comprehensive administrative overview of
Drupal's interaction with Memcached and stats.
A set of tests that can be run to test your memcache setup.

But there is nothing for Drupal 8.

If you read docu http://cgit.drupalcode.org/memcache/tree/README.txt?h=8.x-2.x there is no information how to test/confirm memcache is doing its job.

It shows in Status report it's enabled. Memcached version  3.0.0 But how do you know it's not just hanging around or idling?

Anyway, I read the 7.x docu and it had this:

## CACHE HEADER ##

Drupal core indicates whether or not a page was served out of the cache by
setting the 'X-Drupal-Cache' response header with a value of HIT or MISS. If
you'd like to confirm whether pages are actually being retreived from Memcache
and not another backend, you can enable the following option:

  $conf['memcache_pagecache_header'] = TRUE;

So I put in $settings['memcache_pagecache_header'] = TRUE;, but I don't see anything in my Network tab of Firefox's dev tools. All I see is X-Drupal-Cache UNCACHABLE with or without the setting.

You can enable the memcache_admin module and this will provide a stats page at /admin/reports/memcache, where you can see the number of sets and gets, hits and misses percentages and how much of the allocated memory is in use.

On the server, you can run this from the command line (assuming port 11211):

echo stats | nc 127.0.0.1 11211


How can I change the value of a field in Entity B based on the value of a field in Entity A? I need a bit of help with Rules. I'm trying to create a rule that if a check box is checked on one entity, change the value of another checkbox on another entity. I have the conditions "Entity has field - Checkbox A" + "Data Comparison Checkbox A, value = Checked". But for the Action, I don't know how to set the value of Checkbox B on the other entity.

More detail: it's for a hotel booking site. I have an entity for the booking and an entity for the room itself. I want it so that when the "Checked-out" box is selected in the booking entity, the "Needs Cleaning" box in the room entity is checked. The two entities are linked by the room_ID number.

You may need to write a quick custom action for this given your use case but its fairly easy to do. First create a custom module and add this hook to declare that you are creating a new action to be taken when 'someone checks out'.

/**
 * Implements hook_action_info().
 */

function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_room_checkout_action' => array(
      'label' => t('Action to take after someone checks out'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
}

Presumably, you want to attach this action to the trigger you already have, perhaps 'when booking content type is updated'.

Next, all you need to do is write your payload function that gets triggered for the action. The name for this is the same as what we defined in the array above. After that, you just need to set the two values which is a bit more involved but the pseudo code here should get your started.

/**
 * Action function for 'check out of room' action.
 *
 * @see action_example_action_info()
 */
function YOURMODULE_room_checkout_action(&$entity, $context = array()) {

  // find entity id for your room entity and load entity as $room
  // set $room->needs_cleaning field to 1 (or same value as $booking->checked_out
  // note that the $entity passed here is the one from your trigger (ex. the booking node)

}


Sort Tablesort by Computed Field? I am using an EntityFieldQuery with ->tableSort() and then adding a few columns to each row programatically. Is there a way to have tableSort() sort by my computed fields instead of only raw db fields? (Note: I don't mean the module Computed Field - which I now realize is probably the solution.)

Unfortunately not; an EntityFieldQuery is just an interface to a normal SQL query.

All values for computed fields are determined after the data has been loaded from the database (in the _computed_field_compute_value() function) so this won't be possible using the TableSort extender.


Errors when trying to install adaptive theme on D8 from backend GUI method When I try to install the Adaptive Theme for Drupal 8 on https://simplytest.me/, I get the following error on /core/autorize.php.

  drupal 8.2.0-rc1
    Update manager
    Error message
    Installation failed! See the log below for more information.

  adaptivetheme

  Error installing/updating
      File Transfer failed, reason: Cannot copy /home/r1rkn/www/tmp/update-extraction-3b2e9e06/adaptivetheme/Gemfile.lock to /home/r1rkn/www/themes/adaptivetheme/Gemfile.lock.

This is for the latest Drupal 8 development snapshot version.

How can I fix this error?

First thing is you don't install it.

All you have to do is make sure adaptivetheme is somewhere in the /themes/ directory.

Then download and install the AT Tools module and it's AT Theme Generator sub-module, then create a sub-theme via the UI (a tab in the Appearance section). The at_core base theme will install automatically when you enable your sub-theme.

Also, this theme will never show up on the Appearance page, it's hidden deliberately, because it's just a collection of scripts and libraries that support features in sub-themes. It's never intended to be interacted with via a UI, or be set as default etc.


Show all child terms in user page I have field in taxonomy term field_user which references to User.

At user own page (for example: user/1) I need to show taxonomy tree like this:
-user1 (this is the user whose page we are)
--user2
--user3
---user4
----user5
----user6
--etc

And if we are for example user4 page then:
-user4
--user5
--user6
--etc

It is not necessary to show current user at the tree, but it should show all terms under that user.

I'm using Views to trying to achieve this, but could not figure out proper settings for it. How to do this?

First, create a new term view using the fields row style / unformatted list of fields (it is important that the tree style not be chosen now). Then:

Add relationship for taxonomy term: parent term
Add field term id (do not use relationship) and exclude it from display
Add field term id with relationship, exclude from display
Add any fields you want to display, like term name, term description, etc...
Change style / format plugin to Tree (Adjacency model)
Set Main field to Term ID
Set Parent field to Term ID with parent relationship

For details refer
https://www.drupal.org/node/1493366

https://www.drupal.org/project/views_tree (Compatibility and Usage)


Countdown timer on discount products pages I have created discounts on products, with an end date.

How do I display a countdown timer on my product pages (as in the screenshot) ?

Thank you

You can use the Field Timer module

  This module provides field which can be displayed as a
  timer/countdown. A start/target date can be any date or an entity
  property which represent a date (for example, created date of a node).
  Module provides 4 field formatters: simple text and 3 formatters based
  on jQuery plugins County and jQuery Countdown. If you are looking for
  a configurable countdown/timer, this module is for you. It allows to
  configure backgrounds, effects, formats, language of timer.

OR

Countdown Timer Field

  Countdown timer field module allows you to create countdown timer
  field to count the days, hours, minutes, and seconds until a specified
  event. The module uses jQuery Countdown Timer to display the countdown
  timer in a nice graphical way.


How to get the last record ID? I'm inserting values using user_save(). I have used this, but it is returning the wrong values.

SELECT LAST_INSERT_ID() FROM <table name>

How can I get the ID of the last record user_save()inserted?

First you acquire the user object by using its return value and then you read the uid, which is also the unique value that belongs to the database row:

$user = user_save($user_obj);
$id = $user->uid;


Where do I find the comment IP address? I am searching for comments ip address in D8 and I can't find where they are located in database. In D7 it was easy to find.

Is there a chance that D8 is not storing the commenters ip address? If it is not, how can I store it?

IP addresses are stored in the hostname field of the comment entity (which you'd usually find in the comment_field_data table).

This functionality is disabled by default, though (see Stop logging comment IP addresses by default). To enable it, it looks like you need to set the config manually, e.g.

 \Drupal::configFactory()->getEditable('comment.settings')
   ->set('log_ip_addresses', TRUE)
   ->save(TRUE);

After running that, IP addresses will start being logged in the hostname field.


Pass selected values to node add form I have a view of nodes.  I'd like to be able to select rows (thinking VBO is the best) and pass those selected nodes to a form (specifically /node/add/payments) to pre-populate entity references.

Any thoughts on how to do this?  I've been playing around with several options and can't figure it out.

At a high level, you could do something like this with a custom module:

Create a custom VBO action (see docs) to take action on your selected nodes.
Have your custom VBO action redirect to /node/add/payments with some query parameter that encodes your selected nodes (e.g. /node/add/payments?my_nids=1,2,3).
Add hook_form_alter() invocation in your module to read this query parameter (e.g. $nids = explode(',', \Drupal::request()->request->get('my_nids')) and pre-populate the entity ref field with your values.


How to get last insert ID of drupal_write_record I need to get the last inserted id in drupal 7. I am using

drupal_write_record('user_log', $log)

How we can get the last_instered_id?

Assuming your {user_log} table has a PRIMARY KEY with it, or something else serial, then it should be set in in the array you passed to it.  In your case, it would be something like

$last_log_id = $log['log_id'];


Question about AuthorizeNet ARB functionality with UC Recurring Module I am confused about how the AuthorizeNet ARB functionality is supposed to work in Ubercart 2, and am hopeful that someone here has experience with AuthNet ARB recurring orders. I have the UC Recurring Payments and Subscriptions module and my AuthNet gateway set up. I created a recurring test order, and the recurring information is being displayed properly in my AuthorizeNet account. Last night, the first recurring charge took place, and I see that charge in my AuthorizeNet account, but it did not create any new order or any other message within my Ubercart account. The Recurring Fees screen for the order in question still shows that it has all of its recurring charges remaining. I ran cron, but that did not update anything.

The only thing I did not do in my AuthorizeNet gateway setup in Ubercart is the "Log reported ARB payments in watchdog." setting... I do not have that setting enabled, and I did not add the url to the Silent POST URL setting in AuthorizeNet. Is that what I'm missing? Or does it sound like there is something else missing?

Thanks!

I enabled the "Log reported ARB payments in watchdog" setting and added the url to the Silent POST URL setting in AuthorizeNet. It is now working fine and recording the recurring transactions in my Ubercart Orders screen.


How to make Ajax request from a drupal page? I have tried to make an Ajax request from drupal page. But output data is not correct . I have tried this

Ajax code:

function searchemail()
{
var email =$('#email').val();
    alert(email);
        $.ajax({
        method: "POST",
        contentType: "application/json; charset=utf-8",
        url: "emailcheck.php",
        data: "email="+"test",
        success: function(ret){
     alert(ret);
        },
        error: function(x,e){
            alert("error occur");
        }
    })

}

Output Code

<?php

echo "test"+$_REQUEST['email'];

But it prints only a 0 instead of 'test'

Have look at jQuery.ajax():

$.ajax({
  method: "POST",
  url: "emailcheck.php",
  data: { email: "test" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});

Also check your url. Your PHP file has to be in the same folder as your js file when you use relative paths.


Adding new menu items to hook_menu I am building a module which already has the function Mymodule_menu() at the beginning of the code. I was wondering if it is possible to use hook_menu_alter() to add new menu items (i.e. building new pages) somewhere down the code.

What I'm trying to do is build a form module whereas when the user presses "Submit", the code inside the form_submit() function will build a new page using the form values the user entered, and then redirects the user to that page.

Is that even possible. Appreciate the help from anyone. Thank you all in advance!

No, hook_menu_alter() is not thought to dynamically add new routes. As any similar alter hook, it is thought to alter the routes defined from other modules.
It would not work for dynamically adding new routes for the simply fact that, similarly to hook_menu() is only invoked in specific cases, for example, when a module is installed, uninstalled, enabled, or disabled.

If you need to have dynamic pages, you need to do what Drupal does for nodes: You define a route with wildcards, which is similar to the node/%node route defined for nodes.
hook_menu() has some example for this kind of routes, under Wildcards in Paths.

For example, a route definition as the following could be used to serve a page like my-module/1, my-module-2, etc. mymodule_abc() would recive the wildcard value as argument, and it could use that argument to access data from a database table, which is essentially what Drupal does when a user visits node/1: It loads the node whose ID is equal to 1 from the node table, and it shows it to the user who requested that page.

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

As side note, as said in Auto-Loader Wildcards, instead of my-module/%, you could use my-module/%mymodule_abc, and mymodule_abc_load() will be called every time a page like my-module/1 is accessed, getting the wildcard value (1) as argument; it could then return the object saved in the database from the form submission handler.
See node_load() as example. That function returns the object saved in the database from the form submission handler of the node edit form.

Auto-Loader wildcards are helpful when there are more routes that your module defines. For example, the Node module uses them because the routes it defines using wildcards are node/%node, node/%node/edit, and node/%node/delete. Instead of putting the code to load the node in 3 different page callbacks, it puts the code in a single function (node_load()) automatically called from Drupal.


Default terms based on user role I have Node with taxonomy terms.
Example

Term A
Term B
Term C

and user role like this

Role 1
Role 2
Role 3

Using Taxonomy Access Control(TAC) I can limit Role 1 can add all terms, Role 2 only add Term B, Role 3 only add term C.

With CSS I can hide disabled options, so when Role 3 want to add content. ex: Role 3 will only see Term C.

But how can I make Term C autofilled when Role 3 want to add. Right now Role 3 must choose or fill two options, nothing and Term C.

Any ideas?

There might be better ways to do it, but this what I did in my case.

In hook_form_alter loop through the '#options' for this field.
Store every item in a new array skipping the one you don't want as options for this field.
 (in my case it was the item at index 0 with value 'N/A').
Assign this new array of options as '#options' for the field.

Worked for me.


How would files be uploaded to a 2nd domain? So I have a Drupal site on my company intranet, and when uploading files, it all goes to the default/files folder as normal, however when uploading video files specifically, the base url is different from the Drupal base, it's a second domain specifically created for hosting assets.

I.E.

Drupal base / source of all uploads except videos

server.domain.com

Source of videos

assetserver.domain.com/sites/default/files/movie.mp4

I have no access to the server outside of the Drupal back end, and I cannot find the settings for specifying a domain anywhere (within File settings, Media settings, etc). As far as I know, there is no mention of this 2nd domain (assetserver) anywhere within the drupal codebase or backend. I'm just wondering if there's a setting outside of Drupal that can be used to set this, for example in the .htaccess file or something along those lines?

Any insight from someone who has worked with similar issues will be appreciated.

Remote stream wrapper may help...also look Media Mover module...and, at the end, take a look on THIS post...


Create an SVG using data from Views I am looking for a way to create a dynamically-generated SVG graphic based on data returned in a view from the Views module. Since Views creates lists and SVG is ultimately XML and therefore DOM-based, they seem perfectly well-suited to work together.

I have seen a few posts around saying that SVG support/integration in Drupal is very limited, and I have only ever seen Javascript used to create an SVG and then manipulate it's DOM. There are some popular javascript libraries already in use, such as Raphaël and svgweb.

Has anyone seen PHP used to do this as well? I have seen the svg_embed module but it's very new, hasn't been updated since July, and almost nobody is using it.

Does anyone know of a better way to integrate SVG and Drupal Views?

Without knowing your exact use case (I'm assuming you want to just use Views to use the results to build an SVG); it sounds like building a custom Views display style plugin might be in order.

There's a tutorial on Drupal.org (for Drupal 8, but the premise is the same), although I must confess I've only skim read it; and haven't tried implementing it: Building a Views display style plugin for Drupal 8.


Selecting correct entities and fields in Rules I am using the Rules interface to set up some rules about a booking site I am building. (using AGReservations+Ubercart in Drupal 7)

I have a field called Duration which is part of an entity called Reservation, which is itself is part of Ubercart's Order entity. I am having trouble getting my conditions to fire on the value of Duration, because there are many different entities and I am not sure if fields bundled with Entities are entities themselves, or how to pull the values out so that I can run my conditions and have the desired action.

Is there any module or tutorial to simplify this process? Something that makes it easier to know what kinds of data you have rather than plain trial and error?

Rules Module

Rules has a built-in debugger that can be fairly useful to see what was passed to your rule.  It can be found and enabled at admin/config/workflow/rules/settings

Devel Module

The Devel module is another tool that is very valuable when debugging Rules. If you are working with custom code there are two functions in particular that will save you tons of time.

dd() and dpm().

dd() will write debugging data to file.  Generally to /tmp/drupal_debug.txt on *nix based systems.

dpm() will display debugging data to screen, but may be a little less useful when debugging rules as redirects at times can cause issues while viewing.

Usage Examples

dpm($form);
dd($form_state);

Rules is an incredible module, but debugging can be a pain for sure.  I would be happy to clarify if the above doesn't answer your question.


Jquery after ajax loaded in view So I created a view listing all the users. I implement a search form with autosubmit function.

The autosubmit works with an ajax script.

Into my page view, I changed a few things in Jquery like this (main.js) :

$(document).ready(function(){
    //code for others pages.....
});

$(document).ajaxComplete(function(){
   $('h2').text('filters');
});

But when I filter my list of users, the ajax script is loading and after that, Jquery changes do not appear due to ajax load.

Do you know a trick to keep Jquery changes when ajax script is loading ?

Thanks for your help !

Find the solution below:

(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('#views-exposed-form-recherche-artiste-page', context).ajaxSuccess(function(){
         $('h2').text('filters');
      });
    }
  };
})(jQuery);


How can I show a message to visitors of a blocked user account page in Panels? When a user account is blocked, the user profile can no longer be viewed.  This makes sense, but is it possible to use Panels to override the user profile display to show a custom variant that has a message like "This user has closed his/her account"?

I looked through the available Selection rules, but the only one that seemed like it might work is User has permission (I tried one of the "edit content" permissions since I don't think that blocked users have permission to edit content).  However, setting "not having edit permission" as a selection rule did not cause my custom variant to be displayed.

Again, what I want to do is show a message on the user profile page ("This user closed his/her account") instead of the default behavior, which is giving me a "too many redirects" error.

You could try to use the Rules module for this, using an approach that is similar to my answer to the question "How to create a redirect to point to the user's id?", in which you use values for the_old_path and the_new_path that fit your needs here, i.e.:

Change all occurences of the_old_path to the path of the user profile.
Change all occurences of the_new_path to the path of your custom variant.
Add a Rules condition to check if the user account is blocked.
Fit the message being displayed to fit your needs. If you don't want such message to appear, then just delete the line containing drupal_message in the rule.


How do I use message stack (or other) to send new blog post (nodes) to "email-only subscribers" like Wordpress? How can we set up Drupal 7 to let someone simply put in their email and then receive an email notification every time a blog (node) is created?

In my ecosystem I already have rules, views, CiviCRM, and the message-stack/flag, but do not see a clear and easy way to do this without forcing the user to register an account, flag the content, and receive a rules-based email that way.

To summmarize: We want an anonymous user to put in only their email, and then receive an email every time a blog node is posted, automatically.

I am using Drupal 7.

There are three modules that support this type of subscription and notification workflow without requiring subscribers to actually be registered users on the Drupal site:

Simple Subscription https://www.drupal.org/project/simple_subscription
Total Subscription https://www.drupal.org/project/total_subscription
Simple News https://www.drupal.org/project/simplenews

Below are some notes and caveats to each module/approach:

Simple Subscription: the 7.x-1.x branch provides the basics, but hasn't seen much maintenance/activity since the move toward the 7.x-2.x alpha in 2016.  The alpha has some nice features and intent, but is also just an alpha release.  This module has token support and can work nicely with out of the box rules based messaging.
Total Subscription: This module does not offer to site managers any administrative functionality to unsubscribe email addresses or toggle on/off notifications for testing purposes. You'd have to enable/disable the module to toggle notifications (all or nothing) for any content types or taxonomies setup to publish subscription notifications.  Custom html email templates can be generated with the HTML Mail module, but templating only supports the default body/summary field and not any custom fields applied to the content type.  Messages are queued and sent via Drupalcron.
SimpleNews: This module is probably the most stable of the options and offers a D8 version; but it requires the extra step for content managers having to switch to the Newsletter tab and manually send the notifications after node creation.


replacing article or basic page image with video How can I replace the main image at an article  or a basic page with a video?
I used the Video Embed Field module but it only embeds the video in the body.
What I need is the video to be in the place of the main image, not in the body of the content.

Here is a standard front page. The teaser view. I think this is what you see and where you would like to see the video instead of the image.

This seems like what you would like. On the preview, add the video.

This is the full node view. As you can see, the full text is here.

When you go to the content type admin/structure/types/manage/article/display the default display is the full node view

On the teaser display, /admin/structure/types/manage/article/display/teaser (this is for the article content type). At the top right it says teaser.

Here you need to add the "Embed field". By default it was hidden.

You can move the image to hidden if you want.

And with this you get the image from the second screenshot.

I think that's what you want/need.

Original answer. Updated above based on comments.

If you want to upload, instead of embed, the video module has the option,

https://www.drupal.org/project/video


Dynamically change email recipient in webform based on dropdown list I have a reservation form for booking restaurants. All restaurants are added dynamically into the webform using Webform Views Select.

When the user selects resturant1, that restaurant should get an email of the reservation. Restaurants are nodes and, when I add them, I add an email field too, so this is in the database. But still I can't figure out how to make this work.

I know I need to use rules but I'm not really sure how to set it up.

I assume the view you are using creates an option list of key|value pairs of the form nid|Restaurant name. For this answer, I will call your select element restaurant.

Install and activate the Webform node value module. This is a new module, and you will have to apply this patch. (If you are not familiar with patches have a look at Applying Patches.)
Edit your webform, and under Form components create a "Hidden" webform element called send_to_email.
Under E-mails add Component value: send_to_email as the to address.
Under Form settings go to the bottom and open the Set Value From A Node group.

The Path To Node is From webform field.
Since the key returned is nid, set the Path Alias Prefix to node/ so the nodes can be found using node/nid as the path.
The Webform Source Field is restaurant (your select element).
If the field containing the email address of the restaurant is $node->field_email, set the Node Source Field to field_email.
The Webform Target Field is send_to_email.


Looking to create a taxonomy term path with a query string I have seen this question asked over on DO and here, but there doesn't seem to be a clear answer.

How to create a path alias with a query string in the target?

I need to able to send a query string when someone clicks on a Taxonomy Tag.

So, I set my tags such as
Things-To-Do/All/[term:name]/?shs_term_node_tid_depth=[term:tid]

Which encodes the string to
/Things-To-Do/All/arts-culture-history/%3Fshs_term_node_tid_depth%3D612

Which does pull up my view, but of course, doesn't filter.

I have tried creating a custom module, as well as using global redirect, but no luck.

Is this simply not possible? Can I stick something in View Pre-render or something that will unencode the string before it renders.

I have been hitting my head against this problem for a while now and really don't know where to turn.

I should point out that the above answer 'works' but not really with dynamic content.

Well, I finally figured it out.

    function cin_rd_init(){

    //first I see if this is a taxonomy page
    if (arg(0) == 'taxonomy') {

    //then I get the termID from the argument
    $termid=arg(2);
        $newterm=taxonomy_term_load($termid);

        if(!empty($newterm)){
        $thetermname=str_replace(' ','-',$newterm->name);
        $thetermid=$newterm->tid;
        $newtermvid=$newterm->vid;

        //Next I check the vocabularyID to see if it should be redirected
        //Important, I also check to see if my parameter string is set already so I don't have an endless redirect.
        if($newtermvid==18 && (!isset($_REQUEST['shs_term_node_tid_depth']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('shs_term_node_tid_depth' => $thetermid)));
        }
        //I can change the destination and query string depending on the vocab I am using
        if($newtermvid==19 && (!isset($_REQUEST['features']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('features[]' => $thetermid)));
        }
} //not empty
} //end if taxonomy
} //end function

So now, anyone who goes to a taxonomy term page will either go directly to the term page, unless the term belongs to either of these vocabularies.

If so, then it will redirect those with a query string.


How to show Child term in list box? I just want to know how to show child terms in list box see the below image

i tried http://drupal.org/project/hierarchical_select this module but don't know how to achieve this.

http://wimleers.com/demo/hierarchical-select/az-standards this is the link to achieve in Hierarchical Select, but no idea to implement this, hope someone implemented this.

or is there is any module available?

hierarchical select does support this feature. Just to conform you have created the field with term reference and set a proper vocabulary which has parent and child relation. and while creating the field you have selected widget as hierarchical select. Please follow this approach.


Using Ajax-Callback with ajax_command_invoke to invoke custom jQuery command I have a button on a form that when clicked adds an additional subsection to the form via ajax. Now I need to make it so the form automatically scrolls to the start of the newly added content.

I rewrote the ajax callback function so it returns an ajax command array instead of just the changed form data, and added an ajax_command_replace call in the array to still have my content replaced. This works and from the user side everything is unchanged.

Now I found out that I can add an ajax_command_invoke command to have a jQuery function called upon the DOM element I want to interact with. Unfortunately there didn't seem to be an in-built scrollTo jQuery function, so I had to add my own.

This function works when I call it via Firebug, but the ajax callback just gives me an error:

  TypeError: $element[response.method] is undefined
  $element[response.method].apply($element, response.arguments);

So I guess my problem is that my custom jQuery module isn't actually added to jQuery at the time the callback is handled, but only after that?

Here's my configuration (sensitive data hidden with <...>:

Within the Drupal Module, my callback function:

function callback($form,&$form_state) {

  drupal_add_js(drupal_get_path('module', '<...>') . '/js/jquery_plugins.js');

  $commands = array();

  $commands[] = ajax_command_replace(NULL, drupal_render($form[<element>]));
  $commands[] = ajax_command_invoke('<...>', 'scrollTo', array(750));

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

}

In the included file, my jQuery scrollTo function:

(function(jQuery) {
  jQuery.fn.scrollTo = function(data) {
    jQuery('html, body').animate({
      scrollTop: jQuery(this).offset().top
    }, data);
  };
})(jQuery);

Where should I include my jQuery module so the callback knows what I want from it when it's handled?

Update:

I had most of my help until that point from this similar discussion on Drupal.org. It seems to have worked for them.

Using drupal_add_js() in an AJAX callback will (at best) have weird results. Come to think of it I'm not sure I've ever actually seen it work.

The simplest solution is to add the JS in the form function itself, that way it'll always be available regardless of the AJAX state of the page:

function MYMODULE_some_form($form, &$form_state) {
  // Moved from the AJAX callback to here.
  $form['#attached']['js'][drupal_get_path('module', '<...>') . '/js/jquery_plugins.js'] = array();

  // ... Rest of the form
}


I have 2 commerce feeds imports, one must run before the other I have a drupal 7 commerce site, each day our client uploads a .csv with updates to approx. 4000 products, including published status.

2 imports have been configured, 1 to update the product information and the other to update the product references (node/display) - both read the same .csv.

The importers must run 3 times a day, in order to avoid errors, the product importer must execute before the reference importer. If we use Drupal cron, both will start at the same scheduled time, which leads to errors.

What we really want is to run the product importer until it is completed (multiple times if necessary), and only then to run the reference importer. All of the above 3 times a day.

I imagine there is a hook allowing execution of a specific importer, so I can run it via bash cron, but I don't know where to begin looking, any pointers would be appreciated.

There are multiple solutions to this problem:

Cron manager
One is indeed to use a cron manager module. I think you would need Feeds Ultimate Cron for this. This solution would require you though to guess when the first import is completed.

Rules
Using the Rules action 'Execute feeds importer' (requires latest dev of Feeds 7.x-2.x or the patch from https://www.drupal.org/node/2446307). In this case you would create a Rules component of type 'Action set' and then add two times the action for executing a feeds importer (one for each importer). Perhaps it possible with Rules Scheduler to run this action set on a regular basis? Note that you should configure the importers to not run in background, else both imports may still run simultaneously. Also note that Feeds would try in this case to perform the whole import in one go, so it could perhaps cause max runtime issues.

Drush
Feeds has a drush command called feeds-import with which you can perform an import in one go. So you could create a shell script that runs both imports after eachother and then run that script on a regular basis. For details about this command, see https://drushcommands.com/drush-7x/feeds/feeds-import/

Implement hook_feeds_after_import()
Feeds has a hook called hook_feeds_after_import() that you could use to initiate an other import programmatically:

/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  // Run product display importer after product importer.
  if ($source->importer->id == 'product_importer') {
    $product_display_source = feeds_source('product_display_importer');
    $product_display_source->existing()->startImport();

    // Execute batch, if there is any. Set 'progressive' to false to prevent
    // batch from triggering a drupal_goto().
    // (note: this code is not needed when using the 'process in background' option.)
    $batch =& batch_get();
    if (!empty($batch)) {
      $batch['progressive'] = FALSE;
      batch_process();
    }
  }
}


Storing php query result into an array How can I store php query result into an array in Computed field code(PHP)?

For example:

$query = db_query('SELECT field_holiday_date_value FROM field_data_field_holiday_date');

how can I store it into an array?

$result = $query->fetchAll();

This will store the records in $result as an array. You then need to store it in the computed field, which is something like this:

$entity_field[0]['value'] = $result;

References:

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7

https://drupal.org/node/126522


Drush command to show installed modules but not being used? In the process of developing a site I inevitably install modules thinking they are the ones I want but they are not. I am looking for drush command to find these modules to disable them and reduce my resource overhead. Can anyone point me in the right direction?

maybe something like [drush resource cleaner];

Drush has no way of knowing if a module might have some hook that is performing an active service for the site, even in the absence of any configuration information, so no, this feature is not available.


How to get route name YAML Block/Form? I am not a coder, how can I get a route name from YAML Form (ex.Contact form) and put it to YAML Block?
Is there a route name UI like path auto UI?
thank you

Drupal routes aren't display in a UI anywhere, but you can look them up in a database client (e.g. PHPMyAdmin). The route defnitions are stored in the router table. The name, path, & pattern_outline columns should be enough to search for what you're looking for. The name column contains the unique ID for each route. In your case, contact.site_page is the name of the contact form route.


How to programmatically create an exposed filter? Is there a way to create programmatically exposed filters in Drupal 7?

I searched a lot but I found only topics related remove or alter exposed filters already available in a view.

By instance my view doesn't provide any exposed filter.
I must create it through the code in my module.
I have a view but I can't change it via Views administration interface.
I must achieve the result by implementing hook_views_pre_view() and add_item().

Unfortunately add_item is not very well documented or, at least, not the part concerning the $options array structure.

Given 'field_status' a "select list" with 3 items defined in the field configuration, and the following piece of code:

 function hook_views_pre_view(&$view, &$display_id, &$args) {
   $field = field_info_field('field_status');
   if (!empty($field)) {
    $filter = array(
     'identifier' => 'field_status',
     'exposed' => TRUE,
     'is_grouped' => FALSE,
     'table' => 'field_data_field_status',
     'type' => 'list_text',
     'expose' => array(
       'operator_id' => 'field_status_value',
       'label' => 'Status',
     )
   );
   $view->add_item($view->current_display, 'filter', 'field_data_field_status', 'field_status_value', $filter);
   $view->display_handler->set_option('css_class', 'view-status');
}

what should be the structure of the array $options (in my case $filter)?

As a result of this I can see the submit button 'Apply' and the label "Status" in an empty widget 'div'.

Here is the code edited following suggestions in comments:

function my_module_views_default_views_alter(&$views) {
  if (array_key_exists('my_view_name', $views)) {

    $options = array (
      0 => 'Blocked',
      1 => 'Active',
    );

    $display = $views['my_view_name']->display['my_view_page'];

    $display->display_options['filters']['field_status']['id'] = 'field_status';
    $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
    $display->display_options['filters']['field_status']['field'] = 'field_status';
    $display->display_options['filters']['field_status']['exposed'] = TRUE;
    $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
    $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
    $display->display_options['filters']['field_status']['value'] = $options;

    $views['my_view_name']->display['my_view_page'] = $display;
  }
}

--- ALTERNATIVE SOLUTION ---

Since this problem seems to be hard to fix (@ least for my specific case) I have used a workaround to achieve the goal.
The solution consists basically on a Views Block Clone with Exposed Filters which overrides the Views Block (without exposed filters) according to specific cases (Is User LoggedIn, Content Type, Contextual Filters ecc..).

Can you please try with hook_views_default_views_alter function. This function should be defined in MODULE_NAME/views/MODULE_NAME.views.inc file. And don't forget to include this file on .info file as files[] = views/MODULE_NAME.views.inc.

 function MODULE_NAME_views_default_views_alter(&$views) {
        if (array_key_exists('MY_VIEW_NAME', $views)) {
          $options = array(
          0 => 'Blocked',
          1 => 'Active',
          );
          $display = $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'];
          $display->display_options['filters']['field_status']['id'] = 'field_status';
          $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
          $display->display_options['filters']['field_status']['field'] = 'field_status';
          $display->display_options['filters']['field_status']['value'] = $options;
          $display->display_options['filters']['field_status']['exposed'] = TRUE;
          $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
          $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
          $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'] = $display;
          }
    }


I can rsync with drush but not `drush @remote status` I know it's not equivalent, but I can drush rsync @local @remote but not drush @remote status -v.  So my ssh keys are in place, I'm on the right port etc.

I get:

Loaded alias @remote from file /Volumes/Users/blah/.drush/aliases.drushrc.php
Begin redispatch via drush_invoke_process().
Calling proc_open(ssh -p 22009 BLAH@xxx.xxx.xxx.xxx 'env COLUMNS=238 drush  --verbose --root=/home/REMOTE/d7 --uri=d7.REMOTE.co.uk  core-status 2>&1' 2>&1);

env: drush: Permission denied

What do I need to set on @remote to make it work?  Drush is installed there (same version) and works happily.

Is there are Drush error log or will I need to get the hosting company to have a look through logs?

Here is my alias:

$aliases['REMOTE'] = array(
   'root' => '/home/REMOTE/SUBDIRECTORY',
   'uri' => 'http://REMOTE.co.uk',
   'remote-host' => 'xx.xx.xx.xx',
   'ssh-options' => '-p 22009',
   'remote-user' => 'SSH_USER',
   'path-aliases' =>
   array (
      '%drush' => '/home/REMOTE/.composer/vendor/drush/drush',
      '%site' => 'sites/default/',
      '%dump-dir' => '/home/REMOTE/drush.dbdumps',
   ),
   'databases' =>
   array (
      'default' =>
      array (
         'default' =>
         array (
            'database' => 'xxx',
            'username' => 'xxx',
            'password' => 'xxx',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
         ),
      ),
   ),
);

The first thing to do is to ensure that the 'remote-user' in your site alias is the same user that you use when you log in to the site.

The next thing to check is whether or not drush is on your $PATH on the remote site.  You have probably set this up explicitly in a .bashrc file, since it is working when you log in locally.  However, often, .bashrc files exit early when called in non-interactive mode, as Drush does.

Perhaps the easiest way to get around this is to figure out what the correct full path to the drush script is, and set '%drush-script' in the 'path-aliases' of your site alias to point at the correct executable.  See example.aliases.drushrc.php.

UPDATE: Use '%drush-script', not '%drush'.

'remote-user' is the user that Drush will use to log in via ssh. It should be a user that has permission to use Drush. Some people use the webserver user for this, but if you have a separate web admin user, that would be a preferable choice.


How to get flag count for any time period I have View which displays a list of nodes with counters (flags), but the counters for all the time. How to display a list of nodes with counters (flags), for example, over the last week or last month?

Did you try to use the filter criteria : Flagged Time and eventually expose it to users?

Then you can define :
- the operator: is equal to / is less than / ...
- a specific date or offset

Is that what you are looking for?


How to access fields in a view template so, I really got stuck. I did a lot of discussion in the IRC and reading but I just fail at it. It should be very easy since it's very simple.

I have a content-type "foo" and I use a view (as a block) to query them from the DB. Now, I'd like to create HTML in one big template. Currently, I created a node template for that content-type and a view template but this doesn't allow to build proper html, instead it forces me to use rather ugly html since it just passes the html created in the node template to my view template.

What I need is to mix the HTML. E.g. if my content-type has the fields "field1, field2, field3" and 3 items, then I'd like to create a html like this:

   item1-field1
   item2-field1
   item3-field1

   item1-field2
   item2-field2
   item3-field2

   item1-field3
   item2-field3
   item3-field3

so how can I do that? How can I access all items and their fields within a view template? I'd like to have full control over the rendered html of the block. I'm on D7.

There are a couple ways you can do this. The easiest way and probably the way you will end up doing it is in your view you need to change the format to a table and then output as fields. It sounds like you are outputting a rendered entity instead of the fields. Then under theme information you will see the available templates that you can overwrite.

The one you will want is under Style. Notice the naming convention. For a view named test and a block the view would be views-view-table--test--block-1.tpl.php.

Create this template and put it into your theme folder and clear your cache. Inside that template you have access to the $rows variable that will contain all of your output.

<?php
dpm($rows); // If you have devel module enabled see your rows;
?>

This should then allow you to style your HTML as needed.

I would advise against this unless you have a special need. A better way to do this would be to use Display Suite in which you can create your own view mode and manage the fields like that. I wont go into detail on how to do that but research would be good to see if it is a good way to go for you.


How to theme table inside vertical tabs? I have a simple test module:

function tabletabs_menu() {
  $items['tabletabs'] = array(
    'title' => 'Table Tabs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tabletabs_form'),
    'file' => 'tabletabs.module',
    'access arguments' => array('admin'),
  );

  return $items;
}

function tabletabs_form($form, &$form_state) {
  $form['tabs'] = array(
    '#type' => 'vertical_tabs',
    '1' => array (
      '#type' => 'fieldset',
      '#title' => 'Tab 1',
      'a' => array(
        'x' => array (
          '#markup' => '1-a-x',
        ),
        'y' => array (
          '#markup' => '1-a-y',
        ),
      ),
      'b' => array(
        'x' => array (
          '#markup' => '1-b-x',
        ),
        'y' => array (
          '#markup' => '1-b-y',
        ),
      ),
    ),
    '2' => array (
      '#type' => 'fieldset',
      '#title' => 'Tab 2',
      'a' => array(
        'x' => array (
          '#markup' => '2-a-x',
        ),
        'y' => array (
          '#markup' => '2-a-y',
        ),
      ),
      'b' => array(
        'x' => array (
          '#markup' => '2-b-x',
        ),
        'y' => array (
          '#markup' => '2-b-y',
        ),
      ),
    ),
  );
  return $form;
}

It gives me:

This is pretty much expected result. Now, if I add:

function tabletabs_theme() {
  return array(
    'tabletabs_form' => array(
      'render element' => 'form',
      'file' => 'tabletabs.module',
    ),
  );
}

function theme_tabletabs_form($variables) {
  $form = $variables['form'];
  $output = '';
  foreach ( element_children($form['tabs']) as $id_tab ) {
    if(is_int($id_tab)) {
      // Initialize the variable which will store our table rows.
      $rows = array();

      // Iterate over each element in our $form['tabs'] array.
      foreach ( element_children($form['tabs'][$id_tab]) as $id_row ) {
        $classes = array('');

        $rows[] = array(
          'data' => array(
            drupal_render($form['tabs'][$id_tab][$id_row]['x']),
            drupal_render($form['tabs'][$id_tab][$id_row]['y']),
          ),

          'class' => $classes,
        );
      }

      $header = array(t('x'), t('y'));

      $table_id = 'tabletabs';

      $output .= theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

this cannot work. I'm rendering tables before vertical tabs, so of course they appear before, too:

But how do I render them to appear inside vertical tabs instead? I'm sure I'm missing something little and obvious (once you know it).

Not sure if it's the right way to do, but you would create a new form element with the table, instead of adding a table directly.

function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // create a new form element with the table
      $form['tabs'][$id_tab]['table']['#markup'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

Option #2:

function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // set the table as a value of each vertical tab item
      $form['tabs'][$id_tab]['#value'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

This will give following output:


How to use browser caching for images? I am learning to improve Drupal's performance and I discovered Google's PageSpeed Insights tool. It urges me to use browser caching and presents me a list of all my images at mytheme/images and default/files. To be honest, I am not too sure about what this means. I assumed that Drupal's default caching could handle this, but apparently that is not the case, since caching is already enabled at Performance (both minimal lifetime and expiration time are set to 1 hour).

How can I cache all those images as well? Should I install some extra modules like Varnish or Boost to solve this? As a beginner, I can't really wrap my head around all these performance modules and what they do.

Images are directly served by the web server. You need to configure your web server to server images (and other files) with the appropriate headers. On Apache HTTP server, this is usually done with the mod_expires module.


Filter view content by data in text field I've created a text field on a custom content type. The text field is called "targetUser" on my content type "message".

targetUser is meant to collect the uid of a user that a current app user is sending a message to. E.g. If user 1 is sending a message to user 7, the number "7" will post to the targetUser field.

I want to create a view that ONLY displays "messages" with the targetUser number that matches the logged in user's uid, so that they may ONLY see messages meant for them.

I essentially want my view to say: "Only display messages with this user's uid in the field targetuser" - is this doable? Hope I explained this well enough.

targetUser is meant to collect the uid of a user that a current app
  user is sending a message to

IMO the better approach would be to make targetUser an entity reference field.

Download and install the Entity Reference module

In content type Message fields, add a new field with Entity Reference and a widget of Auto complete (tag style)

For example: I named mine lalala (click picture below to enlarge)

For Target Type, select User
Number of Values: Unlimited (as you could send a message to multiple users)

Then add or edit a message node and start typing user name, you will see the name in the drop down, select it and save.

Use a comma , to add other user account.

In your view

contextual filter of Logged in User id (uid)
add a relationship of lalala Referenced Entity

If not, try Referencing entity, but if my memory is correct it's Referenced

Result: you should get a view of all the nodes where the logged in user was referenced.

  The autocomplete only allows by username, and not uid. E.g. posting 47
  into this field isn't allowed?

Create a new USER view.

1) click on +Add

2) Select Entity Reference

3) Remove user:name and add user:uid

4) click on settings and checkmark uid (if you don't do this step, it won't let you save the view)

Go to your Content Type Messages manage fields and edit your entity reference field.

At the bottom check mark ✓ Render Views filters as select list
Change to mode to View and select your view.

  Also, "logged in user id (uid)" isn't an option? Just (author) User:
  Uid ?

You will need to create a CONTENT view and then add:

Relationship of Referenced User
Now since you have a relationship User: Uid becomes available as contextual filter


How to show dynamic text on node/add form with Panels (using AJAX)? I am using Panels. There is an entity reference field (project) on a content type. It shows the title of nodes where the user is the creator using the viewreference module.

On the node/add form, is there a way to show a field (body) from the node when the user selects a specific project? I am ok with contexts in panels and views, some some general thoughts might help already quite a lot.

Thanks for any tipps.

you do not need to use panels, just add an ajax callback on that form select field, where you add a node's body in the postfix of the field.


Simpletest fails to create the field_config table I'm only just getting into TDD with Drupal and unfortunately run into trouble right away. For some reason the simpletest####field_config table isn't being created, and I don't get why; many other tables do get created. The (seemingly) relevant part of the error I get is:

  Base table or view not found: 1146 Table 'mcdonalds.simpletest405637field_config&#039

coming from /modules/field/field.crud.inc (that is the project's root modules folder, NOT the modules folder in any theme or something).

I'm a bit stuck here, so I hope someone can tell me how to debug this, or even how to solve, that would be great of course;) Thanks!

The issue is definitely related to cache backends.

Disable cache backends if you are testing using Simpletest classes.


Content type with date groups I currently have a content type called Training from which I have created a node for each training course I have. Each node has a multiple date field for when a course runs over more than one day (not necessarily days running after each other).

How would I create additional occurrences of a course dates without duplicating the node.

Eg

Fire course
2 day course
Session 1:
25/12/14 & 25/01/15
Session 2:
14/3/15 & 15/3/15

You need to separate your sessions from your course type. The ideal solution would be to implement Field Collection.

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

It is an actively maintained module with views integration. For a quick intro look at this tutorial.


How do I set up an article view that validates both article and category? I'm working with Drupal 7, and trying to get a view set up that will display blog categories and articles based on their category.
The category is a Taxonomy - Blog Categories - let's assume it's:

rock-and-roll
pop
jazz
other

I'm hoping for the following path behavior:

/blog/ should list all articles.
/blog/rock-and-roll/ should list articles that have the rock-and-roll taxonomy set.
/blog/non-existant-term/ should show page not found
/blog/rock-and-roll/real-article-title should show the relevant article
/blog/rock-and-roll/fake-article-title should show page not found

I've tried a ton of different combinations of relationships and contextual filters, but I just can't get it to work. The closest I can get is where all of the 'proper' urls work... I get category lists, or I get article displays... but I also still get a page when I go to a path with either an invalid taxonomy term or an invalid article name.
It seems like it should be something with the Contextual Filter validation stuff... but anything I've tried with like validation based on a taxonomy or whatever just stops anything from working. I no longer get listings or articles properly.
I'm not sure what other information to include - I'm trying to avoid adding any modules (because I've basically been told not to) and I'm trying to avoid making it multiple views.
-------- EDIT --------
I've tried some of the stuff suggested by prkos but I'm not having any more success. I've attached some screenshots of my configs... with a little bit of censored stuff. It probably doesn't matter, but I'm expected to be circumspect.
The original URL/Taxonomy I used isn't actually the final stuff, it was just example... so there might be some mismatch there.

So, with these changes in place... now if I go to url/news2/ I get a Page not found. url/news2/all seems to work, but then url/news2/validterm doesn't work. validterm doesn't get any results in the view preview thing either... where it did before.

You can make the Validation through the Contextual filter.
When dealing with 2 Contextual filters it's always best to first fully configure each independently, make sure they work before you add both to work together.

First create the Category Contextual. Since you want to use term names, and not term IDs (only term IDs are stored in ER fields), you have to add the Relationship first for the ER field (require it if you want to show only the results that have this field filled in).

Once you add the Relationship you can add the Term Name Contextual fiter, it will use the Relationship, and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary
Category
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term name
Category
Transform dashes in URL to spaces in term name filter values
Action to take if filter value does not validate
Hide view
Adjust the Case options, and any other option to your needs.

Test that it's working by entering a name of your category into the View Preview field jazz and checking the results only show nodes with that term. (Preview only tests that Views filtering is working correctly, but it doesn't test passing of the argument to Views because you're feeding them manually, that needs to be tested on a live page.)
Test single word categories first, if they work test complex ones with dashes and adjust the settings if necessary until you get the desired result.
Test that you can bypass it by entering all into Preview, it should show all Views results (you can change it to something else in Contextual settings).
Entering a wrong word (notmycategory) should display No query was run in Views, which means you would get Page not found in live conditions.

Now create the second Contextual, for the Title. You don't have to remove the first one to test the second one without interference.
Bypass the first filter by always entering the all as the first argument into Preview. Once you add the second Contextual you will have to enter two arguments into Preview to test it (all/some-title, or jazz/all, or all/all to bypass both contextual filters).
When the filter value is NOT available
Provide default value
Raw value from URL
3
When the filter value IS available or a default is provided
Specify validation criteria
Basic validation
Action to take if filter value does not validate
Show "Page not found"
Adjust the Case and other options to your needs.

Test the second Contextual by entering various titles in your appropriate Case in Preview: all/my-title and entering the wrong title all/notmytitle to get the "No query was run".

Test that the two Contextual filters are working together, although if they work on their own there shouldn't be any problems combining them (jazz/some-title, notcategory/title, jazz/not-title, etc.)

Once it's working in Views Preview, test everything on the live page to make sure arguments are passed through correctly.

Once all this is said, if all you need is path control in your site you can do that with Pathauto module to create aliases for your nodes based on categories and their titles.
Views only creates lists of content, it doesn't affect the core paths. You will still have the node/ID paths active on your system, and any path aliases you might have. You should take care not to create duplicate paths for the same content, as it can be considered duplicate content by search engines (it dilutes in any case), and it's confusing to users.


Term Reference Autocomplete field that searches fields besides name Is there any way to have a term reference autocomplete field search other fields than just the title?  In my case I have a organizations vocabulary with the taxonomy name and an acronym.  The main point of adding an acronym field is to stop users from putting in the acronym in place of the full organization name.

If I turned it into an entity reference field would, the autocomplete widget type allow me to do this?

As far as I've been able to determine, there is no way to modify what autocomplete searches in a term reference field, though if seems possible, even likely that there might be a module or hook that does this, I didn't find it.

To answer my second question, yes, making this an entity reference enables the use of views to power the autocomplete, at which point you can handle the formatting and search fields of the autocomplete.

Better answers on this are very welcome!


{{ front_page }} doesn't work in partial I have a partial, partials/header.html.twig, I am calling on one of my sub pages with this code.
{% include directory ~ '/partials/header.html.twig' %}

Whenever I use {{ front_page }} inside the partial to link back to the front page, it doesn't work, but it works on everything else. I have been searching for an answer all morning but can't seem to find anything.

Try:

<a href="{{ path('<front>') }}" title="{{ 'Some Title'|t }}" rel="home" class="some-class">
     Some Text
    </a>


Handle node save concurrency Introduction

I need to prevent node update when two or more users try to update node on almost same instance (simultaneously) and instead put the requests in a queue and process one by one.

A live example

For node/1, if three users u1, u2, u3 try to update node, then only the user on the basis of "First Come First Serve" should be allowed to update the node(read & write) and others should wait in a Queue.

If users u1, u2, u3 request one by one, In this case when the node update by u1 is completed successfully(until then don't allow next request to read data), then only allow u2 to process(read & write), and similarly for u3 and so on.

Here read from u2 depends on final write by u1. One operation should be isolated.

Also the problem is with node_save(). It takes much time when the traffic is more. Is there any way to boost it.

System details:

  Drupal 7.22, 2013-04-03

  Mysql version: 5.1

  PHP : 5.3

  Apache: 2.4

There's a module called Content locking that covers your use case.

  Block concurrent editing: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing
  so, and notified that the content is already being edited.

You can also adjust when a lock will expire if an edit is abandoned.


How do I save uploaded file permanently in file_manged table? How do I save a uploaded file with status equal to 1 in the file_managed table, in Drupal 8?

Whenever I upload a file, it is stored in the file_managed table with status value 0.
I have used File::load( $form_state->getValue('image')) to load the file. What do I need to do next?

In Drupal 7, I would use $file->status = FILE_STATUS_PERMANENT. What is the equivalent code for Drupal 8?

class AddBannerForm extends FormBase {

public function getFormId()
{
  return 'add_banner_form';
}

public function buildForm(array $form, FormStateInterface $form_state)
{

  $form['image'] = array(
    '#type'          => 'managed_file',
    '#title'         => t('Choose Image File'),
    '#upload_location' => 'public://images/',
    '#default_value' => '',
    '#description'   => t('Specify an image(s) to display.'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
      ),
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save image'),
  );

  return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state)
{
    File::load( $form_state->getValue('image') );
}

public function submitForm(array &$form, FormStateInterface $form_state)
{

}
}

Thank you @Clive &  @kiamlaluno

/* Fetch the array of the file stored temporarily in database */
   $image = $form_state->getValue('image');

/* Load the object of the file by it's fid */
   $file = File::load( $image[0] );

/* Set the status flag permanent of the file object */
   $file->setPermanent();

/* Save the file in database */
   $file->save();


Views taxonomy terms page with two content types This is the structure:

menu1 - taxonomy/term1
menu2 - taxonomy/term2
menu3 - taxonomy/term3
menu4 - taxonomy/term4

The custom content type is using taxonomy terms and with enabled Views Taxonomy term that comes with the module, every content is displaying very well in categories. I can see that uses path /taxonomy/term/%

I'm displaying the nodes as a grid style with specific fields.

Now I want to add a second content type that will use the same category from the first content type and will be displayed over the first content type nodes.

EDIT: I've tried to clone the view and change only one field, but it didn't work. The result is only the content from the fist view. I've used the same path like the default view taxonomy term, but I guess it's not possible to do like that.

EDIT2: So I can see that it's not possible to achieve with adding block and use the same url like the default view taxonomy term.

I've checked the taxonomy display module and I can see that I can associate only one view.

Directly modifying the default "taxonomy/term/%" view is not a good option, you can clone the default view and can make the required changes to the cloned view.

The better solution for the above problem is the Taxonomy Display module. Taxonomy display lets you associate a vocabulary with a particular view. Now, when I click on particular term link, which is an alias for taxonomy/term/%, the view takes over and this is actually rendered correctly maintaining the integrity of the field structure.

The detailed documentation of taxonomy display module is available here.


Missing bundle entity, entity type block_content_type, entity id basic I have updated one of my D8 sites to the latest stable version - 8.3.1 using drush up. When applying the database update, the update fails with the following error message:

  Failed: LogicException: Missing bundle entity, entity type block_content_type, entity id basic. in Drupal\Core\Entity\EntityType->getBundleConfigDependency() (line 882 of /var/www/sitename/core/lib/Drupal/Core/Entity/EntityType.php).

This has only happened on 1 site, so it's possibly a config issue specific to the site.

How do I manually create the missing bundle entity?

To get passed this error I deleted some rows in the config table:

delete from config where name in ('block_content.type.basic', core.entity_view_display.block_content.basic.default', field.field.block_content.basic.body');


Is there a way to exclude the addthis module's output in the $content variable? The $content variable in my node.tpl.php file outputs some CCK field content, the content body, five star content, and the add this content. I don't want it to show add this content. Is there a way to override the $content variable to make it not show add this content? I can't do this by editing the addthis module's settings, because I invoked the add this in another place.

You can unset or alter items in $node->content by implementing hook_nodeapi() and using the 'alter' $op.


How to implement less than / greater than in views contextual filters I want to filter my view like

field_opening_hour_start_time > <?php date("g"); ?>

How can I make this happen? The filter criteria does not let me to use PHP and the contextual filter does not let me to use less than (or greater than), but only equal (=) comparison. Is there a way around this? Or a way to use PHP in filter criteria box?

edit. I am using Office hours module

Have you tried using the regular filter (granularity of hour) and selecting the 'relative date' instead of the hard-coded date?  You could use 'now' to do a greater than or or equal to the current time, which is the same as

Screenshot attached:


Blocks created twice for a single page load In a template file I am using this code

$blocks= block_get_blocks_by_region('revel_card_dashboard');

To grab blocks for a region to render at specific parts of the template. This is causing the regions to be created twice.

Checking stack traces the first time the blocks are created is by drupal core.

 2 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\module.inc',
    'line' => 799,
    'function' => 'call_user_func_array',
  ),
  3 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 854,
    'function' => 'module_invoke',
  ),
  4 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 674,
    'function' => '_block_render_blocks',
  ),
  5 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 318,
    'function' => 'block_list',
  ),
  6 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 268,
    'function' => 'block_get_blocks_by_region',
  ),
  7 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 5616,
    'function' => 'block_page_build',
  ),
  8 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 2583,
    'function' => 'drupal_render_page',
  ),
  9 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 2471,
    'function' => 'drupal_deliver_html_page',
  ),
  10 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\menu.inc',
    'line' => 531,
    'function' => 'drupal_deliver_page',
  ),
  11 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\index.php',
    'line' => 21,
    'function' => 'menu_execute_active_handler',

How can I grab the already created blocks instead of creating them a second time as the call up top seems to do?

Clarification: I do not want to simply cache the block because its important to update the block when the user revisits the page, but there is no point in updating it with time expensive methods twice a page view.

$blocks = $page['revel_card_dashboard'];

This line of code grabbed the blocks that had already been created by drupal's original passthrough.


How can I implement a form into a DC view footer? I am trying to make a shipping quote module for Drupal Commerce (DC) and I am trying to do it within the DC cart view footer by sending a form within a view.

I have done quite a bit of research and just can't seem to find the answer. The place I am now is trying to do it with a views handler. However, I can't even get the handler to show up in the footer add options.

My current .module code:

<?php
function MY_MODULE_form($form, &$form_state) {
  $form = array();

  //Zip Code
  $form['zip_code'] = array(
'#title' => '',
'#type' => 'textfield',
'#field_prefix' => t('Zip Code:'),
'#maxlength' => 5,
'#size' => 5,
  );

  //Shipping Select
  $form['carrier_select'] = array(
    '#type' => 'select',
    '#options' => array(
      'null' => 'Select Shipping',
      'ups_ground' => 'UPS Ground',
      'usps_priority' => 'USPS Priority'),
      '#ajax' => array(
      'callback' => 'MY_MODULE_form_callback',
    ),
    '#suffix' => '

',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
  );
  return $form;
}

/**
 * Ajax callback triggered by select.
 */
function MY_MODULE_form_callback($form, $form_state) {
  require_once(DRUPAL_ROOT . '/sites/all/modules/commerce_shipping/modules   /MY_MODULE/includes/plugins/ups/fd_getrate.php');
  $commands = array();
  $commands[] = ajax_command_html('#commerce_ups_ship_price',    get_ups($form_state['values']['zip_code']));
  $commands[] = ajax_command_data('#commerce_ups_ship_price', 'form_state_value_select', $form_state['values']['zip_code']);
  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Implementation of hook_views_api
 */
function MY_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MY_MODULE') . '/includes/views',);
}
?>

Plus .inc for the view handler:

class MY_MODULE_shipping_form extends views_handler_area {

  function option_definition() {
    $options = parent::option_definition();

    // TODO: Update with options

    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    unset($form['empty']);

    // TODO: Update with options
  }

  function render($values) {
    return drupal_render(drupal_get_form('MY_MODULE_form'));
  }
}

Plus the .inc for views:

function MY_MODULE_views_data() {
  $data = array();
  // Define an footer handler for displaying shipping quotes.
  $data['MY_MODULE']['handler'] = array(
     'handler' => 'MY_MODULE_shipping_form',
     'title' => t('Shipping API Quotes'),
     'help' => t('Display a user input form to allow the retrieval of shipping quotes.'),
  );

  return $data;
}

On this last one I don't have a clue of what I am doing.

Anyone who can help me on this one?

FYI - I am using Commerce Kickstart + Views3

You might want to consider using the Commerce Shipping module to handle the integration to Drupal Commerce, it doesn't support adding the shipping quote form in the cart footer, but it would help in handling the actually shipping quote with commerce.

The problem you are facing is in the hook_views_data, you should do something like this:

function MY_MODULE_views_data() {
  $data = array();
  // Define an footer handler for displaying shipping quotes.
  $data['MY_MODULE']['shipping_footer'] = array(
    'title' => t('Shipping API Quotes'),
    'help' => t('Display a user input form to allow the retrieval of shipping quotes.'),
    'area' => array(
      'handler' => 'MY_MODULE_shipping_form',
    ),
  );

  return $data;
}

You need to define an area handler as shown above, that should let you select the form in the views UI.


Simple views handler to compute math expression. In Views, I would like to expose a fake field that is just an elementary mathematical expression of other fields of the table (let's say, for example, field1+field2).

I expose the field in hook_vies_data via some

  $data['my_table']['fake_field'] = array(
   'field' => array(
     'handler' => 'views_handler_my_handler',
  );

Which function of the handler shall I define? And how do I get in the handler the two values of field1 and field2?

Alternatively, where do I found the documentation of what I am looking for?

Instead of creating own handler you should use already existent Global: math expression that allows you using of tokens to calculate everything you want.


How can I use Twig Tweak to show a token in a Webform template in Drupal 8 I have a Webform form (formerly the YAMLForm module) on which I need to show the title of the form. The template I am using is based on page.html.twig (because of twig debug suggestion) page--webform--stories-submission.html.twig.

According to the tokens listed in both in the form creation area and in admin/help/token, I have several tokens available including [webform:title], [webform:url], and [webform:id] to name a few.

When I use

    {{ drupal_token('webform:title') }}

on my template, all that prints out on the page is [webform:title].

Just to make sure I'm doing it right, I put all of the following smack into the middle of my template:

    {{ drupal_token('current-date:long') }}
    {{ drupal_token('site:name') }}
    {{ drupal_token('webform:title') }}
    {{ drupal_token('webform:id') }}

I get this in return:

Wednesday, January 18, 2017 - 09:00 ECLKC [webform:title] [webform:id]

The first two prove that Twig Tweak is a wonderful thing, and the second two prove that I'm still not doing it right.

Can anyone recommend a next step for me?

If I can't get Tweak working, I guess I might need to preprocess myself a variable? Kint says that my title is right there as a page variable:

'page' => array(25)
~
  '#title' => string(29) "Submit your Head Start Story!"

In that case, I think I would need to follow this advice:  How do I add a variable for a Twig template in my preprocess function?

To sum up:

Can I get Twig Tweak to show my title for me?
If not, should I use that advice about adding a variable to my template preprocess?

Currently, it looks like the Twig Tweak module's drupal_token Twig function does not support passing in the $data argument, which would contain the webform entity.

You might want to create an issue in the Twig Tweak module's issue queue.