Trying to create a static page for my module using page callback in hook_menu I’m taking first steps in building a module for Drupal 7 and am trying to create a static page within hook_menu function. In the $items array, for ‘page callback' I create an very simple function named ‘semi_static_page’. This simple function returns some html. the code is below.

$items['admin/config/media/tsoundcloud/config/soundcloud_static'] =             array(
    'title' => t('Semi Static Page'),
    'description' => 'Temp page to show data',
    'page callback' => 'semi_static_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );

function semi_static_page(){
  $output = 'this is some output, etc…….’;
  return $output;
}

But this page generate the following error.

Fatal error: Unsupported operand types in /Users/tomcarden/Sites/sweetteas/includes/form.inc on line 1079

How can this be resolved? Ultimately I want to load an .inc in the semi_static_page function.

thanks in advance!

$output = 'this is some output, etc…….’;

If you see in the above line, you are using wrong sign, which I have  highlighted after ...... That is wrong. It should be '

Above isuue is for sure!!!!

Other just my suggestion, As I am also learning Hooks, may be TOTALLY WRONG but for your attention.

I have changed code as below and after that, I have written my point..

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['admin/config/media/tsoundcloud/config/soundcloud_static'] = array(
    'title' => 'Semi Static Page',
    'description' => 'Temp page to show data',
    'page callback' => 'mymodule_semistaticpage',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );
    return $items;
 }

/**
 * Page callback
 */
function mymodule_semistaticpage(){
  $output = 'this is some output, etc…….';
  return $output;
}

The following points are for code which you have posted in main-question, and I have corrected those in above code,

See function name, it should start with module name.
The _page(), may creating confusion as some hook has _page() part..so I did change function name to mymodule_semistaticpage()
where is return $items;?
I think title do not need, t()?


Difference between upgrade and migration What is the difference between upgrade and migration in Drupal?

Seen as a process, upgrading will keep your existing database (where content and configuration lives) and update the code of your system. After the code is updated, all needed database modifications (configuration and content) will be performed.

Migration on the other hand, usually refers to content migration. That said, the migration process targets a Drupal instance different from the existing one, where the content will be transfered to.

A definitely good reference is the official Upgrade documentation page


Error Passing Extra Parameter to Custom Form I have a simple custom form that works until I try to add a custom parameter for my module called "forms_admin".

These are the contents of my forms_admin.routing.yml

forms_admin.settings:
  path: 'admin/config/system/forms/{arg1}'
  defaults:
    _form: '\Drupal\forms_admin\Form\FormSettings'
    _title: 'Forms Settings'
  requirements:
    _permission: 'access content'

This is a relevant part of my FormSettings.php file (Currently do not have any custom Validation or Submit actions)

public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#required' => TRUE,
    );

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

return $form;
}

And my third file is: forms_admin.links.menu.yml

forms_admin.config:
  title: Forms
  route_name: forms_admin.settings
  parent: system.admin_config_system
  description: 'Forms settings'
  weight: 0

The moment that I add {arg1} to my forms_admin.routing.yml and , $arg1 = NULL to my FormSettings.php file, I am unable to acces the website.

I receive a white page with the error that states:

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

After removing arg1 from my two files and going to the Recent Log messages, this is the error I receive:

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg1") to generate a URL for route "forms_admin.settings". in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 182 of /var/www/test_site/docroot/core/lib/Drupal/Core/Routing/UrlGenerator.php).

I have tried changing arg1 to other names, not making $arg1 = NULL, etc. and I receive an error every time.

What am I missing?

The problem is that your FormSettings class is not the controller in this case. It's the controller method which is where the routing system expects $arg_1.

I think you need to define your own controller which accepts the request and passes the argument to the form. Extending the core Drupal\Core\Controller\FormController class is probably the simplest way forward.


Suggestions for settings.php - Local dev, Development server, Live server Basically, one of the greatest questions of all time: What are some ways you're using settings.php in your development/staging workflow?

Right now, I have my settings.php file set up like the following, and I base my development on the server's $HOST directive—meaning I can work on dev.example.com for the development (shared) server, local.example.com for my local computer (and other dev's local code checkouts), and www.example.com (or just example.com) for the live site.

(This code is in the 'Database settings' section of settings.php):

$host = $_SERVER['HTTP_HOST'];
$base_url = 'http://'.$host;
$cookie_domain = $host;

switch($host) {
  case 'example.com': # Production server
    $db_url = 'mysqli://prod_sql_user:password@127.0.0.1/prod_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
    );
    break;

  case 'dev.example.com': # Development server
    $db_url = 'mysqli://dev_sql_user:password@127.0.0.1/dev_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
    );
    break;

  case 'local.example.com': # Local server
    $db_url = 'mysqli://local_sql_user:password@127.0.0.1/local_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
      // Turn off most core caching.
      'cache_inc' => 'includes/cache.inc',
      'cache' => CACHE_DISABLED,
    );
    break;

}
?>

This works pretty well for most purposes, but it means we have a lot of extraneous code sitting around in our shared settings.php file... is there a better way?

What I do is separating that file into a settings.php and a local.settings.php.

At the end of settings.php is the following code:

if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include dirname(__FILE__) . '/local.settings.php';
}

The local file is then excluded from whatever VCS you are using. The advantage is that you can put settings which are common over all instances in settings.php and have that versioned/distributed automatically and keep the local stuff in local.settings.php.


How can I prevent anonymous users from accessing taxonomy pages? I would like to prevent anonymous users from accessing any of the taxonomy pages on my site.

I am already using the Panels module to provide variants for each vocabulary, and these variants have access rules limiting them to authenticated users only.  However, anonymous users can still access the default taxonomy pages provided by Drupal.

I thought about adding a new variant (301 redirect) and forcing anonymous users to the front page-- is there a better solution?

Don't need to force using panels.

Having better solution to set permission for your taxonomy pages by code.

Default taxonomy page permission is 'Access content'.

Override that permission in your own by custom module.

Using hook_menu_alter() to change permission

Sample:

function [MODULENAME]_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('custom permission');
}

Set that custom permission in your hook_perm().

sample :

function [MODULENAME]_perm() {
  return array('custom permission');
}

Clear your site cache once.

Then Goto admin/user/permissions

Set permission by role.


Adding check boxes to contact form I am attempting to make a contact form in Drupal 8 using "Contact forms" included in core.  I'm struggling to figure out how to really customize it, like adding radio buttons or check boxes - does this have to be done through the theme_name.theme file?  If so, can someone give me an example of adding elements to the page? I'm new to Drupal so thanks for helping out.

In Drupal 8, contact forms are entities listed in admin/structure/contact. Once you created the new contact form, on that page select Manage fields in the Operations column; it's a drop-down selector, so you will need to select it to see that operation, since the default operation for contact forms you create is Edit.

On the page you will see, you can add new fields.

The tricky part is understanding how to show checkboxes: You need to select the right field type. For example, if you want to show 4 checkboxes, then you select Text (list) as field type.

Enter the 4 values you want to show, and enter 4 as Allowed number of values.

To show it as checkboxes, you go to the Manage form display of your contact form (in my case, admin/structure/contact/manage/test/form-display, since test is the machine name of the contact form I created). For the field you created, it should show the following.

Change it to Check boxes / radio buttons and save.

Since the allowed values are 4, the contact form will show checkboxes, not radio buttons.


Download file one time only for auth user (Suggestion needed) I have a website has a books & categorize each book to unites, each units has a download link..

when user have a role, he can download file just 1 time .. no more for each unit ..

for example:

Book1 --> unit1 --> download --> if(user NOT download) else { Remove Link }

Book1 --> unit2 --> download --> this link was removed since you download a file

Book1 --> unit3 --> download --> if(user NOT download) else { Remove Link }

Book2 --> unit1 --> download --> if(user NOT download) else { Remove Link }

Book2 --> unit2 --> download --> if(user NOT download) else { Remove Link }

Note: books & unit is term, units are child in books.

my idea for solve this issue is create a normal text field and set user id if he click on download link..

Any suggestion for solve a problem, way, or module, field setting ...
thanks every body

Please use the modules tag if you're looking for a module hosted at Drupal.org.

There exist a module named Deep Link.  With 13 installs and no full release in sight, I wouldn't have high hopes for the usefulness of this, but the project page says:

  Deep link module allows the direct access to a specific item of content under certain circumstances and limitations. Such as one-off or time-limited deeplinks.

There is also Expiring Private File Link.

It says:

  This module was created when the need arose to offer a downloadable file to users of a site, without revealing the actual URL of the file itself. It also allows through the permissions system a method of allowing the file to only be available for download to registered users. If enabled, anonymous users will see the same dynamic link as registered users, but when they click on it they are presented with a login dialog informing them they must register to have access to the file.

This is a sandbox for Drupal 7, so its usefulness is even more questionable, but you may still want to check it out.


Configuring Lightbox2 to Pop-Up Images embedded in nodes all my nodes have an image added to them (uploaded the usual way when creating new content for a content type), so when the viewer is viewing the node they can see the image inline with the text.

It's styled to look nice, but the image is small, and sometimes a user might want to see the details of the image more clearly (however we still want to keep it small on the page by default).

So I was thinking it would be nice for the user to be able to click the image and have the image get larger (possibly as a pop-up or overlay) on the page.

My research led me to Lightbox2 and so I installed that module. I enabled it and when into the settings in the configuration page and made sure it's loading on all pages. I also made sure the setting for 'Automatic Image Handling' > 'Image Node Settings' was set to 'Lightbox'. [I actually tried all of the options available there]. I then cleared the cache as usual.

It seemed all too simple no doubt. And indeed I went to one of my nodes and clicked on the image and nothing happened.

Can someone please help me configure Lightbox2 correctly to achieve my objective? (or perhaps give me an alternative solution).

Thanks!

Colorbox and lightbox are the famous modules for this, once you done with all configuration, go to Content type Manage display settings tab and render the image in lightbox. it will automatically shows up in the popup.
http://i.imgur.com/KA69Iqu.png


views_get_view_result in template.php? I want global variables using view results I can't seem to get this to work..

function mytheme_preprocess(&$variables) {
    global $user;
    // Classes of logged in User
    $view_result = views_get_view_result(
        'profile_page_flagged_pages',
        'panel_pane_1',
        $user->uid
    );
    // Create array
    $class_array = [];
    foreach($view_result as $item_class) {
        $class_array[] = $item_class->nid;
    }
    // Count Classes
    $class_count = sizeof($class_array);
    $variables['classes'] = $class_count;
}

If I set string values, it's fine. But trying the view gives a 500 error. This code works fine in a tpl file.

The theme_preprocess() function is jused to preprocess EVERY SINGLE template. What you do by now: for EVERY SINGLE template you run a view (I am not sure if it gets chached during to a single page request - so it may be that you run the view a hundred times during one page request). This may hit your servers capabilities.

1.) It is bad practice to run any views in the theme layer. Please assure that on the theme level no data alteration or processing is done any more no matter if done in a preprocess function in template.php or - even worst - in a tpl-file.

2.) Please consider a better place where to add this information by views. Where exactly do you want to add the classes? Which element?


how to allow span inside p (ckeditor) I have a paragragh which has 3 font colors throughout it, however every time I try to add the spans inside the paragraph CKEditor takes it upon it's self to remove them on me. How do I get the spans to stay inside the paragraph?

I save this:

Have TROUBLING SYMPTOMS and health concerns taken over your life? Muse can help.

but it turns into this:

Have TROUBLING SYMPTOMS and health concerns taken over your life? Muse can help.

Did these links not help:

https://stackoverflow.com/questions/18349048/ckeditor-strips-span-and-style-attributes

"If you are using the CKeditor module then there is an option in Advanced Options that is also mentioned in the module homepage where you should set"

or:
Prevent WYSIWYG+CKEditor from stripping html classes
"There is an issue with CKEditor 4.1+, which has a feature called Automatic Content Filter (ACF) that will automatically strip attributes not defined for the editor"


Aggregating data to show latest result? I'm currently using the Elasticsearch Connector to get my data from Elasticsearch for displaying. I've managed to set up some basic pages and display the data successfully, but am now looking for a way to group it.
for example, if I have several results but they are all from the same server address, I would like to group them by server and show only the lastest input.

I've looked through options on views, and the aggregator module but can't seem to manage it.
Is this something that's possible, and I've missed?
Or is that not possible in drupal anyway?

In Views you can group by a particular field if the display allows fields (table, not teaser, etc). Under the Settings for Table for example you can choose the field to group the results:

The field has to be present in the list of Fields, but can be excluded from display if desired.


Trying to convert db_fetch_object for Drupal 7 I am trying to convert a line of code from Drupal 6 for Drupal 7

for ($i = 0; $order = db_fetch_object($result); ++$i) {

Above is what it is -- and below is what I made it

for ($i = 0; foreach ($result as $order); ++$i) {

BUT . . . I get a parse error:

  Parse error: syntax error, unexpected 'foreach' (T_FOREACH), expecting
  ';' in / [PATH TO FILE] on line 483

Which is this

for ($i = 0; foreach ($result as $order); ++$i) {

SQL syntax checkers find no error in the syntax - I only a novice

the syntax is incorrect, and the error is correct. If you need to track $i, you could do something like:

$i = 0;
foreach($result as $order){
  ...
  $i++;
}


Getting Node Field Values from Referenced Entity within a Paragraph I'm trying to create a featured content paragraph type, however, I can't figure out how to grab anything from the referenced node that is in my entity reference. I don't see any twig documentation that covers this seemingly crucial task at all either.

Does anyone know of a way to call something like get_node() within a twig template?

If you're doing this in a node template you could access it like so

{{ node.field_paragraph.entity.field_in_paragraph.value }}

Obviously replace field_paragraph with the machine name of the paragraph field and field_in_paragraph with the machine name of the field inside the paragraph you want.


How can I keep a long-running Drush script from gradually exhausting available RAM? I've got a drush script that's used to clear out old, unpublished nodes that have come in from feedapi. The script is fairly simple: get all the nodes with status 0 of a certain type ("post") and age (older than 90 days), loop through them, delete each one.

The script runs through about 4,000 nodes at a time, then exhausts the memory available to its PHP process. I can watch the script's footprint grow from top and the 4,000 node limit is somewhat consistent. I've got over 100,000 nodes to work through, though, so I don't think it will be practical to just jack up the RAM available to the process long enough to get a run out of it.

Is there anything I can add at the bottom of each iteration to release the RAM it's consuming?

You could use the Drupal batch API and call it from Drush.  You could use the Drush batchTest unit test as another reference on how to use the batch API from Drush.


Login not redirecting to SSO (external) server login page I'm trying to replace Drupal authentication with the authentication from a SSO server, in a scenario discussed here. I'm trying to modify the login_block (on "Homepage" as well as "Access Denied" page), and login_block_form (at mysite.com/user/login). I did reset the default "Log in" button and replaced it with "SSO Log in" button, and on its #submit, using drupal_goto, I'm trying to redirect it to SSO server Login page. But, I'm still getting redirected to mysite.com/node?destination=node. I'm not able to figure out what the problem is. And inputs would be appreciated.

function MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Add a button to form, used to login to SSO
        $form['foo'] = array(
            '#type' => 'button',
            '#value' => t('SSO Log in'),
            '#submit' => array('MODULE_user_login_foo_submit'),
            '#limit_validation_errors' => array(),
        );
        // unset the current default login button of Drupal
        unset ($form['actions']['submit']);
  }
}

function MODULE_user_login_foo_submit($form, &$form_state) {
  drupal_goto('PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX', array('external' => TRUE));
}

Unset the destination before calling drupal_goto():

unset($_GET['destination']);
drupal_goto('PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX', array('external' => TRUE));

Another option would be to code the redirection logic yourself (brought up as an answer by Dave here).

The problem exists because drupal_goto() is overriding the given path with the destination if the latter is not external (check the function code).

Additionally:

Since you are using the button type the submit handler isn't being invoked (documentation). For my solution to work you would have to change the type to 'submit' or move the redirection logic into the validation handler (by changing '#submit' to '#validate').


How to configure the existing search system to exclude content types and/or nodes from the search index? As far as I see, the search api has no effect on the existing search. The video about State of Search Drupal 8 - Basic Usage of Search API  indicates that you have to supply an own view for the search results.

Isn't there a way to configure the existing search system to exclude content types and/or nodes from the search index?

There is a new Search Exclude (Node) module

  Exclude content types from node search for Drupal 8.


How to show the slide dots using the Slick Carousel module? I'm using the Slick Carousel module and I can't see where / how to add the paging dots below the carousel images. The module boasts that it has this feature.

I've tried altering the .js file (and the .min version) but can't seem to force them to show.

Does anyone know where to turn this on?

You need to enable the slick module and the slick ui module, after that go to Configuration -> Media -> Slick Carousel (admin/config/media/slick).

From there you can edit the default profile for slick carousel or create a custom one. There you can enable or disable dots and of course various other options.


How can I create a view on a profile page that shows content related to the user we are viewing I have a specific "sport user id" that the user provides in order to grab sports results about that user. I want to display their results, which I keep updated and organized programmatically in a cron job, on their profile. The way I would like to link the content would be by keeping the "sport user id" as a field in the result content type and also as a field in the user.

How do I go about creating a filter to do this?

Check out the EVA (Entity Views Attachment) module. This allows you to create views, which you can use as a field on any entity (node, profile, user or whatever) you like.

After you created the view, go to "Manage Display" of your content type and move the field in the right position.


Render default value of views exposed filter I have a view in Drupal 7 using an exposed filter. When I access the view without any ($_GET) values in the URL I want to display all items. The drop down selection has the value -Any- as I want it, but the view is still empty, even the empty result text will not shown. If I hit the submit-button all items appear.
Already tried different things from post I found about this, but nothing worked so far. I have no Idea why it is rendering nothing at all by default and why I can't make it render something...

Here are my settings for the filter:

Exposed: YES
Type: SINGLE
FILTER Operator: IS ONE OF
Options: -nothing_selected- (already tried selecting everything)
Checked options: Reduce duplicates

I'm using View 7.x-3.5 and have CCK 7.x-2.x-dev enabled.
Hope anyone has an idea. Thanks a lot!

Saduras

This may because of the exposed form settings. Change the settings of exposed form to "Basic" if it is "Input required".


How to change a field value in a product variation when someone edited the order manually? I had implemented a "Event Subscriber" controller to change the stock value in the product variation. Stock is a field in product variation.

Depending upon the quantity in order items I am decreasing the value of stock by subscribing to Drupal 8 event order $events['commerce_order.place.post_transition']. Similarly I increased stock value if he cancels the order using the event $events['commerce_order.cancel.post_transition'].

If somebody revise the order quantity from Back-office that time, stock should be increased or decreased accordingly. How can we achieve that? Is there any event when order items is edited?  we are currently decreasing stock when order is placed... how can we decrease/increase when somebody edit the order from backend manually?

Is there any event when order items is edited?

You could use hook_ENTITY_TYPE_update

/*
 * Implements hook_ENTITY_TYPE_update()
 */
function mymodule_order_update(\Drupal\commerce_order\Entity\OrderInterface $order) {
  // your code goes here
}

If you don't want to use a hook, then consider using the Hook Event Dispatcher module.

  This module dispatches events for several Drupal core hooks. This
  allows you to use the D8 Event Subscriber system, instead of the
  outdated hook system, to react on certain events. The module includes
  events for the most common hooks.


Allow users to annotate content in Drupal 7 Is there any way to allow users to add some private annotations when reading a book page for example ?

It seems that the annotate module is not anymore supported.

The book Pro Drupal Development is probably the most popular book for learning how to build Drupal modules. In the 3rd edition, which covers Drupal 7, the author uses the Annotate module as an example of how to build a module from scratch.

If you read the first chapters of the book you could easily write the module yourself, or even better, try to port the module you mention to 7.x. By the way, remember to check Errata of the book first.


Error in drupal_form_submit when taxonomy reference (tid) is set While trying to creating a node programmatically using 'drupal_form_submit' i've come across a php error in the form.inc code

Here's my code

function vl_sample_data_generate_yvbct1() {

  module_load_include('inc', 'node', 'node.pages');

  global $user;

  $content = 'Generating YVB CT1';
  $form_state = array();
  $data = array();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => $user->name,
    'type' => 'yvb_ct1',
    'language' => LANGUAGE_NONE,
  );
  node_object_prepare($node);

  $data['uid'] = $user->uid;
  $data['created'] = time();
  $data['type'] = 'yvb_ct1';
  $data['language'] = LANGUAGE_NONE;
  $data['title'] = 'Node created on ' . time();
  $data['status'] = 1;
  $data['op'] = 'Save';

  $data['field_middle_name'][LANGUAGE_NONE][0]['value'] = 'Alex';
  $data['field_gender'][LANGUAGE_NONE][0]['tid'] = 24;

  $form_state['values'] = $data;

  drupal_form_submit('yvb_ct1_node_form', $form_state, $node);

  return $content;
}

The error i get when i run the function (as a menu callback) is

Warning: Illegal offset type in isset or empty in _form_validate() (line 1333 of /opt/httpd/htdocs/www/staging/jns/trunk/includes/form.inc).
An illegal choice has been detected. Please contact the site administrator.

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /opt/httpd/htdocs/www/staging/jns/trunk/includes/entity.inc).

Warning: Illegal offset type in taxonomy_field_validate() (line 1519 of /opt/httpd/htdocs/www/staging/jns/trunk/modules/taxonomy/taxonomy.module).

Notice: Trying to get property of non-object in taxonomy_field_validate() (line 1519 of /opt/httpd/htdocs/www/staging/jns/trunk/modules/taxonomy/taxonomy.module).

However, if i comment out the line

  $data['field_gender'][LANGUAGE_NONE][0]['tid'] = 24;

It works fine. Am using Drupal 7.26.
Also, the term tid does exist and belongs to the valid Vocabulary which is
assigned in the content type.

Any help regarding the above problem is appreciated.

Thanks

Yashesh

It is possible that 24 is not a valid taxonomy term ID in the system, but I'm not sure if that's it. So I would check that using taxonomy_get_term_by_name or something. Also, and perhaps first, make sure to verify the field_gender field exists, as it might not always be there in the system and you don't want nasty bugs down the road.

// Check if field_gender field exists for node type yvb_ct1
$field_instances = field_info_instance('node', 'field_gender', 'yvb_ct1');
if (isset($field_instances['field_gender'])) :

  // Now check if the taxonomy ID is correct
  // I assume you are looking for a term name of 'female'
  if (!empty(taxonomy_get_term_by_name('female', 'gender')))
    // now try setting term reference field value

endif;

This is untested but I hope it might help get you closer.


How to redirect to another page after submitting the ctools modal form Actually i want to redirect to some other page after submitting the multistep ctools modal form .I have tried using form_state['redirect] and drupal_goto in submit function but didnt work.

function get_quote_menu(){

$items=array();
$items['get_quote'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'get_quote_form',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
$items['get_quote/%ctools_js/details'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'quote_ajax_details_form',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
return $items;
}
function quote_ajax_details_form($js = NULL, $step = NULL){

if ($js) {

    ctools_include('modal');
    ctools_include('ajax');
 }
  $form_info=array(

    'id' => 'quote_details',
    'path' => "get_quote/" . ($js ? 'ajax' : 'nojs') . "/details/%step",
    'show trail' => TRUE,
    'show back' => TRUE,
    'show cancel' => TRUE,
    'show return' => FALSE,
    'next callback' =>  'get_quote_details_next',
    'finish callback' => 'get_quote_details_finish',
    'cancel callback' => 'get_quote_details_cancel',

    'order' => array(
        'start' => t('View the plans and premiums best suited to you <br/>in 4 straight forward steps.'),
        'second'=>t(''),
    ),

    'forms' => array(
        'start' => array(
            'form id' => 'get_quote_start',
       ),
       'second'=>array(
            'form id'=> 'get_actual_quote_details',
       )
    ),
);

$object_id = 1;

if (empty($step)) {
// We reset the form when $step is NULL because that means they have
// for whatever reason started over.
get_quote_cache_clear($object_id);
$step = 'start';
}

// This automatically gets defaults if there wasn't anything saved.
$object = get_quote_cache_get($object_id);

$form_state = array(
'ajax' => $js,
// Put our object and ID into the form state cache so we can easily find
// it.
'object_id' => $object_id,
'object' => &$object,
);

ctools_include('wizard');
$form = ctools_wizard_multistep_form($form_info, $step, $form_state);
$output = drupal_render($form);

if($js){

$commands=array();

if($output===FALSE  || !empty($form_state['complete'])){

  $commands[] = ajax_command_html('#ctools-sample', finish($form_state['object']));
  $commands[] = ctools_modal_command_dismiss();

}else if(!empty($form_state['cancel'])) {

    $commands[] = ctools_modal_command_dismiss();

}else {

     $commands = ctools_modal_form_render($form_state, $output);
}

 print ajax_render($commands);
 exit;
}else{

 return $output;

 }
}
 function get_quote_start($form, &$form_state){
            $form['first_name'] = array(

'#title' => t('Your Name'),
'#type' => 'textfield',
'#size'=>20,
'#default_value' => $form_state['object']->first_name,
'#attributes'=>array(
    'placeholder'=>t('First Name'),
    'id'=>array('quote-first-name'),
),
//'#required'=>true,
);
$form['middle_name'] = array(
'#type' => 'textfield',
'#default_value' => $form_state['object']->middle_name,
'#size'=>20,
'#attributes'=>array(
    'placeholder'=>t('Middle Name'),
    'id'=>array('quote-middle-name'),
 ),
//'#required'=>true,
);
 return $form;
}
 function get_quote_start_submit(&$form, &$form_state){

global $user;

 $form_state['object']->uid=$user->uid;
}
function get_actual_quote_details($form, &$form_state){
$form['adults']=array(

    '#type'=>'select',
    '#title' => t('Adults'),
    '#options'=>array(
        1=>1,
        2=>2,
        3=>3,
    ),

 );
return $form;
}
function get_actual_quote_details_submit(&$form, &$form_state){

    // Not working redirect
       // drupal_goto('node/add/page');
        $form_state['redirect]='node/add/page',
}

This is a bit old, but hopefully it'll help someone. Down where you write your commands[] array. Change it to something like this. In the submit function of one of the earlier forms I set the redirectpath parameter on the object, then i just use that in ctools_ajax_command_redirect() after calling the dismiss modal function ctools_modal_command_dismiss().

  // If $output is FALSE, there was no actual form.
  $commands = array();
  if ($output === FALSE || !empty($form_state['complete'])) {
    // Dismiss the modal.
    $finish = _aap_main_add_finish($form_state['object']);
    $commands[] = ctools_modal_command_dismiss();
    ctools_add_js('ajax-responder');
    $commands[] = ajax_command_html('#ctools-sample', $finish);
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect($form_state['object']->redirectpath);
  }
  else if (!empty($form_state['cancel'])) {
    // If cancelling, return to the activity.
    $commands[] = ctools_modal_command_dismiss();
  }
  else {
    $commands = ctools_modal_form_render($form_state, $output);
  }


Control display of post date as standard field? Like many who came before me... I have a problem with the way drupal 7 allows me to control the display of the post datetime of a node.

I would like to be able to control the display of the post date as a standard field so that I can just simply order it within my fields. I know that I can edit the node.tpl.php but that's not what I'm trying to do. I want it rendered within the content fields.

Is there a module that will create a virtual field that mimics the post date or something like that?

Or is there a module that provides a date time which will automatically set itself to "now" when a new node is created?

display suite creates a "virtual" field for the post date and also for other properties of the node (submitted by, author,..). You can also set a date format for the post date.

To use it, enable ds and ds_ui, go to Manage display of a content type and choose a layout. You will see the mentioned fields.


D8: Cannot redirect user at onKernelRequest event I want to redirect the user at "onKernelRequest" event and I have this method:

  public function onKernelRequest($event) {
    // Restricts access to nodes (views/edit).
    if (!empty($event->getRequest()->attributes->get('node'))) {
      $nid = $event->getRequest()->attributes->get('node')->get('nid')->getValue()['0']['value'];
      if (!$this->accessCheckService->canUserAccessByNodeId($nid)) {
        $response = new RedirectResponse('/access-restricted-by-taxonomy-term');
        $response->send();
        return;
      }
    }

The response is being sent, but the user is not redirected to the given address (access-restricted-by-taxonomy-term). It seems that RedirectResponse takes no action at onKernelRequest event. How can I fix this?

Instead of sending the response yourself you can try to use the method setResponse() of $event:

$event->setResponse($response);


Add button to teaser on specific content type I have a custom content type for Real Estate
I have a custom view on the homepage that displays the 5 most recently added real estate properties and displays basic information about this property

This view is in a block on the home page.

I essentially want to put a button on these teasers that links to the full node for the user to view. I'm not sure what the easiest way to do this is?

Then, once in the full node I want to have a button that 1. Checks if the user is logged in (using php session or however that is handled with drupal) and then 2. if user is logged in it directs them to another page or if not logged in directs them to log in.

I would check out Display Suite's custom fields capability.

It allows you to create custom code "fields" that can be attached to nodes and other entities, and can be included in views. These fields can be, for example HTML code with tokens to create links that redirect user to the full node.

These fields also have the capability of accepting php code, which would allow you to evaluate if the user is logged in and include logic to redirect to the appropriate place. Check out the tutorial for custom fields here: https://drupalize.me/videos/display-suite-fields?p=1141


ajaxify content via a callback function I am trying to ajaxify my site. I want the "Main page content" to be passed via an ajax-command to a custom js-function.

To accomplish this I would do the following:

I need to register a path for my ajax requests

code:

$items['_custom_ajax_'] = array(
  'title' => 'AHAH callback',
  'page callback' => 'ajax_form_callback',
  'delivery callback' => '_custom_ajax_deliver',
  'access callback' => TRUE,
  'theme callback' => 'ajax_base_page_theme',
  'type' => MENU_CALLBACK,
);

use a custom delivery callback function _custom_ajax_deliver which is the copy of the ajax_deliver()

original code:

function ajax_deliver($page_callback_result) {
  // Browsers do not allow JavaScript to read the contents of a user's local
  // files. To work around that, the jQuery Form plugin submits forms containing
  // a file input element to an IFRAME, instead of using XHR. Browsers do not
  // normally expect JSON strings as content within an IFRAME, so the response
  // must be customized accordingly.
  // @see http://malsup.com/jquery/form/#file-upload
  // @see Drupal.ajax.prototype.beforeSend()
  $iframe_upload = !empty($_POST['ajax_iframe_upload']);

  // Emit a Content-Type HTTP header if none has been added by the page callback
  // or by a wrapping delivery callback.
  if (is_null(drupal_get_http_header('Content-Type'))) {
    if (!$iframe_upload) {
      // Standard JSON can be returned to a browser's XHR object, and to
      // non-browser user agents.
      // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
      drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
    }
    else {
      // Browser IFRAMEs expect HTML. With most other content types, Internet
      // Explorer presents the user with a download prompt.
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    }
  }

  // Print the response.
  $commands = ajax_prepare_response($page_callback_result);
  $json = ajax_render($commands);
  if (!$iframe_upload) {
    // Standard JSON can be returned to a browser's XHR object, and to
    // non-browser user agents.
    print $json;
  }
  else {
    // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
    // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
    // links. This corrupts the JSON response. Protect the integrity of the
    // JSON data by making it the value of a textarea.
    // @see http://malsup.com/jquery/form/#file-upload
    // @see http://drupal.org/node/1009382
    print '<textarea>' . $json . '</textarea>';
  }

  // Perform end-of-request tasks.
  ajax_footer();
}

create an custom function which do the ajax request like Drupal.ajax
bind the ajax request to some selector e.g. a.ajaxify
add a custom ajax-command

Im not sure if this is the right way, or if I can extend the core easier somehow.
Basicly my approach is simmilar  to the module Ajaxify Drupal with JQuery Ajax

Better Ideas?

Update: one more thing – I need an event to be triggered everytime an ajax-link is clicked.

IMHO, I'd like to use Drupal AJAX API instead of jQuery AJAX because it supports many commands, events and content are manageable, error control and event binding for new content, those features are supported by Drupal.

But the disadvantage is it sends too much data, process is more complicated, using POST all the times. But of course, at javascript level, we can override the default behaviors and make it better :)

For example, If you have any ajax errors, like ajax request is running and you change document location, you will see an alert box with error message. That's a bit annoying so I always override it by re-write this function in my theme

Drupal.ajax.prototype.error

About your working process, I have some comments

1 & 2: It's ok for me, but why do you need to use another copy of ajax_deliver(), why don't you use it directly?
3: Are you going to write another thing like Drupal.ajax or just attach new function to Drupal.ajax? something like

Drupal.ajax.prototype.commands.log = function (ajax, response) {
    console.log(response);
};

Drupal.ajax.prototype.commands.open_popup = function (ajax, response) {
    var id      = typeof response.id      === 'string' ? response.id : 'gfc';
    var content = typeof response.content === 'string' ? response.content : '';
    var options = typeof response.options === 'object' ? response.options : {};

    Gfc.popup.open(id, content, options);
};

I'm ok if you do like that.
4: Yes of course
5: Errr, are you going to write something new instead if using Drupal.ajax?


How to prepare directories in private file system? I've configured private file system. Using it from UI works well.
I want to generate dump site content via devel_generate with custom modifications. So I'm hooking into Node API for assigning sample PDF files to nodes.

Inside private directory I want to create directory structure:

  $dir = sprintf('private://org%d/%d/person%d', $this->getOrganization()->nid,
                    date('Y'), $this->getEmployee()->uid);

  if (!file_prepare_directory($dir)) {
    throw new Exception('Cannot create document file directory or it\'s not writable');
  }

But exception is thrown.

How to set proper directory permissions? Content is generated  via drush command - drush genc.

Ok, I solved it by passing proper flag (for UI):

file_prepare_directory($dir, FILE_CREATE_DIRECTORY);

For using drush command still don't know and failing.


Passing Node Variables to Content and Blocks I'm really struggling with how to get variables created in page.tpl.php and node.tpl.php in rendered content and blocks. I hope I'm just missing something simple.

Basically, I'm trying to have a unique ID number passed around the site. To do that (as far as I know) I need to add it to all the links, IE /?a_uid=123456.

I'm generating the random ID in success_preprocess_page (full code is below).

function success_preprocess_page(&$variables, $hook) {
  //echo '
'; print_r($variables); echo '
';\

        if (isset($_GET['utm_campaign']))
            $adkey = $_GET['utm_campaign'];
        elseif (isset($_POST['utm_campaign']))
            $adkey = $_POST['utm_campaign'];
        else
            $adkey = NULL;

        if (isset($_GET['a_uid']))
            $a_uid = $_GET['a_uid'];
        elseif (isset($_POST['a_uid']))
            $a_uid = $_POST['a_uid'];
        else
            $a_uid = NULL;

    if ($adkey != NULL)
    {
        $a_uid = "123456";
    }
    $variables['adkey'] = $adkey;
    $variables['a_uid'] = $a_uid;

   if(isset($variables['a_uid'])){
    // add the flag to the node to say it's been set and there is only a single node to display
       if(isset($variables["page"]["content"]["system_main"]["nodes"]) && count($variables["page"]["content"]["system_main"]["nodes"]) == 2){
            $keys = array_keys($variables["page"]["content"]["system_main"]["nodes"]);
           // Set a new variable called sidebar_first equal to true on the node.tpl level
           $variables["page"]["content"]["system_main"]["nodes"][$keys[0]]['#node']->a_uid = $a_uid;
      }
    }
}

Any links that are in page.tpl.php, ex:

<a href="programs/?a_uid=<?php echo $a_uid; ?>">Programs

Display the correct $a_uid variable result of 123456.

And if I try to echo $a_uid in node.tpl.php, ex:

<?php $a_uid = $node->a_uid; ?>
<?php //echo 'A_UID: '.$a_uid.'

'; ?>

Also displays 123456 fine.

But if I try anything like this in my content pages (even with them set as PHP Code Text Format, which correctly processes other PHP code), everything result is blank.

For instance, I currently have a content page that has this in it, trying to hit all the marks I can think of:

<?php echo $a_uid; ?>
<?php print $a_uid; ?>
<?php echo $node->a_uid; ?>
<?php echo $content->a_uid; ?>
<?php print $node->a_uid; ?>
<?php print $content->a_uid; ?>
<?php print ($page['a_uid']); ?>
<?php print ($node['a_uid']); ?>

Not a single one of those displays anything.

As far as I can tell it seems like the variable is just not getting passed to the content? I just don't understand why, or how to fix it.

I assume this is standard, but this is how my content is being called in node.tpl.php:

print render($content);

I am also having the same problems in my header and footer blocks. Those are being called from page.tpl.php as:

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

Any help with this would be greatly appreciated. Thanks! Oh and 123456 is just a placeholder in here for my random unique ID generator code :)

Apparently I was just looking at my process wrong this morning. I went back to it after reading what you wrote and realized I could just use  in my html.tpl file and it would handle everything I need it to do.

But thank you for answering! I'm not sure how but what you posted led me in the right direction after I was reading your links :)


How to record a log message when saving a Commerce Order via Drupal EntityWrapper? I'm modifying a set of orders programmatically and want to record a log message when doing so.

Is there an existing method to add a revision and log when doing so?

$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('test@example.com');
// $order_wrapper->log->set('Changed order owner and mail');
// $order_wrapper->revision->set(true);
$order_wrapper->save();

Currently if I try $order_wrapper->log->set('x'); I see EntityMetadataWrapperException: Unknown data property log., but I believe this is a property of the order (based on getPropertyInfo() etc).

Does Commerce Order + Entity Metadata Wrappers have support for creating a new revision on save, or recording an order log message?

You may need to set the revision and log properties on the default order object, instead of the wrapper.

e.g:

$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('test@example.com');
// Set revision details on order object
$order->revision = TRUE;
$order->log = t('Changed order owner and mail');
$order_wrapper->save();

As the order object is passed by reference, from memory the revision log info can be set that way.


Using custom CSS3/HTML on generated pages? I created new pages on my (soon to be) photography website using Panels and Views. I want to have my own hover effects for pictures on my albums page. How am I supposed to use custom HTML and CSS3 animations like those found here on these images which are loaded by modules such as Panels and Drupal which are basically creating their own markup on the page load i.e. not in hard coded files which I can add markup to.

You can override the views template and create your own template/markup to achieve what you want.  You can read more on how to achieve that here: http://drupal.org/node/1089656


How to upgrade my Zen sub-theme so that navigation and most of the blocks are no longer missing? I have been looking quite a bit for a "step by step" for what people did to upgrade their Zen Sub-themes from its 6.x version to the 7.x-5.x version.

I did not make the sub theme I'm working with and I am not familiar with the process (last webmaster made it).

The issue I am having: the front page and all other pages don't have navigation and almost all the blocks are missing.

In my searching I saw that the .info file and template.php file have something that needs to be done. Haven't been able to really get a good outcome at all.

This is how my 6.x regions look like:

regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[navigation]     = Navigation bar
regions[highlight]      = Highlighted content
regions[content_top]    = Content top
regions[content_bottom] = Content bottom
regions[header]         = Header
regions[footer]         = Footer
regions[page_closure]   = Page closure

regions[footer_col1]   = Footer Column 1
regions[footer_col2]   = Footer Column 2
regions[footer_col3]   = Footer Column 3
regions[footer_col4]   = Footer Column 4

regions[homepage_col1]   = Homepage Column 1
regions[homepage_col2]   = Homepage Column 2
regions[homepage_col3]   = Homepage Column 3

Any suggestions about how I should proceed?

The issue about How to upgrade Zen theme from 6.2 to 7.3 contains quite some info (and links to other resources) about such Zen upgrade. However it also includes these suggestions about possible alternatives to consider:

Something like "maybe you should just consider restarting from scratch".
Swap from the Zen theme to the Omega theme (by creating an Omega sub-theme from scratch).

For more in depth documentation, you might want to look at Upgrading 6.x themes to 7.x.

Based on the current (further edited) content of your question, these are some of the topics to be sorted out (at least):

Navigation:

The navigation items shown in D6, possibly correspond to your primary and/or secundary menus (though they may also come from some "custom" menu that got added). Check which technique was used to actually display that menu in D6. Possible options I can think of: (a) some block makes them show up or (b) some theme settings is turned on (enabled checkbox) to make them display. Depending on which option was used, try to find the corresponding D7 options to do the same there.
Blocks:

For any of the blocks shown in the D6 version, in which theme region were they displayed? Head over to the D7 version to verify where probably "most of these blocks" will be shown within the "disabled" list of blocks. For any such block you find, in the D7 version start experimenting with moving those disabled blocks to what you think will be the most appropriate region in D7.

Keep repeating this for each of your blocks that are missing (= iterative process). In doing so, little by little most (if not all) of your blocks should start showing up).

If sorting out the above topics appears to be too complicated and/or turns out to take too long, then I'd really consider going the route of either possible alternatives mentioned above, because creating a "sub-theme" from the most recent Zen or Omega theme might simplify further maintenance of your "custom" theme also.


Is it possible to override configuration with yml files? Override configuration guide shows how users can override configuration with global $config variable, for example by using settings.php file (the same method as for D7).

But is it possible to override the configuration in a similar way but with yml file? It's much more convenient to use yml instead of php to override settings.

A real life example: let's say my module offers some configuration but I don't want to expose it via UI. I only want users to be able to change the settings via yml files (there are reasons for that). Obviously they shouldn't change my modules yml config file. Can they create a new yml file, name it accordingly (how?) and put inside sites dir?

No, you can't override with YAML files.

But, all configuration is YAML. You can edit them manually with single export and then import again, you can do a mass export and then change the exported files (then you even get a diff of the changes that you can confirm).

You can also use drush cedit yourmodule.settings or drush cset yourmodule.settings some.key the_value (or the export/import commands for editing configuration.

None of those touch the YAML files in your module.. those are only the starting point and are then imported into the active config store of a site, after which they can be edit with the mentioned tools.


In a view, how can I link a field to the node? In a fields view, the "title" field has a check box "Link this field to the original piece of content". But this check box isn't available for other fields. How can I achieve this functionality for other fields?

E.g. in my case I have a custom "subtitle" field, and I would like to list the nodes subtitles. The subtitles should be links that point to the node.

as @Daphna mentioned and you can see here: drupal.org/node/1234862 you can use Content: Path field value as a token for the field you want to be linked to the content:

add Content: Path field and in the configure field modal box check Exclude from display to hide this field from being displayed and rearrange fields so this field is above the field you want to be linked to the content.
click the field you want to be linked to the content to open configure field modal box and in the Rewrite results section check Rewrite the output of this field.
in the opened textarea under Rewrite results write this: [field_name]. you should replace field name with proper token of the field you want to be linked. you can find all the fields token in the Replacement patterns section under Rewrite results.


Redirect page without exit I have checkout function which uses drupal_goto to redirect to the confirmation page after validating all info. I want to redirect to the confirmation page before all validation. Then in the background I need it to complete all validation and email me any errors.

Problem is, drupal_goto calls drupal_exit so all further code stops running. I can implement my own goto function without the exit but then it won't redirect until all validation is completed. I need validation to run in the background after the redirect.

During checkout, you'll need to create a transaction because the order needs to be paid before it is actually completed. If you're needing to do other processing, you might consider looking at the architecture of Commerce License, where a license can have a post-checkout set of processes.

The short version of it looks like this:

You create the license or the "queue item" that needs to process.
Redirect to the completion page.
Have an AJAX watcher that looks for the completion of whatever needs to be done (could be handled by queues or some external system that updates state on the site).
Use JavaScript to take action.


Do custom theme suggestions execute on every page load and does that impact performance? I've been working with Drupal for a little while now and one nagging question I've had is about whether or not logic in my *.theme or *.module files have any impact on server load.

Let's say I have this bit of code in my *.theme file:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MY_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if(\Drupal::routeMatch()->getRouteName() == 'entity.node.edit_form' && \Drupal::routeMatch()->getParameter('node')->bundle() === 'blog_general') {
    $suggestions[] = 'page__no_sidebars';
  }
}

This bit of code adds a template theme at the page.html level. I only need this for about 1% of my site and it bothers me a little that this would need to execute on every page load just so 1% of my site can templated correctly.

So my question is, would this code get executed on every page load? Or does the caching take care of it? If it does execute on every page load then this one bit of code might be trivial. However, I'm slowly building up a lot of these types of altering hooks and it's bugging me that they could be taxing the server.

I appreciate any insights. Thanks!

To answer your questions:

Yes, it executes on every page load.
It won't impact your server load any noticeable amount.

The amount of processing power for that one function is extremely low. You could probably run it 1000 times without causing a noticeable performance it.


Setting field attribute as read only in hook_form_alter? I'm trying to create a simple custom module to stop the Title of a specific node being edited.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form') {
    unset($form['title']);
  }
}

Currently it just removes any reference to the Title from the edit pages. Does anyone know how I can set the Title field attribute read only?

You can use the #disabled attribute:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form' && $form['nid']['#value']) {
    $form['title']['#disabled'] = TRUE;
  }
}

I made the assumption that you want this when editing nodes only (not when they are being added) which is what the && $form['nid']['#value'] part is for.


How can I access the raw value of a view in a template? I am looking for a way to get the url of an image dynamically to put it as a background.
So I created a view that get the image field of the node or taxonomy term, which is supposed to output the url only (I have tried only with the node so far). I have been cleaning as much as possible everything inside the view and also the template of the view looks basically like {{rows}} and that's it.
But there is still a wrapper div that I can't trim:

/sites/default/files/2018-08/bg_image.jpg

How can I trim the twig variable created in the theme to get rid of the html tags ?

When I try strip_tags() function in the theme preprocess or |striptags or |trim directly in the template, it's not working and I have a lot of errors starting with Warning: strip_tags() expects parameter 1 to be string, array given in __TwigTemplate for example

I found a solution. I was looking at the problem the wrong way. It is possible to get the raw url value of an image field in a page template by using native twig-drupal functions instead of using a view => https://drupal.stackexchange.com/a/224311/16146


How do I override a taxonomy/term/% list with a view? I have a vocabulary attached to a content type. Only one term can be selected to categorize a node made with this content type. The vocabulary is called Vehicles and has terms 'cars, trucks, boats.' The content type is also named Vehicles.

I use path auto so that it shows [vocabulary:name]/[term:name] so when rendered it will show site.com/vehicles/trucks, for example, which will show all the trucks... typical Drupal stuff.. Ok...

Now, I have a View that is a page with a path 'vehicles.' It is setup to to display all of the items of content type 'vehicles.' This page view is also setup to take an argument 'taxonomy term id.'

Note that when the taxonomy term is present, the url alias generated for the taxonomy path is the exact same as as the Views page with an argument supplied:

URL Aliased taxonomy path = vehicles/trucks.
Views page with argument = vehicles/trucks.

This is on purpose. My goal was to show all results of that content type when an argument was not present, and when it was present, it would most importantly filter the results based on that taxonomy term AND keep the same fields and structure as without the argument (same as site.com/vehicles).

The problem is, this is not working as expected.
site.com/vehicles correctly shows my view and related filters.
site.com/vehicles/trucks shows just the regular, unformated taxonomy list supplied by Drupal.

Is this because Taxonomy term ID argument is not configured correctly?

Is this a weight issue where taxonomy hooks are firing after Views? If so, how can I rearrange the weights here so that it fires correctly and gives me the results I need?

I know what you are going to suggest - that Views comes with taxonomy/term/% view to override drupal default views.

However, this is not going to work in my case. I have multiple content types each with its own vocabulary and each with its on view and distinct set of fields (houses and cars, for example have very different field sets). The taxonomy/term/% would work if all content types had the same fields, then I could just mimic those in that override, but since that is not the case, how can I correctly get my path with argument to show the results based on that vocabulary term and keep my field structure?

Sorry if that was confusing. A link to the site for reference http://www.buyagainbaby.com. The site does currently use taxonomy/term/% as an override, but again, that has to change so that each view is responsible for how it renders its result set based on taxonomy.

All of these answers are great solutions, and thanks for taking the time to provide such infomative answers.  Ashlar, your response taught me a lot about how taxonomy works works as well as the relationship between views and taxonomy.

I found a solution that works great for my situation, and I will share that in case it may help you guys too.

As I explained above, the my problem was that my view, with no argument, supplied the results I wanted, but the default taxonomy view with an argument, which was not what I wanted.

To solve this, I installed the module Taxonomy Display http://drupal.org/project/taxonomy_display.  I then reconfigured each view to have Taxonomy Term ID as an argument.

Taxonomy display lets you associate a vocabulary with a particular view. Now, when I click on vehicles/trucks, which is an alias for taxonomy/term/3, the view takes over and this is actually rendered correctly maintaining the integrity of the field structure.

If anyone wants to know more details about the configuration please let me know.


How can I print e-mail messages sent by Drupal to the screen for debugging purposes? For debugging, I'd like to print the values being used to send e-mail messages to the screen.

After enabling the devel module, I tried this code (modified as per Letharion's comment):

function MY_MODULE_mail_alter(&$message) {
  dpm($message, 'email_test');
}

I don't get any error message, but I don't see any output, either.  How can I print the value of '$message' to the screen?

More details about my site:

I'm trying to debug the e-mails sent upon user registration.  There should be one sent by Drupal itself via the Logintoboggan module and another sent by the Rules module.

Anonymous users have the same permissions as admin to view debug messages; I tested this by adding a dpm() in my page.tpl.php.

I tried setting Display redirection page to on as per Clive's comment but the workflow is unchanged from before.  If I add debug($message) to the MY_MODULE_mail_alter() then debug() will print the message from Drupal/logintoboggan but not the message from Rules.

The way I debug email is by using the TestingMailSystem class:

// Use testing mail system.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

You can then capture and print the mail contents with the following statement:

$mails = $this->drupalGetMails();
debug($mails); // $mails is an array holding all mails sent.

Here $this is the current testing class (instance of DrupalWebTestCase).

This is very simple to use as part of automated testing (using the Testing framework that is part of the Drupal core).

If you don't want to be troubled by setting up the full Testing framework, an alternative method for debugging email is to hijack drupal_mail.

To do this you need to install the Devel module and
edit the core mail.inc by replacing the standard drupal_mail with the following function:

/**
 * Function to debug mail.
 */
 function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
  dpm('Using hacked version of drupal_mail.');
  dpm($params, 'mailbody');
  // Print out more arguments if required.
  return TRUE;
}

And yes, this is hacking core, so:  1) Don't do this on a production site; and 2) Remember to restore mail.inc with a pristine version when done debugging.

Note: The latter method is a rather nasty hack (but I've found it useful a few times).  Using the Testing framework to debug mail is the recommended method.


Commerce 2.x confusion about multiple order types and order item types I have two different order types and two different order item types. Let's say they're "Default" and "Custom". On the configuration page for the Default order item type, I've specified Default as the Order type. On the configuration page for the Custom order item type, I've specified Custom as the Order type. For both order types, I use the "Inline entity form - Complex" widget for the Order items. I've set the "Allow users to add new order items" option and left the "Allow users to add existing order items" option unselected.

I expect that when I create an order of type Default, I will only be allowed to add Default order items. And when I create an order of type Custom, I will only be allowed to add Custom order items.

However, what I get instead is the option to choose from a select list whether I want to add a Default or Custom order item, regardless of the order type. So it's possible to create orders that have a mix of Default and Custom type order items. I do not understand why this is so. It seems that the "Order type" value for order item types is being ignored.

Is there a way to set up commerce order/order item types so that an order item can only be added to an order if the order type is the one specified in the order item type configuration?

As BojanZ (the maintainer of the module) has stated in his comment above, you have located a bug :) Congrats! Post it to the Commerce issue queue here:

https://www.drupal.org/project/issues/commerce?categories=All


How to make a comment only visible to the commenter before approval? There is no registered users (apart from user/1 of course ...) in the website and anonymous visitors have the permission to comment on the website.

Comments are not shown before approval.

What I want to do is to display a comment to commenter only before I approve it. So this is what I'm looking for:

  Only display a comment posted by 'X' to 'X' (nobody else) for as long
  as the comment has not been approved by a reviewer, AND on condition X
  is using the same browser as the one the comment got posted with.

I couldn't use "userid" etc. for (anonymous) visitors. What can be used for that (session, IP address etc.)?

The feature I asked for is similar to the peer review feature you see on any SE site, which is like so:

How can I do it?

Things you need to know:

hook_node_view
hook_query_TAG_alter
db_or

Step I read code.
Step 1: find function comment_node_view this function define element comment in array render of node.
Step 2 find line 711
$node->content['comments'] = comment_node_page_additions($node);//define comment

Step 3 go to function comment_node_page_additions see code.
if (($node->comment_count && user_access('access comments')) || user_access('administer comments')) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $node);
      $build['pager']['#theme'] = 'pager';
      $additions['comments'] = $build;
    }
  }

Step 4 If user is anonymous $node->comment_count = 0. so condition is false. Don't add comment. (Problem 1)
Step 5 function comment_get_thread
if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }

this function return array store cids (all comment of node) with condition status is published (don't get comment of user is anonymous) Problem 2.
Problem solving
Problem 1: Use hook_node_view to set $node->commentcount != 0 (require this function run before function comment_node_view. You can set weigh of module (sure test with value is -1) or name of module start with a or b (not sure)).
/**
 * Implements hook_node_view().
 */
function ModuleName_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($user->uid == 0 && $node->comment_count == 0) {
    $node->comment_count = 1;
  }
}

Problem 2
You need alter this query to get comment published or current user is author of comment. To do it i need hook_query_TAG_alter.
You can write a custom module with code:
/**
 * Implements hook_query_TAG_alter().
 */
function ModuleName_query_comment_filter_alter(QueryAlterableInterface $query){
  global $user;
  if (!user_access('administer comments')) {
    $conditions = &$query->conditions();
    foreach ($conditions as $key => $condition) {
      if (is_array($condition) && is_string($condition['field'])
        && $condition['field'] == 'c.status'
        && $condition['value'] == COMMENT_PUBLISHED) {
        unset($conditions[$key]); // unset condition comment is public
        $or = db_or();
        $or->condition('c.status', COMMENT_PUBLISHED);
        //$or->condition('c.uid', $user->uid); this case for require use login to comment
        $or->condition('c.hostname', $user->hostname); // Ip of user
        $query->condition($or);
        return;
      }
    }
  }
}

NOTE: All the users have the same IP are seeing comment.


View To Show Tagged Comments Via Arguments Hello i like how you can add taxonomy to comments now in D7. Im having a few problems though creating a View that will take a tid contextual filter and show the comments in the taxonomy page as a block. Has anyone managed to achieve this?

Thanks

Add Relationships Field: newtag (whatever your term referance field is called)

Contextual filters (term from field_newtag) (add relationship from above)


Views: Exposed filter If anonymous. Filter by user field if authenticated I have created two 'Postal code' (text) fields: one in a content type (Event) and another in the user account. I have also created a view showing Events. Now I would like to do the following:

When a user go to the events view:
  If the user is anonnymous a exposed filter must be show.
  If the user is authenticated, show only events with the postal code of the user.

Have you tried the module Views Dependent Filters?

For example, you could create a filter which checks if the user is logged in (or has a postal code) and set a dependency to that filter in your postal code filter.

You could also write some custom code (which might be easier in my opinion):

function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
  // Get the current logged in user object.
  global $user;

  // Check for the exposed form, you would do good to add
  // some extra checks to make sure you only identify your
  // postal code exposed filter.
  if($form_id == 'views_exposed_form') {
    // Load the full user object.
    $account = user_load($user->uid);

    // Check if the user has a postal code.
    if (!empty($account->field_postal_code[LANGUAGE_NONE][0]['value'])) {
      // Hide the exposed postal code field.
      $form['field_postal_code']['#type'] = 'hidden';
      // Set a default value for the exposed postal code field.
      $form['field_postal_code']['#default_value'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];
    }
  }
}

You might want to apply the filter immediately without needing to submit the form. You could use hook_views_pre_view for that:

function YOUR_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  global $user;

  if ($view->name == 'your_view') {
    // Do the same user postal code check as above here.

    // Apply the exposed filter.
    $view->exposed_input['field_postal_code'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];;
  }
}

I'm not sure if the hook_views_pre_views part works, though, so you might need to do a little research there.


How to tell if an image was updated I'm using images generated by Drupal (drupal 7) to feed an application. I'm then caching those images in the app. I'm trying to figure out a way to determine if the image has been updated since the last download, is there anyway to access this information about an image, without actually loading the image?

You can use ETags - when the app receives an image, there will be an HTTP header that looks like:

ETag: "686897696a7c876b7e"

Whenever the app wants to check for a new image, perform a GET request with this header:

If-None-Match: "686897696a7c876b7e"

If the file is unchanged, your web server will respond with HTTP 304 Not Modified status.


Drupal 7 CDN Module not altering URLs for themed Pages I have themed a page on my Drupal 7 website by mentioning the template file as
page--node--.tpl.php
The CSS and Images which are coming on this page are getting picked from the site itself and not from the static url i have configured in CDN.
Other than this page my website is picking CSS JS & Images from CDN
Any suggestions ?

Basic page--node--123.tpl.php

<?php
global $base_url;
$img_actl_path =  "$base_url/".drupal_get_path('theme','theme-name')."/images/v1/";
?>
<img src="<?php print $img_actl_path;?>image1.jpg" width="380" height="197" />

The problem is that you are not using the Drupal API.

The CDN module needs to be able to alter the path from your Drupal site to your CDN.  It does this by catching the URL via hook_file_url_alter(), and changing it.

The proper way to to make a URL in this case is with file_create_url().  Something like this should work

function MYTHEME_preprocess_page(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');
  $variables['mysrc'] = file_create_url($path . '/images/v1/image1.jpg');
}

And then in your theme you would use

<img src="<?php print $mysrc; ?>" width="380" height="197" />

However, as Mołot suggests, using a proper theme function to make a renderable image would probably be best.


How do I hide the AJAX Cart block when cart is empty? How can I hide Ubercart AJAX Cart block when the user's shopping cart is empty?

I know I could hide it with some jQuery tricks (for example, looking for the "cart-empty" class under my AJAX cart block (which has the class "block-uc_ajax_cart"), and hide the whole block if I found it), but this way I also would have to solve if cart is updated... Too messy.

I haven't found any opportunities to hide the block in this case under block settings, nor under the AJAX Cart Settings (http://<mysite>/admin/store/settings/uc_ajax_cart).

Thanks for your help in advance!

OK, in the meantime I found the solution.

1.) Set "Block title" in the appropriate block configuration to <none>. (http://<mysite>/admin/build/block/configure/uc_ajax_cart/0) (you'll see later why)

Block title:
<none>

2.) Copy the UC AJAX Cart template files (uc_ajax_cart_block_content.tpl.php, uc_ajax_cart_block_content_empty.tpl.php) from http://<mysite>/sites/all/modules/uc_ajax_cart/templates/
to your own theme's templates directory (http://<mysite>//sites/all/themes/<mytheme>/templates/).

3.) After that, open both copied files (which are now in your template directory) in a text editor.

4.) Delete (or put in a comment) the content of uc_ajax_cart_block_content_empty.tpl.php, and upload the edited file to the server.

5.) Prepend the following to uc_ajax_cart_block_content.tpl.php to have the block title back:

        <?php print t('Shopping cart')?>

(The rest should stay intact!!)

6.) Clear the theme registry cache (http://<mysite>/admin_menu/flush-cache/theme), and you're done.

UPDATE:
the method above breaks the toggling opportunity of the shopping cart content (if the following is checked in the settings: "Make the shopping cart block collapsible by clicking the name or arrow.") when clicking on the block title ("Shopping Cart"), because the title part is also updated with AJAX from the uc_ajax_cart_block_content.tpl.php file, BUT there IS a solution in jQuery, which you have to put in your own JavaScript-file (which is e.g. put in your theme's .info file), and it looks like this:

$(document).ready( function(){
    if( $('#ajaxCartToggleView').length > 0 ){
        // live: "Attach an event handler for all elements which match the current selector, now and in the future." (http://api.jquery.com/live/)
        $("#ajaxCartToggleView").live("click", function(){
            ajaxCartToggleView();
            return false;
        });
    }
}


Custom module over ride blazy.html.twig template I have a small custom module that needs override blazy.html.twig that comes from the Blazy contributed module in Drupal 8. The code below shows what I have so far, can anyone give me some direction on how to go about this?

/**
 * Implements hook_theme().
 */

function slider_overlay_text_theme($existing, $type, $theme, $path)
{
    // In the template file I have blazy.html.twig
    $templates = $path . '/templates';

    return [
            'template' => 'blazy',
            'path' => $templates
    ];
}

/**
 * Prepares variables for blazy.html.twig templates.
 * Implements hook_preprocess_HOOK() for field templates.
 */
function slider_overlay_text_preprocess_blazy(&$variables) {

    // This variable is in the template ready to be printed
     $variables['display_hero_text'] = 'right-hero-text1';
  }

I found the issue to override the module template you have to call the modules name in the _theme hook $return['blazy'].

function slider_overlay_text_theme($existing, $type, $theme, $path)
{
    $templates = $path . '/templates';

    $return['blazy'] = [
        'template' => 'blazy',
        'path' => $templates
    ];
    return $return;
}


Action on module enable? I want to show a message when a module is being enabled. I used hook_modules_enabled and it shows me the message while enabling a new module.

Now I need the currently enabled module machine name in the hooks argument.
But hook_modules_enabled($modules) returns an array of modules in the argument.

Eg:

When views is enabled, I need to set a message as:

  "Views Module is enabled"

Here I need "views" (i.e. the module name) as argument in hook_modules_enabled in order to print it in message but it returns me an array.

How can I achieve this. Is there any other hook for this?

hook_module_enable() should do the job unless I'm missing something from your question.

  Perform necessary actions after module is enabled.

  The hook is called every time the module is enabled. It should be
  implemented in the module's .install file. The implementation can rely
  on the .module file being loaded.


get the permission must the user have to access to the 'Access denied ' page i'm working on a drupal 7 online payment module ,

and i need to know if there is a Drupal 7 function that can track (each time and for all the users) if 'the logging online user' is requesting an 'Access denied ' page , and then get the permission must the user have to access to that page

  PS: i'm creating a drupal payment module , the payment will be by
  roles , for exemple ( user1 can create 'Blog content type' just if he
  has the permission on that, if not i i need to know which 'Access
  denied ' page he is in and it's role so i can show him a message to
  buy this role depending on the price in the database) all what i need
  is the string permission of the page

thanks in advance ^_^

The only answer I can think of is to roll this functionality yourself with some coding in a custom module.

You probably want to use Chain Menu Access and the drupal API function user_role_permissions.

You can use the chain menu access api to put a fired-last menu access check that does some comparisons over previous access checks and Roles:

<?php
  chain_menu_access_chain($menu, 'an/existing/path', '_mymodule_new_access_callback_check_permissions_to_roles');
?>

Then use the drupal api user_role_permissions to see what Role has X permission that was failed in a parent-chained access callback. You could store that for example in the users $_SESSION data. Then write a custom 404 page that shows them purchase options.


Use created year as condition in Entity Query I'm performing an entity query that searches for nodes of my custom content type called 'news'. I want to perform the query in a way that only produces the 'news' nodes that have a Authored Date that fits within a specific date . Here is an attempt I made below.
'

$year = 2018-02;
$query = \Drupal::entityQuery('node')
  ->condition('type', 'news')
  ->condition('created', [date('Y-M','created'), $year], '=')
  ->range(0, 10);

Try this function get_nodes_by_authored_month_date('news', '2018-02')

use Drupal\node\NodeInterface;

 /**
 * @param string $bundle_type
 * @param string $year_month
 *
 * @return array|int
 */
function get_nodes_by_authored_month_date($bundle_type = '' , $year_month = '') {

  $full_date = date_parse_from_format('Y-m', $year_month);
  //- Get number of days of month
  $number_of_days_of_month = cal_days_in_month(CAL_GREGORIAN, $full_date['month'], $full_date['year']);
  //- Get the timestamp of the first minute in the month
  $first_minute_of_month = mktime(0, 0, 0, $full_date['month'], 1, $full_date['year']);
  //- Get the timestamp of the last minute in the month
  $last_minute_of_month = mktime(23, 59, 59, $full_date['month'], $number_of_days_of_month, $full_date['year']);

  $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', $bundle_type)
    ->condition('created', [$first_minute_of_month, $last_minute_of_month], 'BETWEEN')
    ->range(0, 10);

  return $query->execute();
}


Load a view block into a custom page generated in a module Is it possible to programatically insert an existing view into a block generated by a custom module and pass it a parameter?

I am generating a block based on some external api data. I have been asked to add a view that pulls in related content from the website. To do this I would like pass a view to my block and pass it a parameter I extract from the api data.

Can this be done, and if so... how?

Just like in D7, using views_embed_view.

print views_embed_view('view_name','machine_name', $parameter);

In case you are wondering, this is the machine_name

Example:

$parameter = 1;
print views_embed_view('hello_world','block_1', $parameter);


Validation on modal dialog forms I opened my form in a jQuery modal dialog using the Simple Dialog module. I am unable to do any sort of validations on it.
Is it a limitation of the module? Would it validate if I use any other method of creating a  modal dialog form, such as using a CTools modal dialog, or using the Drupal overlay?

I used the Chaos tool suite module, and it does that!


Why am I getting the error "Unknown data property" when the field exists? I am trying to grab all of the fields of a node (which I am doing by using array_keys). At this point, I want to feed them all to entity_metadata_wrapper(), and grab their values.

I will then, if they are strings, print them to a PDF document using TCPDF's Text() function.

Everything looks like it will work correctly; however, certain fields give an error as such:

  EntityMetadataWrapperException: Unknown data property field_grade. in
  EntityStructureWrapper->getPropertyInfo()

The field exists in my node, though.

'field_grade' =>
    array (size=13)
      'default_value' => null
      'description' => string '' (length=0)
      'display' =>
        array (size=4)

This is the code I am using.

$wrapper = entity_metadata_wrapper('node', $node);
$trip_fields = field_info_instances('node', 'trip');
$trip_fieldskeys = array_keys($trip_fields);
$margintop = 0;

foreach($trip_fieldskeys as $item) {
  $value = $wrapper->$item->value();
  if (gettype($value) == "string") {
    $pdf->Text(0, $margintop, $value, false, false, true, 0, 0,
       '', false, '', 0, false, 'T', 'M', false);
    $margintop = $margintop + 25;
  }
}

If it is a custom field that you have defined in your module (using hook_field_info()) then you need to add a property_type to your field info.  See https://www.drupal.org/docs/7/api/entity-api/property-info-for-fields for an example and https://www.drupal.org/node/905580 for a full list of possible types.

If your field is a complex (multiple value) data structure you may also additionally need to include property_callbacks as well.  See http://d7.thecarneyeffect.co.uk/describe-field-properties-make-custom-fields-work-entity-metadata-wrappers for a good example of this.


How to set url alias as article title? I'm getting url alias for all articles like mysite.com/node/14 but I wanted to set the url as aritcle titles like this: mysite.com/article-title

So, How to set all url alias as per the articles title?

Use Pathauto module.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


How do I get masonry to run again once twitter widgets have rendered? I am using the Masonry API and Masonry Views modules to get a view to render nicely, it works well.

I'm using oEmbed Core to render the URL provided by the user into an embedded tweet for a specific node type.  That also works fine.

When the tweet shows up in the view however, my blocks get overlapped because the twitter widget is rendering after masonry has run.  How do I rerun masonry once the tweet has fully rendered?

I went through the twitter documentation and found a way to call functions on twitter widget events:

// Load the twitter widgets script
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

// Bind an event to rerun the masonry layout when a tweet is rendered
twttr.ready(
  function (twttr) {
    twttr.events.bind(
      'rendered',
      function (event) {
        jQuery(function($) {
          $('.view-content.masonry').masonry();
        });
      }
    );
  }
);


When is hook_file_download triggered I wonder which files are being considered to go through hook_file_download. When this function is triggered, what are conditions ?

(Generally, how I can track myself hooks conditions ?)

I am trying to put some custom created download links (files are not uploaded via drupal, but link to them are defined manually, as described in this issue.)

EDIT: For those searching for hook_file_download related issue, it seems that it is triggered (also) whenever you try to access a valid link to a file in private filesystem.

The easiest way to track where core hooks are called, from core code, is to look on the docs page.

For hook_file_download(), you'll see this:

A nice list of all implementations/invocations of the hook with links to the relevant functions.

For the cases that don't get covered there, I usually just grep the codebase for, e.g.

module_implements('file_download'

That takes me straight to file.inc, and the file_download() function, which I guess answers your main question.

If that's not quite enough, I thoroughly recommend using Eclipse/Netbeans with XDebug which will let you set breakpoints to see what's happening in more depth.


How to update/change anonymous author to authenticated current user upon logging in? This is the case:

Anonymous user can create nodes
Anonymous user will leave their email address
Anonymous user must register with the same email to "claim" the contents they created
When that user logs in, the contents with anonymous author but same email address will update then the author will change from "anonymous" to current user.

I created a rule:

I've read some posts that I just need to add events on rules, there are no "AND" "OR" to events then rules will trigger that event but I noticed that it doesn't trigger the event "user logged in".

I tried testing this rule. changing Action, setting the value of author to ="1" ("admin") and removing condition of data comparison.

It does change the author to "admin" when saving new content either logged in or not.

When I saw that was working I returned the data comparison for the email.

Then If a user with the same email address logged in it does not change/update the author.

I tried placing the when user logged in first before the event after saving new content, as a result  I wasn't able to use the [node:etc] on comparison and action. I also tried creating a rule with just one event = "User logged in". same result, I can't find the necessary token/arg I need.

Is there something wrong with my settings? Anyone here could point me to the right direction and steps?

Thank you very much!

Try using the trigger 'after saving a new user account'.  You don't want to check for content every time they log in, just when they create an account that matches email addresses with those node.

For security purposes you should probably prevent people from being able to change their email address too or they might somehow steal someone else's content.

As for people who create content when they already have an account but are not logged in: create a rule that checks for accounts when a new node is saved.  So in summary:

New users should claim existing content when the 'after saving a new user account' is triggered.
New content by existing users (that are not logged in) should be automatically claimed by the user account upon saving the node.

Neither of these events require you to check when a user logs in.


Attachment node field vs. file fields in a content view Sorry, can't think of a better title...

I've created a content view for a specific content type where each node has lots of attached files in one 'attachment'' field.

I want a table of files with columns for file description and file size, grouped by node title.

This is (almost) fine if I use the Nodes 'attachment' field, giving me a list of files (one per row) with the file name or (even better) the file's description.

However, if I want the file size, I create a relationship to File Usage, but this creates a combinatorial explosion in the number of results, returning one file size per file linked to the node per file row...

If I remove the attachment field, just getting the file name and size, its fine. But I want the file description and the size.

The thing is the description seems to be a node property but the size is a file property and the relationship is at the node level, not the file level.

If I drop the relationship, I found that changing the file formatter to 'table of files' shows the size column. Magic. Gives me 98% of what I want, so I'm happy enough.


How to add v1 when specifying the URL of an API? I'm creating an API service using Services (Drupal 7) and would like to create an URL like /api/avu/v1/{id}.

I have api in Path to endpoint and in hook_services_resources() I have $resources['avu'] with

"args" => array(
   array(
     "name" => "id",
     "optional" => false,
     "source" => array("path" => 0),
     "type" => "int",
     "description" => "The id of the course to retrieve."
   )
),

So /api/avu/{id} works but I can't figure out how to add v1.

All I had to do was to add another argument and clear the cache.

"args" => array(
   array(
     "name" => "version",
     "optional" => false,
     "source" => array("path" => 0),
     "type" => "string",
     "description" => "The API version."
   ),
   array(
     "name" => "id",
     "optional" => false,
     "source" => array("path" => 1),
     "type" => "int",
     "description" => "The id of the course to retrieve."
   )
),


How can we show the difference between values in consecutive rows in views I am building a site where users will fill webforms (these are quality of life questionnaires). Users will fill the same form several times. I want to show the change in the value of fields in the webform. For example, if there is a field, say score 1 which has a value of 10 on 13 May 2020, and 15 on 14 May 2020, I want to show that the value has changed by 5 points.

I want to show this using Views as it will allow us to filter by dates on which the form was filled as well as the users (and use contextual / exposed filters).

The Views Aggregator field allows us to calculate the range for a column and using the a modified range formula (which the maintainer kindly developed very quickly) we can show the difference between two values. However, this is constrained to be displayed as a table row and not a field.It also has the disadvantage that the value is always maximum - minimum of the two values.

Is it possible that we can get this as a field in Views (so that I can apply custom css code). The motivation for doing this is to show the value in different colors depending on the value (e.g. red color if the value is more than 10 and green if it is less than 5).

It is noteworthy that each questionnaire can have many different scores computed and I would like to make a display for each. Note that for the display of the change we are looking for change of the recent value as compared to last filled.

Any pointers will be appreciated.

Daniel Cothran, the developer of the Views Cumulative field prepared a field (in no time at all) that serves the purpose. The link to the file is available here Measure of Change Field in Views Cumulative Field Module


How to run custom command running drush cron via sudo? The documentation for drush cron says:

  You should set up crontab to run your cron tasks as the same user that runs the web server; for example, if you run your webserver as the user www-data:

I wrote a wrapper drush command to do this.  In my drush_hook_COMMAND, I call

system('sudo -i -u www-data /usr/bin/drush --uri=http://BLAH --root=BLAH cron');

This works in almost all ways.  However it does not correctly check for updates.  On my drupal status page I get

  There was a problem checking available updates for Drupal...

I've tried using drush_shell_exec instead of system, just the same.  However if I do it via drush eval, it does work:

drush eval "system('sudo -i -u www-data /usr/bin/drush --uri=http://BLAH --root=BLAH cron');"

So I'm completely baffled.  Any idea what could be different between eval and the command hook?

OK, I've finally solved my own problem.

In summary, it wasn't actually a Drush thing in the end.

In detail, my custom drush command was also fixing file permissions and ownership, as per https://drupal.org/node/244924 (because cron can sometimes create a file, and then the file may have the wrong owner/perms).  This sets the ctime on all files, and it turns out that Drupal update checking relies on the ctime.

With hindsight of course I should have done a test with the permissions line removed from my custom command, but it hadn't occurred to me it could be relevant.


How can I send myself an email whenever a user views a Panels page? I have a page that users rarely visit but I would like to send myself an e-mail to the effect of "UID 555 visited the special page."

My site has several hundred pages but I only want to send an e-mail for this specific page.

I thought of using rules (event: when content is viewed), but

this event has to be evaluated on every page hit
it doesn't seem to trigger when the page is embedded within a panel

So, I was wondering if there is some way to easily send myself an email with the UID whenever a user visits a specific panel page.

Add the code below to any of your module. I assumed the name of the module to be my_module.

define('MY_SPECIFIC_NODE_NID', 3); // define the nid for which you want to send email

function my_module_panels_post_render($panels_display, $renderer) {
  $content = $panels_display->content;
  foreach ( $content as $key => $value) {
    if($content[$key]->type == 'node' && $content[$key]->configuration['nid'] == MY_SPECIFIC_NODE_NID){
      dpm('This is my node. I will send email here!');
      // Uncomment the line below to actually send email - remember to substitute variables appropriately
      // drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE);
    }
  }
}

It should work for your scenario.


Using "Profile" Data I have used "Profiles 2" module, and created a form where users can input their profile data.

I have also defined a content type, say "Blog" for example, which has a title and a body. I have used "Views" module to generate the output.

The question is, I would like to display a line like :
'Posted By : '

Is there a way I can extract the data from Profiles?

Yes, you use relationships under advanced to first expose the Content:Author. Then you use relationships again which will now show the User:Profile relation. Now you will have access to all the user details :)

It should look like this when you are done:


Do default emails support HTML? I haven't got around to sending user emails yet.

I wonder if we are able to send HTML emails by default from the Emails section (admin/config/people/accounts), or if we need to use modules for this.

Out of the box (w/ core modules only) default account emails (and any other emails) that Drupal generates do not support HTML. Drupal converts all html emails to plain text before sending. You can install and configure MimeMail module and its dependencies. Then you'll be able to insert html markup into the account email body field at 'admin/config/people/accounts' and have those emails sent properly in html.


Leave Page Alert "warning " Unless Submit Button Clicked I have a website where users submit application forms. The form is based on Entity forms.

How can I popup a message "warning" if user try to close browser without submitting the application.

something similar to this http://jsfiddle.net/DerekL/GSWbB/show/

Many thanks,

You can use the dirty forms module.

Currently there is only a drupal 6 version on the project page, however in this issue there is a drupal 7 version that apparently has been well tested and works.

With this module you can configure it to target your form using css seletors like classes and ids.