Save pdf files in folder using TCPDF I have installed Print module and also TCPDF library to generate PDF files. However, Print module can just create PDF files to download, but not to save in server folder. I have tried to change method _print_pdf_tcpdf in Print module, so files can be saved in server folder. I have changed _print_pdf_tcpdf function  as follows:

I have changed line

$pdf->Output($filename, $output_dest);

to this line:

$pdf->Output($filename, 'F');

But this code throws error:

TCPDF ERROR: Unable to create output file: https://mywebsite/sites/default/files/aaa.pdf

I have set permissions for sites folder to write. Another modules can write into this folder, so I dont think the problem is in permissions.
Can anybody help
where can be problem?

I've made a couple of TCPDF implementations myself in Drupal. As Clive suggested, you shouldn't use URIs in TCPDF's output() method, instead you'll want to provide absolute filepaths.

This code has always worked for me:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$path = drupal_realpath('public://folder/folder2/folder3');

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

EDIT: As Clive mentioned in the comment, drupal_realpath() is deprecated. Here's an alternative:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$uri = 'public://folder/folder2/folder3';
$stream = file_stream_wrapper_get_instance_by_uri($uri);
$path = DRUPAL_ROOT . '/' . $stream->getDirectoryPath() . '/' . file_uri_target($uri);

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

Just make sure you're always providing an absolute path for TCPDF.

$pdf->Output( "myfile.pdf", "F");
TCPDF ERROR: Unable to create output file: myfile.pdf

In the 'include/tcpdf_static.php' file about 2435 line in the static function 'fopenLocal' if I delete the complete 'if statement'... works fine.

public static function fopenLocal($filename, $mode) {

    /*if (strpos($filename, '://') === false) {
        $filename = 'file://'.$filename;
    } elseif (strpos($filename, 'file://') !== 0) {
        return false;
    }*/
    return fopen($filename, $mode);


Drupal 7 "The form has become outdated. Copy any unsaved work in the form below and then reload this page." I have a problem. When I put this code in my module checkboxes work great but form throws an error:

"The form has become outdated. Copy any unsaved work in the form below and then reload this page."

Alert one add node form.

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

  $form['add_phone'] = array (
    '#type' => 'fieldset',
    '#title' => t('Adauga telefon'),
    '#weight' => 6,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['add_phone']['phone'] = array(
    '#type' => 'phone',
    '#title' => t('Phone Number'),
    '#required' => TRUE,
  );

  $form['add_phone']['phone_submit'] = array (
    '#type' => 'button',
    '#value' => 'Add',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'automobil_add_phone_callback',
      'wrapper' => 'add-new-phone',
      'effect' => 'fade',
    ),
  );

  if(isset($form_state['values']['phone']['prefix'])) {
    $upload_users_phone = _upload_users_phone($form, $form_state, 'add');
  } else {
    $upload_users_phone = _upload_users_phone($form, $form_state, '');
  }

  $form['field_temporary_phone'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => t('Telefon'),
    '#type' => 'checkboxes',
    '#weight' => 5,
    '#options' => $upload_users_phone,
  );
}

Ajax Callback

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

Function that returns a list of user_phone that is stored in user profile.
If a user adds new phone it adds it and return the updated list.

    function _upload_users_phone($form, $form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

What is a problem (why is the 'form outdated form' error thrown)?

The reason you get the "The form has become outdated." error is because the token fails validation (meaning the old string doesn't match the new string). The token is determined by running a hash on several things including the session_id(). When you call user_save(), the session is changed/invalidated/whatever. Hence, when the token is tested next time around, it generates a different token because you have a different session_id() and therefore fails, thinking you were using an old form.

I have the same issue after calling user_save() from within my form processing. The way I fixed it feels like a pretty big hack, but I don't know that there's a clean way around it. The form code doesn't seem to expect that you would ever change/invalidate the session whilst in the middle of handling a form (in this case, a multi-part form).

Once you call user_save you must modify the form state manually to insert the updated token. Then, when it checks tokens your new token will match since you generated it after the 'session_id()' was updated.

So the resulting code looks like this. Notice that the input element is changed for $form_state to pass by reference so that the modification gets propagated up.

function _upload_users_phone($form, &$form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
    $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

You might also need to set $form_state['values']['form_token'], but I'm pretty sure it's unnecessary. Again, don't forget the & in front of the declaration of the function variable $form_state or the value won't make it into the real array.

This happens, because somehow you're not using Form API correctly.

As for workaround, try adding form_token into your form, for example:

$form ['#token'] = $form_id;
$form ['form_token'] = array(
  '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
  '#type' => 'token',
  '#default_value' => drupal_get_token($form['#token']),
  '#parents' => array('form_token'),
);
}

and see if that works.

See also: Getting “The form has become outdated” error


View not displaying correctly for all visitors I have created a simple view that displays upcoming events on a page.  Both the events and the pages are meant to be viewed by all site visitors.  The problem that I am having is that in order to see all the events, you need to be logged into the site.  I checked the nodes and permissions and don't see anything out of the ordinary.  The View is supposed to display 17 events, but for the anonymous user they are only getting 12 events.  Inside the view the access is Unrestricted.  I have tried re-entering the 5 events that are missing and they still do not show in the View.

I also have a calendar that displays the events.  Similar to the view, it is not displaying all events.  The ones that are missing from the View are also missing from the calendar.

Any suggestion on what is causing this and how to fix it?  Thank you.

I am using Drupal 6.2 and Views 6.x-2.16

Chris

Okay, this may or may not work...but...lately D7 has a similar issue.

If you select the view, and click the link "settings" under "Query Settings", you can make the view appear by selecting "Disable SQL Rewriting". There is a security risk, and this issue needs to be solved, ex-post-haste, but it works.

This has been an issue with every View I have seen of late, provided all your permissions are legit.


drupal_goto(request_uri()) replaces my '?', '=' and '&' in url I need to redirect user from a page with example.com/node/add/dispo?arg1=1&arg2=2 to the same type of URL. But when I simply do a drupal_goto(request_uri());, it redirects my user to example.com/node/add/dispo%25F%3C etc....

I tried a str_replace but it didnt work.

Would you have any workaround ?

drupal_goto() accepts an $options parameter to be passed on to the url() function. You can pass a query string like this:

$options = array('query' => array('foo' => 'bar'));
drupal_goto('path', $options);

That example will forward on to /path?foo=bar

Actually I made it work by using header("location: " . $base_path . request_uri());


Webform with File upload field throwing "... field is required" error I have created a Webform, which has two file fields (i.e. Attach document 1 and Attach document 2). Both of them are mandatory and files are to be uploaded in the "Private" folder.

Now when someone attaches the files and submits the form, it throws error messages "Attach document 1 field is required" and "Attach document 2 field is required". If I invoke the validation, then it works. I have checked in the server and the files are uploaded properly. So I think it is "Webform" or "Form" issue.

This can be solved by applying the patches found here:

#49 https://www.drupal.org/node/2675170#comment-10908802
#22 https://www.drupal.org/node/2678822#comment-10926613

This will hopefully be resolved just by updating for future versions of drupal core and webform.

I experience the same problem (using Webform 4.1). I found out that this issue only appears when I have the File entity (7.x-2.0-beta1) module enabled.


Want to add tabs from /user/* pages to other pages When I go to any "user" pages on my site in /users/* I have menu tabs for the various pages in that section, like below.

I want to add the top level of tabs to another set of pages. Specifically, I am trying to setup the Private Msg module, which has everything in /messages/* When someone is reading their messages, I want to have the same top level of tabs they see in /users/*

You can use Tab Tamer module to arrange tabs at your user/% location or some where else too. You can change orders or enable/disable as per your requirement.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully
  when javascript is disabled.


How do I use views_pre_execute I am trying to run a subquery  through views and found this call. I cannot get it to work. Here is how I am using it

function module_name_custom_views_pre_execute(&$view) {
    if($view->name=="view_name") {
            if($view->build_info['query_args'][1]==0) {
            $view->build_info['query']="my subquery";

                //echo ($view->build_info['query'] );
                //var_dump($view);
            }
    }
}

Without to test it I tried replacing the $view->build_info['query'] with the query generated in the view. Instead of a view result I get a blank page. Any other query I put in there myself results in a blank page as well.

I am writing the queries like so:

$view->build_info['query']="SELECT nid FROM node WHERE node.status='1'";

So I am not assigning any array objects values but rather writing the query in as if I would in any other db call. Should I build the query through the means of creating an object?  So something like this to start:

["build_info"]=> array(3) {
    ["query"]=> object(SelectQuery)#752 (21) {
        ["fields":protected]=> array(4) {
            ["nid"]=> array(3) {
                ["field"]=> string(3) "nid"
                ["table"]=> string(4) "node"
                ["alias"]=> string(3) "nid" }
        ["node_created"]=> array(3) {
            ["field"]=> string(7) "created"
            ["table"]=> string(4) "node"
            ["alias"]=> string(12) "node_created" }
        ["og_og_membership_label"]=> array(3) {
            ["field"]=> string(5) "label"
            ["table"]=> string(16) "og_og_membership"
            ["alias"]=> string(22) "og_og_membership_label" }
        ["node_title"]=> array(3) {
            ["field"]=> string(5) "title"
            ["table"]=> string(4) "node"
            ["alias"]=> string(10) "node_title" } }

Is there is another way to implement a subquery in views?

Using Drupal 7 Views 3

Also checkout http://drupal.org/sandbox/Fabianx/1184598 as this is adding a subquery to a view; which is exactly what your trying to do.

You will have to make db_select() query object (In Drupal 7 Views 3 you can not use simple SQL query any more). For further detail on "Dynamic queries" go to this link.

http://drupal.org/node/310075

Thanks


Unpublish node based on field option Is there a way to unpublish a node if a user selects an option from a select list in field?

I have a field that has a list of cities. What I would like is if the user selects a certain city like London for example, the node is automatically unpublished so it can be moderated.

I have been trying with rules but every time I test my rule nothing happens so I'm sure there is something wrong with my rule or maybe there is an easier approach?

You could also hook on hook_node_presave() and check here the value of the field... No ?

mymodule_node_presave($node) {
if($node->yourfield[.....]['value'] == 'London') {
$node->state = '0';
}
}

That can be done with some code in a custom module...

In the example below I'm assuming your content type is called article, and articles have a field called category, and when the category is Javascript then we unpublish the node.

First we need to modify the node form and add a new submit handler that fire after the one that saves the node (the order here is important):

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
    if($form_id=='article_node_form') {
        $form['actions']['submit']['#submit'][] = 'article_node_form_custom_submit';
    }
}

Now we need to define our custom form submit handler:

function article_node_form_custom_submit($form, &$form_state) {
    // check if the category is Javascript
    if($form_state['values']['field_category']['und'][0]['value']=='Javascript') {
        // load the node
        $node = node_load($form_state['values']['nid']);
        // set the status to 0 to unpublish it
        $node->status = 0;
        // save the node
        node_save($node);
        // set a message to say what we've done
        drupal_set_message($node->title.' has been unpublished as the category was set to Javascript.');
    }
}

And that's all there is to it :)


How can I obscure what I am using to run my site? Is there anything I can do to prevent somebody from knowing my site is using Drupal by looking at the source code of the front page? I am referring to people who scan sites using software that detects the software used to run the website to be able to attack it using any known weak point.

If it is not possible to completely hide the fact that the site is using Drupal, is it at least possible to confuse them (e.g., by aliasing the node pages with URLs like http://example.com/servlets/<node-id>.jsp)?

You can't hide it completely. Most of what's needed to do it, would require hacking core. The biggest tell, is the Drupal JavaScript variable which is readable from the front page, or any page for that matter.

If you want to improve your sites security by hiding that it's a Drupal site, your effort is better spent on code reviews than it is on trying to hide the fact that the site is made with Drupal.

In that past I've swapped my fonts for the typical Ruby project fonts like Lucida Sans, also increasing input sizes like all the hip kids do.

Another give away is the "throbber" graphic for autocomplete fields. It also doesn't work when you increase the input size. Here's one you can steal: http://beta.seattlebedandbreakfast.com/misc/throbber.gif


how to use two different feeds on one drupal I am using drupal.org/project/views_export_xls Views Excel export
I added two different feeds to my drupal view , but only one of them (the second one) shows as an icon on the page , and if I remove the second one the first one shows up on the page.  how can I see both of them on the view page?

I was able to create a page view w/ two RSS icons with the following steps.

Create a view with a page display.

Add a first "feed" display. You can customize what you want the feed to return here.

Set a path for the first feed display.

Attach the first feed display to the "page" display.

Repeat steps 2-4 to create and attach a second feed display. It should look something like this.

Save the view and view the page. There should be two separate feed icons.

I hope this helps!


extra fields in views module I am using hook_form_alter to add few extra fields in a node. I have also managed to expose those fields in user interface using hook_field_extra_fields. All good until now but I can not see those exposed fields in views module? any suggestions?

In order to expose your field to Views, you need to implement Views API:

http://views-help.doc.logrus.com/help/views/api

This can be made much easier if you implement your field as a proper field, rather than a form alter. The Examples project has some examples, notably Field Permission Example.


How to add more Display Suite template suggestions If you have Display Suite installed, then on the "Manage Display" tab of any content type you will see template suggestions:

  Possible template suggestions are:

  ds-1col--node.tpl.php
  ds-1col--node-page.tpl.php
  ds-1col--node-page-search-result.tpl.php

None of these suit what I'm wanting to achieve, as I wanted a template to apply to all "search-result" view modes for any content type. So my template suggestion would be:

  ds-1col--search-result.tpl.php

But it seems it's not by default accepted. Which hook can I use to add this template suggestion? I was thinking of hook_preprocess_node and adding my own template suggestion to theme_hook_suggestions but this didn't work as it wasn't using my suggestion on node types which have search_result view mode applied to them. The template was only being used on the ones without any search_result view mode configurations, and even then only normal node.tpl.php variables such as $content was passed to this DS template so I don't think it's the right way to do it.

The problem actually wasn't in ds-1col--search-result.tpl.php. It was when I suggested a custom template for a node when I was doing quick tests, with print $ds_content; in them, the nodes which didn't have the search_result view mode configured, weren't being preprocessed by display suite hence didn't have the $ds_content variable set which was being printed on the custom template. Hence it gave me the impression that it wasn't working.

But to answer the question, there's no special stuff you need to do to suggest a template for display suite. First copy the template from display suite folder to your themes folder. And then all you have to do is use the normal hook_process_node and suggest that template for a certain view mode.

In case you have Panels installed, DisplaySuite will benefit from the numerous layouts Panels (and its extentions) have to offer. You can even choose if you want to use the DS own Field UI, or the Panels editor to arrange the fields.

If you don't have Panels installed then ignore this reply. Maybe a more specific reply will help you out.


Countdown timer field with a scheduler module i am using https://drupal.org/project/field_countdown and https://drupal.org/project/scheduler modules.

I have added field_countdown field to my content type 'items'.
I have enabled scheduler for my content type 'items'.

When i am creating a node, i have to choose a date for field_countdown (it shows jQuery timer countdown until set date), also i have to set Scheduler date after that. So you have to set 2 dates instead of one, because these modules are not working together.

So i want to fill only 1 field instead of 2 of them, in my case its a field_countdown and copy its options to a scheduler input.

I've tried jquery without success:

(function($) {
    // jquery timer
    Drupal.behaviors.MyTimer = {
        attach: function (context, settings) {
            // This code will run, on load, even in overlay!!!!!!
            var timerDate = $('#input-id').val();
            alert(timerDate);
        }
    };
})(jQuery);

But js console says that timerDate is undefined. I am using overlay and bartik theme for administration pages.

Here is a good place to start:

http://code.zeurois.com/jquery-countdown/configurator/new/-/tpl/t105-900


Add bootstrap row class on every n views rows I am using Drupal Bootstrap and to get the correct positioning I am using bootstrap rows and columns classes.

How do I render a bootstrap row class on every let's say 3 view rows (bootstrap columns)? The structure must be like this

Use views bootstrap module, in views format style chose Bootstrap Grid it will solve your problem.

You add class in Unformatted list formate .

and your class show like this


Which cache have to clear to update new hooks? I added a new hook inside a module (hook_cart_commerce_pricecomponent_type_info_alter), which cache have to clear to only update that new hook? I mean i do not want to clear all caches.

Administration menu?
Class registry?
Menu?
Page and else?
Theme registry?
Token registry?
Update data?

To register a new hook, you can clear the following caches:

cache_clear_all('module_implements', 'cache_bootstrap');
cache_clear_all('hook_info', 'cache_bootstrap');

More info: https://api.drupal.org/api/drupal/includes%21module.inc/function/module_implements/7

You can rebuild the registry to force Drupal to re-scan the code files and register your hook implementations. To do this with drush:

Before first use, install registry_rebuild:

drush dl registry_rebuild

Rebuild the registry:

drush rr

This worked for me in a case where both drush cc registry, drush cc all and clearing the hook_info and module_implements caches failed.


How to upload a csv file with an admin form? In a custom module, I created an admin form but I need an input to upload a csv file. When the file is uploaded I need to parse in and then I add data to db.

I already made "add to db" and "parsing" functions because when I installed the module, a default file is parsing and added to the db.

Thanks.

EDIT :

I'm using Drupal 7...

The data is stocked in a custom table that is create when the admin user will install the module. There is no node or content type. I just need to save all data of the CSV file (5 columns) in the table by an admin user form. 1 time par month the admin user need to update the table with a new .CSV.

In frontend I have a form and when the user will submit it I check that the code is in the table.

My issue is that I didn't know how to upload the file into a Drupal directory and then access to it after the form submit.

As I said above I already created a parsing function and I tested with a CSV file directly in the module directory, it's working. Data is insert into the table that I have created.

In your custom form create input button like

$form['upload_csv'] = array(
        '#name' => 'files[mycsv_data]',
        '#type' => 'file',
        '#title' => 'Upload csv'
    );

Next in form submit you can use

file_save_upload($source,
                array('file_validate_extensions' => array('csv')),
                $destination_dir,
                FILE_EXISTS_REPLACE)

Here for getting uploaded file details like file name and file path you can use $_FILES global variable.

and then,

if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}


Pager doesn't work in views block if views php field is used I have a views block that shows nodes in some conditions. The views has pager and normally it works but if I use Global: PHP field the pager doesn't work and it only show the first page.

The Global: PHP field is as below:

Value Code: emtpy
Output Code:

->

<?php if ($row->type == 'book') { ?>

<?php }
elseif ($row->type == 'article') {
?>

<?php }
elseif ($row->type == 'thesis') {
?>

<?php } ?>

UPDATE:

I'm listing the nodes in this views block. There are 3 different content types and what I want to do with this PHP field is to print an icon according to content type. The code checks the content type with if ($row->type == ...).

(End of update.)

The PHP field works correctly and gives what I want but I wonder if I do something wrong in the PHP structure.

Do you have any idea what can cause this problem?

There is a patch for that: Pager disappears when Global: PHP used in Views 3.8

  After upgrading from Views version 7.x-3.7 to 7.x-3.8, the pager was
  missing from all views that used Global: PHP fields.

If patch#6 does not work for you, just follow the links in comment#27

For one thing I know Drupal does not like ending php tags '?>' at the end of pages and no start or ending tags in most PHP fields I have seen. If that is not the issue can you put up an image of the field from the edit screen it might help to better understand what you mean?


Custom token [node:customtoken] not available in rules action 'set a data value' I've created module with hook_token_info() and hook_tokens(). Now i can see my token in list of all availble tokens:

$ drush token | grep customtoken
 node        customtoken         Node related token

But this token is not available in rules action 'Set a data value'. What is the problem with custom token?

My rule looks like:

Events: 'After saving new content', 'After updating existing content'
Conditions: 'Content is of type'
Action: 'Set a data value'

1) The easy, but dirty way:
You can nest your tokens in an existing type (see http://drupal.org/node/1714418#comment-6468184). Eg, in hook_token_info() do:
  return array(
    'types' => $types,
    'tokens' => array(
      'site' => $my_tokens,
    ),
  );

Your tokens will appear under "Site information"
2) The harder, but cleaner way:
Define your own rules data type with hook_rules_data_info()
function mymodule_data_info() {
  return array(
    'vub_events_data' => array(
      'label' => t('My Module Data'),
      'group' => t('My Module'),
      'token type' => 'my_module',
      'property info' => array(),
    ),
  );
}

and use this in your hook_token_info() implementation.


How to get achievements notification popup for Ajax Callbacks? I'm using the Achievements module to award the badges to users on certain actions.

In the following example user will get badges after posting 5 and 10 comments.

function MYMODULE_comment_insert($comment) {
  $current_count = achievements_storage_get('comment-count', $comment->uid) + 1;
  achievements_storage_set('comment-count', $current_count, $comment->uid);

  foreach (array(5,10) as $count) {
    if ($current_count == $count) {
      achievements_unlocked('comment-count-' . $count, $comment->uid);
    }
  }
}

The above code is working, user is able to achieve badge after posting 5 comments but since the comment form is being submitted through AJAX, the rewarded achievements notification popup is not being shown until page refresh.

So how can I show achievement notification popup for Ajax callbacks? Any suggestions?

Here is another try at this (various assumptions follow):

The whole thing should run through the Wall module's code, since this is the base for any other interaction happening.
By means of the Form API and AJAX callbacks, there is a possible entry point. This is to wrap the submit callback for the _drupal_wall_comment_post_form into another callback that will make sure the Achievements' related elements are updated.
The steps in this process would be:

Use hook_form_alter to modify _drupal_wall_comment_post_form
Modify _drupal_wall_comment_post_form by hijacking the ajax callback for the wall comment submissions:
$form['drupal_wall_submit']['#ajax']['callback'] =>_your_custom_wall_ajax_callback
Wrap the original callback in your ajax callback and extend it to trigger the Achievements popup functionality using the Ajax framework commands family:

function _your_custom_wall_ajax_callback($form, $form_state) {
  $wall_wrapper = $form['drupal_wall_submit']['#ajax']['wrapper'];
  $wall_content = _drupal_wall_comment_ajax_form_post($form, $form_state);
  $commands = array();
  $commands[] = ajax_command_replace($wall_wrapper, $wall_content);

  // This is where you can write ajax commands to trigger Achievements functionality
  $commands[] = ajax_command_*();

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

Hope this brings you a step further!

You could try using Rules to add a rule for when a user post a comment and then do your thing

After creating the rule you can set conditions and actions, so you can check for the comment count and then act accordingly


Views Exposed Filters AND result for multi select field I'm working with a view with exposed filters for a directory style page.

One of the filters is a multi-select check list, however, we want the results to return AND results only. It is currently returning OR.

For example: Activity open to:
- Men
- Women
- Older People
- Children

So I only want to see results that have both selected.

All the testing I've done returns OR options, so they can have Men OR Women. I want Men AND Women returned.

Views' filters default to an OR between all the options selected. If you pick the "Is all of" option, it will change to an AND operator.

You can modify the query as you like before executing it using hook_views_query_alter.


Different front page for anonymous users and authenticated users I have an app in Drupalgap. I would like to display a different frontpage for anonymous users and authenticated users, for example /dashboard for the first and /user_listing for the last.

I have read "Display Different Text for Anonymous and Authenticated Users", but it is not the same scenario. (/user_listing has ['access user profiles'] as access_arguments.)

I also have tried with drupalgap_goto() without succeed.

How can it be done?

You can achieve this using Context Reaction: Front page module, which extends the great Context module.

Create a new context and:

Add a condition for User role
Add a reaction Front page putting the path for the roles you want to affect.

Save the context and all should be done.

drupalgap_goto() worked for me.

I have front page set to go to qleva_start which has this page callback:

function qleva_start_page() {
  try {
    if (drupalgap_user_has_role('authenticated user')) {
      drupalgap_goto('qleva_start_auth');
    }
    else {
      drupalgap_goto('user/login');
    }
  }
  catch (error) { console.log('qleva_start - ' + error); }
}

so if anon, front is login page and if authenticated, it is qleva_start_auth


How can I set the view mode of a node through rules I'd like to change the view mode of a node based on the role of a user and another flag in the node, and by using the Rules module.

Since a call to display the node by default is full content, I wrote a rule that on Content is Viewed for that node type, it then checks the conditions and sets data value view-mode to teaser.

However, even when the conditions are met properly the node still displays full text.

From this I am assuming that Content is Viewed is being executed after rendering or am I missing something in my approach?

What "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

Be aware: this applies to D7 ... and D6 is another story (from the question context I'm not sure if this is fopr D6 or D7 ...).

You might alternatively try the combination of Display Suite and Contextual View Modes (for setting the view mode) and Context (for getting the condition) modules.
Obviously this is an overkill for what you and me want to achieve plus for some reason Contextual View Modes doesn't work for me right as I'm getting errors.

If you manage to use rules, please make sure to share the rule you wrote to change the view mode!

Edit: OK this setup actually does work very well and the errors don't interfere with functionality. Regarding your specific problem (I know it's a lot of modules but what the hell):

Install Display Suite, Contextual View Mode, Context
Set up your custom view modes with display suite
Add invisible taxonomy term to content type
Make rules trigger a term change in that taxonomy field when node is flagged (this is needed because context module doesn't listen to flags - the sandbox modules intended for that don't work for me either)
Create a taxonomy and user role context (as per your requirements)
Set up Contextual View Modes module (see module page for instructions)

This should work.

BTW I was using the latest development releases.


How to change line-wrap length on Drupal 6 Blog? I'm currently managing a Drupal 6 website which has a blog displaying about 155 characters per line. I'd like to set that to under 85 if possible. Is this buried somewhere in the menus or it is something I'm going to have to find in some php file?

hi you can use the module maxlength to achieve it, it can be used to set the charecter limit to any of the cck field like body, summary, title etc.


Drush not installing correctly I'm attempting to install Drush on a new system OSX 10.10.4.

The process is no longer the simple one it used to be :(

I've complied with the requirement to install via Composer (that was not small feat either), and finally have Drush installed.

However, executing Drush results in the following:

which drush
env: sh\r: No such file or directory

I've seen issues logged similar to this with scripts that had spurious LF/CR. I haven't written any scripts. No idea where this is coming from.

Solutions I've tried include using Composer to uninstall the Drush and install 6. Process appears to work, but results the same when attempting to run Drush.

The error message suggests that the script you're invoking has embedded \r characters, which in turn suggests that it has Window-style \r line endings.

Try to install from other source or something


Passing values from text field to a javascript function in Drupal 8 i am new to Drupal and i am building a form (Drupal 8)that needs to calculate an amount based on the input in two text fields.
What i want to achieve is for the "calculate" button to be hidden until the two text fields have been filled but i'm not sure how to achieve this with behaviors.
Code example:

    $form['weight'] = array(
        '#type'  => 'number',
        '#title' => t('Weight:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'weight',
            ),
    );
    $form['number'] = array(
        '#type'  => 'number',
        '#title' => t('Number:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'number',
            ),

    );
   // Here if weight and number are not empty, show button

Thanks

You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.

e.g.

$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);

You can change the fields name as per your requirement. Hope this will help.

Thanks

Using jQuery you can achieve this

For example if you have input class for weight is input1 and for number it is input2
first hide both the classes using css then using jquery u can show it based on below condition.

if($('.input1,.input2').length && $('.input1,.input2').val().length)){
//your code here showing calculate button
$('.calculate').show();
}

length evaluates to false in a condition, when the value is 0


Save PDF file using webform2pdf I am using Drupal 7.12 and Webform2PDF 7.x-3.0. Is there any feature to save the PDF file to server using this module? Or how can I do this with this module? Or is there any other module ?

No you cannot save it on the server. One way would be to create your own code to grab the pdf with a tool like cURL and save it to the server. You could trigger your code to run every time a webform is submitted throught Rules and Webform Rules. You could issue a feature request to the module developer in case he wants add this fuctionality.

There is also this module: Fill PDF that does what you require. It is quite harder to get it to work with Webforms since you need to build your own pdf form template.

Have you read the documentation ? It states

  The Webform2PDF Drupal module is an extension of the Webform module.
  It can be used to generate PDF document from the results of a form.
  The generated PDF document can be attached to the form summary e-mail
  sent by Webform module, or it can be downloaded from the /Results/
  page.

As it can be downloaded it should be in your server. You can access it by typing the URL for sure.

See Webform2PDF Module Users' Guide


Send site emails to multiple administrators Simple question, though I cannot find the answer anywhere --

How does one specify multiple addresses for the primary administrator account in Drupal 7?

Put another way -- how does one make Drupal administrator emails go to multiple people, without setting up a bunch of forwarding filters on the mailserver?

Thanks!

This is much similar to Pontus's answer but in a different approach. and I have tested this and it worked on a Ubuntu server email program (not through an external SMTP server but it should work in a decent program). Pontus's solution will work as it seems. But recipient will see both email addresses. A good approach would be to set the BCC address (Blind Carbon Copy) instead of a new CC.

If you are not willing to make a module, I'd suggest http://drupal.org/project/maillog .

function MYMODULE_mail_alter(&$message) {
 if (-- enter your condition here -- ) {
   $message['headers']['BCC'] = $message['headers']['Bcc'] = 'hidden@example.com';
 }
 }

Note that now you have opened a serious security risk that hidden@example.com can now see any email, including password reset email address for the super user. So don't forget  to add some condition using $message['id] that contains the message's ID.

You can make the module fancy and really usable by adding some sort of system_settings_form()'d form and a few variable_get().

Also, if the purpose of this is to send multiple emails on new security releases for modules, don't forget that you can add multiple email addresses in settings out-of-the-box.

there is a module available. drupal 6 version is stable and d7 dev is also working for me
you can try that http://drupal.org/project/multiple_email


How to apply focus for specific tab in quicktab I have used quicktabs to search my channels and profiles.I have set default tab "Channels/Videos" in quicktabs setting.When a user enters the text and selects "Profile" tab the focus automatically reverts back to "Channels/Videos".What I want want is,it should remain on the option whichever is been selected("Channels/Videos" or "profile").How can i do this? I also checked by setting the default tab as"none" in quicktabs setting but when a user search for "Channels/Videos"(or "Profile") focus on tab( which is in blue color ) disappears. How can i fix this problem?

You can alter the search form hook_for_alter using form id.

Add a hidden field name it 'mytab' whose by default value will be channel and on click of tab its value will be toggled between channel and profile.

So when we submit the form to search the content, it will look this way ?title=hello&mytab=channel

Now on in your hook_form_alter inline js code to select the default tab based on the mytab value that you can get using $_GET.

Let me know if it works for you.

mymodule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
  return $quicktabs;
}

This works fine.


How to programmatically get the NID of the current node I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.

And solutions like

global $node;
$nid = $node->nid;

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value.

It feels like there must be something really obvious that I'm missing.

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?

Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

or

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.

Another option, in D7:

function _my_module_get_nid() {
  $path_args = explode('/', current_path());
  //$nid = $path_args[1];
  if(is_int($path_args)) {
    return($path_args[1]);
  }
  // Log that we failed to load a NID.
  else {
    watchdog('my_module', 'Unable to gather NID at: ' . current_path(),  WATCHDOG_WARNING, NULL);
  return FALSE;
  }
}

If you plan to use the function outside your module, do not use the leading _ at the begining of the name of the function.


How to set up URL alias patterns? I would like to set the URL patterns in such a way that the page name of the parent page gets inserted into the URL. For example, in the Main Menu I've got an "About Us" link (about-us) and I would like to create a child page Contact Us (contact-us) underneath it.

How do I set up the URL alias patterns so that the child page URL is automatically set to about-us/contact-us?

URL aliases is supported in Drupal by help of pathauto module; if you enable the Token module, you can use it efficiently by using tokens. Once these modules are enabled, you can visit admin/config/search/path/patterns to set the patterns for URLs.

But as I see in your question, you are looking to set this for menu; you can't do that here.

There is logic behind it for not supporting it. Suppose you have a node/18 for about-us and you have two menu 'About-Us" & "About-Company". Now you can add this same node/18 to both places as child.

How can you have two URL aliases for single node/18? So this is the reason why menu are not supported I think.

You can go for creating content type & use pattern for that. You can set pattern for taxonomy, users, etc.

This page holds good information on creating url alias in drupal.

http://www.drupalasisee.com/url-alias


Adding a library to a module using composer I'm working on a module which will require a library that is already in composer.

I added a line to my module's composer.json file:

"require": {
   "markrogoyski/math-php" : "dev-master"
}

I ran the command:

composer update .

and a "vendor" directory was created in my module's directory and the files were downloaded.  However, If I add a use statement to the file my_module/src/Controller/Test.php I get an error:

----Test.php----

<?php
namespace Drupal\lims\Controller;

use Drupal\Core\Controller\ControllerBase;
use Math\Functions\Map\Single;

class Sample extends ControllerBase {
    public function content() {
        print_r(Single::square([1,2,3,4,5]));
    }
}

I see the error:

PHP Fatal error:  Class 'Math\\Functions\\Map\\Single' not found in [module path]/src/Controller/Test.php on line 9

Is there another step that I need to do to get the library autoloaded in the correct namespace?

Using composer update, Composer created the vendor directory, and the autoload.php file, which is necessary to autoload the library. Unfortunately, Drupal doesn't load all the autoload.php files found in each of the directories containing a module.

Instead of adding the dependency of your module in the composer.json file used by Drupal, you should edit its extra/merge-plugin section to include the directory containing the modules you add.  (I added the "modules/*/composer.json" line.)

"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},

In this way, running composer update from the Drupal root directory would  add the required classes in the vendor directory used by Drupal, making them automatically loaded.

If the modules you install are all hosted on drupal.org (i.e., you don't use any custom module), you can instead edit the repositories section to contain the following lines.

"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packagist.drupal-composer.org"
    }
}

In this way, you could add a module hosted on drupal.org running composer require drupal/module-name from the Drupal root directory, and Composer would install its dependencies (declared in the module's composer.json file) in the vendor directory, making the classes automatically loaded.

As per the documentation you will need to use the dump-autoload command to recreate the autoloader file.


Set a token as the default value of a new field In Drupal 7, you can set defaults values for most fields. Is it possible to set a token as the default value.

I remember this being possible in Drupal 6, but it doesn't seem possible in Drupal 7.

There is a thread here that discuss the possibility, but its not clear if it was solved.

What information do you try to get??

In one of my Content Type, I need to retrieve the node ID. I found that the token for the current node ID is this:

[current-page:url:args:last]

Tested and working for me!!

Install the Field default token module.

  This module enables to use tokens as field default values.
  The main discussion: #1070878: Allow tokens to be used in the default value of a field.


How to get Users Email address in an Rest Export View for auth users i build a Rest export view for autocompletion of an textfield. The input should autocomplete email addresses of all logged in users. As admin thats possible, but not as authenticated user, the email addresses get stripped from the result on field access level.

The use case is a share form between users on the same platform ( contact form is not suitable ).

I know this is a security measurement but this platform is for logged in users only and all users are from the same company.

I could hack around the core functions but i wanted to ask if there is a better way to do this?

Greetings,

yobottehg

Access to the user fields is controlled by \Drupal\user\UserAccessControlHandler::checkFieldAccess(). Which returns forbidden() for email except if it's the current user or the user has administer users permission (which you obviously don't want to grant your normal users).

That is called by \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess(), collects the default access and everything returned by hook_entity_field_access(). You can't directly overrrule a forbidden(), but you can implement hook_entity_field_access_alter() and replace the default access check with one that allows access.


How to use Rules to prevent the creation of nodes if certain conditions are true? I need this in Rules:

  When a node is being created (before the node is saved), and certain conditions are true, the user can't create the node, and an error message appears instead.

I have a rule that is working, and the error message is displaying. But the node is still created.

Is there a way to prevent node creation in rules?

Note:
I'm using Drupal 7. I selected the Action "Show error message" directly on rules.

Out-of-the Rules module-box, I think there is no solution to "prevent node creation in rules?" (as in your question). However, without using custom code and custom PHP in your Rules conditions or actions and without deleting the node after it got created, you may get it to work if you also use the Rules Forms Support module.
More details about Rules Forms Support (from its project page):

Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
For help getting started with Rules Forms Support, please see the module documentation.
Features

Activate events for form creation, validation, and submission on a form-by-form basis.
Target individual form elements or the entire form in conditions and actions.
Manipulate the attributes of a form element like title, description, weight, and more.
Validate the values of form elements during form validation.
Set form errors when rule-based validation fails.
Redirect users to a different page upon viewing or submitting a form.
Examine the attributes of elements in active forms with the element inspection tool.

Especially the "Set form errors when rule-based validation fails" should help to address your question.
More details about how to use this module can be found in the community documentation "Altering & validating forms".

if you are using a react on event "Before saving content" a node will be saved anyway.
There is a way to use "After saving new content" option and node_delete($node->nid) ("Execute custom php code option" in action to add) if some conditions are met. But it is too overcoded way.
So if you are using Drupal 7 you can try to use hook_form_FORM_ID_alter() function without creating any rules. Additional validation can prevent node creation.

function your_module_form_YUOR_NODE_TYPE_FORM_alter(&$form, &$form_state, $form_id)
{
   array_unshift($form['#validate'], 'your_new_validation_function');
}
function your_new_validation_function($form, &$form_state) {

if ($some_condition == 'some_condition_variable') {
// Do some things here
}
else {
form_set_error('', 'Form Error, node was not created!');
}

if ($form_state['values']['some_field'] == 'some condition') {
//Do some staff here
}
else {
form_set_error('some_field', 'Form Error, node was not created!');
}

}


Placeholders must have a trailing [] if they are to be expanded with an array of values In Drupal 8 I am trying to insert some data in my custom table. While executing query I am getting error:

  InvalidArgumentException: Placeholders must have a trailing [] if they are to be expanded with an array of values. in Drupal\Core\Database\Connection->expandArguments()

Please find my code below:

$qt = new \stdClass();
$qt->name = 'test name';
$qt->machine_name = 'test machine name';
$qt->settings = array('setting1'=>value1, 'setting2'=>value2);

$query = \Drupal::database()->insert('my_custom_table');
$query->fields([
  'machine_name',
  'name',
  'settings',
]);
$query->values([
  $ob->machine_name,
  $ob->name,
  $ob->settings,
]);
$query->execute();

If I am giving values like below it is working. Please help me whats wrong with above code.

$query->values([
  'test',
  'ttt',
  'dfs',
]);
$query->execute();

That issue got resolved. It was regarding passing array in to the db. Added serialise function resloved the issue.

$query->values([
$ob->machine_name,
$ob->name,
serialize($ob->settings),
]);
$query->execute();

My issue had to do with logging something incorrectly:
 $this->myLogger->log('My message @somePlaceholder', ['@somePlaceholder' => 'hi']);

But from the documentation Logger::log(), the first parameter was supposed to be $level.
I just switched to Logger::info()
 $this->myLogger->info('My message @somePlaceholder', ['@somePlaceholder' => 'hi']);


How do I make a custom module trigger a function when content is unpublished? In short:

Utilizing Drupal 8, I'm hoping to to "hook" into an entity update event for a specific content type so that I can then take further action when that event occurs. In this case, delete the node if it's unpublished.

In long:

The Scheduler module allows scheduling of nodes to publish and unpublish as scheduled. My goal is to then delete a specific-type node when it gets unpublished.

At first I tried to use the Rules module to trigger removal of the unpublished node. However, Rules is not working properly on my website currently (getting errors when attempting to configure unpublish event node type). It spurs interest to see how I can accomplish the same task with a small custom module. I'm moving forward with a goal to understand Drupal 8 modules and module development better.

As a result, I wish to move handling of unpublish events for my content type into module code. Other examples I'm finding relate to Drupal 7. I'm building a Drupal 8 module.

Here is my starting module code so far (rough, draft, untested as I work out logistics).

Module structure:

hour_helper
  hour_helper.info.yml
  hour_helper.services.yml
  src
    EventSubscriber
      HourUnpublishEventSubscriber.php

hour_helper.info.yml:

name: Hours of Operation Helper
type: module
description: 'Utilities to assist with hours of operation, starting with the removal of hour content once it is unpublished via the scheduler module.'
package: Custom
core: 8.x

hour_helper.services.yml:

services:
  hour_helper.node_subscriber:
    class: Drupal\hour_helper\EventSubscriber
    arguments: ['@entity.manager']
    tags:
      - { name: event_subscriber }

HourUnpublishEventSubscriber.php:

<?php

/**
 * @file
 * Event subscriber
 */

namespace Drupal\hour_helper\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

//!!! use (... something entity or node related, we want to subscribe to entity updates?)

/**
 * Remove hour of opperation nodes after/when they are scheduled to unsubscribe to prevent garbage accumulation
 */
class HourUnpublishSubscriber implements EventSubscriberInterface  {
  /**
   * {@inheritdoc}
   */
  public function getSubscribedEvents() {

    // Subscribe to node update events with priority 0.
    //!!! which event....
    $events[SomethingEvents::SOMETHING][] = array('checkForRemoveStatus');
    return $events;
  }

  /**
   * This method is called whenever the ????? event is dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function checkForRemoveStatus(GetResponseEvent $event) {

    //print '<pre>';
    //print_r($event);
    //print '</pre>';

    die('Well, at least an event has been triggered to be handled here...');

  }

}

I continue to ponder
the Drupal events doc page...

Based on this: My goal is to then delete a specific-type node when it gets unpublished.

You can use hook_ENTITY_TYPE_update.

You will have to just check, if the (not the original) entity is unpublished, and the it's type is the one you are looking for.

+1: From OO perspective you can also take a look on events.

If it is your own ContentEntity, hook on the ::save() method of your ContentEntityForm descendant (you may also \Drupal::service('event_dispatcher')->dispatch(... something ...) here. This would be OO.

If you can not do this, go for the hook_entity_update, this is not OO. But there is currently no Event in core for this.

Regards,

Rainer


What is node_access table? For granular node access, TAC, TAC lite, Content Access or ACL can be used, but because of some technical limitations and issues, I can not use them.

While implementing the node access part of my module, I've realized there are 2 type of hooks, total of 3. I've watched hours of videos, read many articles and I am still confused which one does what:

hook_node_access()
hook_node_access_records()
hook_node_grants()

For granular access control over each node with an specific nid, I can implement hook_node_access and see if the user has permission to view/update/delete the requested node.
I will also disable any other kind of node access system (roles permissions to access nodes, TAC, ACL,...) so only my module decides who has access to what.

This should work fine but the question is: what is node_access table used for? ACL and other fellas use it. But what is it? does it direcrly concern me too?

hook_node_access() is a standalone hook and has nothing to do with the node_access table.

hook_node_access_records() and hook_node_grants() go together and are different to hook_node_access(). These hooks use the node_access table.

Basically, the node_access table stores all the access grants for nodes.
These grants can then be queried and joined to other queries to check the access rules for a node.

hook_node_access_records() is invoked when writing access rules to the node_access table and hook_node_grants() is invoked when reading them out again.

To give you a better idea of how the hooks work, look at the code where they get invoked from.

For hook_node_access_records() this is node_access_acquire_grants().
It invokes the hook and then writes all the returned grants to the node_access table.

hook_node_grants() is called from a few places, but generally via the node_access_grants() function, which is called from a few places. Take a look at the node_access() function as an example.

It queries the node_access table, adding to the query conditions any access grants returned by modules that implement hook_node_access_grants(). Note that grants are also alterable via hook_node_grants_alter().

While you are looking at the node_access() function you can also see how hook_node_access() is called and you'll see how it is different and why it's not as flexible a solution to access control.

In case you haven't seen it, this is a good article on the topic: http://www.phase2technology.com/blog/drupal-7-node-access-grants-locks-and-keys/

nid - node id
gid - userid if realm is "workflow_access_owner". role_id if realm is workflow_access
realm - enum (all, workflow_access_owner, workflow_access)
grant_view - has view privileges?
grant_update - has update privileges?
grant_delete - has delete privileges?


Disappearing Content I just inherited a Drupal 7 website from another agency. The site was fairing well in our DEV and STAGE environments. The problem started occurring when we switched DNS over to our PRODUCTION site.

We have all the nodes (from the same content type) that seem to be "randomly" disappearing.

I've made sure to upgrade the core to the latest and any security fixes for any modules that are being used.

I was wondering what I could do to troubleshoot this issue - as I'm exhausting all my efforts and nothing seems to be working.

It looks like a cache problem. I will suggest to do this, as usual backup is always a good idea:

See if this happens also if you are login. You might have your node permissions corrupted. If you rebuild and have a lot of node, it might take a little while to do this.
Turning cache off for page and blocks.
is your content generated by a view? if so check the permission

Local module is disabled. Enable the Local module. It will solve it.


How to map multiple existing term IDs to an entity I'm trying to map multiple existing terms using their target_id values to an entity (Commerce Product) and I can only get the first value to map.

My yml file looks like this:

  'field_prod_category/target_id':
    plugin: explode
    source: tid
    delimiter: ','

And, for now, I'm hard coding two existing term ID values in through the source plugin like so:

$row->setSourceProperty('tid', '806,635');

But no matter what I try only the first term is referenced. And, yes, the term field is set to unlimited.

Any ideas?

You need to use plugin sub_process. File yml have soure like this:

  field_prod_category:
    plugin: sub_process
    source: tids
    process:
      target_id: tid

and soure plugin need to prepare:

$tids = [
      'tid' => 806,
      'tid' => 635
    ];
$row->setSourceProperty('tids', $tids);


How to insert Google Tag Manager code into pages with variable account value I need to insert the Google Tag Manager snippet code into each page just after the opening <body> tag. This is fine, except I would also like the user to specify the account number in an admin form, so what is put in this form will be output in the snippet.

In the snippet, the account number is required twice:

<noscript><iframe src="//www.googletagmanager.com/ns.html?id=<ACCOUNT NO HERE>"
...
(window,document,'script','dataLayer','<ACCOUNT NO HERE>');</script>

Setting up the admin form and storing and retrieving it by variable_set() and variable_get() is no problem, but what's the best way to insert it into the template?

My thought is to use hook_preprocess_page(), but I'm not sure if this is the right hook to use, and if it is - what part of the array I would need to change to get this to appear? Or would a better way would be to make a variable available to the tpl.php file and insert it there? In which case, how would this be achieved? Thanks!

you should use these two modules:

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

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

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

User Id is part of default data added to dataLayer by data layermodule on each page, so you'll have it there.

Regarding your noscript part, you'd have to alter the module i think.

Bala, I think it would be best to update html.tpl.php in the appropriate <head> (script) and <body> (noscript) positions.  This is where our GTM code is located, and it appears on all pages.

Typical location is .../sites/all/themes/<theme-name>/templates/html.tpl.php

Regarding how to make the variable available, perhaps this info from the header of html.tpl.php will provide all the information you need:

* Complete documentation for this file is available online.
* @see https://drupal.org/node/1728208


Panels block title translation I use blocks in a panel with Drupal 8. With view generated blocks there are no problems: The block titles are translated accordingly to the view settings. With custom blocks, it appears to be problematic to get the block title translated. I hoped that these titles would be translatable via the user interface translation but they are not; plus, in the panel settings, I can set the block title, but I cannot translate it.

How can I translate block titles (and maybe block content) of custom blocks in a panel, with Drupal 8?

You can override the block.html.twig template and handle the translation of the title directly on the template:

    {{ label|t }}

You may need to confirm the title structure (if is #markup or plain text/string)

Page variants are translatable using config translation at /admin/config/regional/config-translation


how to hide the adminblog link in the teaser how to remove admin`s blog in footer of teasers i can remove the add comment link with this code :

function  mytheme_node_view_alter(&$build){
if ($build['#view_mode'] == 'teaser')
{
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);

    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
}

but i cant remove admins blog what can i do ?!

Try to use something like the below code to hide admin's blog from teaser's view in your theme's template.php, hope it will work for you:

function THEME_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'teaser') {
        if ($variables['type'] == 'blog' && (arg(0) != 'blog' || arg(1) != $variables['uid'])) {
          unset($variables['content']['links']['blog']['#links']['blog_usernames_blog']);
          unset($variables['content']['links']['node']['#links']['node-readmore']);
        }
      }
    }

Check out the module Tab Tamer

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.


How do I put a taxonomy term on a panel page? I'd like to put several hand-picked taxonomy terms on a panels page, each term as a panels pane, showing their descriptions, with a more link to the term's view page, and maybe some of the fields that I have added.  Is there any module to do this?

Right now for each term I have to create a page, panelize it, add a view pane of the term to it, and then add the page to the panels I want them to show up. Seems to be working nicely enough but still too troublesome for ordinary editors to do it themselves.

Create a Page
Give it a %term argument and map it to a taxonomy term
Create a view pane that takes a taxonomy term as argument.
Create a mini panel that requires a taxonomy term argument.
Add the View to the mini panel. Configure it to use the taxonomy term.
Add the mini panel to the Page.

Are you confortable with custom coading?..If so here is an approach that might be friendly:

Create a Select field with simple yes/no option, to taxonomy term vocab (whose terms you want to be displayed in panels pane). lets call this "field_check". For each terms you want to be placed in panels, you will select yes, others will default to no.
In a custom module implement hook_block, to generate a block for all terms, which have the above field checked.

for example:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
  $vid = $vocab->vid;
  //get the taxonomy terms by vocab id
  $terms_array = taxonomy_get_tree($vid);
  foreach ($terms_array as $key => $voc) {
    if($voc->field_check['und'][0][value] == 'yes') {
      $blocks['term:' . $voc->tid]['info'] = $voc->name;
    }
  }
}

Also implement a corresponding hook_block_view().

This will create a separate block for each term you have chosen to be exposable to be added to panels. Now your content editor can just go in and add the blocks to the panels as panes.
Please remember the output will depend on the implementation of hook_block_view corresponding to each term you have exposed.

Hope this helps.


Remove users with no created nodes D7 I have a site setup where users create a node as soon as they login from the activation link sent via email. I've recently been getting tons of people signing up but not creating any nodes because the emails they register with are obviously fake so I would like to remove all the users with the role listing user that hasn't created a node withing a day of registration.

I need help doing this with Rules if at all possible please. If you have any other methods that doesn't involve complex php that would help as well.

Thanks

You can create a View that shows the users who haven't authored any nodes, and then use VBO https://www.drupal.org/project/views_bulk_operations  to delete those users.

You can hook to the cron that runs daily that check and delete those users.


Conditionally show fields viewing a node (not in the node add form) I know conditional fields can be use to create CCK optional fields, but I need something similar to display part of a node, according to user decisions.

I will have a question "do you like cats?", then the user will be shown another question according to what they answer to the first one, and so on.

I was thinking to create this all in one node

field1 -> answer 'yes' -> show field2,
field1 -> answer 'no' -> show field3),

but I guess this could be done the same with multiple nodes

node1 -> answer 'yes' -> show node2,
node1 -> answer 'no' -> show node3.

Do you have any module to suggest me to reach my goal?

If you haven't solved this yet, the Webform Conditional module might help.

  This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.

You can use the Entityform module, combined with Conditional Fields.


How can I make revision log message required based on revision checkbox by node_form_alter? My goal is to make the "revision log message" required if "Create new revision" is checked on create/edit node.

I do able to add the visible and required mark based on the "create new revision" field.

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

  $form['revision_information']['log']['#states'] = [
    'required' => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
    'visible'  => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
  ];
}

I also able to make the "revision log message" as required.

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

  $form['revision_information']['log']['#required'] = [
    'required' => [
      ':input[name="revision"]' => ['checked' => TRUE],
    ],
  ];
}

But I don't know how to make the field required based on the "create new revision" checkbox.

PS: I want to make this simple and don't want to use the "Enforce revision log message" module.

// update 1: I found it require a custom hook validate and Im searching for it

I found an answer after hours of searching. Basically, I just need to add a custom hook validation for revision log. See below for my code.

function MYMODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
    // change revision log status based on revision checkbox
    $form['revision_information']['log']['#states'] = array(
        'required' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
        'visible' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
    );
}
function MYMODULENAME_node_validate($node, $form, &$form_state) {
    // add revision log validation
    if (empty($form_state['values']['log']) && ($form_state['values']['revision'])) {
        form_set_error('log', 'Revision log message cannot be empty!');
    }
}

I hope this helps someone who needs revision log message required.

I created a simple module that does this.  Note, it will require the log message on any revision of a node, but not on initial creation.  Also, it currently affects all node types without regard to if the create new revision is clicked on the content type configuration.
https://www.drupal.org/project/require_revision_log_message/


Hide field label with hook_form_alter() In hook_form_alter(), I am trying to disable/hide a field label in a custom form. I know I could use $form['my_field']['#enableLabel'] = FALSE;.

Is there a way without unsetting the title?

Unsetting not really, hide yes : use #title_display and its get accessible to screenreader :

$form['my_field']['#title_display'] = 'invisible';

you can try:

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    $form['title']['widget']['0']['value']['#title_display']=none;

 }

Note: change "title" by your machine name field.


How to programmatically create new revision and publish it? (I am using Revisioning.) I call node_load(nid, vid) (with the latest version id), give new values to some fields, and then save the node. Setting $node->is_current = TRUE before saving will ensure that this version of the node is now published. However, it does not create a new revision. So I try setting $node->revision = TRUE also, but this creates a new unpublished revision which is not what I would expect.

How can I edit a node, and save it as a new revision and also as the current published revision? Not sure if it is a bug in the module.

// Node has some new revisions since the version that is currently published.
$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
node_save($node);
// New revision created, but not published.

I think it will work when you explicitly set revision_moderation to FALSE. If moderation is not required, it should be published right away.

$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
$node->revision_moderation = FALSE;
node_save($node);

From the example here: http://drupalprogrammatically.com/anwsers/7/create-node

Poster of above url also sets $node->revision = FALSE;, but that would give me the impression no new revision is saved, which is not what you want.
I hope it helps.

Too easy - just separate the steps. First set a new revision and save, then load it again and adjust the fields and set published and save.


theme_key does not switch theme when URL user//edit is called Hello fellows and Gurus,

I am having a problem with a mobile theme of our standard website (running Drupal 7)

We therefore have two URLs:

mywebsite.com
m.mywebsite.com

We use the ThemeKey module to redirect to the correct theme/templates. We also tried Mobile Tools, but it does not work any better, so it is currently disabled.

For most pages, the url detection works and successfully redirects to the mobile theme when m.mywebsite.com/<somepage> is called.

However, when user wants to edit his own profile (m.mywebsite.com/user/<uid>/edit), the standard page is shown instead.

Same happens with the "cancel account page" (m.mywebsite.com/user/<uid>/cancel).

However the registration page (m.mywebsite.com/user/register), and the forgot your password page (m.mywebsite.com/user/password) works OK. Even when the user is connected for the latter.

Any ideas of what could be wrong in our configuration/code ?

Here is the answer : http://drupal.org/node/1130158
To quote:

user/%/edit is an admin path. See function user_admin_paths for details.
So if you enabled an "Administration theme" at "/admin/appearance", this theme will be applied instead of any theme configured using ThemeKey.

Also: Don't forget to specify "system" in your settings for theme_key.


How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/* I have been searching for the answers to this question with no luck at all.
From what I observe in the database structure, the location to the modules are specified in the 'system' table.
The only solution I have is to write an SQL query to update the 'filename' column.

Is there a better/cleaner solution in solving this, for eg., a contrib module?

You only need to move your modules to the your new location and rebuild the regisry. When the registry rebuilds the path to the modules will be updated. Check registry_rebuild().

  Rescans all code in modules or includes directories, storing the location of each interface or class in the database.

Although, I would recommend you to backup you database before testing this.

If you are using drush you could also rebuild the registry using the following command:

drush cc registry

You can also install the registry_rebuild command for drush:

// install registry_rebuild
drush dl registry_rebuild
// rebuild the registry
drush rr

You could just add a sym link in the sites/all/modules diretory pointing to sites/all/contrib.
I'm not sure if it solves your problem. There are other solutions too, including the installation profile, or a drush make file. I don't know enough to provide details on them but at least it's a direction you can look at.


Contextual link for individual node? When I hover over a block on the front end, I get the Contextual Links popup to edit the block.  Can I also set this so when someone with permissions to do so hovers over a node, they get a link popup to edit that story?

To avoid hacking core, this code put in a custom module accomplishes the exact same thing as the solution by Psykoral/Clive:

//Implements hook_node_view_alter()
function mymodule_node_view_alter(&$build) {
  if(isset($build['#node'])) {
    $node = $build['#node'];
    if(!empty($node->nid)) {
      $build['#contextual_links']['node'] = array('node', array($node->nid));
    }
  }
}

Because I went looking around for this FOREVER, hopefully it'll help someone still digging up this thread. I searched for 3 days, found all kinds of 200 lines of code nonsense, custom modules that claimed to do this, yada yada, all to no avail.

Basically what I found was that the PHP that builds contextual links specifically looks for it NOT to be it's own page node, or in full view mode. Well jeebs, thanks, that's exactly where I wanted contextual links! How awesome of you to hard code it and decide not to give me them on pages I want to be able to edit without going into the Admin interface.

Anyway, bitterness aside (can you tell I've been looking for this answer for a while?)... it's time to brute force remove that so we can enable it for all full page nodes in one shot.

Edit /modules/node/node.module
About line 1303 you should see this line:

if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node)))
Comment it out and make it this instead:

if (!empty($node->nid))
Save, upload, and dance!

Basically, what this does is make contextual links available to every block, view, or node, when previously the code was specifically blocking them from 'full view mode' and if the node is being viewed as an entire page.

May not be the most 'official' way to do it via the Drupal UI, but it does what I want it to do anyway. Hope it helps someone. Going to glue my hair back to my head now.


Hook menu url giving access denied for post method but working for get method I defined a custom url using hook_menu and a custom delivery callback that returns json output.

I wanted the url to work on the post method but it is giving access denied for requests done using the post method but it is working without issues for get method.

How do I debug and see why post methods are being denied access?

/**
 * @file
 * Implements menu functions for returning json output.
 */

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['api/json/select/programs'] = array(
    'access callback' => TRUE,
    'access arguments' => array('access content'),
    'page callback' => 'mymodule_api_return_aid_program',
    'delivery callback' => 'mymodule_api_json_output_wrapper',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
 return $items;
}

/**
 * Custom page callback function - Retuns the uid of the user on passing
 * valid username and passowrd returns error otherwise
 *
 * @return $uid
 *   Uid of the user on success, NULL if other wise
 *
 * @return $status
 *   success of the user on success, failure if otherwise
 */
function mymodule_api_return_aid_program() {
  try {

    // Fetching the primary parameters
    //product code
    $product = $_POST['product'];
    //country code
    $country = $_POST['country'];
    // language code
    $language = $_POST['language'];

    // age
    //citizenship
    // veteran_status
    $values = _find_product_specific_to_country($product, $country);

    return array('message' => array('nodes' => $values));
  }
  catch(Exception$e) {
    return array('status' => FALSE, 'message' => $e);
    watchdog('Aid API ERROR', $e);
  }
}

/**
 * Custom delivery callback function
 *
 * @param $var
 *   The argument to the delivery callback function
 *
 * @return array
 *   Contains json encoded format of $var on succes,
 */
function mymodule_api_json_output_wrapper($var) {
  // If the access callback is FALSE
  // it will pass MENU ACCESS DENIED to the
  // delivery callback function
    //return drupal_json_output($var);
  if ($var == MENU_ACCESS_DENIED) {

    return drupal_json_output(array('status' => FALSE, 'message' => 'Invalid Token. Access Denied'));
  }
  else {
    return drupal_json_output($var);
  }
}
e

your code works for me:

Try to move watchdog before return if there is any exception, will log into your report log.
Change your function to like this:

function mymodule_api_return_aid_program() {
  try {
    // Fetching the primary parameters
    //product code
    $product = $_POST['product'];
    //country code
    $country = $_POST['country'];
    // language code
    $language = $_POST['language'];
    // age
    //citizenship
    // veteran_status
    $values = _find_product_specific_to_country($product, $country);
    return array('message' => array('nodes' => $values));
  } catch (Exception $e) {
    watchdog('mymodule', 'Aid API ERROR ' . $e->getMessage(), array(), WATCHDOG_NOTICE, NULL);
    return array('status' => FALSE, 'message' => $e->getMessage());
  }
}

Update: debug
Getting access denied maybe another module add/alter your menu and add another access arguments then access content so in your callback function print you menu object and see something like :

  $menu_item = menu_get_item('api/json/select/programs');
  // print the menu array
  print_r($menu_item);
  // Print access arguments
  print_r($menu_item['access_arguments']);
  // Print access callback
  print_r($menu_item['access_callback']);

You need to setup a REST API endpoint and assign/authorize it to use the POST API calls. the /api should be setup as a REST API endpoint on your website first.
Follow this guide on how to use the Services module.

Update: Do not forget to use the CSRF token with a POST request. Check the guide above for more details on how to obtain that.


How to parse out links and img src references from body copy? I need to modify links and img references in the body of nodes and comments. MPD already gave me good advice regarding using a script.

Is there an easy way in Drupal or PHP to parse out all the links in the body copy?

It's never easy to do something like this because parsing HTML is a bit hit-and-miss, depending on how well formatted the input is.

I've always found the best way to do it is to load the HTML into a DOMDocument object, loop through and change whatever element attributes/values I need to, then use the DOMDocument to give me the new output.

This is a very rough example but hopefully it'll give you the idea:

$html = '

Blah blah blah

Link Text

';

$doc = new DOMDocument;

// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc->loadHTML($html);

// Get the links.
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
  // Change the value of an attribute based on the current value.
  if ($link->getAttribute('href') == '/some-path') {
    $link->setAttribute('href', '/some-other-path');
  }
}

// Get the images.
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) {
  // Change the value of an attribute based on the current value.
  if ($image->getAttribute('src') == '/some-path.jpg') {
    $image->setAttribute('src', '/some-other-path.jpg');
  }
}

// Get the new HTML
$new_html = $doc->saveHTML();

// Strip out the tags that loadHTML() introduces to get the clean HTML.
$patterns = array("/^\<\!DOCTYPE.*?/si", "!$!si");
$body_text = preg_replace($patterns, '', $new_html);

// Update the node body.
$node->body[$node->language][0]['value'] = $body_text;

EDIT

I knew I'd seen a good question about this on SO; have a look at How to parse and process HTML with PHP? for a good discussion on the subject in general.

Maybe you are not looking at the good way.

Have you try to make a replace in the database?

update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, 'find this string', 'replace found string with this string');

update client_table set company_name = replace(company_name, 'Old Company', 'New Company')

I have use use them for some migrations. It's no easy—you must check and map all the replace—but it works.


How do I schedule a reminder email with Rules to users that have flagged an event? I have a content type: event
It has a single date field: date
It has a flag on it: reminder

When the user flags the node, I want to schedule a rule to send them an email the day of the event.

Can someone walk me through the steps on how to do this?

Edit: I have now gotten as far as being able to schedule the email

This is what I have so far.

Add new component
 - Type: Action set
 - Name: Send reminder email
 - Data Type: User
 - Data Type: Node

Add action
 - Send reminder mail
 - To: 'user:mail'
 - Subject: Don't forget about [node:title]
 - Body:
 - Don't forget about [node:title] tomorrow!

Create new Rule
 - Name: Schedule reminder email
 - React on Event: A node has been flagged, under "Remind"

Condition: Entity has field Data Selector flagged-node  Field: Date

Action: Schedule component evaluation Action set: Send reminder email

Sounds like you know how to set up the Flag. Triggering a Rule with Flag is piece of cake and NodeOne has an create 15min tutorial covering all the details. They also have all the needed training on Rules if your fuzzy about Rules in general. Once your ready to set up your rule and you have the event to trigger it, you can set up the email action following a recipe similar to this other answer. In your case you have the future event. Lullabot has a tutorial specifically on the Rules Scheduler.

You can add flag on your node called "reminder users" to send bulk emails. create rule on that flag so that rule will run once the flag update. in rules action. fetch users who flagged this node for attending this event. next create a loop to add users emails into your list and use send HTML e-mail into same loop to send email to all users who flagged this node.


How to create a drop down menu for monthly archives? I'd like to be able to display a block on the right sidebar with a drop-down menu for the monthly archives ("blog post" content type). Exactly as shown in the following screenshot taken from http://curbed.com/

Can anybody please advise me on how to do this with Drupal 7? Thanks!

I have create a new content type name with blog which have default fields(node title and body) Steps are given below.

First create a view(jump menu) for monthly archive.

Select post date of node one for drop-down text and second for link. All settings are given in screenshot.

Settings for jump menu

Settings for post date(first)

Settings for post date(Second)

Now add a page where display list of node based on drop-down value selection

Follow Page settings

Contextual filter settings for year

Contextual filter settings for year

Select a region for your monthly archive block. Here I am adding views export code that will help you better.

Views export code

$view = new view();
$view->name = 'monthly_archives';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Monthly Archives';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['style_options']['default_value'] = TRUE;
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created']['alter']['text'] = '[created]';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'F Y';
/* Field: Content: Post date */
$handler->display->display_options['fields']['created_1']['id'] = 'created_1';
$handler->display->display_options['fields']['created_1']['table'] = 'node';
$handler->display->display_options['fields']['created_1']['field'] = 'created';
$handler->display->display_options['fields']['created_1']['label'] = 'link path';
$handler->display->display_options['fields']['created_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['text'] = 'archive/[created_1]';
$handler->display->display_options['fields']['created_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created_1']['date_format'] = 'custom';
$handler->display->display_options['fields']['created_1']['custom_date_format'] = 'Y/m';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = '';
$handler->display->display_options['fields']['body']['element_label_colon'] = FALSE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Created year */
$handler->display->display_options['arguments']['created_year']['id'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['table'] = 'node';
$handler->display->display_options['arguments']['created_year']['field'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_year']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_year']['default_argument_options']['index'] = '1';
$handler->display->display_options['arguments']['created_year']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_year']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_year']['summary_options']['items_per_page'] = '25';
/* Contextual filter: Content: Created month */
$handler->display->display_options['arguments']['created_month']['id'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['table'] = 'node';
$handler->display->display_options['arguments']['created_month']['field'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_month']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_month']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_month']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['path'] = 'archive/%/%';

with views and date modules' and an exposed form (in advanced) you'll be able to do something like that.


Cannot override template provided by contrib module in theme I'm leveraging the Superfish module for our menus but need to tweak the output a bit.
Normally I'd just copy the relevant template file (in this case superfish-menu-items.html.twig) into my theme and call it a day.
This isn't working in this case. Any ideas why that might be and how to get around it?

Before voting to close this issue, I'd ask that you request information you think would be valuable to providing additional specificity.
I can only assume that this issue is due to some issues with the construction of the Superfish module itself and its theming implementation, so I'm trying to figure out how to work around this.
Any solution would likely be applicable in similar contexts as well.

I've tried modifying the element in hook_theme() and hook_theme_registry_alter() to point to my theme's implementation of the template, but in both cases I end up hitting

  Twig_Error_Loader: Template is not defined errors.

EDIT: I'd already enabled debugging prior to posting. Please stop suggesting that I enable debugging. This is what is shown before and after copying the template into my theme. I've cleared caches and verified the template name in my theme.

For drupal8 you need to enable twig debug in the service.yml file. Then clear cache. After that, you will see in the browser inspector all templates name suggestion to override a part of the page.